language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Drive { constructor (options) { this.authProvider = options.provider = Drive.authProvider options.alias = 'drive' options.version = 'v3' this.client = purest(options) } static get authProvider () { return 'google' } list (options, done) { const directory = options.directory || 'root' const trashed = options.trashed || false return this.client .query() .get('files') .where({ fields: DRIVE_FILES_FIELDS, q: `'${directory}' in parents and trashed=${trashed}` }) .auth(options.token) .request(done) } stats ({ id, token }, done) { return this.client .query() .get(`files/${id}`) .where({fields: DRIVE_FILE_FIELDS}) .auth(token) .request(done) } download ({ id, token }, onData) { return this.client .query() .get(`files/${id}`) .where({ alt: 'media' }) .auth(token) .request() .on('data', onData) .on('end', () => onData(null)) .on('error', (err) => { logger.error(err, 'provider.drive.download.error') }) } thumbnail ({id, token}, done) { return this.stats({id, token}, (err, resp, body) => { if (err) { logger.error(err, 'provider.drive.thumbnail.error') return done(null) } done(body.thumbnailLink ? request(body.thumbnailLink) : null) }) } size ({id, token}, done) { return this.stats({ id, token }, (err, resp, body) => { if (err) { logger.error(err, 'provider.drive.size.error') return done(null) } done(parseInt(body.size)) }) } }
JavaScript
class ItemList extends Component { constructor(props) { super(props) } render() { localStorage.setItem('updateTime', new Date) const { killmail_list, name, options } = this.props if(killmail_list.length >= parseInt(options.maxKillmails)) { deleteLast() } const items = killmail_list.filter((item) => { if(item.active) return true }) .map((item, index) => { return <Item key={ index } item={ item } /> }) return ( <div> <Infinite className={ name } containerHeight={ window.innerHeight - 55 } elementHeight={ 50 }> { items } </Infinite> </div> ) } }
JavaScript
class Linky extends React.Component { render() { const { text } = this.props const { link } = this.props return ( <a className="linky" data-text={text} href={link}>{text}</a> ) } }
JavaScript
class Live extends base_1.Base { /** * Get a new entry pattern. * @param identifier Entry identifier. * @param references Entry references. * @param patterns Entry patterns. * @returns Returns the pattern. */ getEntry(identifier, references, patterns) { return new Core.ExpectFlowPattern(new Core.OptFlowPattern(new Core.RepeatFlowPattern(new Core.ChooseFlowPattern(...patterns))), new Core.EndFlowPattern()); } /** * Get a new route. * @param path Route path. * @param value Optional route value. * @param pattern Optional route pattern. * @returns Returns the route. */ getRoute(path, value, pattern) { const [test, ...remaining] = path; if (value !== void 0) { if (pattern !== void 0) { return new Core.SetValueRoute(value, pattern, ...path); } return new Core.SetValueRoute(value, test, ...remaining); } if (pattern !== void 0) { return new Core.FlowRoute(pattern, test, ...remaining); } return new Core.UnitRoute(test, ...remaining); } /** * Get a new map pattern. * @param routes Map routes. * @returns Returns the pattern. */ emitMapPattern(...routes) { return new Core.MapFlowPattern(...routes); } /** * Get a new token pattern. * @param identity Token identity. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitTokenPattern(identity, ...patterns) { return new Core.EmitTokenPattern(identity, ...patterns); } /** * Get a new node pattern. * @param identity Node identity. * @param output Output node direction. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitNodePattern(identity, output, ...patterns) { return new Core.EmitNodePattern(identity, output, ...patterns); } /** * Get a new identity pattern for dynamic directives. * @param identity New identity. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitIdentityPattern(identity, ...patterns) { return new Core.SetValuePattern(identity, ...patterns); } /** * Get a new condition pattern. * @param test Test pattern. * @param success Success pattern. * @param failure Failure pattern. * @returns Returns the pattern. */ emitConditionPattern(test, success, failure) { return new Core.ConditionFlowPattern(test, success, failure); } /** * Get a new choose pattern. * @param patterns Possible patterns. * @returns Returns the pattern. */ emitChoosePattern(...patterns) { return new Core.ChooseFlowPattern(...patterns); } /** * Get a new choose units pattern. * @param units Possible units. * @returns Returns the pattern. */ emitChooseUnitsPattern(units) { return new Core.ChooseUnitPattern(...units); } /** * Get a new expect pattern. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitExpectPattern(...patterns) { return new Core.ExpectFlowPattern(...patterns); } /** * Get a new expect units pattern. * @param units Expected units. * @returns Returns the pattern. */ emitExpectUnitsPattern(units) { return new Core.ExpectUnitPattern(...units); } /** * Get a new not pattern. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitNotPattern(...patterns) { return new Core.NotFlowPattern(...patterns); } /** * get a new opt pattern. * @param patterns Optional patterns. * @returns Returns the pattern. */ emitOptPattern(...patterns) { return new Core.OptFlowPattern(...patterns); } /** * Get a new repeat pattern. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitRepeatPattern(...patterns) { return new Core.RepeatFlowPattern(...patterns); } /** * Get a new place node pattern. * @param current Current node destination. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitPlacePattern(current, ...patterns) { return new Core.PlaceNodePattern(current, ...patterns); } /** * Get a new append node pattern. * @param identity Node identity. * @param current Current node destination. * @param head Head pattern. * @param patterns Optional patterns. * @returns Returns the pattern. */ emitAppendPattern(identity, current, head, ...patterns) { return new Core.AppendNodePattern(identity, 1 /* Right */, current, head, ...patterns); } /** * Get a new prepend node pattern. * @param identity Node identity. * @param current Current node destination. * @param head Head pattern. * @param patterns Optional patterns. * @returns Returns the pattern. */ emitPrependPattern(identity, current, head, ...patterns) { return new Core.PrependNodePattern(identity, 1 /* Right */, current, head, ...patterns); } /** * Get a new pivot node pattern. * @param identity Node identity. * @param pivot Pivot pattern. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitPivotPattern(identity, pivot, ...patterns) { return new Core.PivotNodePattern(identity, 1 /* Right */, 0 /* Left */, pivot, ...patterns); } /** * Get a new symbol pattern. * @param identity Symbol identity. * @param symbol Symbol pattern. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitSymbolPattern(identity, symbol, ...patterns) { return new Core.EmitSymbolPattern(identity, symbol, ...patterns); } /** * Get a new symbol scope pattern. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitScopePattern(...patterns) { return new Core.ScopeSymbolPattern(...patterns); } /** * Get a new error pattern. * @param value Error value. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitErrorPattern(value, ...patterns) { return new Core.EmitErrorPattern(value, ...patterns); } /** * Get a new has pattern. * @param state Expected state value. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitHasPattern(state, ...patterns) { return new Core.HasStatePattern(state, ...patterns); } /** * Get a new set pattern. * @param state New state value. * @param patterns Expected patterns. * @returns Returns the pattern. */ emitSetPattern(state, ...patterns) { return new Core.SetStatePattern(state, ...patterns); } /** * Get a new reference pattern. * @param entry Referenced entry. * @returns Returns the pattern. */ emitReferencePattern(entry) { if (!entry.pattern) { return new Core.RunFlowPattern(() => entry.pattern); } return entry.pattern; } /** * Get a new any pattern. * @returns Returns the pattern. */ emitAnyPattern() { return new Core.AnyUnitPattern(); } /** * Get a new range pattern. * @param from From unit value. * @param to To unit value. * @returns Returns the pattern. */ emitRangePattern(from, to) { return new Core.RangeUnitPattern(from, to); } }
JavaScript
class TraditionalChineseLanguagePack extends DefaultLanguagePack { constructor(locale) { super(locale); } getTokenizer() { if (this._tokenizer) return this._tokenizer; // TODO: the Chinese tokenizer only recognizes simplified characters // for numbers and dates return this._tokenizer = new ChineseTokenizer(); } postprocessSynthetic(sentence, program) { keys.forEach((key) => { let re = new RegExp("\\b" + key[0] + "\\b", "g"); if (sentence.match(re)) sentence = sentence.replace(key[0], key[1]); }); return sentence; } detokenize(buffer, prevtoken, token) { // join without space return buffer + token; } pluralize(noun) { // TODO return undefined; } toVerbPast(phrase) { return phrase + '了'; } }
JavaScript
class GitCommander { constructor(path) { this.workingDirectory = path; } /** * Spawns a process to execute a git command in the GitCommander instances * working directory. * * @param {array|string} args - arguments to call `git` with on the command line * @param {function} callback - node callback for error and command output */ exec(args, callback) { if (!isArray(args) || !isFunction(callback)) { return; } const child = childProcess.spawn('git', args, {cwd: this.workingDirectory}); let stdout = ''; let stderr = ''; let processError; child.stdout.on('data', function (data) { stdout += data; }); child.stderr.on('data', function (data) { stderr += data; }); child.on('error', function (error) { processError = error; }); child.on('close', function (errorCode) { if (processError) { return callback(processError); } if (errorCode) { const error = new Error(stderr); error.code = errorCode; return callback(error); } return callback(null, stdout.trimRight()); }); } /** * Executes git blame on the input file in the instances working directory * * @param {string} fileName - name of file to blame, relative to the repos * working directory * @param {function} callback - callback funtion to call with results or error */ blame(fileName, callback) { const args = ['blame', '--line-porcelain']; // ignore white space based on config if (atom.config.get('git-blame.ignoreWhiteSpaceDiffs')) { args.push('-w'); } args.push(fileName); // Execute blame command and parse this.exec(args, function (err, blameStdOut) { if (err) { return callback(err, blameStdOut); } return callback(null, parseBlame(blameStdOut)); }); } /** * Executes git config --get * * @param {string} name - the name of the variable to look up eg: "group.varName" * @param {function} callback - callback funtion to call with results or error */ config(name, callback) { const args = ['config', '--get', name]; // Execute config command this.exec(args, function (err, configStdOut) { if (err) { // Error code 1 means, this variable is not present in the config if (err.code === 1) { return callback(null, ''); } return callback(err, configStdOut); } return callback(null, configStdOut); }); } }
JavaScript
class Platform { #platformName #platformUrl #clientId #authEndpoint #authConfig #ENCRYPTIONKEY #accesstokenEndpoint #kid #logger #Database /** * @param {string} name - Platform name. * @param {string} platformUrl - Platform url. * @param {string} clientId - Client Id generated by the platform. * @param {string} authenticationEndpoint - Authentication endpoint that the tool will use to authenticate within the platform. * @param {string} accesstokenEndpoint - Access token endpoint for the platform. * @param {string} kid - Key id for local keypair used to sign messages to this platform. * @param {string} _ENCRYPTIONKEY - Encryption key used * @param {Object} _authConfig - Authentication configurations for the platform. */ constructor (name, platformUrl, clientId, authenticationEndpoint, accesstokenEndpoint, kid, _ENCRYPTIONKEY, _authConfig, logger, Database) { this.#authConfig = _authConfig this.#ENCRYPTIONKEY = _ENCRYPTIONKEY this.#platformName = name this.#platformUrl = platformUrl this.#clientId = clientId this.#authEndpoint = authenticationEndpoint this.#accesstokenEndpoint = accesstokenEndpoint this.#kid = kid this.#logger = logger this.#Database = Database } /** * @description Sets/Gets the platform name. * @param {string} [name] - Platform name. */ async platformName (name) { if (!name) return this.#platformName try { await this.#Database.Modify(false, 'platform', { platformUrl: this.#platformUrl }, { platformName: name }) } catch (err) { provPlatformDebug(err.message) if (this.#logger) this.#logger.log({ level: 'error', message: 'Message: ' + err.message + '\nStack: ' + err.stack }) return false } this.#platformName = name return this } /** * @description Sets/Gets the platform url. * @param {string} [url] - Platform url. */ async platformUrl (url) { if (!url) return this.#platformUrl try { await this.#Database.Modify(false, 'platform', { platformUrl: this.#platformUrl }, { platformUrl: url }) } catch (err) { provPlatformDebug(err.message) if (this.#logger) this.#logger.log({ level: 'error', message: 'Message: ' + err.message + '\nStack: ' + err.stack }) return false } this.#platformUrl = url return this } /** * @description Sets/Gets the platform client id. * @param {string} [clientId] - Platform client id. */ async platformClientId (clientId) { if (!clientId) return this.#clientId try { await this.#Database.Modify(false, 'platform', { platformUrl: this.#platformUrl }, { clientId: clientId }) } catch (err) { provPlatformDebug(err.message) if (this.#logger) this.#logger.log({ level: 'error', message: 'Message: ' + err.message + '\nStack: ' + err.stack }) return false } this.#clientId = clientId return this } /** * @description Gets the platform key_id. */ platformKid () { return this.#kid } /** * @description Gets the RSA public key assigned to the platform. * */ async platformPublicKey () { try { const key = await this.#Database.Get(this.#ENCRYPTIONKEY, 'publickey', { kid: this.#kid }) return key[0].key } catch (err) { provPlatformDebug(err.message) if (this.#logger) this.#logger.log({ level: 'error', message: 'Message: ' + err.message + '\nStack: ' + err.stack }) return false } } /** * @description Gets the RSA private key assigned to the platform. * */ async platformPrivateKey () { try { const key = await this.#Database.Get(this.#ENCRYPTIONKEY, 'privatekey', { kid: this.#kid }) return key[0].key } catch (err) { provPlatformDebug(err.message) if (this.#logger) this.#logger.log({ level: 'error', message: 'Message: ' + err.message + '\nStack: ' + err.stack }) return false } } /** * @description Sets/Gets the platform authorization configurations used to validate it's messages. * @param {string} method - Method of authorization "RSA_KEY" or "JWK_KEY" or "JWK_SET". * @param {string} key - Either the RSA public key provided by the platform, or the JWK key, or the JWK keyset address. */ async platformAuthConfig (method, key) { if (!method && !key) return this.#authConfig if (method !== 'RSA_KEY' && method !== 'JWK_KEY' && method !== 'JWK_SET') throw new Error('Invalid message validation method. Valid methods are "RSA_KEY", "JWK_KEY", "JWK_SET"') if (!key) throw new Error('Missing secong argument key or keyset_url.') const authConfig = { method: method, key: key } try { await this.#Database.Modify(false, 'platform', { platformUrl: this.#platformUrl }, { authConfig: authConfig }) } catch (err) { provPlatformDebug(err.message) if (this.#logger) this.#logger.log({ level: 'error', message: 'Message: ' + err.message + '\nStack: ' + err.stack }) return false } this.#authConfig = authConfig return this } /** * @description Sets/Gets the platform authorization endpoint used to perform the OIDC login. * @param {string} [authEndpoint] - Platform authorization endpoint. */ async platformAuthEndpoint (authEndpoint) { if (!authEndpoint) return this.#authEndpoint try { await this.#Database.Modify(false, 'platform', { platformUrl: this.#platformUrl }, { authEndpoint: authEndpoint }) } catch (err) { provPlatformDebug(err.message) if (this.#logger) this.#logger.log({ level: 'error', message: 'Message: ' + err.message + '\nStack: ' + err.stack }) return false } this.#authEndpoint = authEndpoint return this } /** * @description Sets/Gets the platform access token endpoint used to authenticate messages to the platform. * @param {string} [accesstokenEndpoint] - Platform access token endpoint. */ async platformAccessTokenEndpoint (accesstokenEndpoint) { if (!accesstokenEndpoint) return this.#accesstokenEndpoint try { await this.#Database.Modify(false, 'platform', { platformUrl: this.#platformUrl }, { accesstokenEndpoint: accesstokenEndpoint }) } catch (err) { provPlatformDebug(err.message) if (this.#logger) this.#logger.log({ level: 'error', message: 'Message: ' + err.message + '\nStack: ' + err.stack }) return false } this.#accesstokenEndpoint = accesstokenEndpoint return this } /** * @description Gets the platform access token or attempts to generate a new one. * @param {String} scopes - String of scopes. */ async platformAccessToken (scopes) { const token = await this.#Database.Get(this.#ENCRYPTIONKEY, 'accesstoken', { platformUrl: this.#platformUrl, scopes: scopes }) if (!token || (Date.now() - token[0].createdAt) / 1000 > token[0].expires_in) { provPlatformDebug('Valid access_token for ' + this.#platformUrl + ' not found') provPlatformDebug('Attempting to generate new access_token for ' + this.#platformUrl) provPlatformDebug('With scopes: ' + scopes) const res = await Auth.getAccessToken(scopes, this, this.#ENCRYPTIONKEY, this.#Database) return res } else { provPlatformDebug('Access_token found') return token[0].token } } /** * @description Deletes a registered platform. */ async remove () { try { return Promise.all([this.#Database.Delete('platform', { platformUrl: this.#platformUrl }), this.#Database.Delete('publickey', { kid: this.#kid }), this.#Database.Delete('privatekey', { kid: this.#kid })]) } catch (err) { provPlatformDebug(err.message) if (this.#logger) this.#logger.log({ level: 'error', message: 'Message: ' + err.message + '\nStack: ' + err.stack }) return false } } }
JavaScript
class EditorHandlerCommand extends Command { constructor(id, handlerId, description) { super({ id: id, precondition: undefined, description: description }); this._handlerId = handlerId; } runCommand(accessor, args) { const editor = accessor.get(ICodeEditorService).getFocusedCodeEditor(); if (!editor) { return; } editor.trigger('keyboard', this._handlerId, args); } }
JavaScript
class DuelFlow extends BaseStepWithPipeline { constructor(game, duel, costHandler, resolutionHandler) { super(game); this.duel = duel; this.resolutionHandler = resolutionHandler; this.pipeline.initialise([ new SimpleStep(this.game, () => this.game.checkGameState(true)), new HonorBidPrompt(this.game, 'Choose your bid for the duel\n' + this.duel.getTotalsForDisplay()), new SimpleStep(this.game, costHandler), new SimpleStep(this.game, () => this.modifyDuelingSkill()), new SimpleStep(this.game, () => this.determineResults()), new SimpleStep(this.game, () => this.announceResult()), new SimpleStep(this.game, () => this.applyDuelResults()), new SimpleStep(this.game, () => this.cleanUpDuel()), new SimpleStep(this.game, () => this.game.checkGameState(true)) ]); } modifyDuelingSkill() { this.duel.modifyDuelingSkill(); } determineResults() { this.duel.determineResult(); } announceResult() { this.game.addMessage(this.duel.getTotalsForDisplay()); if(!this.duel.winner) { this.game.addMessage('The duel ends in a draw'); } } applyDuelResults() { if(this.duel.winner) { this.game.raiseEvent('onDuelResolution', { duel: this.duel }, () => this.resolutionHandler(this.duel.winner, this.duel.loser)); } } cleanUpDuel() { this.game.currentDuel = null; this.game.raiseEvent('onDuelFinished', { duel: this.duel }); } }
JavaScript
class Controller { /** * Constructor. * @param {!angular.Scope} $scope * @ngInject */ constructor($scope) { /** * @type {?angular.Scope} * @private */ this.scope_ = $scope; $scope.$on('$destroy', this.destroy_.bind(this)); } /** * Clean up listeners/references. * * @private */ destroy_() { this.scope_ = null; } /** * Called on clicking the button to display the onboarding for the element this directive is attached to. * * @export */ show() { OnboardingManager.getInstance().showContextOnboarding(this.scope_['context']); } }
JavaScript
class ArticleTemplate extends React.Component { render() { // console.log(this.props) const recipe = this.props.data.drupalRecipes console.log(recipe) const listItems = recipe.ingredients.map((ingredient) => <li>{ingredient}</li> ) return ( <div> <Link to="/" > ← Back </Link> <h4>{recipe.title}</h4> <div> <img src={recipe.image.url} /> </div> <div> {recipe.difficulty} </div> <div> <ul> {listItems} </ul> </div> </div> ) } }
JavaScript
class IndexPage extends React.Component { constructor(props) { super(props) this.state = { } } componentDidMount () { } componentWillUnmount () { } render() { return ( <View style={styles.container}> <View style={styles.inner_container}> <Header/> <Hero /> <Menu/> </View> </View>) } }
JavaScript
class RecastVectors { static min( a, b, i) { a[0] = Math.min(a[0], b[i + 0]); a[1] = Math.min(a[1], b[i + 1]); a[2] = Math.min(a[2], b[i + 2]); } static max( a, b, i) { a[0] = Math.max(a[0], b[i + 0]); a[1] = Math.max(a[1], b[i + 1]); a[2] = Math.max(a[2], b[i + 2]); } static copy3( out, _in, i) { RecastVectors.copy4(out, 0, _in, i); } static copy2( out, _in) { RecastVectors.copy4(out, 0, _in, 0); } static copy4( out, n, _in, m) { out[n] = _in[m]; out[n + 1] = _in[m + 1]; out[n + 2] = _in[m + 2]; } static add( e0, a, verts, i) { e0[0] = a[0] + verts[i]; e0[1] = a[1] + verts[i + 1]; e0[2] = a[2] + verts[i + 2]; } static subA( e0, verts, i, j) { e0[0] = verts[i] - verts[j]; e0[1] = verts[i + 1] - verts[j + 1]; e0[2] = verts[i + 2] - verts[j + 2]; } static subB( e0, i, verts, j) { e0[0] = i[0] - verts[j]; e0[1] = i[1] - verts[j + 1]; e0[2] = i[2] - verts[j + 2]; } static cross( dest, v1, v2) { dest[0] = v1[1] * v2[2] - v1[2] * v2[1]; dest[1] = v1[2] * v2[0] - v1[0] * v2[2]; dest[2] = v1[0] * v2[1] - v1[1] * v2[0]; } static normalize( v) { let d = (1.0 / Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])); v[0] *= d; v[1] *= d; v[2] *= d; } }
JavaScript
class TableOfContentsPlugin extends Plugin { /** * @inheritDoc */ static get pluginName() { return 'TableOfContents'; } /** * Validate if an item is a DOM node * * @param {String|Element} item The item to check for * @param {String} name The name of the item * @return {Element} Target element if a match is found */ static validateNode(item, name) { if (!item) { throw new Error(`Invalid option passed for ${name}. A valid ${name} selector or element must be provided`); } else { if (typeof item === 'string') { const element = document.querySelector(item); if (!element) { throw new Error(`Could not find a matching element as table of contents ${name} with selector ${item}`); } else { return element; } } else { return item; } } } /** * Validate the plugin options * @param {Object} Plugin options * @return {Object} Normalized and parsed options */ static validateOptions(options) { let parsed = {}; parsed.trigger = TableOfContentsPlugin.validateNode(options.trigger, 'trigger'); parsed.target = TableOfContentsPlugin.validateNode(options.target, 'target'); if (typeof options.query !== 'string') { throw new Error('The query to select items for the outline must be a valid DOM selector'); } parsed.query = options.query; const refreshDelay = Number(options.refreshDelay); if (isNaN(refreshDelay)) { throw new Error('Refresh delay must be a number (denotes number of seconds to wait before refresh)'); } parsed.refreshDelay = refreshDelay; return parsed; } init() { let options = this.editor.config.get( 'tableOfContents' ); // Validate the options options = TableOfContentsPlugin.validateOptions(options); this.query = options.query; // Setup initial outline DOM element this.setupOutlineElement(options.target); // Setup event listeners on trigger this.setupEventListeners(options.trigger); // Debounce this.rebuildOutline = debounce(this._rebuildOutline.bind(this), options.refreshDelay * 1000); this.handleOutlineElementClick = this.handleOutlineElementClick.bind(this); // Setup listener on editor and debounce changes this.editor.model.document.on( 'change:data', () => { this.rebuildOutline(); } ); } /** * Setup an outline element to respond and show outlines * @param {Element} element The element to use for showing table of contentents */ setupOutlineElement(element) { this.outlineView = element; this.outlineView.style.display = 'none'; this.outlineView.innerHTML = '<div class="toc-outline-header">Outline <i class="zmdi zmdi-close"/></div>'; this.handleCloseOutline(); } /** * Setup event listeners on the given element * * @param {Element} The element to toggle outline on */ setupEventListeners(element) { element.addEventListener('click', () => { // Toggle outline view const display = this.outlineView.style.display; if (display === 'none') { // Refresh view this._rebuildOutline(); } this.outlineView.style.display = display === 'block' ? 'none' : 'block'; }); } /** * Handle clicking on close button for outline content */ handleCloseOutline() { let zmdiClose = document.querySelector('.zmdi-close'); this.setupEventListeners(zmdiClose); } _rebuildOutline() { // Run over children and deregister event listeners if any for (let child of this.outlineView.querySelectorAll('h4')) { child.removeEventListener('click', this.handleOutlineElementClick); child.parentNode.removeChild(child); } let matches = Array.from(document.querySelectorAll(this.query)); this.matches = matches; matches.forEach((match, i) => { // Hide hidden nodes in hi-fi view if applicable if (match.offsetParent === null) { return; } let h4Node = document.createElement('h4'); h4Node.appendChild(document.createTextNode(match.textContent)); h4Node.setAttribute('data-index', i); h4Node.addEventListener('click', this.handleOutlineElementClick); this.outlineView.appendChild(h4Node); }); } handleOutlineElementClick(e) { const target = e.target; const index = target.getAttribute('data-index'); const match = this.matches[index]; if (match && match.scrollIntoView) { match.scrollIntoView({ behavior: 'smooth', block: 'start' }); } } }
JavaScript
class Featurizer { constructor() { if (this.constructor === Featurizer) { throw new AbstractClassError( "Featurizer is an abstract class." + " It should not be instantiated." ); } // methods this.transform = (parse) => { throw new NotImplementedError( "Featurizer subclasses must implement a transform method." ); } // attributes } }
JavaScript
class ParseCountsFeaturizer extends Featurizer { constructor() { super(); // helper functions /** * addParseCounts : Parse Object -> undefined * Add counts from `parse` into the `features`. * * @param {Parse} parse - the parse from which to add * features. * @param {Object} features - the feature map to add features * to. */ function addParseCounts(parse, features) { if (!features.hasOwnProperty(parse.tag)) { features[parse.tag] = 0; } features[parse.tag] += 1; parse.children.forEach( child => addParseCounts(child, features) ); } // methods /** * transform : Parse -> {String: Number} * Transform a parse into an object of features. * * @param {Parse} parse - the parse to featurize. */ this.transform = (parse) => { const features = {}; addParseCounts(parse, features); return features; } // attributes } }
JavaScript
class ParsePrecedenceFeaturizer extends Featurizer { constructor() { super(); // helper functions /** * addParsePrecedenceFeatures : Parse Object -> undefined * Add parse precedence features from `parse` to `features`. * * @param {Parse} parse - the parse from which to add the * features. * @param {Object} features - the feature map to add features * to. * @param {Set[String]} parseTags - the tags already * encountered closer to the root of the parse tree. */ function addParsePrecedenceFeatures( parse, features, parseTags ) { const parseTag = parse.tag; // add the parse tag precedence features for (let oldParseTag of parseTags) { const key = [oldParseTag, parseTag]; if (!features.hasOwnProperty(key)) { features[key] = 0; } features[key] += 1; } // add the current parse tags to the set of seen parse tags if (!parseTags.has(parseTag)) { parseTags.add(parseTag); } // clone parseTags when making the recursive call so that // siblings don't create precedence features for each other // by mutating a shared parseTags set. parse.children.forEach( child => addParsePrecedenceFeatures( child, features, new Set(parseTags) ) ); } // methods /** * transform : Parse -> {String: Number} * Transform a parse into an object of features. * * @param {Parse} parse - the parse to featurize. */ this.transform = (parse) => { const features = {}; addParsePrecedenceFeatures( parse, features, new Set() ); return features; } // attributes } }
JavaScript
class ParseDepthsFeaturizer extends Featurizer { constructor() { super(); function addParseDepths(parse, parseDepths, depth) { if (!parseDepths.hasOwnProperty(parse.tag)) { parseDepths[parse.tag] = []; } parseDepths[parse.tag].push(depth); parse.children.forEach( child => addParseDepths( child, parseDepths, depth + 1 ) ); } this.transform = (parse) => { // aggregation function const aggFunc = Math.min; const features = {}; const parseDepths = {}; addParseDepths(parse, parseDepths, 0); for (let feature in parseDepths) { features[feature] = aggFunc( ...parseDepths[feature] ); } return features; } } }
JavaScript
class ParseLengthsFeaturizer extends Featurizer { constructor() { super(); function addParseLengths(parse, parseLengths) { if (!parseLengths.hasOwnProperty(parse.tag)) { parseLengths[parse.tag] = []; } parseLengths[parse.tag].push(parse.span.length); parse.children.forEach( child => addParseLengths( child, parseLengths ) ); } this.transform = (parse) => { // aggregation function const aggFunc = Math.max const features = {}; const parseLengths = {}; addParseLengths(parse, parseLengths); for (let feature in parseLengths) { features[feature] = aggFunc( ...parseLengths[feature] ); } return features; } } }
JavaScript
class ConcatFeaturizer extends Featurizer { constructor(featurizers) { super(); // methods this.transform = (parse) => { const features = {}; for (let i = 0; i < this.featurizers.length; i++) { const newFeatures = this.featurizers[i] .transform(parse); for (let feature in newFeatures) { features[`${feature}_${i}`] = newFeatures[feature]; } } return features; } // attributes this.featurizers = featurizers; } }
JavaScript
class Operation extends Record(DEFAULTS) { /** * Create a new `Operation` with `attrs`. * * @param {Object|Array|List|String|Operation} attrs * @return {Operation} */ static create(attrs = {}) { if (Operation.isOperation(attrs)) { return attrs } if (isPlainObject(attrs)) { return Operation.fromJSON(attrs) } throw new Error( `\`Operation.create\` only accepts objects or operations, but you passed it: ${attrs}` ) } /** * Create a list of `Operations` from `elements`. * * @param {Array<Operation|Object>|List<Operation|Object>} elements * @return {List<Operation>} */ static createList(elements = []) { if (List.isList(elements) || Array.isArray(elements)) { const list = new List(elements.map(Operation.create)) return list } throw new Error( `\`Operation.createList\` only accepts arrays or lists, but you passed it: ${elements}` ) } /** * Create a `Operation` from a JSON `object`. * * @param {Object|Operation} object * @return {Operation} */ static fromJSON(object) { if (Operation.isOperation(object)) { return object } const { type } = object const ATTRIBUTES = OPERATION_ATTRIBUTES[type] const attrs = { type } if (!ATTRIBUTES) { throw new Error( `\`Operation.fromJSON\` was passed an unrecognized operation type: "${type}"` ) } for (const key of ATTRIBUTES) { let v = object[key] // Default `data` to an empty object. if (key === 'data' && v === undefined) { v = {} } if (v === undefined) { throw new Error( `\`Operation.fromJSON\` was passed a "${type}" operation without the required "${key}" attribute.` ) } if (key === 'path' || key === 'newPath') { v = PathUtils.create(v) } if (key === 'mark') { v = Mark.create(v) } if (key === 'marks' && v != null) { v = Mark.createSet(v) } if (key === 'node') { v = Node.create(v) } if (key === 'properties' && type === 'merge_node') { v = Node.createProperties(v) } if ( (key === 'properties' || key === 'newProperties') && type === 'set_mark' ) { v = Mark.createProperties(v) } if ( (key === 'properties' || key === 'newProperties') && type === 'set_node' ) { v = Node.createProperties(v) } if ( (key === 'properties' || key === 'newProperties') && type === 'set_selection' ) { v = Selection.createProperties(v) } if ( (key === 'properties' || key === 'newProperties') && type === 'set_value' ) { v = Value.createProperties(v) } if (key === 'properties' && type === 'split_node') { v = Node.createProperties(v) } if (key === 'data') { v = Map(v) } attrs[key] = v } const node = new Operation(attrs) return node } /** * Check if `any` is a list of operations. * * @param {Any} any * @return {Boolean} */ static isOperationList(any) { return List.isList(any) && any.every(item => Operation.isOperation(item)) } /** * Apply the operation to a `value`. * * @param {Value} value * @return {Value} */ apply(value) { const next = apply(value, this) return next } /** * Invert the operation. * * @return {Operation} */ invert() { const inverted = invert(this) return inverted } /** * Return a JSON representation of the operation. * * @param {Object} options * @return {Object} */ toJSON(options = {}) { const { object, type } = this const json = { object, type } const ATTRIBUTES = OPERATION_ATTRIBUTES[type] for (const key of ATTRIBUTES) { let value = this[key] if ( key === 'mark' || key === 'marks' || key === 'node' || key === 'path' || key === 'newPath' ) { value = value.toJSON() } if (key === 'properties' && type === 'merge_node') { const v = {} if ('data' in value) v.data = value.data.toJS() if ('type' in value) v.type = value.type value = v } if ( (key === 'properties' || key === 'newProperties') && type === 'set_mark' ) { const v = {} if ('data' in value) v.data = value.data.toJS() if ('type' in value) v.type = value.type value = v } if ( (key === 'properties' || key === 'newProperties') && type === 'set_node' ) { const v = {} if ('data' in value) v.data = value.data.toJS() if ('type' in value) v.type = value.type value = v } if ( (key === 'properties' || key === 'newProperties') && type === 'set_selection' ) { const v = {} if ('anchor' in value) v.anchor = value.anchor.toJSON() if ('focus' in value) v.focus = value.focus.toJSON() if ('isFocused' in value) v.isFocused = value.isFocused if ('marks' in value) v.marks = value.marks && value.marks.toJSON() value = v } if ( (key === 'properties' || key === 'newProperties') && type === 'set_value' ) { const v = {} if ('data' in value) v.data = value.data.toJS() if ('decorations' in value) v.decorations = value.decorations.toJS() value = v } if (key === 'properties' && type === 'split_node') { const v = {} if ('data' in value) v.data = value.data.toJS() if ('type' in value) v.type = value.type value = v } if (key === 'data') { value = value.toJSON() } json[key] = value } return json } }
JavaScript
class AffiliateService { constructor (xmlApi) { this._api = xmlApi } /** * Retrieve Clawbacks * * Retrieves all clawed back commissions for a particular affiliate. * Claw backs typically occur when an order has been refunded to the customer. * * @typedef getClawbacksParams * @property {number} affiliateId The Id number for the affiliate record you would like the claw backs for * @property {Date} filterStartDate The starting date for the date range which you would like affiliate claw backs for * @property {Date} filterEndDate The ending date for the date range which you would like the affiliate claw backs for */ async getClawbacks ( /** @type getClawbacksParams */ { affiliateId, filterStartDate, filterEndDate } ) { return this._api.request('APIAffiliateService.affClawbacks', [ Types.Integer(affiliateId, true), Types.DateTime(filterStartDate, true), Types.DateTime(filterEndDate, true) ]) } /** * Retrieve Commissions * * Retrieves all commissions for a specific affiliate within a date range. * * @typedef getCommissionsParams * @property {number} affiliateId The Id number for the affiliate record you would like the commissions for * @property {Date} filterStartDate The starting date for the date range which you would like affiliate commissions for * @property {Date} filterEndDate The ending date for the date range which you would like the affiliate commissions for */ async getCommissions ( /** @type getCommissionsParams */ { affiliateId, filterStartDate, filterEndDate } ) { return this._api.request('APIAffiliateService.affCommissions', [ Types.Integer(affiliateId, true), Types.DateTime(filterStartDate, true), Types.DateTime(filterEndDate, true) ]) } /** * Retrieve Payments * * Retrieves all payments for a specific affiliate within a date range * * @typedef getPayoutsParams * @property {number} affiliateId The Id number for the affiliate record you would like the claw backs for * @property {Date} filterStartDate The starting date for the date range which you would like affiliate payments for * @property {Date} filterEndDate The ending date for the date range which you would like the affiliate payments for */ async getPayouts ( /** @type getPayoutsParams */ { affiliateId, filterStartDate, filterEndDate } ) { return this._api.request('APIAffiliateService.affPayouts', [ Types.Integer(affiliateId, true), Types.DateTime(filterStartDate, true), Types.DateTime(filterEndDate, true) ]) } /** * Retrieve Redirect Links * * Retrieves a list of the redirect links for the specified Affiliate. * * @param {number} affiliateId The Id number for the affiliate record you would like the redirect links for */ async getRedirectLinksForAffiliate (affiliateId) { return this._api.request('AffiliateService.getRedirectLinksForAffiliate', [ Types.Integer(affiliateId, true) ]) } /** * Retrieve a Summary of Affiliate Statistics * * Retrieves a summary of statistics for a list of affiliates. * * @typedef getSummaryParams * @property {number[]} affiliateId An integer array of Affiliate ID numbers you would like stats for * @property {Date} filterStartDate The starting date for the date range which you would like affiliate stats for * @property {Date} filterEndDate The ending date for the date range which you would like the affiliate stats for */ async getSummary ( /** @type getSummaryParams */ { affiliateIds, filterStartDate, filterEndDate } ) { return this._api.request('APIAffiliateService.affSummary', [ Types.Array(Types.Integer, affiliateIds, true), Types.DateTime(filterStartDate, true), Types.DateTime(filterEndDate, true) ]) } /** * Retrieve Running Totals * * Retrieves the current balances for Amount Earned, Clawbacks, and Running Balance. * * @param {number[]} affiliateIds An integer array of the Affiliate ID numbers that you would like balances for */ async getRunningTotals (affiliateIds) { return this._api.request('APIAffiliateService.affRunningTotals', [ Types.Array(Types.Integer, affiliateIds, true) ]) } }
JavaScript
class VerbBase extends GrBase { constructor(nodes, fromNode, linkType, toNode, matchResult) { super(nodes, fromNode, linkType, toNode, matchResult); this.name = 'VerbBase'; } static getMatchToken() { //return ['define:VB.*', 'is:VB.*', 'defined:VB.*']; //return ['.*:VB.*']; //return [{name:'verb-1', toPOS:'VB.*', edge:'((?!cop).)*'} ]; return [{name:'verb-1', toPOS:'VB.*', edge:'((?!cop).)*'}, {name:'verb-2', toPOS:'VB.*', edge:'cop', applyToParent:true}]; //return [{name:'verb-1', toPOS:'VB.*']; } /* getValues() {; return this.match.verb;//this.nodes.getTokens().getToken(this.verb); }*/ dict() { let r = this.processNode(); return r; return this.match.vb; } text() { return this.name + ':: ' + JSON.stringify(this.match); } getVerb() { return this.match.verb;//this.nodes.getNodeMap(this.verb).getValues(); } getValues(tagged=false) { let res = []; if (this.linkType === 'cop'){ let children = this.fromNode.getChildren(); for(let child in children) { let c = this.fromNode.getChild(child); if (this.toNode.getTokenId() !== c.node.getTokenId()) { res.push(c.node.getValues(tagged)); } } res.push(this.fromNode.getToken()); //console.log(' \t\t getValues::Verb called for id ' + this.toNode.getTokenId() + ' reeturning :' + res.join(' ')); res = res.join(' '); if (tagged) { res = 'obj::<' + res + '>'; res = this.getName() + '::' + this.toNode.getValues(tagged) + ' ' + res; } else { res = this.toNode.getValues(tagged) + ' ' + res; } return res; } else { return super.getValues(tagged); } } processNode() { let node = this.toNode; let nodeList = this.nodes; let copNode = 'cop'; if (this.linkType === copNode) { node = this.fromNode; } // check all the child nodes let children = node.getChildren(); //let dbg = nodeList.dbg; for (let child in children) { let ch = children[child]; } let ret = {}; // process the verb node if (this.linkType === copNode) { // ret.verb = {tokenId:this.toNode.getTokenId(), obj : {tokenId: this.fromNode.getTokenId()}}; //ret.verb = {tokenId: this.fromNode.getTokenId(), cop : {tokenId:this.toNode.getTokenId()}}; ret['verb:' + this.linkType] = {tokenId: this.fromNode.getTokenId(), cop : {tokenId:this.toNode.getTokenId()}}; } else { //ret.verb = {tokenId:this.toNode.getTokenId()}; ret['verb:' + this.linkType] = {tokenId:this.toNode.getTokenId()}; } ret = super.processNode(ret); if (false) console.log(' ---[' + this.linkType + ']-->> ' + JSON.stringify(ret)); return ret; } static checkValid(nodeList, fromNode, linkType, toNode) { let dbg = nodeList.dbg; return [true, {}]; } }
JavaScript
class VolumeDrawable { constructor(volume, options) { this.PT = !!options.renderMode; // THE VOLUME DATA this.volume = volume; this.onChannelDataReadyCallback = null; this.translation = new THREE.Vector3(0,0,0); this.rotation = new THREE.Euler(); this.maskChannelIndex = -1; this.maskAlpha = 1.0; this.gammaMin = 0.0; this.gammaLevel = 1.0; this.gammaMax = 1.0; this.channel_colors = this.volume.channel_colors_default.slice(); this.channelOptions = new Array(this.volume.num_channels).fill({}); this.fusion = this.channel_colors.map((col, index) => { let rgbColor; // take copy of original channel color if (col[0] === 0 && col[1] === 0 && col[2] === 0) { rgbColor = 0; } else { rgbColor = [col[0], col[1], col[2]]; } return { chIndex: index, lut:[], rgbColor: rgbColor }; }); this.specular = new Array(this.volume.num_channels).fill([0,0,0]); this.emissive = new Array(this.volume.num_channels).fill([0,0,0]); this.roughness = new Array(this.volume.num_channels).fill(0); this.sceneRoot = new THREE.Object3D();//create an empty container this.meshVolume = new MeshVolume(this.volume); if (this.PT) { this.volumeRendering = new PathTracedVolume(this.volume); this.pathTracedVolume = this.volumeRendering; } else { this.volumeRendering = new RayMarchedAtlasVolume(this.volume); this.rayMarchedAtlasVolume = this.volumeRendering; } // draw meshes first, and volume last, for blending and depth test reasons with raymarch !this.PT && this.sceneRoot.add(this.meshVolume.get3dObject()); this.sceneRoot.add(this.volumeRendering.get3dObject()); // draw meshes last (as overlay) for pathtrace? (or not at all?) //this.PT && this.sceneRoot.add(this.meshVolume.get3dObject()); this.bounds = { bmin: new THREE.Vector3(-0.5, -0.5, -0.5), bmax: new THREE.Vector3(0.5, 0.5, 0.5) }; this.sceneRoot.position.set(0, 0, 0); this.setScale(this.volume.scale); // apply the volume's default transformation this.setTranslation(new THREE.Vector3().fromArray(this.volume.getTranslation())); this.setRotation(new THREE.Euler().fromArray(this.volume.getRotation())); this.setOptions(options); } setOptions(options) { options = options || {}; if (options.hasOwnProperty("maskChannelIndex")) { this.setChannelAsMask(options.maskChannelIndex); } if (options.hasOwnProperty("maskAlpha")) { this.setMaskAlpha(options.maskAlpha); } if (options.hasOwnProperty("clipBounds")) { this.bounds = { bmin: new THREE.Vector3(options.clipBounds[0], options.clipBounds[2], options.clipBounds[4]), bmax: new THREE.Vector3(options.clipBounds[1], options.clipBounds[3], options.clipBounds[5]) }; // note: dropping isOrthoAxis argument this.setAxisClip('x', options.clipBounds[0], options.clipBounds[1]); this.setAxisClip('y', options.clipBounds[2], options.clipBounds[3]); this.setAxisClip('z', options.clipBounds[4], options.clipBounds[5]); } if (options.hasOwnProperty("scale")) { this.setScale(options.scale.slice()); } if (options.hasOwnProperty("translation")) { this.setTranslation(new THREE.Vector3().fromArray(options.translation)); } if (options.hasOwnProperty("rotation")) { this.setRotation(new THREE.Euler().fromArray(options.rotation)); } if (options.hasOwnProperty("renderMode")) { this.setVolumeRendering(!!options.renderMode); } if (options.hasOwnProperty("channels")) { // store channel options here! this.channelOptions = options.channels; this.channelOptions.forEach((channelOptions, channelIndex) => { this.setChannelOptions(channelIndex, channelOptions); }); } } setChannelOptions(channelIndex, options) { // merge to current channel options this.channelOptions[channelIndex] = Object.assign(this.channelOptions[channelIndex], options); if (options.hasOwnProperty("enabled")) { this.setVolumeChannelEnabled(channelIndex, options.enabled); } if (options.hasOwnProperty("color")) { this.updateChannelColor(channelIndex, options.color); } if (options.hasOwnProperty("isosurfaceEnabled")) { const hasIso = this.hasIsosurface(channelIndex); if (hasIso !== options.isosurfaceEnabled) { if (hasIso && !options.isosurfaceEnabled) { this.destroyIsosurface(channelIndex); } else if (!hasIso && options.isosurfaceEnabled) { // 127 is half of the intensity range 0..255 let isovalue = 127; if (options.hasOwnProperty("isovalue")) { isovalue = options.isovalue; } // 1.0 is fully opaque let isosurfaceOpacity = 1.0; if (options.hasOwnProperty("isosurfaceOpacity")) { isosurfaceOpacity = options.isosurfaceOpacity; } this.createIsosurface(channelIndex, isovalue, isosurfaceOpacity); } } else if (options.isosurfaceEnabled) { if (options.hasOwnProperty("isovalue")) { this.updateIsovalue(channelIndex, options.isovalue); } if (options.hasOwnProperty("isosurfaceOpacity")) { this.updateOpacity(channelIndex, options.isosurfaceOpacity); } } } else { if (options.hasOwnProperty("isovalue")) { this.updateIsovalue(channelIndex, options.isovalue); } if (options.hasOwnProperty("isosurfaceOpacity")) { this.updateOpacity(channelIndex, options.isosurfaceOpacity); } } } setScale(scale) { this.scale = scale; this.currentScale = scale.clone(); this.meshVolume.setScale(scale); this.volumeRendering.setScale(scale); } setOrthoScale(value) { this.volumeRendering.setOrthoScale(value); } setResolution(viewObj) { const x = viewObj.getWidth(); const y = viewObj.getHeight(); this.volumeRendering.setResolution(x, y); this.meshVolume.setResolution(x, y); } // Set clipping range (between 0 and 1) for a given axis. // Calling this allows the rendering to compensate for changes in thickness in orthographic views that affect how bright the volume is. // @param {number} axis 0, 1, or 2 for x, y, or z axis // @param {number} minval 0..1, should be less than maxval // @param {number} maxval 0..1, should be greater than minval // @param {boolean} isOrthoAxis is this an orthographic projection or just a clipping of the range for perspective view setAxisClip(axis, minval, maxval, isOrthoAxis) { this.bounds.bmax[axis] = maxval; this.bounds.bmin[axis] = minval; !this.PT && this.meshVolume.setAxisClip(axis, minval, maxval, isOrthoAxis); this.volumeRendering.setAxisClip(axis, minval, maxval, isOrthoAxis); } // Tell this image that it needs to be drawn in an orthographic mode // @param {boolean} isOrtho is this an orthographic projection or a perspective view setIsOrtho(isOrtho) { this.volumeRendering.setIsOrtho(isOrtho); } setOrthoThickness(value) { !this.PT && this.meshVolume.setOrthoThickness(value); this.volumeRendering.setOrthoThickness(value); } // Set parameters for gamma curve for volume rendering. // @param {number} gmin 0..1 // @param {number} glevel 0..1 // @param {number} gmax 0..1, should be > gmin setGamma(gmin, glevel, gmax) { this.gammaMin = gmin; this.gammaLevel = glevel; this.gammaMax = gmax; this.volumeRendering.setGamma(gmin, glevel, gmax) } setMaxProjectMode(isMaxProject) { !this.PT && this.rayMarchedAtlasVolume.setMaxProjectMode(isMaxProject); } onAnimate(canvas) { // TODO: this is inefficient, as this work is duplicated by threejs. // we need camera matrix up to date before giving the 3d objects a chance to use it. canvas.camera.updateMatrixWorld(true); canvas.camera.matrixWorldInverse.getInverse( canvas.camera.matrixWorld ); const isVR = canvas.isVR(); if (isVR) { // raise volume drawable to about 1 meter. this.sceneRoot.position.y = 1.0; } else { this.sceneRoot.position.y = 0.0; } // TODO confirm sequence this.volumeRendering.doRender(canvas); !this.PT && this.meshVolume.doRender(canvas); } // If an isosurface exists, update its isovalue and regenerate the surface. Otherwise do nothing. updateIsovalue(channel, value) { this.meshVolume.updateIsovalue(channel, value); } getIsovalue(channel) { return this.meshVolume.getIsovalue(channel); } // Set opacity for isosurface updateOpacity(channel, value) { this.meshVolume.updateOpacity(channel, value); } hasIsosurface(channel) { return this.meshVolume.hasIsosurface(channel); } // If an isosurface is not already created, then create one. Otherwise do nothing. createIsosurface(channel, value, alpha, transp) { this.meshVolume.createIsosurface(channel, this.channel_colors[channel], value, alpha, transp); } // If an isosurface exists for this channel, destroy it now. Don't just hide it - assume we can free up some resources. destroyIsosurface(channel) { this.meshVolume.destroyIsosurface(channel); } fuse() { if (!this.volume) { return; } if (this.PT) { this.pathTracedVolume.updateActiveChannels(this); } else { this.rayMarchedAtlasVolume.fuse(this.fusion, this.volume.channels); } } updateMaterial() { this.PT && this.pathTracedVolume.updateMaterial(this); !this.PT && this.rayMarchedAtlasVolume.fuse(this.fusion, this.volume.channels); } updateLuts() { this.PT && this.pathTracedVolume.updateLuts(this); !this.PT && this.rayMarchedAtlasVolume.fuse(this.fusion, this.volume.channels); } setVoxelSize(values) { this.volume.setVoxelSize(values); this.setScale(this.volume.scale); } cleanup() { this.meshVolume.cleanup(); this.volumeRendering.cleanup(); } getChannel(channelIndex) { return this.volume.getChannel(channelIndex); } onChannelLoaded(batch) { this.volumeRendering.onChannelData(batch); this.meshVolume.onChannelData(batch); for (let j = 0; j < batch.length; ++j) { const idx = batch[j]; this.setChannelOptions(idx, this.channelOptions[idx]); } // let the outside world have a chance if (this.onChannelDataReadyCallback) { this.onChannelDataReadyCallback(); } } onChannelAdded(newChannelIndex) { this.channel_colors[newChannelIndex] = this.volume.channel_colors_default[newChannelIndex]; this.fusion[newChannelIndex] = { chIndex: newChannelIndex, lut:[], rgbColor: [this.channel_colors[newChannelIndex][0], this.channel_colors[newChannelIndex][1], this.channel_colors[newChannelIndex][2]] }; this.specular[newChannelIndex] = [0,0,0]; this.emissive[newChannelIndex] = [0,0,0]; this.roughness[newChannelIndex] = 0; } // Save a channel's isosurface as a triangle mesh to either STL or GLTF2 format. File will be named automatically, using image name and channel name. // @param {string} type Either 'GLTF' or 'STL' saveChannelIsosurface(channelIndex, type) { this.meshVolume.saveChannelIsosurface(channelIndex, type, this.name); } // Hide or display volume data for a channel setVolumeChannelEnabled(channelIndex, enabled) { // flip the color to the "null" value this.fusion[channelIndex].rgbColor = enabled ? this.channel_colors[channelIndex] : 0; // if all are nulled out, then hide the volume element from the scene. if (this.fusion.every((elem)=>(elem.rgbColor === 0))) { this.volumeRendering.setVisible(false); } else { this.volumeRendering.setVisible(true); } } isVolumeChannelEnabled(channelIndex) { // the zero value for the fusion rgbColor is the indicator that a channel is hidden. return this.fusion[channelIndex].rgbColor !== 0; } // Set the color for a channel // @param {Array.<number>} colorrgb [r,g,b] updateChannelColor(channelIndex, colorrgb) { if (!this.channel_colors[channelIndex]) { return; } this.channel_colors[channelIndex] = colorrgb; // if volume channel is zero'ed out, then don't update it until it is switched on again. if (this.fusion[channelIndex].rgbColor !== 0) { this.fusion[channelIndex].rgbColor = colorrgb; } this.meshVolume.updateMeshColors(this.channel_colors); } // TODO remove this from public interface? updateMeshColors() { this.meshVolume.updateMeshColors(this.channel_colors); } // Get the color for a channel // @return {Array.<number>} The color as array of [r,g,b] getChannelColor(channelIndex) { return this.channel_colors[channelIndex]; } // Set the material for a channel // @param {number} channelIndex // @param {Array.<number>} colorrgb [r,g,b] // @param {Array.<number>} specularrgb [r,g,b] // @param {Array.<number>} emissivergb [r,g,b] // @param {number} roughness updateChannelMaterial(channelIndex, colorrgb, specularrgb, emissivergb, roughness) { if (!this.channel_colors[channelIndex]) { return; } this.updateChannelColor(channelIndex, colorrgb); this.specular[channelIndex] = specularrgb; this.emissive[channelIndex] = emissivergb; this.roughness[channelIndex] = roughness; } setDensity(density) { this.density = density; this.volumeRendering.setDensity(density); } /** * Get the global density of the volume data */ getDensity() { return this.density; } setBrightness(brightness) { this.brightness = brightness; this.volumeRendering.setBrightness(brightness); } getBrightness() { return this.brightness; } setChannelAsMask(channelIndex) { if (!this.volume.channels[channelIndex] || !this.volume.channels[channelIndex].loaded) { return false; } this.maskChannelIndex = channelIndex; return this.volumeRendering.setChannelAsMask(channelIndex); } setMaskAlpha(maskAlpha) { this.maskAlpha = maskAlpha; this.volumeRendering.setMaskAlpha(maskAlpha); } getIntensity(c, x, y, z) { return this.volume.getIntensity(c, x, y, z); } onStartControls() { this.PT && this.pathTracedVolume.onStartControls(); } onChangeControls() { this.PT && this.pathTracedVolume.onChangeControls(); } onEndControls() { this.PT && this.pathTracedVolume.onEndControls(); } onResetCamera() { this.volumeRendering.viewpointMoved(); } onCameraChanged(fov, focalDistance, apertureSize) { this.PT && this.pathTracedVolume.updateCamera(fov, focalDistance, apertureSize); } updateClipRegion(xmin, xmax, ymin, ymax, zmin, zmax) { this.volumeRendering.updateClipRegion(xmin, xmax, ymin, ymax, zmin, zmax); } updateLights(state) { this.PT && this.pathTracedVolume.updateLights(state); } setPixelSamplingRate(value) { this.volumeRendering.setPixelSamplingRate(value); } setVolumeRendering(is_pathtrace) { if (is_pathtrace === this.PT) { return; } // remove old 3d object from scene is_pathtrace && this.sceneRoot.remove(this.meshVolume.get3dObject()); this.sceneRoot.remove(this.volumeRendering.get3dObject()); // destroy old resources. this.volumeRendering.cleanup(); // create new if (is_pathtrace) { this.volumeRendering = new PathTracedVolume(this.volume); this.pathTracedVolume = this.volumeRendering; this.rayMarchedAtlasVolume = null; } else { this.volumeRendering = new RayMarchedAtlasVolume(this.volume); this.pathTracedVolume = null; this.rayMarchedAtlasVolume = this.volumeRendering; for (var i = 0; i < this.volume.num_channels; ++i) { if (this.volume.getChannel(i).loaded) { this.rayMarchedAtlasVolume.onChannelData([i]); } } } // ensure transforms on new volume representation are up to date this.volumeRendering.setTranslation(this.translation); this.volumeRendering.setRotation(this.rotation); this.PT = is_pathtrace; this.setChannelAsMask(this.maskChannelIndex); this.setMaskAlpha(this.maskAlpha); this.setScale(this.volume.scale); this.setBrightness(this.getBrightness()); this.setDensity(this.getDensity()); this.setGamma(this.gammaMin, this.gammaLevel, this.gammaMax); // reset clip bounds this.setAxisClip('x', this.bounds.bmin.x, this.bounds.bmax.x); this.setAxisClip('y', this.bounds.bmin.y, this.bounds.bmax.y); this.setAxisClip('z', this.bounds.bmin.z, this.bounds.bmax.z); // add new 3d object to scene !this.PT && this.sceneRoot.add(this.meshVolume.get3dObject()); this.sceneRoot.add(this.volumeRendering.get3dObject()); this.fuse(); } setTranslation(xyz) { this.translation.copy(xyz); this.volumeRendering.setTranslation(this.translation); this.meshVolume.setTranslation(this.translation); } setRotation(eulerXYZ) { this.rotation.copy(eulerXYZ); this.volumeRendering.setRotation(this.rotation); this.meshVolume.setRotation(this.rotation); } }
JavaScript
class MathUtil { /** * Custom modulo function always returning positive values. * @see http://stackoverflow.com/questions/1082917 * @param {number} x * @param {number} m * @return {number} */ static mod (x, m) { m = m < 0 ? -m : m let r = x % m return (r < 0 ? r + m : r) } /** * Integer division (a \ b). * @param {number} a * @param {number} b * @return {number} */ static div (a, b) { return Math.floor(a / b) } /** * Returns wether two integers are coprime. * @param {number} a * @param {number} b * @return {boolean} */ static isCoprime (a, b) { return MathUtil.gcd(a, b) === 1 } /** * Applies the Euclidean algorithm for computing the greatest * common divisor of two integers. * @param {number} a * @param {number} b * @return {number} */ static gcd (a, b) { while (b !== 0) { let h = a % b a = b b = h } return a } /** * Applies the extended Euclidean algorithm, which computes, besides the * greatest common divisor of integers a and b, the coefficients of Bézout's * identity, which are integers x and y such that ax + by = gcd(a, b). * @param {number} a * @param {number} b * @return {number[]} Returns [x, y, d] such that ax + by = gcd(a, b). */ static xgcd (a, b) { if (b === 0) { return [1, 0, a] } else { let [x, y, d] = MathUtil.xgcd(b, a % b) return [y, x - y * MathUtil.div(a, b), d] } } }
JavaScript
class Home extends Component { constructor(props) { super(props); this.state = { ...this.props, }; } componentWillReceiveProps(nextProps) { this.setState(prevState => ({ ...prevState, ...nextProps, })); } render() { let { hero, features = {} } = this.state; return ( <Template> <main role='main'> <Hero {...hero} /> <Features {...features} /> </main> </Template> ); } }
JavaScript
class AccessDeniedException extends RuntimeException { /** * Constructor. * * @param {string} [message = "Access denied."] * @param {Error} [previous] */ __construct(message = 'Access denied.', previous = undefined) { super.__construct(message, 403, previous); this.attributes = []; this.subject = undefined; } }
JavaScript
class VolumeEnvelope { constructor() { // input this.startFlag = false; // output this.dividerCount = 0; this.volume = 0; } /** Decrements `volume` every `period` clocks. If `loop`, it resets the countdown to 15. */ clock(period, loop) { if (!this.startFlag) { if (this.dividerCount === 0) { this.dividerCount = period; if (this.volume === 0) { if (loop) this.volume = constants.APU_MAX_VOLUME; } else { this.volume--; } } else { this.dividerCount--; } } else { this.startFlag = false; this.volume = constants.APU_MAX_VOLUME; this.dividerCount = period; } } /** Returns a snapshot of the current state. */ getSaveState() { return { startFlag: this.startFlag, dividerCount: this.dividerCount, volume: this.volume }; } /** Restores state from a snapshot. */ setSaveState(saveState) { this.startFlag = saveState.startFlag; this.dividerCount = saveState.dividerCount; this.volume = saveState.volume; } }
JavaScript
class Entity { /** * Constructor to initialize a new entity * @param {Number} id the entity id * @param {String} kind the type of entity this is */ constructor(id, kind) { this.id = id; this.kind = kind; this.x = 0; this.y = 0; this.gridX = 0; this.gridY = 0; this.name = ''; this.sprite = null; this.spriteFlipX = false; this.spriteFlipY = false; this.animations = null; this.currentAnimation = null; this.shadowOffsetY = 0; this.hidden = false; this.spriteLoaded = false; this.visible = true; this.fading = false; this.handler = new EntityHandler(this); this.angled = false; this.angle = 0; this.critical = false; this.stunned = false; this.terror = false; this.nonPathable = false; this.hasCounter = false; this.countdownTime = 0; this.counter = 0; this.shadow = false; this.path = false; this.renderingData = { scale: -1, angle: 0, }; this.loadDirty(); } /** * Checks to see if the x,y coordinate is adjacent to the * entity's current position * * @param {Number} x coordinate * @param {Number} y coordinate * @param {Boolean} ignoreDiagonals if true, will ignore diagonal * directions, defaults to false (optional) * @return {Boolean} */ isPositionAdjacent(x, y, ignoreDiagonals = false) { // north west - diagonal if (!ignoreDiagonals && x - 1 === this.gridX && y + 1 === this.gridY) { return true; } // north if (x === this.gridX && y + 1 === this.gridY) { return true; } // north east - diagonal if (!ignoreDiagonals && x + 1 === this.gridX && y + 1 === this.gridY) { return true; } // west if (x - 1 === this.gridX && y === this.gridY) { return true; } // east if (x + 1 === this.gridX && y === this.gridY) { return true; } // south west - diagonal if (!ignoreDiagonals && x - 1 === this.gridX && y - 1 === this.gridY) { return true; } // south if (x === this.gridX && y - 1 === this.gridY) { return true; } // south west - diagonal if (!ignoreDiagonals && x - 1 === this.gridX && y - 1 === this.gridY) { return true; } return false; } /** * This is important for when the client is * on a mobile screen. So the sprite has to be * handled differently. */ loadDirty() { this.dirty = true; if (this.dirtyCallback) { this.dirtyCallback(); } } /** * Tell this to fade in given the duration * @param {Number} time the amount of time to fade in */ fadeIn(time) { this.fading = true; this.fadingTime = time; } /** * Tell this entity to start blinking * @param {Number} speed the interval time between blinks */ blink(speed) { this.blinking = setInterval(() => { this.toggleVisibility(); }, speed); } /** * Tell the entity to stop blinking and force it to be visible */ stopBlinking() { if (this.blinking) { clearInterval(this.blinking); } this.setVisible(true); } /** * Set the entity's name * @param {String} name the name of this entity */ setName(name) { this.name = name; } /** * Set the sprite for this entity * @param {Sprite} sprite the sprite for this entity */ setSprite(sprite) { if (!sprite || (this.sprite && this.sprite.name === sprite.name)) { return; } if (!sprite.loaded) { sprite.load(); } sprite.name = sprite.id; // eslint-disable-line this.sprite = sprite; this.normalSprite = this.sprite; this.hurtSprite = sprite.getHurtSprite(); this.animations = sprite.createAnimations(); this.spriteLoaded = true; if (this.readyCallback) { this.readyCallback(); } } /** * Set the x,y position for the entity * @param {Number} x the x position on the screen * @param {[type]} y the y position on the screen */ setPosition(x, y) { this.x = x; this.y = y; } /** * Set the x,y position of the entity on the tile grid * @param {Number} x the gridX * @param {Number} y the gridY */ setGridPosition(x, y) { this.gridX = x; this.gridY = y; this.setPosition(x * 16, y * 16); } /** * Set the animation on this entity * @param {String} name the name of the animation * @param {Number} speed the animation speed * @param {Number} count how many times to play the animation * @param {Number} onEndCount callback to trigger when the animation * ends after count number of times */ setAnimation(name, speed, count, onEndCount) { if ( !this.spriteLoaded || (this.currentAnimation && this.currentAnimation.name === name) ) { return; } const anim = this.getAnimationByName(name); if (!anim) { return; } this.currentAnimation = anim; if (name.substr(0, 3) === 'atk') { this.currentAnimation.reset(); } this.currentAnimation.setSpeed(speed); this.currentAnimation.setCount( count || 0, onEndCount || (() => { this.idle(); }), ); } /** * Set the count for the count down time * @param {Number} count sets the counter */ setCountdown(count) { this.counter = count; this.countdownTime = new Date().getTime(); this.hasCounter = true; } /** * Returns the instance of the weapon this entity has * @return {Item|Projectile} a weapon or projectile */ hasWeapon() { return this.weapon; } /** * Get the distance from this entity to another entity * @param {Entity} entity the entity you want to get the distance to * @return {Number} the furtherst x or y distance from the given entity */ getDistance(entity) { const x = Math.abs(this.gridX - entity.gridX); const y = Math.abs(this.gridY - entity.gridY); return x > y ? x : y; } /** * Get the distance from this entity to the given x,y coordinates * @param {Number} toX the x coordinate * @param {Number} toY the y coordinate * @return {Number} the further x or y distance to this coordinate */ getCoordDistance(toX, toY) { const x = Math.abs(this.gridX - toX); const y = Math.abs(this.gridY - toY); return x > y ? x : y; } /** * Figure out if this entity is within the attack radius of the given entity * @param {Entity} entity Player|Mob|Character|NPC * @return {Boolean} returns true if they are within the entity's attack radius, * if the entity has no attack radius default to 2 grid cells */ inAttackRadius(entity) { const attackRadius = entity.attackRadius || 2; return ( entity && this.getDistance(entity) < attackRadius && !(this.gridX !== entity.gridX && this.gridY !== entity.gridY) ); } /** * Figure out if this entity is within the extended attack radius of the given entity * @param {Entity} entity Player|Mob|Character|NPC * @return {Boolean} returns true if they are within the entity's attack radius, * if the entity has no attack radius default to 3 grid cells */ inExtraAttackRadius(entity) { const attackRadius = (entity.attackRadius + 1) || 3; return ( entity && this.getDistance(entity) < attackRadius && !(this.gridX !== entity.gridX && this.gridY !== entity.gridY) ); } /** * Look for an animtions list for this specific animation given it's name * @param {String} name the name of the animation * @return {Animation|null} returns the animation object or null if not found */ getAnimationByName(name) { if (name in this.animations) { return this.animations[name]; } return null; } /** * Returns the name of the sprite * @return {String} the name of the sprite */ getSprite() { return this.sprite.name; } /** * Set the visibility on this entity * @param {Boolean} visible true|false */ setVisible(visible) { this.visible = visible; } /** * Toggle the current visibility of this entity */ toggleVisibility() { this.setVisible(!this.visible); } /** * Check whether or not this entity is visible * @return {Boolean} returns true if visibile */ isVisible() { return this.visible; } /** * Check whether or not this entity has a shadow * @return {Object} returns the entity's shadow */ hasShadow() { return this.shadow; } /** * Check if this entity currently has a path * @return {Object} returns the entity's path */ hasPath() { return this.path; } /** * When this entity's sprite is loaded trigger this callback * @param {Function} callback the function to call when the sprite is loaded */ onReady(callback) { this.readyCallback = callback; } /** * When this entity's is dirty (mobile) use this callback * @param {Function} callback the function to call when the sprite isDirty */ onDirty(callback) { this.dirtyCallback = callback; } }
JavaScript
class BinanceBase extends BasicClient { constructor({ name, wssPath, restL2SnapshotPath, watcherMs = 30000, useAggTrades = true, requestSnapshot = true, socketBatchSize = 200, socketThrottleMs = 1000, restThrottleMs = 1000, l2updateSpeed = "", l2snapshotSpeed = "", batchTickers = true, } = {}) { super(wssPath, name, undefined, watcherMs); this._restL2SnapshotPath = restL2SnapshotPath; this.useAggTrades = useAggTrades; this.l2updateSpeed = l2updateSpeed; this.l2snapshotSpeed = l2snapshotSpeed; this.requestSnapshot = requestSnapshot; this.hasTickers = true; this.hasTrades = true; this.hasCandles = true; this.hasLevel2Snapshots = true; this.hasLevel2Updates = true; this.batchTickers = batchTickers; this._messageId = 0; this._tickersActive = false; this.candlePeriod = CandlePeriod._1m; this._batchSub = batch(this._batchSub.bind(this), socketBatchSize); this._batchUnsub = batch(this._batchUnsub.bind(this), socketBatchSize); this._sendMessage = throttle(this._sendMessage.bind(this), socketThrottleMs); this._requestLevel2Snapshot = throttle(this._requestLevel2Snapshot.bind(this), restThrottleMs); } ////////////////////////////////////////////// _onClosing() { this._tickersActive = false; this._batchSub.cancel(); this._batchUnsub.cancel(); this._sendMessage.cancel(); this._requestLevel2Snapshot.cancel(); super._onClosing(); } _sendSubTicker(remote_id) { if (this._tickersActive) return; this._tickersActive = true; const params = this.batchTickers ? ['!ticker@arr'] : [`${remote_id.toLowerCase()}@ticker`]; this._wss.send( JSON.stringify({ method: "SUBSCRIBE", params: params, id: ++this._messageId, }) ); } _sendUnsubTicker(remote_id) { if (this._tickerSubs.size > 1) return; this._tickersActive = false; const params = this.batchTickers ? ['!ticker@arr'] : [`${remote_id.toLowerCase()}@ticker`]; this._wss.send( JSON.stringify({ method: "UNSUBSCRIBE", params: params, id: ++this._messageId, }) ); } _batchSub(args) { const params = args.map(p => p[0]); const id = ++this._messageId; const msg = JSON.stringify({ method: "SUBSCRIBE", params, id, }); this._sendMessage(msg); } _batchUnsub(args) { const params = args.map(p => p[0]); const id = ++this._messageId; const msg = JSON.stringify({ method: "UNSUBSCRIBE", params, id, }); this._sendMessage(msg); } _sendMessage(msg) { this._wss.send(msg); } _sendSubTrades(remote_id) { const stream = remote_id.toLowerCase() + (this.useAggTrades ? "@aggTrade" : "@trade"); this._batchSub(stream); } _sendUnsubTrades(remote_id) { const stream = remote_id.toLowerCase() + (this.useAggTrades ? "@aggTrade" : "@trade"); this._batchUnsub(stream); } _sendSubCandles(remote_id) { const stream = remote_id.toLowerCase() + "@kline_" + candlePeriod(this.candlePeriod); this._batchSub(stream); } _sendUnsubCandles(remote_id) { const stream = remote_id.toLowerCase() + "@kline_" + candlePeriod(this.candlePeriod); this._batchUnsub(stream); } _sendSubLevel2Snapshots(remote_id) { const stream = remote_id.toLowerCase() + "@depth20" + (this.l2snapshotSpeed ? `@${this.l2snapshotSpeed}` : ""); this._batchSub(stream); } _sendUnsubLevel2Snapshots(remote_id) { const stream = remote_id.toLowerCase() + "@depth20" + (this.l2snapshotSpeed ? `@${this.l2snapshotSpeed}` : ""); this._batchUnsub(stream); } _sendSubLevel2Updates(remote_id) { if (this.requestSnapshot) this._requestLevel2Snapshot(this._level2UpdateSubs.get(remote_id)); const stream = remote_id.toLowerCase() + "@depth" + (this.l2updateSpeed ? `@${this.l2updateSpeed}` : ""); this._batchSub(stream); } _sendUnsubLevel2Updates(remote_id) { const stream = remote_id.toLowerCase() + "@depth" + (this.l2updateSpeed ? `@${this.l2updateSpeed}` : ""); this._batchUnsub(stream); } ///////////////////////////////////////////// _onMessage(raw) { let msg = JSON.parse(raw); // subscribe/unsubscribe responses if (msg.result === null && msg.id) { // console.log(msg); return; } // errors if (msg.error) { const error = new Error(msg.error.msg); error.msg = msg; this.emit("error", error); } // All code past this point relies on msg.stream in some manner. This code // acts as a guard on msg.stream and aborts prematurely if the property is // not available. if (!msg.stream) { return; } // batch tickers if (msg.stream === "!ticker@arr") { for (let raw of msg.data) { let remote_id = raw.s; let market = this._tickerSubs.get(remote_id); if (!market) continue; let ticker = this._constructTicker(raw, market); this.emit("ticker", ticker, market); } return; } // single ticker if (msg.stream.toLowerCase().endsWith("ticker")) { let remote_id = msg.data.s; let market = this._tickerSubs.get(remote_id); if (!market) return; let ticker = this._constructTicker(msg.data, market); this.emit("ticker", ticker, market); return; } // trades if (msg.stream.toLowerCase().endsWith("trade")) { let remote_id = msg.data.s; let market = this._tradeSubs.get(remote_id); if (!market) return; let trade = this.useAggTrades ? this._constructAggTrade(msg, market) : this._constructRawTrade(msg, market); this.emit("trade", trade, market); return; } // candle if (msg.data.e === "kline") { let remote_id = msg.data.s; let market = this._candleSubs.get(remote_id); if (!market) return; let candle = this._constructCandle(msg, market); this.emit("candle", candle, market); return; } // l2snapshot if (msg.stream.match(/@depth20/)) { let remote_id = msg.stream.split("@")[0].toUpperCase(); let market = this._level2SnapshotSubs.get(remote_id); if (!market) return; let snapshot = this._constructLevel2Snapshot(msg, market); this.emit("l2snapshot", snapshot, market); return; } // l2update if (msg.stream.match(/@depth/)) { let remote_id = msg.stream.split("@")[0].toUpperCase(); let market = this._level2UpdateSubs.get(remote_id); if (!market) return; let update = this._constructLevel2Update(msg, market); this.emit("l2update", update, market); return; } } _constructTicker(msg, market) { let { E: timestamp, c: last, v: volume, q: quoteVolume, h: high, l: low, p: change, P: changePercent, a: ask, A: askVolume, b: bid, B: bidVolume, } = msg; let open = parseFloat(last) + parseFloat(change); return new Ticker({ exchange: this._name, base: market.base, quote: market.quote, timestamp: timestamp, last, open: open.toFixed(8), high, low, volume, quoteVolume, change, changePercent, bid, bidVolume, ask, askVolume, }); } _constructAggTrade({ data }, market) { let { a: trade_id, p: price, q: size, T: time, m: buyer } = data; let unix = time; let amount = size; let side = buyer ? "buy" : "sell"; return new Trade({ exchange: this._name, base: market.base, quote: market.quote, tradeId: trade_id.toFixed(), unix, side, price, amount, }); } _constructRawTrade({ data }, market) { let { t: trade_id, p: price, q: size, b: buyOrderId, a: sellOrderId, T: time, m: buyer } = data; let unix = time; let amount = size; let side = buyer ? "buy" : "sell"; return new Trade({ exchange: this._name, base: market.base, quote: market.quote, tradeId: trade_id, unix, side, price, amount, buyOrderId, sellOrderId, }); } /** * Kline data looks like: { stream: 'btcusdt@kline_1m', data: { e: 'kline', E: 1571068845689, s: 'BTCUSDT', k: { t: 1571068800000, T: 1571068859999, s: 'BTCUSDT', i: '1m', f: 189927800, L: 189928107, o: '8254.05000000', c: '8253.61000000', h: '8256.58000000', l: '8250.93000000', v: '19.10571600', n: 308, x: false, q: '157694.32610840', V: '8.19456200', Q: '67640.56793106', B: '0' } } } */ _constructCandle({ data }) { let k = data.k; return new Candle(k.t, k.o, k.h, k.l, k.c, k.v); } _constructLevel2Snapshot(msg, market) { let sequenceId = msg.data.lastUpdateId; let asks = msg.data.asks.map(p => new Level2Point(p[0], p[1])); let bids = msg.data.bids.map(p => new Level2Point(p[0], p[1])); return new Level2Snapshot({ exchange: this._name, base: market.base, quote: market.quote, sequenceId, asks, bids, }); } /** { "e": "depthUpdate", // Event type "E": 123456789, // Event time "s": "BNBBTC", // Symbol "U": 157, // First update ID in event "u": 160, // Final update ID in event "b": [ // Bids to be updated [ "0.0024", // Price level to be updated "10" // Quantity ] ], "a": [ // Asks to be updated [ "0.0026", // Price level to be updated "100" // Quantity ] ] } */ _constructLevel2Update(msg, market) { let eventMs = msg.data.E; let sequenceId = msg.data.U; let lastSequenceId = msg.data.u; let asks = msg.data.a.map(p => new Level2Point(p[0], p[1])); let bids = msg.data.b.map(p => new Level2Point(p[0], p[1])); return new Level2Update({ exchange: this._name, base: market.base, quote: market.quote, sequenceId, lastSequenceId, eventMs, asks, bids, }); } async _requestLevel2Snapshot(market) { let failed = false; try { let remote_id = market.id; let uri = `${this._restL2SnapshotPath}?limit=1000&symbol=${remote_id}`; let raw = await https.get(uri); let sequenceId = raw.lastUpdateId; let timestampMs = raw.E; let asks = raw.asks.map(p => new Level2Point(p[0], p[1])); let bids = raw.bids.map(p => new Level2Point(p[0], p[1])); let snapshot = new Level2Snapshot({ exchange: this._name, base: market.base, quote: market.quote, sequenceId, timestampMs, asks, bids, }); this.emit("l2snapshot", snapshot, market); } catch (ex) { this.emit("error", ex); failed = true; } finally { if (failed) this._requestLevel2Snapshot(market); } } }
JavaScript
class Table extends Component { static propTypes = { /** * Should be valid `<table>` children such as * `TableHeader` and `TableBody`. */ children: PropTypes.node, /** * The CSS class name of the root element. */ className: PropTypes.string, }; static contextTypes = { styleManager: PropTypes.object.isRequired, }; static childContextTypes = { table: PropTypes.object }; getChildContext() { return { table: {} }; } render() { const { className: classNameProp, children, ...other, } = this.props; const classes = this.context.styleManager.render(styleSheet); const className = classNames(classes.root, classNameProp); return ( <table className={className} {...other}> {children} </table> ); } }
JavaScript
class Constant { constructor(config, NAME, key) { const { SYNC, ASYNC } = config this.SYNC_LIST = [] this.CONCAT_LIST = [] if (key in SYNC) { // item 例子: { TYPE: 'BAR', storeName: 'bar' } for (const item of SYNC[key]) { this.SYNC_LIST.push({ TYPE: 'SYNC_' + NAME + '_' + item.TYPE, storeName: item.storeName }) // 增加 CONCAT MUTATION 操作 item.opts && item.opts.concat && this.CONCAT_LIST.push({ TYPE: 'CONCAT_' + NAME + '_' + item.TYPE, storeName: item.storeName }) } } if (ASYNC && key in ASYNC) { this.ASYNC_LIST = [] for (const item of ASYNC[key]) { this.ASYNC_LIST.push({ TYPE: 'ASYNC_' + NAME + '_' + item.TYPE }) } } } }
JavaScript
class EventStoreException extends core_1.BaseException { constructor(message = "Event Store Error") { super(message); } }
JavaScript
class Engine { constructor(options) { let canvas; this.isGameOver = false; this.options = Object.assign({}, internals.defaults, options); // Initial settings... helpful when restarting game this.init(); if (this.stage.$canvas.getContext) { this.keyBindings(); this.play(); // window.onresize = this.screenResize.bind(this); // resize canvas } } init() { let canvas; let highScore = ('hud' in this && this.hud.score) ? this.hud.score : 0; this.stage = new __WEBPACK_IMPORTED_MODULE_1__stage__["a" /* default */]({ cellSize: this.options.cellSize }); canvas = this.stage.canvas; this.hud = new __WEBPACK_IMPORTED_MODULE_3__hud__["a" /* default */]({ canvas, highScore, snakeLength: this.options.snakeLength }); this.snake = new __WEBPACK_IMPORTED_MODULE_0__snake__["a" /* default */]({ canvas, trail: [], tail: this.options.snakeLength, position: this.options.snakePosition }); this.apple = new __WEBPACK_IMPORTED_MODULE_2__apple__["a" /* default */]({ canvas, stageTiles: this.stage.tiles }); this.direction = internals.directionsEnum.DIRECTION_RIGHT; } play() { this.timer = setInterval(this.run.bind(this), this.options.interval); } pause() { clearInterval(this.timer); } gameOver() { const { canvas, width, height } = this.stage; const gameOverText = 'GAME OVER!'; const restartText = 'Press `enter` to restart'; const centerX = (width / 2); const centerY = (height / 2); canvas.beginPath(); canvas.fillStyle = 'green'; canvas.fillRect(centerX - 260, centerY - 115, 510, 210); canvas.fillStyle = 'black'; canvas.fillRect(centerX - 255, centerY - 110, 500, 200); canvas.font = '48px serif'; canvas.textAlign = 'center'; canvas.fillStyle = '#2ecc71'; canvas.fillText(gameOverText, centerX, (centerY - 10)); canvas.font = '20px serif'; canvas.fillStyle = '#2ecc71'; canvas.fillText(restartText, centerX, (centerY + 10)); canvas.fill(); // Stop game this.isGameOver = true; this.pause(); } screenResize() { this.width = document.body.clientWidth - 20; this.height = document.body.clientHeight - 20; this.canvas.width = this.width; this.canvas.height = this.height; this.tiles = { horizontal: Math.floor(this.canvas.width / this.options.gridSize), vertical: Math.floor(this.canvas.height / this.options.gridSize) } this.setupCanvas(); this.resetCandy(); } keyBindings() { const handleKeys = event => { // Check if allowed keys where pressed if (this.options.arrowKeys.indexOf(event.keyCode) === -1 && event.keyCode !== 13) { return false; } // Restart game when isGameOver and Enter key pressed if (this.isGameOver === true) { this.isGameOver = false; this.init(); this.play(); return false; } const { DIRECTION_UP, DIRECTION_RIGHT, DIRECTION_DOWN, DIRECTION_LEFT } = internals.directionsEnum; switch(event.keyCode) { case 37: this.direction = DIRECTION_LEFT; break; case 38: this.direction = DIRECTION_UP; break; case 39: this.direction = DIRECTION_RIGHT; break; case 40: this.direction = DIRECTION_DOWN; break; } event.preventDefault(); // Prevents window scroll }; window.addEventListener('keydown', handleKeys); } boundariesSanitation() { const snakePos = this.snake.position; const tiles = this.stage.tiles; if (snakePos.x < 0) { snakePos.x = tiles.horizontal - 1; } if (snakePos.x > tiles.horizontal - 1) { snakePos.x = 0; } if (snakePos.y < 0) { snakePos.y = tiles.vertical - 1; } if (snakePos.y > tiles.vertical - 1) { snakePos.y = 0; } } run() { const { stage, snake, hud, apple, direction } = this; const gameOverCheck = elem => elem.x === snake.position.x && elem.y === snake.position.y; snake.position = { x: snake.position.x + direction.x, y: snake.position.y + direction.y }; // Has game ended? if (snake.trail.findIndex(gameOverCheck) >= 0) { return this.gameOver(); } // Stage drawing stage.draw(); // Manage our snake going out of canvas boundaries this.boundariesSanitation(); // if Snake caught a apple if (snake.position.x === apple.position.x && snake.position.y === apple.position.y) { snake.tail = snake.tail + 1; this.apple = new __WEBPACK_IMPORTED_MODULE_2__apple__["a" /* default */]({ canvas: stage.canvas, stageTiles: stage.tiles }); } // Update Stats hud.draw(snake.tail); // Drawing snake snake.draw(stage.cellSize); // Draw the apple powerup this.apple.draw(); } }
JavaScript
class CurveInput extends Container { /** * Creates a new pcui.CurveInput. * * @param {object} args - The arguments. * @param {number} [args.lineWidth] - The width of the rendered lines in pixels. * @param {string[]} [args.curves] - The names of the curves that the curve input controls. * @param {number} [args.min] - The minimum value that curves can take. * @param {number} [args.max] - The maximum value that curves can take. * @param {number} [args.verticalValue] - The default maximum and minimum values to show if min and max are undefined. * @param {boolean} [args.hideRandomize] - Whether to hide the randomize button in the curve picker. */ constructor(args) { let i; args = Object.assign({ tabIndex: 0 }, args); super(args); this.class.add(CLASS_CURVE); this._canvas = new Canvas({ useDevicePixelRatio: true }); this._canvas.width = 470; this._canvas.height = 22; this.dom.appendChild(this._canvas.dom); this._canvas.parent = this; this._canvas.on('resize', this._renderCurves.bind(this)); // make sure canvas is the same size as the container element // 20 times a second this.on('showToRoot', () => { this._clearResizeInterval(); this._createResizeInterval(); }); this.on('hideToRoot', () => { this._clearResizeInterval(); }); this._pickerChanging = false; this._combineHistory = false; this._historyPostfix = null; this._domEventKeyDown = this._onKeyDown.bind(this); this._domEventFocus = this._onFocus.bind(this); this._domEventBlur = this._onBlur.bind(this); this.dom.addEventListener('keydown', this._domEventKeyDown); this.dom.addEventListener('focus', this._domEventFocus); this.dom.addEventListener('blur', this._domEventBlur); this.on('click', () => { if (!this.enabled || this.readOnly || this.class.contains(pcuiClass.MULTIPLE_VALUES)) return; this._openCurvePicker(); }); this._lineWidth = args.lineWidth || 1; this._min = 0; if (args.min !== undefined) { this._min = args.min; } else if (args.verticalValue !== undefined) { this._min = -args.verticalValue; } this._max = 1; if (args.max !== undefined) { this._max = args.max; } else if (args.verticalValue !== undefined) { this._max = args.verticalValue; } // default value this._value = this._getDefaultValue(); if (args.value) { this.value = args.value; } this.renderChanges = args.renderChanges || false; this.on('change', () => { if (this.renderChanges) { this.flash(); } }); this.curveToggles = args.curves; this.buildDom(curvePickerDom(this)); // arguments for the curve picker this._pickerArgs = { min: args.min, max: args.max, verticalValue: args.verticalValue, curves: args.curves, hideRandomize: args.hideRandomize }; // curve picker variables // color variables this.colors = { bg: '#293538', gridLines: '#20292b', anchors: ['rgb(255, 0, 0)', 'rgb(0, 255, 0)', 'rgb(133, 133, 252)', 'rgb(255, 255, 255)'], curves: ['rgb(255, 0, 0)', 'rgb(0, 255, 0)', 'rgb(133, 133, 252)', 'rgb(255, 255, 255)'], curveFilling: ['rgba(255, 0, 0, 0.5)', 'rgba(0, 255, 0, 0.5)', 'rgba(133, 133, 252, 0.5)', 'rgba(255, 255, 255, 0.5)'], text: 'white', highlightedLine: 'yellow' }; // canvas variables this.padding = 10; this.axisSpacing = 20; this.anchorRadius = 4; this.curveHoverRadius = 8; this.anchorHoverRadius = 8; this.textSize = 10; // input related variables this.curves = []; // holds all the curves this.enabledCurves = []; // holds the rendered order of the curves this.numCurves = args.curves.length; // number of pairs of curves this.betweenCurves = this._randomizeToggle.value; this.curveType = 0; this.curveNames = []; this.verticalValue = 5; this.verticalTopValue = 5; this.verticalBottomValue = -5; this.maxVertical = null; this.minVertical = null; this.hoveredAnchor = null; this.hoveredCurve = null; this.selectedAnchor = null; this.selectedAnchorIndex = -1; this.selectedCurve = null; this.selectedCurveIndex = -1; this.dragging = false; this.scrolling = false; this.gradient = false; this.mouseY = 0; this.swizzle = [0, 1, 2, 3]; this._pickerCanvas.width = 470; this._pickerCanvas.height = 200; this._pickerCanvasContext = this._pickerCanvas.element.getContext('2d'); this._pickerCanvasContext.setTransform(this._pickerCanvas.pixelRatio, 0, 0, this._pickerCanvas.pixelRatio, 0, 0); this.value = args.curves .map((_, i) => { this._toggleCurve(this.curves[i], true); return [ { type: 1, keys: [0, 0], betweenCurves: false }, { type: 1, keys: [0, 0], betweenCurves: false } ]; }) .flat(); this._renderPicker(); this._typeSelect.on('change', (value) => { this.curveType = Number(value); this.curves.forEach((curve) => { curve.type = value; }); this._renderPicker(); }); this._randomizeToggle.on('change', (value) => { this.changing = true; this.betweenCurves = value; var paths, values; if (!this.suspendEvents) { paths = ['0.betweenCurves']; values = [this.betweenCurves]; } if (!this.betweenCurves) { for (i = 0; i < this.numCurves; i++) { if (!this.curves[i + this.numCurves]) continue; // disable the secondary graph this._toggleCurve(this.curves[i + this.numCurves], false); if (!this.suspendEvents) { paths.push(this._getKeysPath(this.curves[i + this.numCurves])); values.push(this._serializeCurveKeys(this.curves[i])); } } } else { // enable the secondary graphs if their respective primary graphs are enabled for (i = 0; i < this.numCurves; i++) { if (!this.curves[i + this.numCurves]) continue; if (!this.suspendEvents) { paths.push(this._getKeysPath(this.curves[i + this.numCurves])); values.push(this._serializeCurveKeys(this.curves[i + this.numCurves])); } var isEnabled = this.enabledCurves.indexOf(this.curves[i]) >= 0; this._toggleCurve(this.curves[i + this.numCurves], false); if (isEnabled) { this._toggleCurve(this.curves[i + this.numCurves], true); } } } if (!this.suspendEvents) // this._onPickerChange(paths, values); this._renderPicker(); }); this._timeInput.on('change', (newValue) => { if (this.selectedAnchor) { this._updateAnchor(this.selectedCurve, this.selectedAnchor, newValue, this.selectedAnchor[1]); this._renderPicker(); } }); this._valueInput.on('change', (newValue) => { if (this.selectedAnchor) { this._updateAnchor(this.selectedCurve, this.selectedAnchor, this.selectedAnchor[0], newValue); this._renderPicker(); } }); this._copyButton.on('click', () => { var data = { primaryKeys: [], secondaryKeys: [], betweenCurves: this.betweenCurves, curveType: this.curveType }; for (i = 0; i < this.numCurves; i++) { data.primaryKeys.push(this._serializeCurveKeys(this.curves[i])); } for (i = 0; i < this.numCurves; i++) { if (! this.curves[this.numCurves + i]) continue; if (this.betweenCurves) { data.secondaryKeys.push(this._serializeCurveKeys(this.curves[this.numCurves + i])); } else { data.secondaryKeys.push(this._serializeCurveKeys(this.curves[i])); } } localStorageSet('playcanvas_editor_clipboard_curves', data); }); this._pasteButton.on('click', () => { var data = localStorageGet('playcanvas_editor_clipboard_curves'); if (! data) return; var paths = []; var values = []; this.curveType = data.curveType; this.betweenCurves = data.betweenCurves && !this._randomizeToggle.hidden; var copyKeys = (i, data) => { if (data && this.curves[i]) { var keys = data; // clamp keys to min max values if (this.minVertical != null || this.maxVertical != null) { keys = []; for (var j = 0, len = data.length; j < len; j += 2) { keys.push(data[j]); var value = data[j + 1]; if (this.minVertical != null && value < this.minVertical) keys.push(this.minVertical); else if (this.maxVertical != null && value > this.maxVertical) keys.push(this.maxVertical); else keys.push(value); } } this.curves[i] = new Curve(keys); this.curves[i].type = this.curveType; paths.push(this._getKeysPath(this.curves[i])); values.push(keys); if (this._typeSelect.value !== this.curveType) { paths.push(i.toString() + '.type'); values.push(this.curveType); } } }; for (i = 0; i < this.numCurves; i++) { copyKeys(i, data.primaryKeys[i]); } for (i = 0; i < this.numCurves; i++) { copyKeys(i + this.numCurves, data.secondaryKeys[i]); } this.enabledCurves.length = 0; for (i = 0; i < this.numCurves; i++) { if (this[`_toggle${i}`].class.contains(CLASS_CURVE_PICKER_TOGGLE_ACTIVE)) { this.enabledCurves.push(this.curves[i]); if (this.betweenCurves) { this.enabledCurves.push(this.curves[i + this.numCurves]); } } } this._setHovered(null, null); this._setSelected(this.enabledCurves[0], null); var suspend = this.suspendEvents; this.suspendEvents = true; if (this._randomizeToggle.value !== this.betweenCurves) { this._randomizeToggle.value = this.betweenCurves; paths.push('0.betweenCurves'); values.push(this.betweenCurves); } if (this._typeSelect.value !== this.curveType) { this._typeSelect.value = this.curveType; } this.suspendEvents = suspend; if (!this.suspendEvents) { // this._onPickerChange(paths, values); } if (this._shouldResetZoom()) this._resetZoom(); this._renderPicker(); }); var resetZoomTooltip = new Tooltip({ title: 'Reset Zoom' }); resetZoomTooltip.attach({ target: this._resetZoomButton }); var resetCurveTooltip = new Tooltip({ title: 'Reset Curve' }); resetCurveTooltip.attach({ target: this._resetCurveButton }); var copyTooltip = new Tooltip({ title: 'Copy' }); copyTooltip.attach({ target: this._copyButton }); var pasteTooltip = new Tooltip({ title: 'Paste' }); pasteTooltip.attach({ target: this._pasteButton }); this._pickerCanvas.element.addEventListener('mousedown', this._onMouseDown.bind(this), { passive: false }); window.addEventListener('mouseup', this._onMouseUp.bind(this), { passive: false }); window.addEventListener('mousemove', this._onMouseMove.bind(this), { passive: false }); this._pickerCanvas.element.addEventListener('wheel', this._onMouseWheel.bind(this), { passive: false }); this._pickerCanvas.element.addEventListener('contextmenu', (e) => e.preventDefault(), { passive: false }); this._resetCurveButton.on('click', () => { this._resetCurve(this.selectedCurve); }); this._resetZoomButton.on('click', () => { this._resetZoom(); }); args.curves.forEach((curve, i) => { var curveToggle = this[`_toggle${i}`]; curveToggle.on('click', () => { var isActive = curveToggle.class.contains(CLASS_CURVE_PICKER_TOGGLE_ACTIVE); if (isActive) { curveToggle.class.remove(CLASS_CURVE_PICKER_TOGGLE_ACTIVE); } else { curveToggle.class.add(CLASS_CURVE_PICKER_TOGGLE_ACTIVE); } this._toggleCurve(this.curves[i], !isActive); }); }); window.curveInput = this; window.parent.curveInput = this; } _renderPicker() { this._renderGrid(); this._renderPickerCurves(); this._renderHighlightedAnchors(); this._renderMask(); this._renderText(); // if (gradient) { // renderColorGradient(); // } } _renderGrid() { var i; // draw background this._pickerCanvasContext.fillStyle = this.colors.bg; this._pickerCanvasContext.fillRect(0, 0, this._pickerCanvas.width, this._pickerCanvas.height); // draw grid for (i = 0; i < 5; i++) { var y = this._gridTop() + this._gridHeight() * i / 4; this._drawLine([this._gridLeft(), y], [this._gridRight(), y], this.colors.gridLines); } for (i = 0; i < 11; i++) { var x = this._gridLeft() + this._gridWidth() * i / 10; this._drawLine([x, this._gridTop()], [x, this._gridBottom()], this.colors.gridLines); } } _gridWidth() { return this._pickerCanvas.width - 2 * this.padding - this.axisSpacing; } _gridHeight() { return this._pickerCanvas.height - 2 * this.padding - this.axisSpacing; } _gridLeft() { return this.padding + this.axisSpacing; } _gridRight() { return this._gridLeft() + this._gridWidth(); } _gridTop() { return this.padding; } _gridBottom() { return this._gridTop() + this._gridHeight(); } _drawLine(start, end, color) { this._pickerCanvasContext.beginPath(); this._pickerCanvasContext.moveTo(start[0], start[1]); this._pickerCanvasContext.lineTo(end[0], end[1]); this._pickerCanvasContext.strokeStyle = color; this._pickerCanvasContext.stroke(); } // Draws text at the specified coordinates _drawText(text, x, y) { this._pickerCanvasContext.font = this.textSize + 'px Verdana'; this._pickerCanvasContext.fillStyle = this.colors.text; this._pickerCanvasContext.fillText(text.toString(), x, y); } _renderText() { // draw vertical axis values const left = this._gridLeft() - this.textSize * 2; this._drawText(+this.verticalTopValue.toFixed(2), left, this._gridTop() + this.textSize * 0.5); this._drawText(+((this.verticalTopValue + this.verticalBottomValue) * 0.5).toFixed(2), left, this._gridTop() + (this._gridHeight() + this.textSize) * 0.5); this._drawText(+this.verticalBottomValue.toFixed(2), left, this._gridBottom() + this.textSize * 0.5); // draw horizontal axis values this._drawText('0.0', left + this.textSize * 2, this._gridBottom() + 2 * this.textSize); this._drawText('1.0', this._gridRight() - this.textSize * 2, this._gridBottom() + 2 * this.textSize); } _renderPickerCurves() { // holds indices of graphs that were rendered to avoid // rendering the same graphs twice var renderedCurveIndices = {}; // draw this.curves in the order in which they were enabled for (var i = 0; i < this.enabledCurves.length; i++) { var curve = this.enabledCurves[i]; var index = this.curves.indexOf(curve); if (!renderedCurveIndices[index]) { renderedCurveIndices[index] = true; var otherCurve = this._getOtherCurve(curve); this._drawCurvePair(curve, this.betweenCurves ? otherCurve : null); this._drawCurveAnchors(curve); if (this.betweenCurves && otherCurve) { var otherIndex = this.curves.indexOf(otherCurve); if (!renderedCurveIndices[otherIndex]) { this._drawCurveAnchors(otherCurve); renderedCurveIndices[otherIndex] = true; } } } } } // If the specified curve is the primary returns the secondary // otherwise if the specified curve is the secondary returns the primary _getOtherCurve(curve) { var ind = this.curves.indexOf(curve); if (ind < this.numCurves) { return this.curves[this.numCurves + ind]; } return this.curves[ind - this.numCurves]; } // Draws a pair of this.curves with their in-between filling. If the second // curve is null then only the first curve will be rendered _drawCurvePair(curve1, curve2) { var colorIndex = this.swizzle[this.curves.indexOf(curve1) % this.numCurves]; this._pickerCanvasContext.strokeStyle = this.colors.curves[colorIndex]; this._pickerCanvasContext.fillStyle = this.colors.curveFilling[colorIndex]; this._pickerCanvasContext.beginPath(); var time = 0; var value = curve1.value(time); var x; var coords = this._calculateAnchorCoords([time, value]); this._pickerCanvasContext.moveTo(coords[0], coords[1]); var precision = 1; var width = this._pickerCanvas._pixelWidth; for (x = precision; x <= Math.ceil(width / precision); x++) { time = x * precision / width; value = curve1.value(time); coords = this._calculateAnchorCoords([time, value]); this._pickerCanvasContext.lineTo(coords[0], coords[1]); } if (curve2) { for (x = Math.ceil(width / precision); x >= 0; x--) { time = x * precision / width; value = curve2.value(time); coords = this._calculateAnchorCoords([time, value]); this._pickerCanvasContext.lineTo(coords[0], coords[1]); } this._pickerCanvasContext.closePath(); this._pickerCanvasContext.fill(); } this._pickerCanvasContext.stroke(); } // Returns the coordinates of the specified anchor on this grid _calculateAnchorCoords(anchor) { var time = anchor[0]; var value = anchor[1]; var coords = [0, 0]; coords[0] = this._gridLeft() + time * this._gridWidth(); var top = this._gridTop(); coords[1] = top + this._gridHeight() * (value - this.verticalTopValue) / (this.verticalBottomValue - this.verticalTopValue); return coords; } // Draws the anchors for the specified curve _drawCurveAnchors(curve) { var colorIndex = this.swizzle[this.curves.indexOf(curve) % this.numCurves]; curve.keys.forEach((anchor) => { if (anchor !== this.hoveredAnchor && anchor !== this.selectedAnchor) { var color = this.colors.anchors[colorIndex]; var lineColor = this.colors.curves[colorIndex]; this._drawAnchor(this._calculateAnchorCoords(anchor), color, lineColor); } }); } // Draws an anchor point at the specified coordinates _drawAnchor(coords, fillColor, lineColor) { this._pickerCanvasContext.beginPath(); this._pickerCanvasContext.arc(coords[0], coords[1], this.anchorRadius, 0, 2 * Math.PI, false); this._pickerCanvasContext.fillStyle = fillColor; this._pickerCanvasContext.fill(); var lineWidth = this._pickerCanvasContext.lineWidth; this._pickerCanvasContext.lineWidth = 2; this._pickerCanvasContext.strokeStyle = lineColor; this._pickerCanvasContext.stroke(); this._pickerCanvasContext.lineWidth = lineWidth; } // renders a quad in the same color as the bg color // to hide the portion of the curves that is outside the grid _renderMask() { this._pickerCanvasContext.fillStyle = this.colors.bg; var offset = this.anchorRadius + 1; // top this._pickerCanvasContext.fillRect(0, 0, this._pickerCanvasContext.width, this._gridTop() - offset); // bottom this._pickerCanvasContext.fillRect(0, this._gridBottom() + offset, this._pickerCanvasContext.width, 33 - offset); } _renderHighlightedAnchors() { // draw highlighted anchors on top of the others if (this.hoveredAnchor) { this._drawAnchor( this._calculateAnchorCoords(this.hoveredAnchor), this.colors.anchors[this.curves.indexOf(this.hoveredCurve) % this.numCurves], this.colors.highlightedLine ); } if (this.selectedAnchor && this.selectedAnchor !== this.hoveredAnchor) { this._drawAnchor( this._calculateAnchorCoords(this.selectedAnchor), this.colors.anchors[this.curves.indexOf(this.selectedCurve) % this.numCurves], this.colors.highlightedLine ); } } // Draws color gradient for a set of curves _renderColorGradient() { // var ctx = gradientCanvas.element.getContext('2d'); // var t; // var rgb = []; // var precision = 2; // var keys = []; // for (var i = 0; i < curves.length; i++) { // var k = curves[i].keys; // var ka = []; // for (var j = 0, len = k.length; j < len; j++ ) { // ka.push(k[j][0], k[j][1]); // } // keys.push(ka); // } // var curveset = new pc.CurveSet(keys); // curveset.type = curveType; // ctx.fillStyle = checkerboardPattern; // ctx.fillRect(0, 0, gradientCanvas.width, gradientCanvas.height); // var gradient = ctx.createLinearGradient(0, 0, gradientCanvas.width, gradientCanvas.height); // for (t = 0; t <= gradientCanvas.width; t += precision) { // curveset.value(t / gradientCanvas.width, rgb); // var rgba = Math.round((rgb[swizzle[0]] || 0) * 255) + ',' + // Math.round((rgb[swizzle[1]] || 0) * 255) + ',' + // Math.round((rgb[swizzle[2]] || 0) * 255) + ',' + // (isNaN(rgb[swizzle[3]]) ? 1 : rgb[swizzle[3]]); // gradient.addColorStop(t / gradientCanvas.width, 'rgba(' + rgba + ')'); // } // ctx.fillStyle = gradient; // ctx.fillRect(0, 0, gradientCanvas.width, gradientCanvas.height); } // zoom in - out based on delta _adjustZoom(delta) { var maxDelta = 1; if (delta > maxDelta) delta = maxDelta; else if (delta < -maxDelta) delta = -maxDelta; var speed = delta * (this.verticalTopValue - this.verticalBottomValue) / 10; var verticalTop = this.verticalTopValue - speed; var verticalBottom = this.verticalBottomValue + speed; // if we have a hovered or selected anchor then try to focus on // that when zooming in var focus = this.hoveredAnchor || this.selectedAnchor; if (delta > 0 && focus) { var value = focus[1]; var mid = (this.verticalTopValue + this.verticalBottomValue) / 2; verticalTop += (value - mid) * delta; verticalBottom += (value - mid) * delta; } else if (delta > 0 && this.minVertical != null) { this.verticalBottom = this.verticalBottomValue; } // keep limits if (this.maxVertical != null && verticalTop > this.maxVertical) verticalTop = this.maxVertical; if (this.minVertical != null && verticalBottom < this.minVertical) verticalBottom = this.minVertical; // try not to bring values too close together if (+(verticalTop - verticalBottom).toFixed(2) <= 0.01) return; this.verticalTopValue = verticalTop; this.verticalBottomValue = verticalBottom; this._renderPicker(); } _resetZoom() { var minMax = this._getCurvesMinMax(this.enabledCurves); var oldVerticalTop = this.verticalTopValue; var oldVerticalBottom = this.verticalBottomValue; var maxLimit = Math.ceil(2 * Math.max(Math.abs(minMax[0]), Math.abs(minMax[1]))); if (maxLimit === 0) { maxLimit = this.verticalValue; } this.verticalTopValue = maxLimit; if (this.maxVertical != null) { this.verticalTopValue = Math.min(maxLimit, this.maxVertical); } this.verticalBottomValue = -this.verticalTopValue; if (this.minVertical != null) { this.verticalBottomValue = Math.max(this.minVertical, this.verticalBottomValue); } this._renderPicker(); return oldVerticalTop !== this.verticalTopValue || oldVerticalBottom !== this.verticalBottomValue; } _scroll(delta) { var range = this.verticalTopValue - this.verticalBottomValue; var fraction = delta / this._gridHeight(); var diff = range * fraction; if (this.maxVertical != null && this.verticalTopValue + diff > this.maxVertical) { diff = this.maxVertical - this.verticalTopValue; } if (this.minVertical != null && this.verticalBottomValue + diff < this.minVertical) { diff = this.minVertical - this.verticalBottomValue; if (this.maxVertical != null && this.verticalTopValue + diff > this.maxVertical) { diff = this.maxVertical - this.verticalTopValue; } } this.verticalTopValue += diff; this.verticalBottomValue += diff; this._renderPicker(); } _getCurvesMinMax(curves) { var maxValue = -Infinity; var minValue = Infinity; curves.forEach(function (curve) { curve.keys.forEach(function (anchor) { var value = anchor[1]; if (value > maxValue) { maxValue = value; } if (value < minValue) { minValue = value; } }); }); if (maxValue === -Infinity) { maxValue = this.maxVertical != null ? this.maxVertical : this.verticalValue; } if (minValue === Infinity) { minValue = this.minVertical != null ? this.minVertical : -this.verticalValue; } return [minValue, maxValue]; } _updateFields(anchor) { var suspend = this.suspendEvents; this.suspendEvents = true; this._timeInput.suspendEvents = true; this._timeInput.value = anchor ? +anchor[0].toFixed(3) : 0; this._timeInput.suspendEvents = suspend; this._valueInput.suspendEvents = true; this._valueInput.value = anchor ? +anchor[1].toFixed(3) : 0; this._valueInput.suspendEvents = suspend; this.suspendEvents = suspend; } _getTargetCoords(e) { var rect = this._pickerCanvas.element.getBoundingClientRect(); var left = Math.floor(rect.left); var top = Math.floor(rect.top); return [e.clientX - left, e.clientY - top]; } // Returns true if the specidifed coordinates are within the grid bounds _areCoordsInGrid(coords) { return coords[0] >= this._gridLeft() && coords[0] <= this._gridRight() && coords[1] >= this._gridTop() && coords[1] <= this._gridBottom(); } _areCoordsClose(coords1, coords2, range) { return Math.abs(coords1[0] - coords2[0]) <= range && Math.abs(coords1[1] - coords2[1]) <= range; } // If there are any anchors with the same time, collapses them to one _collapseAnchors() { var changedCurves = {}; var paths, values; if (!this.suspendEvents) { paths = []; values = []; } this.enabledCurves.forEach(function (curve) { for (var i = curve.keys.length - 1; i > 0; i--) { var key = curve.keys[i]; var prevKey = curve.keys[i - 1]; if (key[0].toFixed(3) === prevKey[0].toFixed(3)) { curve.keys.splice(i, 1); changedCurves[i] = true; if (this.selectedAnchor === key) { this._setSelected(this.selectedCurve, prevKey); } if (this.hoveredAnchor === key) { this._setHovered(this.hoveredCurve, prevKey); } } } }); if (!this.suspendEvents) { for (var index in changedCurves) { var curve = this.curves[parseInt(index, 10)]; if (curve) { var val = this._serializeCurveKeys(curve); paths.push(this._getKeysPath(curve)); values.push(val.slice(0)); // if randomize is false set secondary graph the same as the first if (!this.betweenCurves) { var other = this._getOtherCurve(curve); if (other) { paths.push(this._getKeysPath(other)); values.push(val); } } } } if (paths.length) { // this._onPickerChange(paths, values); } } } // Creates and returns an anchor and fires change event _createAnchor(curve, time, value) { var anchor = curve.add(time, value); if (!this.suspendEvents) this._onCurveKeysChanged(curve); return anchor; } // Updates the time / value of an anchor and fires change event _updateAnchor(curve, anchor, time, value) { anchor[0] = time; anchor[1] = value; curve.sort(); // reset selected anchor index because it // might have changed after sorting the curve keys if (this.selectedCurve === curve && this.selectedAnchor) { this.selectedAnchorIndex = curve.keys.indexOf(this.selectedAnchor); } if (!this.suspendEvents) this._onCurveKeysChanged(curve); } // Deletes an anchor from the curve and fires change event _deleteAnchor(curve, anchor) { var index = curve.keys.indexOf(anchor); if (index >= 0) { curve.keys.splice(index, 1); } // Have at least one key in the curve if (curve.keys.length === 0) { this._createAnchor(curve, 0, 0); } else { if (!this.suspendEvents) this._onCurveKeysChanged(curve); } } _getKeysPath(curve) { var curveIndex = this.curves.indexOf(curve); if (this.numCurves > 1) { return curveIndex >= this.numCurves ? '1.keys.' + (curveIndex - this.numCurves) : '0.keys.' + curveIndex; } return curveIndex === 0 ? '0.keys' : '1.keys'; } _serializeCurveKeys(curve) { var result = []; curve.keys.forEach(function (k) { result.push(k[0], k[1]); }); return result; } _onCurveKeysChanged(curve) { var paths = [this._getKeysPath(curve)]; var values = [this._serializeCurveKeys(curve)]; // if randomize is false set secondary graph the same as the first if (!this.betweenCurves) { var other = this._getOtherCurve(curve); if (other) { paths.push(this._getKeysPath(other)); values.push(values[0].slice(0)); } } // this._onPickerChange(paths, values); } // Make the specified curve appear in front of the others _sendCurveToFront(curve) { var index = this.enabledCurves.indexOf(curve); if (index >= 0) { this.enabledCurves.splice(index, 1); } this.enabledCurves.push(curve); } // Sets the hovered graph and anchor _setHovered(curve, anchor) { this.hoveredCurve = curve; this.hoveredAnchor = anchor; // Change the mouse cursor to a pointer if (curve || anchor) { this._pickerCanvas.element.style.cursor = 'pointer'; this._updateFields(anchor); } else { this._pickerCanvas.element.style.cursor = ''; this._updateFields(this.selectedAnchor); } } // Sets the selected anchor and curve _setSelected(curve, anchor) { this.selectedCurve = curve; this.selectedAnchor = anchor; this._updateFields(anchor); // make the selected curve appear in front of all the others if (curve) { // set selected curve index this.selectedCurveIndex = this.curves.indexOf(curve); // set selected anchor index this.selectedAnchorIndex = anchor ? curve.keys.indexOf(anchor) : -1; // render curve pair in front of the others if (this.betweenCurves) { var otherCurve = this._getOtherCurve(curve); if (otherCurve) { this._sendCurveToFront(otherCurve); } } this._sendCurveToFront(curve); } else { this.selectedCurveIndex = -1; this.selectedAnchorIndex = -1; } } // Return the hovered anchor and graph _getHoveredAnchor(coords) { var result = { graph: null, anchor: null }; var hoveredTime = this._calculateAnchorTime(coords); // go through all the curves from front to back // and check if the mouse cursor is hovering on them for (var j = this.enabledCurves.length - 1; j >= 0; j--) { var curve = this.enabledCurves[j]; if (!result.curve) { // get the value at the current hovered time var value = curve.value(hoveredTime); // convert hoveredTime, value to coords var curvePointCoords = this._calculateAnchorCoords([hoveredTime, value]); if (this._areCoordsClose(coords, curvePointCoords, this.curveHoverRadius)) { result.curve = curve; } } for (var i = 0, imax = curve.keys.length; i < imax; i++) { var anchor = curve.keys[i]; var anchorCoords = this._calculateAnchorCoords(anchor); if (this._areCoordsClose(coords, anchorCoords, this.anchorHoverRadius)) { result.anchor = anchor; result.curve = curve; return result; } } } return result; } // Enables / disables a curve _toggleCurve(curve, toggle) { if (toggle) { // when we enable a curve make it the selected one this._setSelected(curve, null); } else { var otherCurve; // remove the curve from the enabledCurves array var index = this.enabledCurves.indexOf(curve); if (index >= 0) { this.enabledCurves.splice(index, 1); } // remove its matching curve too if (this.betweenCurves) { otherCurve = this._getOtherCurve(curve); if (otherCurve) { index = this.enabledCurves.indexOf(otherCurve); if (index >= 0) { this.enabledCurves.splice(index, 1); } } } // if the selected curve was disabled select the next enabled one if (this.selectedCurve === curve || this.selectedCurve === otherCurve) { this._setSelected(null, null); if (this.enabledCurves.length) { this.selectedCurve = this.enabledCurves[this.enabledCurves.length - 1]; this.selectedCurveIndex = this.curves.indexOf(this.selectedCurve); // make sure we select the primary curve if (this.betweenCurves && this.selectedCurveIndex >= this.numCurves) { this.selectedCurveIndex -= this.numCurves; this.selectedCurve = this.curves[this.selectedCurveIndex]; } } } if (this.hoveredCurve === curve || this.hoveredCurve === otherCurve) { this.hoveredCurve = null; } } this._renderPicker(); } // Returns true if it would be a good idea to reset the zoom _shouldResetZoom() { var minMax = this._getCurvesMinMax(this.enabledCurves); // if min value is less than the bottom vertical value... if (minMax[0] < this.verticalBottomValue) { return true; } // ... or if max is bigger than the top vertical value... if (minMax[1] > this.verticalTopValue) { return true; } // // ... or if min and max are between the [25%, 75%] interval of the editor, return true // if (minMax[1] < Math.ceil(pc.math.lerp(verticalBottomValue, verticalTopValue, 0.75)) && // minMax[0] > Math.ceil(pc.math.lerp(verticalBottomValue, verticalTopValue, 0.25))) { // return true; // } // don't reset zoom return false; } // Calculate the anchor value based on the specified coordinates _calculateAnchorValue(coords) { var top = this._gridTop(); var height = this._gridHeight(); return math.lerp(this.verticalTopValue, this.verticalBottomValue, (coords[1] - top) / height); } // Calculate the anchor time based on the specified coordinates _calculateAnchorTime(coords) { return math.clamp((coords[0] - this._gridLeft()) / this._gridWidth(), 0, 1); } // Handles mouse down _onMouseDown(e) { e.preventDefault(); e.stopPropagation(); if (e.target !== this._pickerCanvas.element) { return; } // TODO // toggleTextSelection(false); var point = this._getTargetCoords(e); var inGrid = this._areCoordsInGrid(point); // collapse anchors on mouse down because we might // have placed another anchor on top of another by directly // editing its time through the input fields var suspend = this.suspendEvents; this.suspendEvents = true; this._collapseAnchors(); this.suspendEvents = suspend; // select or add anchor on left click if (e.button === 0) { this.dragging = true; this.changing = true; this.scrolling = false; // if we are clicking on an empty area if (!this.hoveredAnchor) { if (!inGrid) { return; } var curve = this.hoveredCurve || this.selectedCurve; // create a new anchor if (curve) { var time = this._calculateAnchorTime(point); var value = this._calculateAnchorValue(point); var anchor = this._createAnchor(curve, time, value); // combine changes from now on until mouse is up // editor.emit('picker:curve:change:start'); // select the new anchor and make it hovered this._setSelected(curve, anchor); this._setHovered(curve, anchor); } } else { // if we are hovered over a graph or an anchor then select it this._setSelected(this.hoveredCurve, this.hoveredAnchor); this._onCurveKeysChanged(this.selectedCurve); } } else if (e.button === 2) { if (!this.dragging) { this.scrolling = true; this.mouseY = e.y; // panel.classList.add('scroll'); } } this._renderPicker(); } // Handles mouse move _onMouseMove(e) { e.preventDefault(); e.stopPropagation(); var coords = this._getTargetCoords(e); // if we are dragging the selected anchor if (this.selectedAnchor && this.dragging) { // clamp coords to grid coords[0] = math.clamp(coords[0], this._gridLeft(), this._gridRight()); coords[1] = math.clamp(coords[1], this._gridTop(), this._gridBottom()); var time = this._calculateAnchorTime(coords); var value = this._calculateAnchorValue(coords); // if there is another point with the same time // then make the two points have the same values var keys = this.selectedCurve.keys; for (var i = 0, len = keys.length; i < len; i++) { if (keys[i] !== this.selectedAnchor && keys[i][0] === time) { value = keys[i][1]; } } this._updateAnchor(this.selectedCurve, this.selectedAnchor, time, value); this._updateFields(this.selectedAnchor); // combine changes from now on // editor.emit('picker:curve:change:start'); this._renderPicker(); } else { if (this.scrolling) { this._scroll(e.y - this.mouseY); this.mouseY = e.y; } // mouse is moving without selected anchors so just check for hovered anchors or hovered curves var hovered = this._getHoveredAnchor(coords); if (hovered.curve !== this.hoveredCurve || hovered.anchor !== this.hoveredAnchor) { this._setHovered(hovered.curve, hovered.anchor); this._renderPicker(); } } } // Handles mouse up _onMouseUp(e) { e.preventDefault(); e.stopPropagation(); // this._toggleTextSelection(true); if (e.button === 0) { if (this.changing) { // collapse anchors on mouse up because we might have // placed an anchor on top of another one this._collapseAnchors(); this.dragging = false; this.changing = false; this._renderPicker(); } // editkr.emit('picker:curve:change:end'); } else if (e.button === 2 && !this.dragging) { this.scrolling = false; // panel.classList.remove('scroll'); // delete anchor on right click if (this.hoveredAnchor) { this._deleteAnchor(this.hoveredCurve, this.hoveredAnchor); // clean up selected anchor if (this.selectedAnchor === this.hoveredAnchor) { this._setSelected(this.selectedCurve, null); } // clean up hovered anchor this._setHovered(null, null); this._renderPicker(); } } } // Handle mouse wheel _onMouseWheel(e) { e.preventDefault(); if (e.deltaY > 0) { this._adjustZoom(-0.3); } else if (e.deltaY < 0) { this._adjustZoom(0.3); } return false; } _resetCurve(curve) { if (!curve) { return; } var suspend = this.suspendEvents; this.suspendEvents = true; curve.keys.length = 0; this._createAnchor(curve, 0, 0); this._timeInput.suspendEvents = true; this._timeInput.value = 0; this._timeInput.suspendEvents = suspend; this._valueInput.suspendEvents = true; this._valueInput.value = 0; this._valueInput.suspendEvents = suspend; this._setSelected(curve, null); var paths = [this._getKeysPath(curve)]; var values = [this._serializeCurveKeys(curve)]; // reset secondary curve too var otherCurve = this._getOtherCurve(curve); if (otherCurve) { otherCurve.keys.length = 0; this._createAnchor(otherCurve, 0, 0); paths.push(this._getKeysPath(otherCurve)); values.push(this._serializeCurveKeys(otherCurve)); } this.suspendEvents = suspend; this._renderPicker(); // if (! this.suspendEvents) // this._onPickerChange(paths, values); } // END OF PICKER METHODS _createResizeInterval() { this._resizeInterval = setInterval(() => { this._canvas.resize(this.width, this.height); }, 1000 / 20); } _clearResizeInterval() { if (this._resizeInterval) { clearInterval(this._resizeInterval); this._resizeInterval = null; } } _onKeyDown(evt) { // escape blurs the field if (evt.keyCode === 27) { this.blur(); } // enter opens the gradient picker if (evt.keyCode !== 13 || !this.enabled || this.readOnly || this.class.contains(pcuiClass.MULTIPLE_VALUES)) { return; } evt.stopPropagation(); evt.preventDefault(); this._openCurvePicker(); } _onFocus(evt) { this.emit('focus'); } _onBlur(evt) { this.emit('blur'); } _getDefaultValue() { return [{ type: 4, keys: [0, 0], betweenCurves: false }]; } _openCurvePicker() { // TODO: don't use global functions // editor.call('picker:curve', utils.deepCopy(this.value), this._pickerArgs); // position picker // const rectPicker = editor.call('picker:curve:rect'); // const rectField = this.dom.getBoundingClientRect(); // editor.call('picker:curve:position', rectField.right - rectPicker.width, rectField.bottom); // let evtChangeStart = editor.on('picker:curve:change:start', () => { // if (this._pickerChanging) return; // this._pickerChanging = true; // if (this._binding) { // this._combineHistory = this._binding.historyCombine; // this._historyPostfix = this._binding.historyPostfix; // this._binding.historyCombine = true; // // assign a history postfix which will limit how far back // // the history will be combined. We only want to combine // // history between this curve:change:start and curve:change:end events // // not further back // this._binding.historyPostfix = `(${Date.now()})`; // } // }); // let evtChangeEnd = editor.on('picker:curve:change:end', () => { // if (!this._pickerChanging) return; // this._pickerChanging = false; // if (this._binding) { // this._binding.historyCombine = this._combineHistory; // this._binding.historyPostfix = this._historyPostfix; // this._combineHistory = false; // this._historyPostfix = null; // } // }); // let evtPickerChanged = editor.on('picker:curve:change', this._onPickerChange.bind(this)); // let evtRefreshPicker = this.on('change', value => { // const args = Object.assign({ // keepZoom: true // }, this._pickerArgs); // editor.call('picker:curve:set', value, args); // }); // editor.once('picker:curve:close', function () { // evtRefreshPicker.unbind(); // evtRefreshPicker = null; // evtPickerChanged.unbind(); // evtPickerChanged = null; // evtChangeStart.unbind(); // evtChangeStart = null; // evtChangeEnd.unbind(); // evtChangeEnd = null; // }); } _onPickerChange(paths, values) { if (!this.value) return; // maybe we should deepCopy the value instead but not doing // it now for performance const value = utils.deepCopy(this.value); // patch our value with the values coming from the picker // which will trigger a change to the binding if one exists for (let i = 0; i < paths.length; i++) { const parts = paths[i].split('.'); const curve = value[parseInt(parts[0], 10)]; if (!curve) continue; if (parts.length === 3) { curve[parts[1]][parseInt(parts[2], 10)] = values[i]; } else { curve[parts[1]] = values[i]; } } this.value = value; } _getMinMaxValues(value) { let minValue = Infinity; let maxValue = -Infinity; if (value) { if (!Array.isArray(value)) { value = [value]; } value.forEach((value) => { if (!value || !value.keys || !value.keys.length) return; if (Array.isArray(value.keys[0])) { value.keys.forEach((data) => { for (let i = 1; i < data.length; i += 2) { if (data[i] > maxValue) { maxValue = data[i]; } if (data[i] < minValue) { minValue = data[i]; } } }); } else { for (let i = 1; i < value.keys.length; i += 2) { if (value.keys[i] > maxValue) { maxValue = value.keys[i]; } if (value.keys[i] < minValue) { minValue = value.keys[i]; } } } }); } if (minValue === Infinity) { minValue = this._min; } if (maxValue === -Infinity) { maxValue = this._max; } // try to limit minValue and maxValue // between the min / max values for the curve field if (minValue > this._min) { minValue = this._min; } if (maxValue < this._max) { maxValue = this._max; } return [minValue, maxValue]; } // clamp val between min and max only if it's less / above them but close to them // this is mostly to allow splines to go over the limit but if they are too close to // the edge then they will avoid rendering half-height lines _clampEdge(val, min, max) { if (val < min && val > min - 2) return min; if (val > max && val < max + 2) return max; return val; } _convertValueToCurves(value) { if (!value || !value.keys || !value.keys.length) return null; if (value.keys[0].length !== undefined) { return value.keys.map((data) => { const curve = new Curve(data); curve.type = value.type; return curve; }); } const curve = new Curve(value.keys); curve.type = value.type; return [curve]; } _renderCurves() { const canvas = this._canvas.dom; const context = canvas.getContext('2d'); const value = this.value; const width = this._canvas.width; const height = this._canvas.height; const ratio = this._canvas.pixelRatio; context.setTransform(ratio, 0, 0, ratio, 0, 0); // draw background context.clearRect(0, 0, width, height); const curveColors = ['rgb(255, 0, 0)', 'rgb(0, 255, 0)', 'rgb(133, 133, 252)', 'rgb(255, 255, 255)']; const fillColors = ['rgba(255, 0, 0, 0.5)', 'rgba(0, 255, 0, 0.5)', 'rgba(133, 133, 252, 0.5)', 'rgba(255, 255, 255, 0.5)']; const minMax = this._getMinMaxValues(value); if (!value || !value[0]) return; // draw curves const primaryCurves = value.slice(0, this.numCurves).map((curve) => this._convertValueToCurves(curve)).flat(); if (!primaryCurves) return; const secondaryCurves = value.slice(this.numCurves, this.numCurves * 2).map((curve) => this._convertValueToCurves(curve)).flat(); const minValue = minMax[0]; const maxValue = minMax[1]; context.lineWidth = this._lineWidth; // prevent divide by 0 if (width === 0) return; for (let i = 0; i < primaryCurves.length; i++) { context.strokeStyle = curveColors[i]; context.fillStyle = fillColors[i]; context.beginPath(); context.moveTo(0, this._clampEdge(height * (1 - (primaryCurves[i].value(0) - minValue) / (maxValue - minValue)), 1, height - 1)); const precision = 1; for (let x = 0; x < Math.floor(width / precision); x++) { const val = primaryCurves[i].value(x * precision / width); context.lineTo(x * precision, this._clampEdge(height * (1 - (val - minValue) / (maxValue - minValue)), 1, height - 1)); } if (secondaryCurves) { for (let x = Math.floor(width / precision); x >= 0; x--) { const val = secondaryCurves[i].value(x * precision / width); context.lineTo(x * precision, this._clampEdge(height * (1 - (val - minValue) / (maxValue - minValue)), 1, height - 1)); } context.closePath(); context.fill(); } context.stroke(); } } focus() { this.dom.focus(); } blur() { this.dom.blur(); } destroy() { if (this._destroyed) return; this.dom.removeEventListener('keydown', this._domEventKeyDown); this.dom.removeEventListener('focus', this._domEventFocus); this.dom.removeEventListener('blur', this._domEventBlur); this._clearResizeInterval(); super.destroy(); } get value() { return this._value; } set value(value) { // TODO: maybe we should check for equality // but since this value will almost always be set using // the picker it's not worth the effort this._value = Array.isArray(value) ? utils.deepCopy(value) : [utils.deepCopy(value)]; this.class.remove(pcuiClass.MULTIPLE_VALUES); this.emit('change', value); if (this._binding) { this._binding.setValues(this._value); } this.betweenCurves = value.betweenCurves || false; this.numCurves = value.length / 2; this.curves.length = 0; value.forEach((data) => { if (this.numCurves === 1) { var c = new Curve(data.keys); c.type = this.curveType; this.curves.push(c); } else { data.keys.forEach((keys) => { var c = new Curve(keys); c.type = this.curveType; this.curves.push(c); }); } }); this.enabledCurves.length = 0; for (var i = 0; i < this.numCurves; i++) { // if (this.curveToggles[i].class.contains('active')) { this.enabledCurves.push(this.curves[i]); if (this.betweenCurves) { this.enabledCurves.push(this.curves[i + this.numCurves]); } // } } this._renderCurves(); } /* eslint accessor-pairs: 0 */ set values(values) { // we do not support multiple values so just // add the multiple values class which essentially disables // the input this.class.add(pcuiClass.MULTIPLE_VALUES); this._renderCurves(); } }
JavaScript
class TOC extends Component { constructor(doc) { super(); this.doc = doc; this.defaultState = DefaultState; } render() { // I. Initialization // - A. Variables var level = 1; // - B. DOM this.clearDOM(); var li = this.dom; for(var i = 0; i < this.doc.nodes.length; i++) { let node = this.doc.nodes[i]; if(node instanceof HeadingNode) { if(node.level === 1) { li = this.dom; } else if(node.level > level) { while(node.level > level) { li = li .appendChild(document.createElement("ul")) .appendChild(document.createElement("li")); level++; } } else if(node.level < level || node.level === level) { if(node.level < 0) throw new Error("Heading levels cannot go below 0!"); while(node.level < level) { li = li.parentNode.parentNode; // li ul li level--; } li = li.parentNode.appendChild(document.createElement("li")); } let a = document.createElement("a"); a.href = "#" + node.id; a.appendChild(document.createTextNode(node.state.text)); li.appendChild(a); } } } }
JavaScript
class VanAddress { constructor(vaddr) { this._address = vaddr; this._listenerIds = []; this._connectorIds = []; this._totalFlows = 0; this._currentFlows = 0; vanAddresses[vaddr] = this; this._fireWatches(); } _fireWatches() { let watchList = recordWatches['VAN_ADDRESS'] || []; watchList.forEach(watch => watch.invoke(this)) watchList = flowWatches[this._address] || []; watchList.forEach(watch => watch.invoke(this)); } addListenerId(id) { this._listenerIds.push(id); this._fireWatches(); } addConnectorId(id) { this._connectorIds.push(id); this._fireWatches(); } flowBegin() { this._totalFlows += 1; this._currentFlows += 1; this._fireWatches(); } flowEnd() { this._currentFlows -= 1; this._fireWatches(); } get address() { return this._address; } get listenerIds() { return this._listenerIds; } get connectorIds() { return this._connectorIds; } get obj() { let object = {}; object.rtype = 'VAN_ADDRESS'; object.id = this._address; object.name = this._address; object.listenerCount = this._listenerIds.length; object.connectorCount = this._connectorIds.length; object.totalFlows = this._totalFlows; object.currentFlows = this._currentFlows; return object; } }
JavaScript
class Record { constructor(rtype, id, rec) { this._rtype = rtype; this._id = id; this._record = rec; this._children = []; // List of records IDs this._peerId = undefined; this._van_address = undefined; // // Store this record's identity in the by-type index. // idsByType[this._rtype].push(this._id); // // If this record has a counter-flow attribute, create a mutual cross reference // with the counter-flow record. // this._linkPeer(); // // If this is a LISTENER or CONNECTOR record, do inference regarding the van address // of the record. This includes possibly creating a new VanAddress object or changing // metrics of an existing one. // if (this._rtype == "LISTENER" || this._rtype == "CONNECTOR") { this._newVanAddress(); } // // If this is a record type that participates in process linkage, queue it up in the // to-be-reconciled list. // if (this._rtype == "CONNECTOR") { toBeProcessReconciled.connectors.push(this._id); } else if (this._rtype == "PROCESS") { toBeProcessReconciled.processes.push(this._id); } else if (this._rtype == "FLOW") { toBeProcessReconciled.flows.push(this._id); } // // Normalize LINK names to contain the "0/" prefix if they don't already have it. // This will allow for proper matching of the linked name to a ROUTER record. // if (this._rtype == "LINK") { if (this._record['name'] && this._record['name'][0] != '0') { this._record['name'] = "0/" + this._record['name']; } } // // If this record has a parent reference, set up the parent-child linkage. // if (this.parent) { this._addParent(); } // // If there are any watches relevant to this record, invoke them now. // this._fireWatches(); } get id() { return this._id; } get rtype() { return this._rtype; } get parent() { return this._record[record.PARENT_INDEX]; } get childIds() { return this._children; } get children() { let childObjects = []; this._children.forEach(childId => { childObjects.push(records[childId]); }); return childObjects; } get counterflow() { return this._record[record.COUNTERFLOW_INDEX]; } get obj() { let object = this._record; object.rtype = this._rtype; object.id = this.id; return object; } attribute(attr) { return this._record[attr]; } _addParent() { if (this.parent in records) { let parent = records[this.parent]; parent.addChild(this.id); if (parent._van_address) { this._van_address = parent._van_address; if (this._rtype == 'FLOW') { this._van_address.flowBegin() } } } } _linkPeer() { let peerId = this.counterflow; if (peerId) { let peerRecord = records[peerId]; if (peerRecord) { this._peerId = peerId; let update = {}; update[record.COUNTERFLOW_INDEX] = this._id; peerRecord.update(update); } } } _newVanAddress() { let addr = this._record[record.VAN_ADDRESS_INDEX]; if (addr) { let vanAddr = vanAddresses[addr]; if (vanAddr == undefined) { vanAddr = new VanAddress(addr); } if (this._rtype == "LISTENER") { vanAddr.addListenerId(this._id); } else { vanAddr.addConnectorId(this._id); } this._van_address = vanAddr; } } _fireWatches() { let watches = recordWatches[this._rtype] || []; watches.forEach(watch => watch.invoke(this)); if (this._van_address) { let watches = flowWatches[this._van_address.address] || []; watches.forEach(watch => watch.invoke(this)); } } addChild(childId) { this._children.push(childId); } update(rec) { let prevParent = this.parent; let prevAddr = this._record[record.VAN_ADDRESS_INDEX]; let checkPeer = false; for (const [key, value] of Object.entries(rec)) { this._record[key] = value; if (key == record.COUNTERFLOW_INDEX) { checkPeer = true; } } if (!prevParent && this.parent) { this._addParent(this.parent); } if ((this._rtype == "LISTENER" || this._rtype == "CONNECTOR") && !prevAddr) { this._newVanAddress(); } if (checkPeer && !this._peerId) { this._linkPeer(); } if (this._van_address && this._record.endTime) { this._van_address.flowEnd(); } this._fireWatches(); } }
JavaScript
class MoviesServices { //creamos nuestro constructor constructor() { this.collection = 'movies'; //llamamos a nuestra coleccion this.mongoDB = new MongoLib(); //creamos el objeto de la clase MongoLib } //vamos a crear nuestras funciones para ir a traer nuestras peliculas o borrar o eliminar //metodo para traer toda la coleccion de movies async getMovies({ tags }) { //vamos a traer todas las peliculas que concuerden con los tags que le pasemos const query = tags && { tags: { $in: tags } } //construimos el query donde si hay tags los buscamos con $in: y los taga que recibimos esto es codigo de mongo const movies = await this.mongoDB.getAll(this.collection, query); //esta clase esta definida eb lib de mongo que creamos return movies || [] //retorna la coleccion si las encuentra si no un objecto vacio } //metodo para traer movies por id async getMovie({ movieId }) { //vamos a traer todas las peliculas que concuerden con el id que le pasemos const movies = await this.mongoDB.get(this.collection, movieId); //esta clase esta definida en lib de mongo que creamos return movies || {} //retorna la coleccion si las encuentra si no un json vacio } //crear una movie async createMovie({ movie }) { //vamos a recibir los datos de la movie que queremos crear const createdMovieId = await this.mongoDB.create(this.collection, movie); //esta clase esta definida eb lib de mongo que creamos return createdMovieId //retorna la pelicula que creamos. } //actualizar una movie async updateMovie({ movieId, movie } = {}) { //vamos a recibir el id que queremos actualizar y ademas la data de la movie ya actualizada ahora por defecto la data esta vacia para no tener problemas const updateMovieId = await this.mongoDB.update(this.collection, movieId, movie); //esta clase esta definida eb lib de mongo que creamos return updateMovieId //retorna la pelicula que actualizamos. } //eliminar una pelicula async deleteMovie({ movieId }) { //vamos a recibir el id de la movie a borrar const deleteMovieId = await this.mongoDB.delete(this.collection, movieId); //esta clase esta definida eb lib de mongo que creamos return deleteMovieId //retorna la pelicula que borramos. } }
JavaScript
class TTSService { constructor(options, client) { this.ttsApiKey = options.ttsApiKey; this.client = client; this.phoneticNicknames = options.phoneticNicknames; this.setupVoiceStateListener(); this.defaultTextChannel = options.defaultTextChannel; this.AddTime = options.AddTime; } /** * Get text to Speech stream for given text. * @param {string} text text to convert */ getStream(text) { return new Promise((resolve, reject) => { request.post({ "body": `{"input":{"ssml":"<speak>${text}</speak>"},` + "\"voice\":{\"languageCode\":\"en-US\",\"name\":\"en-US-Wavenet-F\"}," + "\"audioConfig\":{\"audioEncoding\":\"OGG_OPUS\",\"pitch\":0,\"speakingRate\":1}}", "headers": {"content-type": "text/plain"}, "url": "https://texttospeech.googleapis.com/v1beta1/text:synthesize?" + `key=${this.ttsApiKey}` }, (error, response, body) => { if (error) { return reject(error); } const content = JSON.parse(body); if (typeof content.audioContent === "undefined") { return reject(new Error("Audio content not found!")); } const buff = Buffer.from(content.audioContent, "base64"); const stream = new Readable(); stream.push(buff); stream.push(null); return resolve(stream); }); }); } /** * Setup user join or leave events with announcer tts voice. * @private */ setupVoiceStateListener() { this.client.on("voiceStateUpdate", (oldState, newState) => { if (newState.member.user.bot) { return; // Ignore bots. } const newUserChannel = newState.channel; const oldUserChannel = oldState.channel; const voiceConnection = this.client.voice.connections.find((val) => val.channel.guild.id === newState.guild.id); if (typeof voiceConnection !== "undefined") { const newUser = newState.member.displayName; if (newUserChannel && oldUserChannel && newUserChannel.id === oldUserChannel.id) { // Do nothing! } else if (newUserChannel && newUserChannel.id === voiceConnection.channel.id) { // User joins voice channel of bot const line = Math.floor(Math.random() * voiceLines.join.length); const messageJoin = voiceLines.join[line].replace(/#User/gu, this.phoneticNicknameFor(newUser)); this.announceMessage(messageJoin, voiceConnection); if (this.defaultTextChannel) { this.client.guilds.cache.forEach((guild) => { guild.channels.cache.get(this.defaultTextChannel).send(`${newUser} joined the channel (${this.formatDate(this.AddTime)})`); }); } } else if (oldUserChannel && oldUserChannel.id === voiceConnection.channel.id) { // User leaves voice channel of bot const line = Math.floor(Math.random() * voiceLines.leave.length); const messageLeave = voiceLines.leave[line].replace(/#User/gu, this.phoneticNicknameFor(newUser)); this.announceMessage(messageLeave, voiceConnection); if (this.defaultTextChannel) { this.client.guilds.cache.forEach((guild) => { guild.channels.cache.get(this.defaultTextChannel).send(`${newUser} left the channel (${this.formatDate(this.AddTime)})`); }); } } } }); } /** * Lookup phonetic nickname. * @private * @param {string} userName Username to process. */ phoneticNicknameFor(userName) { if (this.phoneticNicknames) { for (const [phoneticNicknameKey, phoneticNicknameValue] of Object.entries(this.phoneticNicknames)) { if (userName.includes(phoneticNicknameKey)) { return phoneticNicknameValue; } } } return userName; } /** * Announce the given message via tts to the given connection. * @private * @param {string} message Message to announce. * @param {VoiceConnection} voiceConnection Discord.js Voice connection to announce to. */ announceMessage(message, voiceConnection) { this.getStream(message). then((stream) => { const oldDispatcher = voiceConnection.dispatcher; const dispatcher = voiceConnection.play(stream); dispatcher.on("end", () => { if (oldDispatcher && !oldDispatcher.paused) { oldDispatcher.end(); } }); }). catch((err) => { if (voiceConnection.dispatcher && !voiceConnection.dispatcher.paused) { voiceConnection.dispatcher.end(); } console.log(err); }); } formatDate(addhour) { let date = Date.now() let Time = Date.now() if (typeof addhour != "number" || Number.isNaN(addhour) == true) { addhour = 0; } Time = Time + addhour * 3600000 date = new Date(Time) let day = date.getDate().toString().padStart(2,'0'); let month = parseInt(date.getMonth().toString().padStart(2,'0')) + 1; let year = date.getFullYear(); let hour = date.getHours().toString().padStart(2,'0'); let minutes = date.getMinutes().toString().padStart(2,'0'); let seconds = date.getSeconds().toString().padStart(2,'0'); let actual_date = day + "." + month + "." + year; return day + "." + month + "." + year + " " + hour + ":" + minutes + ":" + seconds; } }
JavaScript
class UniversalDisposable { constructor(...teardowns) { this.teardowns = new Set(); this.disposed = false; if (teardowns.length) { this.add(...teardowns); } } add(...teardowns) { if (this.disposed) { throw new Error('Cannot add to an already disposed UniversalDisposable!'); } for (let i = 0; i < teardowns.length; i++) { assertTeardown(teardowns[i]); this.teardowns.add(teardowns[i]); } } remove(teardown) { if (!this.disposed) { this.teardowns.delete(teardown); } } dispose() { if (!this.disposed) { this.disposed = true; this.teardowns.forEach(teardown => { if (typeof teardown.dispose === 'function') { teardown.dispose(); } else if (typeof teardown.unsubscribe === 'function') { teardown.unsubscribe(); } else if (typeof teardown === 'function') { teardown(); } }); this.teardowns = null; } } unsubscribe() { this.dispose(); } clear() { if (!this.disposed) { this.teardowns.clear(); } } }
JavaScript
class TimeStampResp { //********************************************************************************** /** * Constructor for TimeStampResp class * @param {Object} [parameters={}] * @param {Object} [parameters.schema] asn1js parsed value to initialize the class from */ constructor(parameters = {}) { //region Internal properties of the object /** * @type {PKIStatusInfo} * @desc status */ this.status = (0, _pvutils.getParametersValue)(parameters, "status", TimeStampResp.defaultValues("status")); if ("timeStampToken" in parameters) /** * @type {ContentInfo} * @desc timeStampToken */ this.timeStampToken = (0, _pvutils.getParametersValue)(parameters, "timeStampToken", TimeStampResp.defaultValues("timeStampToken")); //endregion //region If input argument array contains "schema" for this object if ("schema" in parameters) this.fromSchema(parameters.schema); //endregion } //********************************************************************************** /** * Return default values for all class members * @param {string} memberName String name for a class member */ static defaultValues(memberName) { switch (memberName) { case "status": return new _PKIStatusInfo.default(); case "timeStampToken": return new _ContentInfo.default(); default: throw new Error(`Invalid member name for TimeStampResp class: ${memberName}`); } } //********************************************************************************** /** * Compare values with default values for all class members * @param {string} memberName String name for a class member * @param {*} memberValue Value to compare with default value */ static compareWithDefault(memberName, memberValue) { switch (memberName) { case "status": return _PKIStatusInfo.default.compareWithDefault("status", memberValue.status) && "statusStrings" in memberValue === false && "failInfo" in memberValue === false; case "timeStampToken": return memberValue.contentType === "" && memberValue.content instanceof asn1js.Any; default: throw new Error(`Invalid member name for TimeStampResp class: ${memberName}`); } } //********************************************************************************** /** * Return value of pre-defined ASN.1 schema for current class * * ASN.1 schema: * ```asn1 * TimeStampResp ::= SEQUENCE { * status PKIStatusInfo, * timeStampToken TimeStampToken OPTIONAL } * ``` * * @param {Object} parameters Input parameters for the schema * @returns {Object} asn1js schema object */ static schema(parameters = {}) { /** * @type {Object} * @property {string} [blockName] * @property {string} [status] * @property {string} [timeStampToken] */ const names = (0, _pvutils.getParametersValue)(parameters, "names", {}); return new asn1js.Sequence({ name: names.blockName || "TimeStampResp", value: [_PKIStatusInfo.default.schema(names.status || { names: { blockName: "TimeStampResp.status" } }), _ContentInfo.default.schema(names.timeStampToken || { names: { blockName: "TimeStampResp.timeStampToken", optional: true } })] }); } //********************************************************************************** /** * Convert parsed asn1js object into current class * @param {!Object} schema */ fromSchema(schema) { //region Clear input data first (0, _pvutils.clearProps)(schema, ["TimeStampResp.status", "TimeStampResp.timeStampToken"]); //endregion //region Check the schema is valid const asn1 = asn1js.compareSchema(schema, schema, TimeStampResp.schema()); if (asn1.verified === false) throw new Error("Object's schema was not verified against input data for TimeStampResp"); //endregion //region Get internal properties from parsed schema this.status = new _PKIStatusInfo.default({ schema: asn1.result["TimeStampResp.status"] }); if ("TimeStampResp.timeStampToken" in asn1.result) this.timeStampToken = new _ContentInfo.default({ schema: asn1.result["TimeStampResp.timeStampToken"] }); //endregion } //********************************************************************************** /** * Convert current object to asn1js object and set correct values * @returns {Object} asn1js object */ toSchema() { //region Create array for output sequence const outputArray = []; outputArray.push(this.status.toSchema()); if ("timeStampToken" in this) outputArray.push(this.timeStampToken.toSchema()); //endregion //region Construct and return new ASN.1 schema for this object return new asn1js.Sequence({ value: outputArray }); //endregion } //********************************************************************************** /** * Convertion for the class to JSON object * @returns {Object} */ toJSON() { const _object = { status: this.status }; if ("timeStampToken" in this) _object.timeStampToken = this.timeStampToken.toJSON(); return _object; } //********************************************************************************** /** * Sign current TSP Response * @param {Object} privateKey Private key for "subjectPublicKeyInfo" structure * @param {string} [hashAlgorithm] Hashing algorithm. Default SHA-1 * @returns {Promise} */ sign(privateKey, hashAlgorithm) { //region Check that "timeStampToken" exists if ("timeStampToken" in this === false) return Promise.reject("timeStampToken is absent in TSP response"); //endregion //region Check that "timeStampToken" has a right internal format if (this.timeStampToken.contentType !== "1.2.840.113549.1.7.2") // Must be a CMS signed data return Promise.reject(`Wrong format of timeStampToken: ${this.timeStampToken.contentType}`); //endregion //region Sign internal signed data value const signed = new _ContentInfo.default({ schema: this.timeStampToken.content }); return signed.sign(privateKey, 0, hashAlgorithm); //endregion } //********************************************************************************** /** * Verify current TSP Response * @param {Object} verificationParameters Input parameters for verification * @returns {Promise} */ verify(verificationParameters = { signer: 0, trustedCerts: [], data: new ArrayBuffer(0) }) { //region Check that "timeStampToken" exists if ("timeStampToken" in this === false) return Promise.reject("timeStampToken is absent in TSP response"); //endregion //region Check that "timeStampToken" has a right internal format if (this.timeStampToken.contentType !== "1.2.840.113549.1.7.2") // Must be a CMS signed data return Promise.reject(`Wrong format of timeStampToken: ${this.timeStampToken.contentType}`); //endregion //region Verify internal signed data value const signed = new _SignedData.default({ schema: this.timeStampToken.content }); return signed.verify(verificationParameters); //endregion } //********************************************************************************** } //**************************************************************************************
JavaScript
class TestService extends TestBrowserProxy { constructor() { super([ 'getExtensionsInfo', 'getExtensionSize', 'getProfileConfiguration', 'loadUnpacked', 'retryLoadUnpacked', 'reloadItem', 'setProfileInDevMode', 'setShortcutHandlingSuspended', 'shouldIgnoreUpdate', 'updateAllExtensions', 'updateExtensionCommandKeybinding', 'updateExtensionCommandScope', ]); this.itemStateChangedTarget = new FakeChromeEvent(); this.profileStateChangedTarget = new FakeChromeEvent(); /** @private {!chrome.developerPrivate.LoadError} */ this.retryLoadUnpackedError_; /** @type {boolean} */ this.forceReloadItemError_ = false; } /** * @param {!chrome.developerPrivate.LoadError} error */ setRetryLoadUnpackedError(error) { this.retryLoadUnpackedError_ = error; } /** * @param {boolean} force */ setForceReloadItemError(force) { this.forceReloadItemError_ = force; } /** @override */ getProfileConfiguration() { this.methodCalled('getProfileConfiguration'); return Promise.resolve({inDeveloperMode: false}); } /** @override */ getItemStateChangedTarget() { return this.itemStateChangedTarget; } /** @override */ getProfileStateChangedTarget() { return this.profileStateChangedTarget; } /** @override */ getExtensionsInfo() { this.methodCalled('getExtensionsInfo'); return Promise.resolve([]); } /** @override */ getExtensionSize() { this.methodCalled('getExtensionSize'); return Promise.resolve('20 MB'); } /** @override */ setShortcutHandlingSuspended(enable) { this.methodCalled('setShortcutHandlingSuspended', enable); } /** @override */ shouldIgnoreUpdate(extensionId, eventType) { this.methodCalled('shouldIgnoreUpdate', [extensionId, eventType]); } /** @override */ updateExtensionCommandKeybinding(item, commandName, keybinding) { this.methodCalled( 'updateExtensionCommandKeybinding', [item, commandName, keybinding]); } /** @override */ updateExtensionCommandScope(item, commandName, scope) { this.methodCalled( 'updateExtensionCommandScope', [item, commandName, scope]); } /** @override */ loadUnpacked() { this.methodCalled('loadUnpacked'); return Promise.resolve(); } /** @override */ reloadItem(id) { this.methodCalled('reloadItem', id); return this.forceReloadItemError_ ? Promise.reject() : Promise.resolve(); } /** @override */ retryLoadUnpacked(guid) { this.methodCalled('retryLoadUnpacked', guid); return (this.retryLoadUnpackedError_ !== undefined) ? Promise.reject(this.retryLoadUnpackedError_) : Promise.resolve(); } /** @override */ setProfileInDevMode(inDevMode) { this.methodCalled('setProfileInDevMode', inDevMode); } /** @override */ updateAllExtensions() { this.methodCalled('updateAllExtensions'); return Promise.resolve(); } }
JavaScript
class GameState{ static inject = [HttpClient, GameThemes]; constructor(http, themeAdapter){ this.pages = []; this.story = {}; this.selectedPage = {}; this.themeAdapter = themeAdapter; http.get("/json/pages.json").then( response =>{ this.addRange(this.pages, response.content) }); http.get("/json/story.json").then( response =>{ this.updateValues( this.story, response.content); }); } updateValues(obj, values){ //Object.assign(obj, values); for( var key in values){ obj[key] = values[key]; } } addRange( sourceArr, values){ var len = values.length; for (var i = 0; i < len; i++){ sourceArr.push(values[i]); }; } }
JavaScript
class MDCTextFieldHelperTextAdapter { /** * Adds a class to the helper text element. * @param {string} className */ addClass(className) {} /** * Removes a class from the helper text element. * @param {string} className */ removeClass(className) {} /** * Returns whether or not the helper text element contains the given class. * @param {string} className * @return {boolean} */ hasClass(className) {} /** * Sets an attribute with a given value on the helper text element. * @param {string} attr * @param {string} value */ setAttr(attr, value) {} /** * Removes an attribute from the helper text element. * @param {string} attr */ removeAttr(attr) {} /** * Sets the text content for the helper text element. * @param {string} content */ setContent(content) {} }
JavaScript
class V1ResourceAttributes { static getAttributeTypeMap() { return V1ResourceAttributes.attributeTypeMap; } }
JavaScript
class MemorySessionStorage { constructor() { this.hash = {}; } getItem(key) { return this.hash[key]; } setItem(key, val) { this.hash[key] = val; } removeItem(key) { delete this.hash[key]; } clear() { this.hash = {}; } }
JavaScript
class Snappable extends AbstractPlugin { /** * Snappable constructor. * @constructs Snappable * @param {Draggable} draggable - Draggable instance */ constructor(draggable) { super(draggable); /** * Keeps track of the first source element * @property {HTMLElement|null} firstSource * @type {HTMLElement|null} */ this.firstSource = null; this[onDragStart] = this[onDragStart].bind(this); this[onDragStop] = this[onDragStop].bind(this); this[onDragOver] = this[onDragOver].bind(this); this[onDragOut] = this[onDragOut].bind(this); } /** * Attaches plugins event listeners */ attach() { this.draggable .on('drag:start', this[onDragStart]) .on('drag:stop', this[onDragStop]) .on('drag:over', this[onDragOver]) .on('drag:out', this[onDragOut]) .on('droppable:over', this[onDragOver]) .on('droppable:out', this[onDragOut]); } /** * Detaches plugins event listeners */ detach() { this.draggable .off('drag:start', this[onDragStart]) .off('drag:stop', this[onDragStop]) .off('drag:over', this[onDragOver]) .off('drag:out', this[onDragOut]) .off('droppable:over', this[onDragOver]) .off('droppable:out', this[onDragOut]); } /** * Drag start handler * @private * @param {DragStartEvent} event - Drag start event */ [onDragStart](event) { if (event.canceled()) { return; } this.firstSource = event.source; } /** * Drag stop handler * @private * @param {DragStopEvent} event - Drag stop event */ [onDragStop]() { this.firstSource = null; } /** * Drag over handler * @private * @param {DragOverEvent|DroppableOverEvent} event - Drag over event */ [onDragOver](event) { if (event.canceled()) { return; } const source = event.source || event.dragEvent.source; const mirror = event.mirror || event.dragEvent.mirror; if (source === this.firstSource) { this.firstSource = null; return; } const snapInEvent = new SnapInEvent({ dragEvent: event, snappable: event.over || event.droppable, }); this.draggable.trigger(snapInEvent); if (snapInEvent.canceled()) { return; } if (mirror) { mirror.style.display = 'none'; } source.classList.remove(this.draggable.getClassNameFor('source:dragging')); source.classList.add(this.draggable.getClassNameFor('source:placed')); // Need to cancel this in drag out setTimeout(() => { source.classList.remove(this.draggable.getClassNameFor('source:placed')); }, this.draggable.options.placedTimeout); } /** * Drag out handler * @private * @param {DragOutEvent|DroppableOutEvent} event - Drag out event */ [onDragOut](event) { if (event.canceled()) { return; } const mirror = event.mirror || event.dragEvent.mirror; const source = event.source || event.dragEvent.source; const snapOutEvent = new SnapOutEvent({ dragEvent: event, snappable: event.over || event.droppable, }); this.draggable.trigger(snapOutEvent); if (snapOutEvent.canceled()) { return; } if (mirror) { mirror.style.display = ''; } source.classList.add(this.draggable.getClassNameFor('source:dragging')); } }
JavaScript
class ApplicationGatewayRewriteRule { /** * Create a ApplicationGatewayRewriteRule. * @property {string} [name] Name of the rewrite rule that is unique within * an Application Gateway. * @property {object} [actionSet] Set of actions to be done as part of the * rewrite Rule. * @property {array} [actionSet.requestHeaderConfigurations] Request Header * Actions in the Action Set * @property {array} [actionSet.responseHeaderConfigurations] Response Header * Actions in the Action Set */ constructor() { } /** * Defines the metadata of ApplicationGatewayRewriteRule * * @returns {object} metadata of ApplicationGatewayRewriteRule * */ mapper() { return { required: false, serializedName: 'ApplicationGatewayRewriteRule', type: { name: 'Composite', className: 'ApplicationGatewayRewriteRule', modelProperties: { name: { required: false, serializedName: 'name', type: { name: 'String' } }, actionSet: { required: false, serializedName: 'actionSet', type: { name: 'Composite', className: 'ApplicationGatewayRewriteRuleActionSet' } } } } }; } }
JavaScript
class TouchableNativeFeedback extends React.Component { // could be taken as RNTouchableNativeFeedback.SelectableBackground etc. but the API may change getExtraButtonProps() { const extraProps = {}; const { background } = this.props; if (background) { // I changed type values to match those used in RN // TODO(TS): check if it works the same as previous implementation - looks like it works the same as RN component, so it should be ok if (background.type === 'RippleAndroid') { extraProps['borderless'] = background.borderless; extraProps['rippleColor'] = background.color; } else if (background.type === 'ThemeAttrAndroid') { extraProps['borderless'] = background.attribute === 'selectableItemBackgroundBorderless'; } // I moved it from above since it should be available in all options extraProps['rippleRadius'] = background.rippleRadius; } extraProps['foreground'] = this.props.useForeground; return extraProps; } render() { const { style = {}, ...rest } = this.props; return /*#__PURE__*/React.createElement(_GenericTouchable.default, _extends({}, rest, { style: style, extraButtonProps: this.getExtraButtonProps() })); } }
JavaScript
class AutofillManager { /** * Add an observer to the list of addresses. * @param {function(!Array<!AutofillManager.AddressEntry>):void} listener */ addAddressListChangedListener(listener) {} /** * Remove an observer from the list of addresses. * @param {function(!Array<!AutofillManager.AddressEntry>):void} listener */ removeAddressListChangedListener(listener) {} /** * Request the list of addresses. * @param {function(!Array<!AutofillManager.AddressEntry>):void} callback */ getAddressList(callback) {} /** * Saves the given address. * @param {!AutofillManager.AddressEntry} address */ saveAddress(address) {} /** @param {string} guid The guid of the address to remove. */ removeAddress(guid) {} /** * Add an observer to the list of credit cards. * @param {function(!Array<!AutofillManager.CreditCardEntry>):void} listener */ addCreditCardListChangedListener(listener) {} /** * Remove an observer from the list of credit cards. * @param {function(!Array<!AutofillManager.CreditCardEntry>):void} listener */ removeCreditCardListChangedListener(listener) {} /** * Request the list of credit cards. * @param {function(!Array<!AutofillManager.CreditCardEntry>):void} callback */ getCreditCardList(callback) {} /** @param {string} guid The GUID of the credit card to remove. */ removeCreditCard(guid) {} /** @param {string} guid The GUID to credit card to remove from the cache. */ clearCachedCreditCard(guid) {} /** * Saves the given credit card. * @param {!AutofillManager.CreditCardEntry} creditCard */ saveCreditCard(creditCard) {} }
JavaScript
class AutofillManagerImpl { /** @override */ addAddressListChangedListener(listener) { chrome.autofillPrivate.onAddressListChanged.addListener(listener); } /** @override */ removeAddressListChangedListener(listener) { chrome.autofillPrivate.onAddressListChanged.removeListener(listener); } /** @override */ getAddressList(callback) { chrome.autofillPrivate.getAddressList(callback); } /** @override */ saveAddress(address) { chrome.autofillPrivate.saveAddress(address); } /** @override */ removeAddress(guid) { chrome.autofillPrivate.removeEntry(assert(guid)); } /** @override */ addCreditCardListChangedListener(listener) { chrome.autofillPrivate.onCreditCardListChanged.addListener(listener); } /** @override */ removeCreditCardListChangedListener(listener) { chrome.autofillPrivate.onCreditCardListChanged.removeListener(listener); } /** @override */ getCreditCardList(callback) { chrome.autofillPrivate.getCreditCardList(callback); } /** @override */ removeCreditCard(guid) { chrome.autofillPrivate.removeEntry(assert(guid)); } /** @override */ clearCachedCreditCard(guid) { chrome.autofillPrivate.maskCreditCard(assert(guid)); } /** @override */ saveCreditCard(creditCard) { chrome.autofillPrivate.saveCreditCard(creditCard); } }
JavaScript
class FinnedRenderer { constructor(len) { this._len = len; this._strokeColor = 0; this._fillColor = 150; this._angle = 0; this._angleOffset = 0.2; } render(mover) { rectMode(CENTER); push(); translate(mover._location.x, mover._location.y); rotate(mover._angle); this.renderBody(); pop(); if (mover.isMoving()) this._angle += this._angleOffset; } /** * The Main Body is a curve to form the fish shape. The control points sway to sine wave */ renderBody() { let len = this._len/2.4; let wid = len / 4; stroke(this._strokeColor); strokeWeight(3); fill(this._fillColor); let yOffset = map(sin(this._angle), -1, 1, -wid/3, wid/3); strokeWeight(1); // fins (like an arrow head) beginShape(); vertex(wid*1.2,0); vertex(0, -wid - yOffset - wid/2); vertex(wid/2,0); vertex(0, wid - yOffset + wid/2); endShape(CLOSE); // main body - think of a curve drawn through f-g-d-b-a-c-e-h-f // b g // d // a f // e // c h beginShape(); vertex(-len*1.2, 0); // tail mid (f) vertex(-len*1.4, -wid/2 - yOffset); curveVertex(-len*1.4, -wid/2- yOffset); // tail tip (g) curveVertex(-len, -wid/2 + yOffset); // tail (d) curveVertex(0, -wid - yOffset); // body (b) curveVertex(len, 0); // tip (a) curveVertex(0, wid - yOffset); // body (c) curveVertex(-len, wid/2 + yOffset); // tail (e) curveVertex(-len*1.4, wid/2 - yOffset); // tail tip (h) vertex(-len*1.4, wid/2 - yOffset); endShape(CLOSE); strokeWeight(1); } }
JavaScript
class UnprovisionApplicationTypeDescriptionInfo { /** * Create a UnprovisionApplicationTypeDescriptionInfo. * @property {string} applicationTypeVersion The version of the application * type as defined in the application manifest. * @property {boolean} [async] The flag indicating whether or not unprovision * should occur asynchronously. When set to true, the unprovision operation * returns when the request is accepted by the system, and the unprovision * operation continues without any timeout limit. The default value is false. * However, we recommend setting it to true for large application packages * that were provisioned. */ constructor() { } /** * Defines the metadata of UnprovisionApplicationTypeDescriptionInfo * * @returns {object} metadata of UnprovisionApplicationTypeDescriptionInfo * */ mapper() { return { required: false, serializedName: 'UnprovisionApplicationTypeDescriptionInfo', type: { name: 'Composite', className: 'UnprovisionApplicationTypeDescriptionInfo', modelProperties: { applicationTypeVersion: { required: true, serializedName: 'ApplicationTypeVersion', type: { name: 'String' } }, async: { required: false, serializedName: 'Async', type: { name: 'Boolean' } } } } }; } }
JavaScript
class MediaVideoPreviewComponent { /** * Constructor * * @param String galleryComponent Gallery component DOM selector * @return void [type] */ constructor(galleryComponent, formSelector) { this.galleryComponent = galleryComponent; this.formSelector = formSelector; this.selectedMedia = {}; this._handleSelectedItemFromMediaGalleryEvent(); } /** * Show image preview */ showGallery() { $(this.galleryComponent).removeClass("d-none"); $("textarea#page_content_value").parent().addClass("d-none"); if( $("textarea#page_content_value").val().length ) { this._previewVideoByPath(); } } /** * Listen to selectedItemFromMediaGallery event */ _handleSelectedItemFromMediaGalleryEvent() { var _self = this; document.addEventListener('selectedItemFromMediaGallery', function(e) { _self.selectedMedia = e.detail.video; if( ! _self.selectedMedia ) return; if( typeof e.detail.reset == "undefined" ) e.detail.reset = false; if(e.detail.reset) { // _self.resetImagePreview(); } // Generate image preview _self.previewSelectedVideo(e.detail.reset); // Close modal $("div#modal").modal("hide"); }, false); } /** * Generate video preview for selected gallery item * * @param Boolean reset Indicate if form video path value has to be reset * @return void [type] */ previewSelectedVideo(reset) { if(reset) { $(this.formSelector + ' textarea#page_content_value').val(this.selectedMedia.path); } let fullVideoPath = appUrl + '/uploads/' + this.selectedMedia.path; $("div#selected_video_preview div.dimmer-content h4.video-name").html(this.selectedMedia['name']); $("div#selected_video_preview div.dimmer-content video").attr('src', fullVideoPath); // hide loader $("div#selected_video_preview div.dimmer").removeClass("active"); // show preview component $("div#selected_video_preview").removeClass("d-none"); } /** * Preview video from video path value for saved content. */ _previewVideoByPath() { let videoPath = $("textarea#page_content_value").val(); let mediaDetailRoute = Routing.generate('reaccion_cms_admin_media_detail_by_path'); $("div#selected_video_preview").removeClass("d-none"); // load media data $.post(mediaDetailRoute, { 'path' : videoPath }, function(response) { // create and dispatch event var event = new CustomEvent( 'selectedItemFromMediaGallery', { 'detail' : { 'video' : response } } ); document.dispatchEvent(event); // hide loader $("div#selected_video_preview div.dimmer").removeClass("active"); }, "json"); } }
JavaScript
class ParseCancellationException extends Error { constructor(cause) { super(cause.message); this.cause = cause; this.stack = cause.stack; } getCause() { return this.cause; } }
JavaScript
class GameObject extends MessageDispatcher { /** * Creates new instance of GameObject. */ constructor() { super(true); /** * @private * @type {number} */ this.mId = ++ID; /** * @private * @type {string|null} */ this.mName = null; /** * @private * @type {Array<black-engine~Component>} */ this.mComponents = []; /** * @protected * @type {Array<black-engine~GameObject>} */ this.mChildren = []; /** * @private * @type {number} */ this.mX = 0; /** * @private * @type {number} */ this.mY = 0; /** * @private * @type {number} */ this.mScaleX = 1; /** * @private * @type {number} */ this.mScaleY = 1; /** * @protected * @type {number} */ this.mPivotX = 0; /** * @protected * @type {number} */ this.mPivotY = 0; /** * @protected * @type {number} */ this.mSkewX = 0; /** * @protected * @type {number} */ this.mSkewY = 0; /** * @protected * @type {number|null} */ this.mAnchorX = null; /** * @protected * @type {number|null} */ this.mAnchorY = null; /** * @protected * @type {number} */ this.mPivotOffsetX = 0; /** * @protected * @type {number} */ this.mPivotOffsetY = 0; /** * @private * @type {number} */ this.mRotation = 0; /** * @protected * @type {black-engine~Rectangle} */ this.mBoundsCache = new Rectangle(); /** * @private * @type {black-engine~Matrix} */ this.mLocalTransform = new Matrix(); /** * @private * @type {black-engine~Matrix} */ this.mWorldTransform = new Matrix(); /** * @private * @type {black-engine~Matrix} */ this.mWorldTransformInverted = new Matrix(); /** * @private * @type {black-engine~DirtyFlag} */ this.mDirty = DirtyFlag.DIRTY; /** * @protected * @type {black-engine~GameObject} */ this.mParent = null; /** * @private * @type {string|null} */ this.mTag = null; /** * @private * @type {boolean} */ this.mAdded = false; /** * @private * @type {number} */ this.mNumChildrenRemoved = 0; /** * @private * @type {number} */ this.mNumComponentsRemoved = 0; /** * @private * @type {number} */ this.mDirtyFrameNum = 0; /** * @private * @type {boolean} */ this.mSuspendDirty = false; // cache all colliders for fast access /** * @private * @type {Array<black-engine~Collider>} */ this.mCollidersCache = []; /** * @private * @type {boolean} */ this.mChildOrComponentBeenAdded = false; /** * @private * @type {Array<black-engine~GameObject>} */ this.mChildrenClone = null; /** * @private * @type {Array<black-engine~Component>} */ this.mComponentClone = null; } make(values) { // can be helpful if there are many children this.mSuspendDirty = true; for (let property in values) { if (values.hasOwnProperty(property)) { this[property] = values[property]; } } this.mSuspendDirty = false; this.setTransformDirty(); return this; } /** * Returns unique object id. * * @returns {number} */ get id() { return this.mId; } /** * Returns true if object was clean for at least 1 update. * * Note: Make sure to apply all changes to this game object before checking for static. * * @param {boolean} [includeChildren=true] * @returns {boolean} */ checkStatic(includeChildren = true) { if (includeChildren === false) return this.mDirtyFrameNum < Black.engine.frameNum; let isDynamic = false; GameObject.forEach(this, x => { if (x.mDirtyFrameNum >= Black.engine.frameNum) { isDynamic = true; return true; } }); return !isDynamic; } /** * This method called each time object added to stage. * * @action * @return {void} */ onAdded() { } /** * Called when object is removed from stage. * * @action * @return {void} */ onRemoved() { } /** * Sugar method for adding child `GameObjects` or `Components` in a simple manner. * * @param {...(black-engine~GameObject|black-engine~Component)} gameObjectsAndOrComponents A `GameObject` or `Component` to add. * @return {black-engine~GameObject} This game object */ add(...gameObjectsAndOrComponents) { for (let i = 0; i < gameObjectsAndOrComponents.length; i++) { let gooc = gameObjectsAndOrComponents[i]; if (gooc instanceof GameObject) this.addChild( /** @type {!GameObject} */(gooc)); else this.addComponent( /** @type {!Component} */(gooc)); } return this; } /** * Adds a child `GameObject` instance to this `GameObject` instance. The child is added to the top of all other * children in this GameObject instance. * * @param {black-engine~GameObject} child The GameObject instance to add as a child of this GameObject instance. * @return {black-engine~GameObject} */ addChild(child) { return this.addChildAt(child, this.mChildren.length); } /** * Adds a child `GameObject` instance to this `GameObject` instance. The child is added to the top of all other * children in this GameObject instance. * * @param {black-engine~GameObject} child The GameObject instance to add as a child of this GameObject instance. * @param {number=} [index=0] The index position to which the child is added. * @return {black-engine~GameObject} The GameObject instance that you pass in the child parameter. */ addChildAt(child, index = 0) { Debug.assert(child instanceof GameObject, 'Type error.'); let numChildren = this.mChildren.length; if (index < 0 || index > numChildren) throw new Error('Child index is out of bounds.'); if (child.mParent === this) return this.setChildIndex(child, index); // this operation should be atomic. since __setParent can throw exception. this.mChildren.splice(index, 0, child); child.removeFromParent(); child.__setParent(this); Black.engine.onChildrenAdded(child, this); this.mChildOrComponentBeenAdded = true; return child; } /** * @private * @ignore * @param {black-engine~GameObject} value * @return {boolean} */ __setParent(value) { let p = value; while (p !== null && p !== this) p = p.mParent; if (p === this) throw new Error('Object cannot be a child to itself.'); this.mParent = value; this.setTransformDirty(); return true; } /** * Sets the index (layer) of the specified `GameObject` to the specified index (layer). * * @param {black-engine~GameObject} child The `GameObject` instance to change index for. * @param {number} index Desired index. * @returns {black-engine~GameObject} The `GameObject` instance that you pass in the child parameter. */ setChildIndex(child, index) { let ix = this.mChildren.indexOf(child); if (ix < 0) throw new Error('Given child element was not found in children list.'); if (ix === index) return child; // NOTE: systems needs to know when trees changes this.mChildren.splice(ix, 1); this.mChildren.splice(index, 0, child); if (this.stage !== null) Black.engine.onChildrenChanged(child); this.setTransformDirty(); return child; } /** * Removes this `GameObject` instance from its parent. * * @return {black-engine~GameObject} */ removeFromParent() { if (this.mParent !== null) this.mParent.removeChild(this); this.setTransformDirty(); return this; } /** * Removes specified child `GameObject` instance from children. * * @param {black-engine~GameObject} child `GameObject` instance to remove. * @return {black-engine~GameObject} The `GameObject` instance that you pass in the child parameter. */ removeChild(child) { let ix = this.mChildren.indexOf(child); if (ix < 0) return null; return this.removeChildAt(ix); } /** * Finds children by name. * * @param {string} name Name of the child object to find. * @return {black-engine~GameObject|null} GameObject instance or null if not found. */ getChildByName(name) { for (let i = 0; i < this.mChildren.length; i++) { if (this.mChildren[i].name === name) return this.mChildren[i]; } return null; } /** * Removes `GameObjects` instance from specified index. * * @param {number} index Index of child. Negative index will remove object from it end. * @return {black-engine~GameObject|null} The removed `GameObject` instance or null if not found. */ removeChildAt(index) { let child = this.mChildren.splice(index, 1)[0]; if (child == null) return null; let hadRoot = this.stage !== null; child.__setParent(null); if (hadRoot === true) Black.engine.onChildrenRemoved(child); this.setTransformDirty(); this.mNumChildrenRemoved++; return child; } /** * Removes all children objects. * @returns {black-engine~GameObject} Returns this. */ removeAllChildren() { while (this.mChildren.length > 0) this.removeChildAt(0); return this; } /** * Returns `GameObject` at specified index. * * @param {number} index The index of child `GameObject`. * @return {black-engine~GameObject} The `GameObject` at specified index. */ getChildAt(index) { return this.mChildren[index]; } /** * Adds Component instance to the end of the list. * * @throws {Error} * @param {black-engine~Component} component The instances of Component to be added, * @return {black-engine~Component} The `Component` instance you pass in the instances parameter. */ addComponent(component) { return this.addComponentAt(component, this.mComponents.length); } /** * Adds Component to the list at given position. * * @throws {Error} * @param {black-engine~Component} component The instances of Component to be added, * @param {number} [index=0] Position in the list. * @returns {black-engine~Component} The `Component` instance you pass in the instances parameter. */ addComponentAt(component, index = 0) { Debug.assert(component instanceof Component, 'Type error.'); if (component.gameObject) throw new Error('Component cannot be added to two game objects at the same time.'); let numComponents = this.mComponents.length; if (index < 0 || index > numComponents) throw new Error('Component index is out of bounds.'); this.mComponents.splice(index, 0, component); component.mGameObject = this; if (component instanceof Collider) this.mCollidersCache.push(component); if (this.stage !== null || Black.stage === this) Black.engine.onComponentAdded(this, component); this.mChildOrComponentBeenAdded = true; return component; } /** * Removes component at given index. * * @param {number} index Negative index will remove component from the end. * @returns {black-engine~Component|null} Returns removed component of null. */ removeComponentAt(index) { let instance = this.mComponents.splice(index, 1)[0]; if (instance == null) return null; // detach game object after or before? instance.mGameObject = null; if (instance instanceof Collider) { let colliderIx = this.mCollidersCache.indexOf(instance); if (colliderIx > -1) this.mCollidersCache.splice(colliderIx, 1); } if (this.stage !== null || Black.stage === this) Black.engine.onComponentRemoved(this, instance); this.mNumComponentsRemoved++; return instance; } /** * Remove specified component. * * @param {black-engine~Component} instance The `Component` instance. * @returns {black-engine~Component|null} Returns removed component of null. */ removeComponent(instance) { if (instance == null) return null; Debug.assert(instance instanceof Component, 'Type error.'); let index = this.mComponents.indexOf(instance); if (index > -1) return this.removeComponentAt(index); return null; } /** * Removes all components. * @returns {black-engine~GameObject} Returns this. */ removeAllComponents() { while (this.mComponents.length > 0) this.removeComponentAt(0); return this; } /** * Get component by type. * * @param {Function} typeName The component type. * @return {black-engine~Component|null} The `Component` instance or null if not found. */ getComponent(typeName) { for (let i = 0; i < this.mComponents.length; i++) { let c = this.mComponents[i]; if (c instanceof typeName) return c; } return null; } /** * Returns number of component's of this GameObject. * * @return {number} */ get numComponents() { return this.mComponents.length; } /** * Retrieves `Component` at given index. * * @param {number} index Index of component. * @return {black-engine~Component|null} */ getComponentAt(index) { if (index >= 0 && index < this.mComponents.length) return this.mComponents[index]; return null; } /** * Returns local transformation `Matrix` * * @return {black-engine~Matrix} */ get localTransformation() { if (this.mDirty & DirtyFlag.LOCAL) { this.mDirty ^= DirtyFlag.LOCAL; if (this.mSkewX === 0.0 && this.mSkewY === 0.0) { if (this.mRotation === 0) { return this.mLocalTransform.set(this.mScaleX, 0, 0, this.mScaleY, this.mX - this.mPivotX * this.mScaleX, this.mY - this.mPivotY * this.mScaleY); } else { let cos = Math.cos(this.mRotation); let sin = Math.sin(this.mRotation); let a = this.mScaleX * cos; let b = this.mScaleX * sin; let c = this.mScaleY * -sin; let d = this.mScaleY * cos; let tx = this.mX - this.mPivotX * a - this.mPivotY * c; let ty = this.mY - this.mPivotX * b - this.mPivotY * d; return this.mLocalTransform.set(a, b, c, d, tx, ty); } } else { this.mLocalTransform.identity(); this.mLocalTransform.scale(this.mScaleX, this.mScaleY); this.mLocalTransform.skew(this.mSkewX, this.mSkewY); this.mLocalTransform.rotate(this.mRotation); let a = this.mLocalTransform.data[0]; let b = this.mLocalTransform.data[1]; let c = this.mLocalTransform.data[2]; let d = this.mLocalTransform.data[3]; let tx = this.mX; let ty = this.mY; if (this.mPivotX !== 0.0 || this.mPivotY !== 0.0) { tx = this.mX - a * this.mPivotX - c * this.mPivotY; ty = this.mY - b * this.mPivotX - d * this.mPivotY; } this.mLocalTransform.data[4] = tx; this.mLocalTransform.data[5] = ty; } } return this.mLocalTransform; } /** * @param {black-engine~Matrix} value * @return {void} */ set localTransformation(value) { const PI_Q = Math.PI / 4.0; let a = value.data[0]; let b = value.data[1]; let c = value.data[2]; let d = value.data[3]; let tx = value.data[4]; let ty = value.data[5]; this.mPivotOffsetX = this.mPivotOffsetY = 0; this.mAnchorX = this.mAnchorX = null; this.mX = tx; this.mY = ty; let skewX = Math.atan(-c / d); let skewY = Math.atan(b / a); if (skewX != skewX) skewX = 0.0; if (skewY != skewY) skewY = 0.0; this.mScaleY = (skewX > -PI_Q && skewX < PI_Q) ? d / Math.cos(skewX) : -c / Math.sin(skewX); this.mScaleX = (skewY > -PI_Q && skewY < PI_Q) ? a / Math.cos(skewY) : b / Math.sin(skewY); if (MathEx.equals(skewX, skewY)) { this.mRotation = skewX; this.mSkewX = this.mSkewY = 0; } else { this.mRotation = 0; this.mSkewX = skewX; this.mSkewY = skewY; } this.setTransformDirty(); } /** * Gets cloned Matrix object which represents object orientation in world space. * * @return {black-engine~Matrix} */ get worldTransformation() { if (this.mDirty & DirtyFlag.ANCHOR && (this.mAnchorX !== null || this.mAnchorY !== null)) { this.mDirty ^= DirtyFlag.ANCHOR; this.__updatePivots(this); this.setDirty(/** @type {DirtyFlag} */(DirtyFlag.LOCAL | DirtyFlag.WIRB), true); } if (this.mDirty & DirtyFlag.WORLD) { this.mDirty ^= DirtyFlag.WORLD; if (this.mParent !== null) this.mParent.worldTransformation.copyTo(this.mWorldTransform).append(this.localTransformation); else this.localTransformation.copyTo(this.mWorldTransform); } return this.mWorldTransform; } /** * Returns cloned and inverted Matrix object which represents object orientation in world space * * @readonly * @return {black-engine~Matrix} */ get worldTransformationInverted() { if ((this.mDirty & DirtyFlag.WORLD_INV)) { this.mDirty ^= DirtyFlag.WORLD_INV; this.worldTransformation.copyTo(this.mWorldTransformInverted).invert(); } return this.mWorldTransformInverted; } /** * @ignore * @private * @return {void} */ __update() { this.onUpdate(); if (this.mChildOrComponentBeenAdded === false) return; if (this.mComponents.length > 0) { this.mComponentClone = this.mComponents.slice(); for (let k = 0; k < this.mComponentClone.length; k++) { if (this.mAdded === false) break; let c = this.mComponentClone[k]; if (c.mAdded === false || c.enabled === false) continue; c.onUpdate(); } } if (this.mChildren.length > 0) { this.mChildrenClone = this.mChildren.slice(); for (let i = 0; i < this.mChildrenClone.length; i++) { let child = this.mChildrenClone[i]; if (child.mAdded === true) child.__update(); } } } /** * Called at every engine update. The execution order of onFixedUpdate, onUpdate and onPostUpdate is * going from top to bottom of the display list. * * @action * @protected * @return {void} */ onUpdate() { } /** * Override this method if you need to specify GameObject size. Should be always be a local coordinates. * * @action * @protected * @param {black-engine~Rectangle=} [outRect=undefined] Rectangle to be returned. * @return {black-engine~Rectangle} bounds in local space without taking care about transformation matrix */ onGetLocalBounds(outRect = undefined) { outRect = outRect || new Rectangle(); return outRect.set(0, 0, 0, 0); } /** * Returns world bounds of this object and all children if specified (true by default). * * `object.getBounds()` - relative to parent (default).<br> * `object.getBounds(object)` - local bounds.<br> * `object.getBounds(object.parent)` - relative to parent.<br> * `object.getBounds(objectB)` - relative to objectB space.<br> * * @param {black-engine~GameObject} [space=null] The `GameObject` relative to. * @param {boolean} [includeChildren=true] Specifies if include children in calculations. * @param {black-engine~Rectangle=} [outRect=null] Rectangle to be returned. * @return {black-engine~Rectangle} Returns bounds of the object with/without all children. */ getBounds(space = null, includeChildren = true, outRect = undefined) { outRect = outRect || new Rectangle(); this.onGetLocalBounds(outRect); if (space == null) space = this.mParent; if (space == this) { // local } else if (space == this.mParent) { if (includeChildren === false) { let matrix = Matrix.pool.get(); matrix.copyFrom(this.localTransformation); matrix.transformRect(outRect, outRect); Matrix.pool.release(matrix); } else if (includeChildren === true && this.mDirty & DirtyFlag.BOUNDS) { let matrix = Matrix.pool.get(); matrix.copyFrom(this.localTransformation); matrix.transformRect(outRect, outRect); Matrix.pool.release(matrix); } else { outRect.copyFrom(this.mBoundsCache); return outRect; } } else { let matrix = Matrix.pool.get(); matrix.copyFrom(this.worldTransformation); matrix.prepend(space.worldTransformationInverted); matrix.transformRect(outRect, outRect); Matrix.pool.release(matrix); } if (includeChildren === true) { let childBounds = Rectangle.pool.get(); for (let i = 0; i < this.mChildren.length; i++) { childBounds.zero(); this.mChildren[i].getBounds(space, includeChildren, childBounds); outRect.union(childBounds); } Rectangle.pool.release(childBounds); if (space == this.mParent && this.mDirty & DirtyFlag.BOUNDS) { this.mBoundsCache.copyFrom(outRect); this.mDirty ^= DirtyFlag.BOUNDS; } } return outRect; } /** * Returns stage relative bounds of this object excluding it's children; * * @param {black-engine~Rectangle=} [outRect=null] Rectangle to be store resulting bounds in. * @returns {black-engine~Rectangle} */ getStageBounds(outRect = undefined) { outRect = outRect || new Rectangle(); this.onGetLocalBounds(outRect); let matrix = Matrix.pool.get(); matrix.copyFrom(this.worldTransformation); matrix.prepend(this.stage.worldTransformationInverted); // 120ms matrix.transformRect(outRect, outRect); // 250ms Matrix.pool.release(matrix); return outRect; } /** * Evaluates whether the game object or one of its children intersects with the given point * * @param {black-engine~Vector} localPoint Coordinates vector. * @return {black-engine~GameObject|null} */ hitTest(localPoint) { let c = /** @type {InputComponent}*/ (this.getComponent(InputComponent)); let touchable = c !== null && c.touchable; let insideMask = this.onHitTestMask(localPoint); if (touchable === false || insideMask === false) return null; let target = null; let numChildren = this.mChildren.length; for (let i = numChildren - 1; i >= 0; --i) { let child = this.mChildren[i]; target = child.hitTest(localPoint); if (target !== null) return target; } if (this.onHitTest(localPoint) === true) return this; return null; } /** * @action * @protected * @param {black-engine~Vector} localPoint * @return {boolean} */ onHitTest(localPoint) { let contains = false; // BEGINOF: WTF let tmpVector = /** @type {Vector}*/ (Vector.pool.get()); this.worldTransformationInverted.transformVector(localPoint, tmpVector); // ENDOF: WTF if (this.mCollidersCache.length > 0) { for (let i = 0; i < this.mCollidersCache.length; i++) { let collider = this.mCollidersCache[i]; contains = collider.containsPoint(tmpVector); if (contains === true) return true; } } else { contains = this.localBounds.containsXY(tmpVector.x, tmpVector.y); } Vector.pool.release(tmpVector); return contains; } /** * @action * @protected * @param {black-engine~Vector} localPoint * @return {boolean} */ onHitTestMask(localPoint) { return true; } /** * Returns local bounds of this object (without children). * @returns {black-engine~Rectangle} */ get localBounds() { return this.getBounds(this, false); } /** * Returns parent-relative bounds (including children). * @returns {black-engine~Rectangle} */ get bounds() { return this.getBounds(this.mParent, true); } /** * Sets the object transform in one line. * * @param {number} [x=0] Cord X. * @param {number} [y=0] Cord Y. * @param {number} [r=0] Rotation. * @param {number} [scaleX=1] Scale X. * @param {number} [scaleY=1] Scale Y. * @param {number} [anchorX=0] Anchor X. * @param {number} [anchorY=0] Anchor Y. * @param {boolean} [includeChildren=true] Include children when adjusting pivot? * * @return {black-engine~GameObject} This. */ setTransform(x = 0, y = 0, r = 0, scaleX = 1, scaleY = 1, anchorX = 0, anchorY = 0, includeChildren = true) { this.mX = x; this.mY = y; this.mRotation = r; this.mScaleX = scaleX; this.mScaleY = scaleY; this.mAnchorX = anchorX; this.mAnchorY = anchorY; this.setTransformDirty(); return this; } /** * Calculates GameObject's position relative to another GameObject. * * @param {black-engine~GameObject} gameObject Coordinates vector. * @param {black-engine~Vector|null} [outVector=null] Vector to be returned. * @return {black-engine~Vector} */ relativeTo(gameObject, outVector = null) { outVector = outVector || new Vector(); outVector.set(this.x, this.y); if (this.parent == null || gameObject == null) return outVector; this.parent.localToGlobal(outVector, outVector); gameObject.globalToLocal(outVector, outVector); return outVector; } /** * Calculate global position of the object. * * @param {black-engine~Vector} localPoint Coordinates vector. * @param {black-engine~Vector|null} [outVector=null] Vector to be returned. * @return {black-engine~Vector} */ localToGlobal(localPoint, outVector = null) { return this.worldTransformation.transformVector(localPoint, outVector); } /** * Calculate local position of the object * * @param {black-engine~Vector} globalPoint Coordinates vector. * @param {black-engine~Vector|null} [outVector=null] Vector to be returned. * @return {black-engine~Vector} */ globalToLocal(globalPoint, outVector = null) { return this.worldTransformationInverted.transformVector(globalPoint, outVector); } /** * Gets a count of children elements. * * @return {number} */ get numChildren() { return this.mChildren.length; } /** * Gets/Sets the name of this GameObject instance. * * @return {string|null} */ get name() { return this.mName; } /** * @param {string|null} value * @return {void} */ set name(value) { this.mName = value; } /** * Gets/Sets the x coordinate of the GameObject instance relative to the local coordinates of the parent GameObject. * @return {number} */ get x() { return this.mX; } /** * @param {number} value * @return {void} */ set x(value) { if (this.mX == value) return; Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.mX = value; this.setTransformDirty(); } /** * Gets/Sets the y coordinate of the GameObject instance relative to the local coordinates of the parent GameObject. * * @return {number} */ get y() { return this.mY; } /** * @param {number} value * @return {void} */ set y(value) { if (this.mY == value) return; Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.mY = value; this.setTransformDirty(); } /** * Gets/sets object position. * * NOTE: setting individual values on this vector will give zero results. * @returns {black-engine~Vector} */ get xy() { return new Vector(this.mX, this.mY); } /** * Gets/sets object position. * * @param {black-engine~Vector} value * @returns {void} */ set xy(value) { if (this.mX === value.x && this.mY === value.y) return; this.mX = value.x; this.mY = value.y; this.setTransformDirty(); } /** * Gets/Sets the x coordinate of the object's origin in its local space in pixels. * * @return {number} */ get pivotOffsetX() { return this.mPivotOffsetX; } /** * @param {number} value * @return {void} */ set pivotOffsetX(value) { if (this.mPivotOffsetX === value) return; Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.mPivotOffsetX = value; this.__updatePivots(this); this.setTransformDirty(); } /** * Gets/Sets the y coordinate of the object's origin in its local space in pixels. * * @return {number} */ get pivotOffsetY() { return this.mPivotOffsetY; } /** * @param {number} value * @return {void} */ set pivotOffsetY(value) { if (this.mPivotOffsetY === value) return; Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.mPivotOffsetY = value; this.__updatePivots(this); this.setTransformDirty(); } /** * Gets/Sets the x-coordinate of the object's origin in its local space in percent. * * @param {number|null} value * @return {void} */ set anchorX(value) { if (this.mAnchorX === value) return; Debug.assert(value !== null && !isNaN(value), 'Value cannot be NaN'); this.mAnchorX = value; this.setTransformDirty(); } /** * Gets/Sets the y-coordinate of the object's origin in its local space in percent. * * @param {number|null} value * @return {void} */ set anchorY(value) { if (this.mAnchorY === value) return; Debug.assert(value !== null && !isNaN(value), 'Value cannot be NaN'); this.mAnchorY = value; this.setTransformDirty(); } /** * Returns current anchor-x value in range from 0 to 1. * * @returns {number|null} */ get anchorX() { return this.mAnchorX; } /** * Returns current anchor-y value in range from 0 to 1. * * @returns {number|null} */ get anchorY() { return this.mAnchorY; } /** * Returns current pivot-x value in range from 0 to 1. * * @returns {number} */ get pivotX() { return this.mPivotX; } /** * Returns current pivot-y value in range from 0 to 1. * * @returns {number} */ get pivotY() { return this.mPivotY; } /** * Sets the origin point relatively to its bounds. For example, setting x and y value to 0.5 will set origin to the * center of the object. * * @param {number} [ax=0.5] Align along x-axis. * @param {number} [ay=0.5] Align along y-axis. * * @return {black-engine~GameObject} This. */ alignAnchor(ax = 0.5, ay = 0.5) { Debug.isNumber(ax, ay); this.mAnchorX = ax; this.anchorY = ay; return this; } /** * Sets anchor point to given position. See `alignPivotOffset`. * * @deprecated * * @param {number} [ax=0.5] Align along x-axis. * @param {number} [ay=0.5] Align along y-axis. * @return {black-engine~GameObject} This. */ alignPivot(ax = 0.5, ay = 0.5) { return this.alignPivotOffset(ax, ay); } /** * Sets the origin point offset from current anchor value. For example, setting anchor-x value to 0.5 and pivotOffsetX * to 10 will center object by x-axis and will shift object to the left by 10 pixels from half of the width. * * @param {number} [ax=0.5] Align along x-axis. * @param {number} [ay=0.5] Align along y-axis. * @param {boolean} [includeChildren=true] Include children elements when calculating bounds? * * @return {black-engine~GameObject} This. */ alignPivotOffset(ax = 0.5, ay = 0.5, includeChildren = true) { Debug.isNumber(ax, ay); this.getBounds(this, includeChildren, Rectangle.__cache.zero()); this.mPivotOffsetX = (Rectangle.__cache.width * ax) + Rectangle.__cache.x; this.mPivotOffsetY = (Rectangle.__cache.height * ay) + Rectangle.__cache.y; this.__updatePivots(this); this.setTransformDirty(); return this; } /** * Gets/Sets the scale factor of this object along x-axis. * * @return {number} */ get scaleX() { return this.mScaleX; } /** * @param {number} value * * @return {void} */ set scaleX(value) { if (this.mScaleX == value) return; Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.mScaleX = value; this.setTransformDirty(); } /** * Gets/Sets the scale factor of this object along y-axis. * * * @return {number} */ get scaleY() { return this.mScaleY; } /** * @param {number} value * @return {void} */ set scaleY(value) { if (this.mScaleY == value) return; Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.mScaleY = value; this.setTransformDirty(); } /** * Gets/sets both `scaleX` and `scaleY`. Getter will return `scaleX` value; * @returns {number} */ get scale() { return this.scaleX; } /** * @param {number} value * * @returns {void} */ set scale(value) { if (this.mScaleX == value) return; Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.mScaleX = this.mScaleY = value; this.setTransformDirty(); } /** * Gets/sets horizontal skew angle in radians. * @returns {number} */ get skewX() { return this.mSkewX; } /** * @param {number} value * * @returns {void} */ set skewX(value) { if (this.mSkewX == value) return; Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.mSkewX = value; this.setTransformDirty(); } /** * Gets/sets vertical skew angle in radians. * @returns {number} */ get skewY() { return this.mSkewY; } /** * @param {number} value * * @returns {void} */ set skewY(value) { if (this.mSkewY == value) return; Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.mSkewY = value; this.setTransformDirty(); } /** * Gets/Sets rotation in radians. * * * @return {number} */ get rotation() { return this.mRotation; } /** * @param {number} value * @return {void} */ set rotation(value) { if (this.mRotation == value) return; Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.mRotation = value; this.setTransformDirty(); } /** * Returns this GameObject parent GameObject or null. * @readonly * @return {black-engine~GameObject|null} */ get parent() { return this.mParent; } /** * Returns top most parent object or this if there is no parents. * * @readonly * @return {black-engine~GameObject} */ get root() { let current = this; while (current.mParent != null) current = current.mParent; return current; } /** * Returns the stage Game Object to which this game object belongs to or null if not added on stage. * * @override * @readonly * @return {black-engine~Stage|null} */ get stage() { return this.mAdded === true ? Black.stage : null; } /** * Gets/sets the width of this object. * * @return {number} */ get width() { return this.getBounds(this.mParent).width; } /** * @param {number} value * @return {void} */ set width(value) { Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.scaleX = 1; const currentWidth = this.width; if (currentWidth != 0.0) this.scaleX = value / currentWidth; } /** * Gets/sets the height of this object. * * @return {number} */ get height() { return this.getBounds(this.mParent).height; } /** * @param {number} value * @return {void} */ set height(value) { Debug.assert(!isNaN(value), 'Value cannot be NaN'); this.scaleY = 1; const currentHeight = this.height; if (currentHeight != 0) this.scaleY = value / currentHeight; } /** * Returns width of this GameObject in local space without including children * elements. * * @readonly * @return {number} */ get localWidth() { return this.getBounds(this, false).width; } /** * Returns height of this GameObject in local space without including children * elements. * * @readonly * @return {number} */ get localHeight() { return this.getBounds(this, false).height; } // TODO: precache /** * Returns string representing a url like path to this object in the display * tree. * * @override * @readonly * @return {string|null} */ get path() { if (this.mParent !== null) return this.mParent.path + '/' + this.mName; return this.mName; } /** * Gets/Sets tag of this GameObject. * * @return {string|null} */ get tag() { return this.mTag; } /** * @param {string|null} value * @return {void} */ set tag(value) { if (this.mTag === value) return; /** @type {string|null} */ let old = this.mTag; this.mTag = value; if (this.mAdded) Black.engine.onTagUpdated(this, old, value); } /** * Starts coroutine. * * @param {Function} gen Generator function. * @param {*=} [ctx=null] Context for Generator function. * @return {*} */ spawn(gen, ctx = null) { let iter = gen.apply(ctx == null ? this : ctx); function step(it) { if (it.done) return; if (typeof it.value === 'function') it.value(x => step(iter.next(x))); else step(iter.next(it.value)); } step(iter.next()); return iter; } /** * Waits for given amount of seconds before processing. * * @param {number} [seconds=1] Duration * @return {function(*):*} */ wait(seconds = 1) { return cb => setTimeout(cb.bind(this, (/** @type {number} */(seconds) * 1000)), (/** @type {number} */(seconds) * 1000)); } /** * Waits for a specific message. * * @param {string} message The name of the message to wait for. * @return {function(*):*} */ waitMessage(message) { return cb => this.once(message, cb.bind(this)); } /** * Marks this GameObject and/or its children elements as dirty. * * @param {black-engine~DirtyFlag} flag The flag or flag bit mask. * @param {boolean} [includeChildren=true] Specifies if the flag needed for all children. * @return {void} */ setDirty(flag, includeChildren = true) { if (includeChildren) { GameObject.forEach(this, x => { x.mDirty |= flag; x.mDirtyFrameNum = Black.engine.frameNum; }); } else { this.mDirty |= flag; this.mDirtyFrameNum = Black.engine.frameNum; } Renderer.__dirty = true; } /** * @private * @ignore * @param {black-engine~GameObject} go */ __updatePivots(go) { go.getBounds(go, true, Rectangle.__cache.zero()); go.mPivotX = go.mAnchorX === null ? go.mPivotOffsetX : go.mPivotOffsetX + (Rectangle.__cache.width * go.mAnchorX) + Rectangle.__cache.x; go.mPivotY = go.mAnchorY === null ? go.mPivotOffsetY : go.mPivotOffsetY + (Rectangle.__cache.height * go.mAnchorY) + Rectangle.__cache.y; } /** * Marks the GameObject's parent as dirty. * * @param {black-engine~DirtyFlag} flag The flag or flag bit mask. * @return {void} */ setParentDirty(flag) { let current = this; while (current != null) { current.mDirty |= flag; current.mDirtyFrameNum = Black.engine.frameNum; current = current.mParent; } Renderer.__dirty = true; } /** * Marks this GameObject as Local dirty and all children elements as World dirty. * * @returns {void} */ setTransformDirty() { if (this.mSuspendDirty === true) return; this.setDirty(/** @type {DirtyFlag} */(DirtyFlag.LOCAL | DirtyFlag.BOUNDS), false); this.setDirty(DirtyFlag.WIRB, true); this.setParentDirty(/** @type {DirtyFlag} */(DirtyFlag.BOUNDS | DirtyFlag.ANCHOR)); } /** * Marks this GameObject with Render dirty flag if it is not suspended for dirty. * * @returns {void} */ setRenderDirty() { if (this.mSuspendDirty === true) return; this.setDirty(DirtyFlag.RENDER, true); } /** * @param {boolean} value * @return {void} */ set touchable(value) { let c = /** @type {InputComponent}*/ (this.getComponent(InputComponent)); if (value === true) { if (c === null) this.addComponent(new InputComponent()); else c.touchable = true; } else { if (c !== null) this.removeComponent(c); } } /** * Gets/Sets whether the object will listen for user input messages. * * @return {boolean} */ get touchable() { let c = /** @type {InputComponent} */ (this.getComponent(InputComponent)); return c !== null && c.touchable === true; } // TODO: rename method /** * @ignore * * @param {Array<number>} points * @param {black-engine~Matrix} worldTransformation * @param {black-engine~Rectangle=} outRect * @return {black-engine~Rectangle} */ static getBoundsWithPoints(points, worldTransformation, outRect) { outRect = outRect || new Rectangle(); let minX = Number.MAX_VALUE; let maxX = -Number.MAX_VALUE; let minY = Number.MAX_VALUE; let maxY = -Number.MAX_VALUE; let xx = 0; let yy = 0; let tmpVector = new Vector(); for (let i = 0; i < points.length; i += 2) { worldTransformation.transformXY(points[i], points[i + 1], tmpVector); if (minX > tmpVector.x) minX = tmpVector.x; if (maxX < tmpVector.x) maxX = tmpVector.x; if (minY > tmpVector.y) minY = tmpVector.y; if (maxY < tmpVector.y) maxY = tmpVector.y; } outRect.set(minX, minY, maxX - minX, maxY - minY); return outRect; } /** * Returns whenever a given GameObject intersects with a point. * * @param {black-engine~GameObject} gameObject GameObject to test. * @param {black-engine~Vector} point A point to test. * @return {boolean} True if intersects. */ static intersects(gameObject, point) { let tmpVector = new Vector(); let inv = gameObject.worldTransformationInverted; inv.transformVector(point, tmpVector); return gameObject.localBounds.containsXY(tmpVector.x, tmpVector.y); } /** * Returns a point where intersection were made in local space. * * @param {black-engine~GameObject} gameObject GameObject to test intersection with. * @param {black-engine~Vector} point The point to test. * @param {black-engine~Vector=} outVector If passed point of intersection will be stored in it. * @return {boolean} True if intersects. */ static intersectsAt(gameObject, point, outVector = undefined) { outVector = outVector || new Vector(); Vector.__cache.set(); gameObject.worldTransformationInverted.transformVector(point, Vector.__cache); let contains = gameObject.localBounds.containsXY(Vector.__cache.x, Vector.__cache.y); if (contains === false) return false; outVector.x = Vector.__cache.x - gameObject.localBounds.x; outVector.y = Vector.__cache.y - gameObject.localBounds.y; return true; } /** * Checks if GameObject or any of its children elements intersects the given point. * * @param {black-engine~GameObject} gameObject GameObject to test. * @param {black-engine~Vector} point Point to test. * @return {black-engine~GameObject|null} Intersecting object or null. */ static intersectsWith(gameObject, point) { let obj = null; for (let i = gameObject.numChildren - 1; i >= 0; --i) { let child = gameObject.mChildren[i]; obj = GameObject.intersectsWith(child, point); if (obj != null) return obj; let inside = GameObject.intersects(child, point); if (inside) { obj = child; break; } } if (obj === null && GameObject.intersects(gameObject, point)) return gameObject; return null; } /** * Returns all GameObject with given tag. * * @param {string} tag Tag to find. * @returns {Array<black-engine~GameObject>|null} Array of GameObject or null if not found. */ static findWithTag(tag) { if (Black.engine.mTagCache.hasOwnProperty(tag) === false) return null; return Black.engine.mTagCache[tag]; } /** * Returns a list of Components. * * @param {black-engine~GameObject} gameObject GameObject to start search from. * @param {function (new:black-engine~Component)} type Type of Component. * @return {Array<black-engine~Component>} Array of Component or empty array. */ static findComponents(gameObject, type) { Debug.assert(gameObject !== null, 'gameObject cannot be null.'); Debug.assert(type !== null, 'type cannot be null.'); /** @type {Array<Component>} */ let list = []; /** @type {function(GameObject, function(new:Component)):void} */ let f = function (gameObject, type) { for (let i = 0; i < gameObject.mComponents.length; i++) { let c = gameObject.mComponents[i]; if (c instanceof type) list.push(c); } for (let i = 0; i < gameObject.mChildren.length; i++) f(gameObject.mChildren[i], type); }; f(gameObject, type); return list; } /** * Runs action across all GameObjects. * * @param {black-engine~GameObject} gameObject GameObject to start iteration from. * @param {function(black-engine~GameObject)} action The function to be executed on every GameObject. * @return {void} */ static forEach(gameObject, action) { if (gameObject == null) gameObject = Black.stage; let r = action(gameObject); if (r === true) return; for (let i = 0; i < gameObject.mChildren.length; i++) { r = GameObject.forEach(gameObject.mChildren[i], action); if (r === true) return; } } /** * Finds object by its name. If node is not passed the root will be taken as * starting point. * * @param {string} name Name to search. * @param {black-engine~GameObject=} node Starting GameObject. * * @return {black-engine~GameObject} GameObject or null. */ static find(name, node) { if (node == null) node = Black.stage; if (node.name === name) return node; for (let i = 0; i < node.numChildren; i++) { let r = GameObject.find(name, node.getChildAt(i)); if (r != null) return r; } return null; } /** * Finds object by its id property. If node is not passed the root will be taken as * starting point. * * @param {number} id Id to search. * @param {black-engine~GameObject=} node Starting GameObject or null. * * @return {black-engine~GameObject} GameObject or null. */ static findById(id, node) { if (node == null) node = Black.stage; if (node.id === id) return node; for (let i = 0; i < node.numChildren; i++) { let r = GameObject.findById(id, node.getChildAt(i)); if (r !== null) return r; } return null; } }
JavaScript
class FlattenException { /** * Creates a new FlattenException object * * @param {Error|Exception} exception * @param {int} statusCode * @param {Object<string, string>} headers */ static create(exception, statusCode = undefined, headers = {}) { const e = new __self(); e.message = exception.message; e.code = exception.code; if (undefined === statusCode) { statusCode = Response.HTTP_INTERNAL_SERVER_ERROR; } if (exception instanceof HttpExceptionInterface) { statusCode = exception.statusCode; headers = Object.assign({}, headers, exception.headers); } else if (exception instanceof RequestExceptionInterface) { statusCode = Response.HTTP_BAD_REQUEST; } e.statusCode = statusCode; e.headers = headers; e.trace = exception instanceof Exception ? exception.stackTrace : Exception.parseStackTrace(exception); e.trace = e.trace.filter(t => { return t.file !== asyncReflection.filename; }); let className = exception.constructor.name; try { className = (new ReflectionClass(exception)).name; } catch (ex) { } e.class = className; e.file = e.trace[0].file; e.line = e.trace[0].line; if (exception.previous) { e.previous = __self.create(exception.previous); } return e; } }
JavaScript
class Composer { /** * Restrict the remote methods on the specified model class to a clean subset. * @param {*} model The model class. */ static restrictModelMethods(model) { // We now want to filter out methods that we haven't implemented or don't want. // We use a whitelist of method names to do this. let whitelist; if (model.settings.composer.abstract) { whitelist = []; } else if (model.settings.composer.type === 'concept') { whitelist = []; } else if (model.settings.composer.type === 'transaction') { whitelist = ['create', 'find', 'findById', 'exists']; } else { whitelist = ['create', 'deleteById', 'replaceById', 'find', 'findById', 'exists']; } model.sharedClass.methods().forEach((method) => { const name = (method.isStatic ? '' : 'prototype.') + method.name; if (whitelist.indexOf(name) === -1) { model.disableRemoteMethodByName(name); } else if (name === 'exists') { // We want to remove the /:id/exists method. method.http = [{verb: 'head', path: '/:id'}]; } else if (name === 'replaceById') { // We want to remove the /:id/replace method. method.http = [{verb: 'put', path: '/:id'}]; } }); } }
JavaScript
class ProductVariantService extends BaseService { static Events = { UPDATED: "product-variant.updated", CREATED: "product-variant.created", DELETED: "product-variant.deleted", } /** @param { productVariantModel: (ProductVariantModel) } */ constructor({ manager, productVariantRepository, productRepository, eventBusService, regionService, moneyAmountRepository, productOptionValueRepository, }) { super() /** @private @const {EntityManager} */ this.manager_ = manager /** @private @const {ProductVariantModel} */ this.productVariantRepository_ = productVariantRepository /** @private @const {ProductModel} */ this.productRepository_ = productRepository /** @private @const {EventBus} */ this.eventBus_ = eventBusService /** @private @const {RegionService} */ this.regionService_ = regionService this.moneyAmountRepository_ = moneyAmountRepository this.productOptionValueRepository_ = productOptionValueRepository } withTransaction(transactionManager) { if (!transactionManager) { return this } const cloned = new ProductVariantService({ manager: transactionManager, productVariantRepository: this.productVariantRepository_, productRepository: this.productRepository_, eventBusService: this.eventBus_, regionService: this.regionService_, moneyAmountRepository: this.moneyAmountRepository_, productOptionValueRepository: this.productOptionValueRepository_, }) cloned.transactionManager_ = transactionManager return cloned } /** * Gets a product variant by id. * @param {string} variantId - the id of the product to get. * @return {Promise<Product>} the product document. */ async retrieve(variantId, config = {}) { const variantRepo = this.manager_.getCustomRepository( this.productVariantRepository_ ) const validatedId = this.validateId_(variantId) const query = this.buildQuery_({ id: validatedId }, config) const variant = await variantRepo.findOne(query) if (!variant) { throw new MedusaError( MedusaError.Types.NOT_FOUND, `Variant with id: ${variantId} was not found` ) } return variant } /** * Gets a product variant by id. * @param {string} variantId - the id of the product to get. * @return {Promise<Product>} the product document. */ async retrieveBySKU(sku, config = {}) { const variantRepo = this.manager_.getCustomRepository( this.productVariantRepository_ ) const query = this.buildQuery_({ sku }, config) const variant = await variantRepo.findOne(query) if (!variant) { throw new MedusaError( MedusaError.Types.NOT_FOUND, `Variant with sku: ${sku} was not found` ) } return variant } /** * Creates an unpublished product variant. Will validate against parent product * to ensure that the variant can in fact be created. * @param {string} productOrProductId - the product the variant will be added to * @param {object} variant - the variant to create * @return {Promise} resolves to the creation result. */ async create(productOrProductId, variant) { return this.atomicPhase_(async (manager) => { const productRepo = manager.getCustomRepository(this.productRepository_) const variantRepo = manager.getCustomRepository( this.productVariantRepository_ ) const { prices, ...rest } = variant let product = productOrProductId if (typeof product === `string`) { product = await productRepo.findOne({ where: { id: productOrProductId }, relations: ["variants", "variants.options", "options"], }) } else if (!product.id) { throw new MedusaError( MedusaError.Types.INVALID_DATA, `Product id missing` ) } if (product.options.length !== variant.options.length) { throw new MedusaError( MedusaError.Types.INVALID_DATA, `Product options length does not match variant options length. Product has ${product.options.length} and variant has ${variant.options.length}.` ) } product.options.forEach((option) => { if (!variant.options.find((vo) => option.id === vo.option_id)) { throw new MedusaError( MedusaError.Types.INVALID_DATA, `Variant options do not contain value for ${option.title}` ) } }) let variantExists = undefined variantExists = product.variants.find((v) => { return v.options.every((option) => { const variantOption = variant.options.find( (o) => option.option_id === o.option_id ) return option.value === variantOption.value }) }) if (variantExists) { throw new MedusaError( MedusaError.Types.DUPLICATE_ERROR, `Variant with title ${variantExists.title} with provided options already exists` ) } if (!rest.variant_rank) { rest.variant_rank = product.variants.length } const toCreate = { ...rest, product_id: product.id, } const productVariant = await variantRepo.create(toCreate) const result = await variantRepo.save(productVariant) if (prices) { for (const price of prices) { if (price.region_id) { await this.setRegionPrice( result.id, price.region_id, price.amount, price.sale_amount || undefined ) } else { await this.setCurrencyPrice(result.id, price) } } } await this.eventBus_ .withTransaction(manager) .emit(ProductVariantService.Events.CREATED, { id: result.id, product_id: result.product_id, }) return result }) } /** * Publishes an existing variant. * @param {string} variantId - id of the variant to publish. * @return {Promise} */ async publish(variantId) { return this.atomicPhase_(async (manager) => { const variantRepo = manager.getCustomRepository( this.productVariantRepository_ ) const variant = await this.retrieve(variantId) variant.published = true const result = await variantRepo.save(variant) await this.eventBus_ .withTransaction(manager) .emit(ProductVariantService.Events.UPDATED, { id: result.id, product_id: result.product_id, }) return result }) } /** * Updates a variant. * Price updates should use dedicated methods. * The function will throw, if price updates are attempted. * @param {string | ProductVariant} variant - the id of the variant. Must be a * string that can be casted to an ObjectId * @param {object} update - an object with the update values. * @return {Promise} resolves to the update result. */ async update(variantOrVariantId, update) { return this.atomicPhase_(async (manager) => { const variantRepo = manager.getCustomRepository( this.productVariantRepository_ ) let variant = variantOrVariantId if (typeof variant === `string`) { variant = await this.retrieve(variantOrVariantId) } else if (!variant.id) { throw new MedusaError( MedusaError.Types.INVALID_DATA, `Variant id missing` ) } const { prices, options, metadata, inventory_quantity, ...rest } = update if (prices) { for (const price of prices) { if (price.region_id) { await this.setRegionPrice( variant.id, price.region_id, price.amount, price.sale_amount || undefined ) } else { await this.setCurrencyPrice(variant.id, price) } } } if (options) { for (const option of options) { await this.updateOptionValue( variant.id, option.option_id, option.value ) } } if (metadata) { variant.metadata = this.setMetadata_(variant, metadata) } if (typeof inventory_quantity === "number") { variant.inventory_quantity = inventory_quantity } for (const [key, value] of Object.entries(rest)) { variant[key] = value } const result = await variantRepo.save(variant) await this.eventBus_ .withTransaction(manager) .emit(ProductVariantService.Events.UPDATED, { id: result.id, product_id: result.product_id, fields: Object.keys(update), }) return result }) } /** * Sets the default price for the given currency. * @param {string} variantId - the id of the variant to set prices for * @param {string} currencyCode - the currency to set prices for * @param {number} amount - the amount to set the price to * @param {number} saleAmount - the sale amount to set the price to * @return {Promise} the result of the update operation */ async setCurrencyPrice(variantId, price) { return this.atomicPhase_(async (manager) => { const moneyAmountRepo = manager.getCustomRepository( this.moneyAmountRepository_ ) let moneyAmount moneyAmount = await moneyAmountRepo.findOne({ where: { currency_code: price.currency_code.toLowerCase(), variant_id: variantId, region_id: IsNull(), }, }) if (!moneyAmount) { moneyAmount = await moneyAmountRepo.create({ ...price, currency_code: price.currency_code.toLowerCase(), variant_id: variantId, }) } else { moneyAmount.amount = price.amount moneyAmount.sale_amount = price.sale_amount } const result = await moneyAmountRepo.save(moneyAmount) return result }) } /** * Gets the price specific to a region. If no region specific money amount * exists the function will try to use a currency price. If no default * currency price exists the function will throw an error. * @param {string} variantId - the id of the variant to get price from * @param {string} regionId - the id of the region to get price for * @return {number} the price specific to the region */ async getRegionPrice(variantId, regionId) { return this.atomicPhase_(async (manager) => { const moneyAmountRepo = manager.getCustomRepository( this.moneyAmountRepository_ ) const region = await this.regionService_ .withTransaction(manager) .retrieve(regionId) // Find region price based on region id let moneyAmount = await moneyAmountRepo.findOne({ where: { region_id: regionId, variant_id: variantId }, }) // If no price could be find based on region id, we try to fetch // based on the region currency code if (!moneyAmount) { moneyAmount = await moneyAmountRepo.findOne({ where: { variant_id: variantId, currency_code: region.currency_code }, }) } // Still, if no price is found, we throw if (!moneyAmount) { throw new MedusaError( MedusaError.Types.NOT_FOUND, `A price for region: ${region.name} could not be found` ) } // Always return sale price, if present if (moneyAmount.sale_amount) { return moneyAmount.sale_amount } else { return moneyAmount.amount } }) } /** * Sets the price of a specific region * @param {string} variantId - the id of the variant to update * @param {string} regionId - the id of the region to set price for * @param {number} amount - the amount to set the price to * @param {number} saleAmount - the sale amount to set the price to * @return {Promise} the result of the update operation */ async setRegionPrice(variantId, price) { return this.atomicPhase_(async (manager) => { const moneyAmountRepo = manager.getCustomRepository( this.moneyAmountRepository_ ) let moneyAmount moneyAmount = await moneyAmountRepo.findOne({ where: { variant_id: variantId, region_id: price.region_id, }, }) if (!moneyAmount) { moneyAmount = await moneyAmountRepo.create({ ...price, variant_id: variantId, }) } else { moneyAmount.amount = price.amount moneyAmount.sale_amount = price.sale_amount } const result = await moneyAmountRepo.save(moneyAmount) return result }) } /** * Updates variant's option value. * Option value must be of type string or number. * @param {string} variantId - the variant to decorate. * @param {string} optionId - the option from product. * @param {string | number} optionValue - option value to add. * @return {Promise} the result of the update operation. */ async updateOptionValue(variantId, optionId, optionValue) { return this.atomicPhase_(async (manager) => { const productOptionValueRepo = manager.getCustomRepository( this.productOptionValueRepository_ ) const productOptionValue = await productOptionValueRepo.findOne({ where: { variant_id: variantId, option_id: optionId }, }) if (!productOptionValue) { throw new MedusaError( MedusaError.Types.NOT_FOUND, `Product option value not found` ) } productOptionValue.value = optionValue const result = await productOptionValueRepo.save(productOptionValue) return result }) } /** * Adds option value to a varaint. * Fails when product with variant does not exists or * if that product does not have an option with the given * option id. Fails if given variant is not found. * Option value must be of type string or number. * @param {string} variantId - the variant to decorate. * @param {string} optionId - the option from product. * @param {string | number} optionValue - option value to add. * @return {Promise} the result of the update operation. */ async addOptionValue(variantId, optionId, optionValue) { return this.atomicPhase_(async (manager) => { const productOptionValueRepo = manager.getCustomRepository( this.productOptionValueRepository_ ) const productOptionValue = await productOptionValueRepo.create({ variant_id: variantId, option_id: optionId, value: optionValue, }) const result = await productOptionValueRepo.save(productOptionValue) return result }) } /** * Deletes option value from given variant. * Will never fail due to delete being idempotent. * @param {string} variantId - the variant to decorate. * @param {string} optionId - the option from product. * @return {Promise} empty promise */ async deleteOptionValue(variantId, optionId) { return this.atomicPhase_(async (manager) => { const productOptionValueRepo = manager.getCustomRepository( this.productOptionValueRepository_ ) const productOptionValue = await productOptionValueRepo.findOne({ where: { variant_id: variantId, option_id: optionId, }, }) if (!productOptionValue) return Promise.resolve() await productOptionValueRepo.softRemove(productOptionValue) return Promise.resolve() }) } /** * @param {Object} selector - the query object for find * @return {Promise} the result of the find operation */ async list(selector = {}, config = { relations: [], skip: 0, take: 20 }) { const productVariantRepo = this.manager_.getCustomRepository( this.productVariantRepository_ ) let q if ("q" in selector) { q = selector.q delete selector.q } const query = this.buildQuery_(selector, config) if (q) { const where = query.where delete where.sku delete where.title query.join = { alias: "variant", innerJoin: { product: "variant.product", }, } query.where = (qb) => { qb.where(where).andWhere([ { sku: ILike(`%${q}%`) }, { title: ILike(`%${q}%`) }, { product: { title: ILike(`%${q}%`) } }, ]) } } return productVariantRepo.find(query) } /** * Deletes variant. * Will never fail due to delete being idempotent. * @param {string} variantId - the id of the variant to delete. Must be * castable as an ObjectId * @return {Promise} empty promise */ async delete(variantId) { return this.atomicPhase_(async (manager) => { const variantRepo = manager.getCustomRepository( this.productVariantRepository_ ) const variant = await variantRepo.findOne({ where: { id: variantId } }) if (!variant) return Promise.resolve() await variantRepo.softRemove(variant) await this.eventBus_ .withTransaction(manager) .emit(ProductVariantService.Events.DELETED, { id: variant.id, product_id: variant.product_id, }) return Promise.resolve() }) } /** * Dedicated method to set metadata for a variant. * @param {string} variant - the variant to set metadata for. * @param {Object} metadata - the metadata to set * @return {Object} updated metadata object */ setMetadata_(variant, metadata) { const existing = variant.metadata || {} const newData = {} for (const [key, value] of Object.entries(metadata)) { if (typeof key !== "string") { throw new MedusaError( MedusaError.Types.INVALID_ARGUMENT, "Key type is invalid. Metadata keys must be strings" ) } newData[key] = value } const updated = { ...existing, ...newData, } return updated } }
JavaScript
class AssetsCallBuilder extends CallBuilder { constructor(serverUrl) { super(serverUrl); this.url.segment('assets'); } /** * This endpoint filters all assets by the asset code. * @param {string} value For example: `USD` * @returns {AssetsCallBuilder} */ forCode(value){ this.url.addQuery("asset_code", value); return this; } /** * This endpoint filters all assets by the asset issuer. * @param {string} value For example: `GDGQVOKHW4VEJRU2TETD6DBRKEO5ERCNF353LW5WBFW3JJWQ2BRQ6KDD` * @returns {AssetsCallBuilder} */ forIssuer(value){ this.url.addQuery("asset_issuer", value); return this; } }
JavaScript
class PriceInternalApi { /** * Constructs a new PriceInternalApi. * @alias module:internal/PriceInternalApi * @class * @param {module:ApiClient} [apiClient] Optional API client implementation to use, * default to {@link module:ApiClient#instance} if unspecified. */ constructor(apiClient) { this.apiClient = apiClient || ApiClient.instance; } /** * SeminarCatalog\\Rest\\Resources\\Controller\\ResourceController::create * @param {module:model/Price} pricePost * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/Price} and HTTP response */ priceCreateWithHttpInfo(pricePost) { let postBody = pricePost; // verify the required parameter 'pricePost' is set if (pricePost === undefined || pricePost === null) { throw new Error("Missing the required parameter 'pricePost' when calling priceCreate"); } let pathParams = { }; let queryParams = { }; let headerParams = { }; let formParams = { }; let authNames = []; let contentTypes = []; let accepts = []; let returnType = Price; return this.apiClient.callApi( '/api/price', 'POST', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * SeminarCatalog\\Rest\\Resources\\Controller\\ResourceController::create * @param {module:model/Price} pricePost * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Price} */ priceCreate(pricePost) { return this.priceCreateWithHttpInfo(pricePost) .then(function(response_and_data) { return response_and_data.data; }); } /** * SeminarCatalog\\Rest\\Resources\\Controller\\ResourceController::delete * @param {Number} id Numeric identifier for this resource * @param {Number} lng Numeric identifier for this resource * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/Price} and HTTP response */ priceDeleteWithHttpInfo(id, lng) { let postBody = null; // verify the required parameter 'id' is set if (id === undefined || id === null) { throw new Error("Missing the required parameter 'id' when calling priceDelete"); } // verify the required parameter 'lng' is set if (lng === undefined || lng === null) { throw new Error("Missing the required parameter 'lng' when calling priceDelete"); } let pathParams = { 'id': id, 'lng': lng }; let queryParams = { }; let headerParams = { }; let formParams = { }; let authNames = []; let contentTypes = []; let accepts = []; let returnType = Price; return this.apiClient.callApi( '/api/price/{id}/{lng}', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * SeminarCatalog\\Rest\\Resources\\Controller\\ResourceController::delete * @param {Number} id Numeric identifier for this resource * @param {Number} lng Numeric identifier for this resource * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Price} */ priceDelete(id, lng) { return this.priceDeleteWithHttpInfo(id, lng) .then(function(response_and_data) { return response_and_data.data; }); } /** * SeminarCatalog\\Rest\\Resources\\Controller\\ResourceController::get * @param {Number} id Numeric identifier for this resource * @param {Number} lng Numeric identifier for this resource * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/Price} and HTTP response */ priceGetWithHttpInfo(id, lng) { let postBody = null; // verify the required parameter 'id' is set if (id === undefined || id === null) { throw new Error("Missing the required parameter 'id' when calling priceGet"); } // verify the required parameter 'lng' is set if (lng === undefined || lng === null) { throw new Error("Missing the required parameter 'lng' when calling priceGet"); } let pathParams = { 'id': id, 'lng': lng }; let queryParams = { }; let headerParams = { }; let formParams = { }; let authNames = []; let contentTypes = []; let accepts = []; let returnType = Price; return this.apiClient.callApi( '/api/price/{id}/{lng}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * SeminarCatalog\\Rest\\Resources\\Controller\\ResourceController::get * @param {Number} id Numeric identifier for this resource * @param {Number} lng Numeric identifier for this resource * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Price} */ priceGet(id, lng) { return this.priceGetWithHttpInfo(id, lng) .then(function(response_and_data) { return response_and_data.data; }); } /** * SeminarCatalog\\Rest\\Resources\\Controller\\ResourceController::list * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/PricePaginationResult} and HTTP response */ priceListWithHttpInfo() { let postBody = null; let pathParams = { }; let queryParams = { }; let headerParams = { }; let formParams = { }; let authNames = []; let contentTypes = []; let accepts = []; let returnType = PricePaginationResult; return this.apiClient.callApi( '/api/price', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * SeminarCatalog\\Rest\\Resources\\Controller\\ResourceController::list * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PricePaginationResult} */ priceList() { return this.priceListWithHttpInfo() .then(function(response_and_data) { return response_and_data.data; }); } /** * SeminarCatalog\\Rest\\Resources\\Controller\\ResourceController::update * @param {Number} id The resource identifier * @param {module:model/Price} pricePut * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/Price} and HTTP response */ priceUpdateWithHttpInfo(id, pricePut) { let postBody = pricePut; // verify the required parameter 'id' is set if (id === undefined || id === null) { throw new Error("Missing the required parameter 'id' when calling priceUpdate"); } // verify the required parameter 'pricePut' is set if (pricePut === undefined || pricePut === null) { throw new Error("Missing the required parameter 'pricePut' when calling priceUpdate"); } let pathParams = { 'id': id }; let queryParams = { }; let headerParams = { }; let formParams = { }; let authNames = []; let contentTypes = []; let accepts = []; let returnType = Price; return this.apiClient.callApi( '/api/price/{id}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * SeminarCatalog\\Rest\\Resources\\Controller\\ResourceController::update * @param {Number} id The resource identifier * @param {module:model/Price} pricePut * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Price} */ priceUpdate(id, pricePut) { return this.priceUpdateWithHttpInfo(id, pricePut) .then(function(response_and_data) { return response_and_data.data; }); } }
JavaScript
class SearchBar extends Component{ // Defines a search property type string in the state constructor() { super(); this.state = { search: '' }; }; // Listening to the search bar and limiting the string length to 70 characters. updateSearch(event){ this.setState({search: event.target.value.substr(0,70)}); }; render(){ // load json with list of cities let cities = require('../cityList'); // fiter list of city with the string from the searchbar let filteredCities = cities.filter( (city) => { return city.name.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1; } ); return( <div className="col-10"> <form className="card card-sm"> <div className="card-body row no-gutters align-items-center searchCard"> <div className="col-1"> <i className="fas fa-search h4 text-body"></i> </div> <div className="col-8"> <input className="form-control form-control-lg form-control-borderless inputBar" type="search" value={this.state.search} onChange={this.updateSearch.bind(this)} placeholder="Search (Example: London)" /> </div> </div> </form> <div className="row buttonRow"> <div className="col-4"> <Button city={this.state.search === '' ? null : filteredCities} searchType="weather" description="Today"/> </div> <div className="textSpan"> <span className="font-weight-bold">OR</span> </div> <div className="col-4"> <Button city={this.state.search === '' ? null : filteredCities} searchType="forecast" description="5 Days"/> </div> </div> </div> ) } }
JavaScript
class Foo { x = this static t = this static at = () => this static ft = function () { return this } static mt() { return this } }
JavaScript
class FakeMissingTranslationHandler { /** * @param {?} params * @return {?} */ handle(params) { return params.key; } }
JavaScript
class LikeService { /** * @description saves a like * @param {object} like * @returns {object} it returns the saved object */ static async saveLike(like) { const savedLike = await Like.create(like); return savedLike; } /** * @description find like based on proverbId and likedBy * @param {integer} proverbId * @param {string} likedBy * @returns {object} it returns the object if found */ static async findLikeByProverbIdAndlikedBy(proverbId, likedBy) { const like = await Like.findOne({ where: { proverbId, likedBy } }); return like; } /** * @description delete a like * @param {integer} proverbId * @param {string} likedBy * @returns {null} it returns void */ static async deleteLike(proverbId, likedBy) { await Like.destroy({ where: { proverbId, likedBy } }); } }
JavaScript
class APITool { /** * Enum for authentication. * @readonly * @enum {number} */ static get Auth() { return { /** Use Basic username and password credentials. */ Basic: 0, /** Use an authentication token. */ Token: 1, /** Do not use authentication. */ None: 2 } } /** * Create a new API Tool. * @constructor * @param [config] {APITool~Config} - The configuration to use for the API tool. */ constructor(config = DEFAULT_CONFIG) { this.host = config.host; this.username = config.username; this.password = config.password; this.proxy = config.proxy; this.endpoints = config.endpoints; } /** * Get the Basic authorization header from the provided username and password. * @return {string} - The Basic authorization header. */ get basicAuthorization() { return 'Basic ' + Buffer.from(`${this.username}:${this.password}`).toString('base64'); } /** * Get the Authorization header for the specified authentication type. * @async * @param authType {Auth} - The type of authentication that should be performed. * @return {Promise.<string|null>} */ async getAuthorizationHeader (authType) { switch(authType) { case APITool.Auth.Basic: return this.basicAuthorization; case APITool.Auth.Token: return await this.getToken(); case APITool.Auth.None: return null; default: return null; } } /** * Make a request to the API. * @async * @mixin * @param method {'GET'|'POST'|'PUT'|'PATCH'|'DELETE'} - The HTTP method to use for the request. * @param endpoint {string} - The endpoint to request. * @param [authType] {Auth} - The authentication type to use against the endpoint. * @param [options] {object} - An object containing additional data to pass in the request. * @return {Promise.<*>} - The JSON response from the API, or an error if one occurred. */ async request (method = 'GET', endpoint, authType = APITool.Auth.Token, options = {}) { options.method = method; options.url = Path.join(this.host, endpoint); options.json = true; if(!options.headers) options.headers = {}; options.headers.Accept = 'application/json'; options.headers.Authorization = await this.getAuthorizationHeader(authType); if(this.proxy) { options.proxy = this.proxy; options.strictSSL = false; } return await Request(options); }; /** * Make a GET request to the API. * @mixes request * @param endpoint {string} - The endpoint to request. * @param [authType = Auth.Token] {Auth} - The authentication type to use against the endpoint. * @param [options] {object} - An object containing additional data to pass in the request. * @return {Promise.<*>} - The JSON response from the API, or an error if one occurred. * @see request */ doGet(endpoint, authType, options) { return this.request('GET', endpoint, authType, options) } /** * Make a POST request to the API. * @mixes request * @param endpoint {string} - The endpoint to request. * @param [authType = Auth.Token] {Auth} - The authentication type to use against the endpoint. * @param [options] {object} - An object containing additional data to pass in the request. * @return {Promise.<*>} - The JSON response from the API, or an error if one occurred. * @see request */ doPost(endpoint, authType, options) { return this.request('POST', endpoint, authType, options) } /** * Make a PUT request to the API. * @mixes request * @param endpoint {string} - The endpoint to request. * @param [authType = Auth.Token] {Auth} - The authentication type to use against the endpoint. * @param [options] {object} - An object containing additional data to pass in the request. * @return {Promise.<*>} - The JSON response from the API, or an error if one occurred. * @see request */ doPut(endpoint, authType, options) { return this.request('PUT', endpoint, authType, options) } /** * Make a PATCH request to the API. * @mixes request * @param endpoint {string} - The endpoint to request. * @param [authType = Auth.Token] {Auth} - The authentication type to use against the endpoint. * @param [options] {object} - An object containing additional data to pass in the request. * @return {Promise.<*>} - The JSON response from the API, or an error if one occurred. * @see request */ doPatch(endpoint, authType, options) { return this.request('PATCH', endpoint, authType, options) } /** * Make a DELETE request to the API. * @mixes request * @param endpoint {string} - The endpoint to request. * @param [authType = Auth.Token] {Auth} - The authentication type to use against the endpoint. * @param [options] {object} - An object containing additional data to pass in the request. * @return {Promise.<*>} - The JSON response from the API, or an error if one occurred. * @see request */ doDelete(endpoint, authType, options) { return this.request('DELETE', endpoint, authType, options) } /** * Get the API token for authenticated requests. * @return {Promise.<string>} - The API token, or an error if one occurred. */ async getToken() { if(this._token) return this._token; const response = await this.doPost(this.endpoints.token, APITool.Auth.Basic); // This needs to be adjusted to the specific API implementation. this._token = response.token; return this._token; }; }
JavaScript
class Stagger { /** * Returns a callback function to be used in setTimeout * @param {Array<HTMLElement>} elms * @param {number} i start index * @param {number} j end index */ static showElement(elms, i, j) { if (!elms[i] || i > j) { return } const that = this let c // after animation starts, // animate next element elms[i].addEventListener( 'animationstart', (c = function(e) { if (e.animationName === 'springFadeUp') { setTimeout(() => { that.showElement(elms, i + 1, j) // remove listener this.removeEventListener('animationstart', c) }, 20) } }) ) let c2 elms[i].addEventListener( 'animationend', (c2 = function() { this.classList.replace('stagger-appear', 'stagger-appear-fix') this.removeEventListener('animationstart', c2) }) ) // add a classname that will trigger the animation elms[i].classList.add('stagger-appear') } /** * Show elements by adding classnames sequentially * @param {Array<HTMLElement>} elms */ static show(elms, hasParent = false) { if (!elms || elms.length === 0) { return } // forward // add fixed class name ('stagger-appear-fix' -> opacity: 0) // to the elements which are not in the viewport let i = 0 for (; i < elms.length; i++) { let boundaryTarget = elms[i] if (hasParent) { boundaryTarget = elms[i].parentElement } const rect = boundaryTarget.getBoundingClientRect() const top = rect.top const bottom = rect.bottom if ( (top < 0 && bottom < 0) || (top > window.innerHeight && bottom > window.innerHeight) ) { elms[i].classList.add('stagger-appear-fix') } else { break } } // backward let j = elms.length - 1 for (; j >= 0; j--) { let boundaryTarget = elms[j] if (hasParent) { boundaryTarget = elms[j].parentElement } const rect = boundaryTarget.getBoundingClientRect() const top = rect.top const bottom = rect.bottom if ( (top < 0 && bottom < 0) || (top > window.innerHeight && bottom > window.innerHeight) ) { elms[j].classList.add('stagger-appear-fix') } else { break } } // start animation on elements that are in the viewport this.showElement(elms, i, j) } /** * Hide elements by removing classnames * @param {Array<HTMLElement>} elms */ static hide(elms) { if (!elms || elms.length === 0) { return } elms.forEach((elm) => { elm.classList.remove('stagger-appear') elm.classList.remove('stagger-appear-fix') }) } }
JavaScript
class Response { constructor() { let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; Body.call(this, body, opts); const status = opts.status || 200; const headers = new Headers(opts.headers); if (body != null && !headers.has('Content-Type')) { const contentType = extractContentType(body); if (contentType) { headers.append('Content-Type', contentType); } } this[INTERNALS$1] = { url: opts.url, status, statusText: opts.statusText || STATUS_CODES[status], headers, counter: opts.counter }; } get url() { return this[INTERNALS$1].url || ''; } get status() { return this[INTERNALS$1].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; } get redirected() { return this[INTERNALS$1].counter > 0; } get statusText() { return this[INTERNALS$1].statusText; } get headers() { return this[INTERNALS$1].headers; } /** * Clone this response * * @return Response */ clone() { return new Response(clone(this), { url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected }); } }
JavaScript
class Request { constructor(input) { let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let parsedURL; // normalize input if (!isRequest(input)) { if (input && input.href) { // in order to support Node.js' Url objects; though WHATWG's URL objects // will fall into this branch also (since their `toString()` will return // `href` property anyway) parsedURL = parse_url(input.href); } else { // coerce input to a string before attempting to parse parsedURL = parse_url(`${input}`); } input = {}; } else { parsedURL = parse_url(input.url); } let method = init.method || input.method || 'GET'; method = method.toUpperCase(); if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { throw new TypeError('Request with GET/HEAD method cannot have body'); } let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; Body.call(this, inputBody, { timeout: init.timeout || input.timeout || 0, size: init.size || input.size || 0 }); const headers = new Headers(init.headers || input.headers || {}); if (inputBody != null && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody); if (contentType) { headers.append('Content-Type', contentType); } } let signal = isRequest(input) ? input.signal : null; if ('signal' in init) signal = init.signal; if (signal != null && !isAbortSignal(signal)) { throw new TypeError('Expected signal to be an instanceof AbortSignal'); } this[INTERNALS$2] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal }; // node-fetch-only options this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; this.counter = init.counter || input.counter || 0; this.agent = init.agent || input.agent; } get method() { return this[INTERNALS$2].method; } get url() { return format_url(this[INTERNALS$2].parsedURL); } get headers() { return this[INTERNALS$2].headers; } get redirect() { return this[INTERNALS$2].redirect; } get signal() { return this[INTERNALS$2].signal; } /** * Clone this request * * @return Request */ clone() { return new Request(this); } }
JavaScript
class Compact { #Type; #raw; constructor(registry, Type, value = 0) { this.registry = registry; this.#Type = typeToConstructor(registry, Type); const [raw, decodedLength] = Compact.decodeCompact(registry, this.#Type, value); this.initialU8aLength = decodedLength; this.#raw = raw; } static with(Type) { return class extends Compact { constructor(registry, value) { super(registry, Type, value); } }; } /** @internal */ static decodeCompact(registry, Type, value) { if (value instanceof Compact) { return [new Type(registry, value.#raw), 0]; } else if (value instanceof Type) { return [value, 0]; } else if (isString(value) || isNumber(value) || isBn(value) || isBigInt(value)) { return [new Type(registry, value), 0]; } const [decodedLength, bn] = compactFromU8a(value); return [new Type(registry, bn), decodedLength]; } /** * @description The length of the value when encoded as a Uint8Array */ get encodedLength() { return this.toU8a().length; } /** * @description returns a hash of the contents */ get hash() { return this.registry.hash(this.toU8a()); } /** * @description Checks if the value is an empty value */ get isEmpty() { return this.#raw.isEmpty; } /** * @description Returns the number of bits in the value */ bitLength() { return this.#raw.bitLength(); } /** * @description Compares the value of the input to see if there is a match */ eq(other) { return this.#raw.eq(other instanceof Compact ? other.#raw : other); } /** * @description Returns a BigInt representation of the number */ toBigInt() { return this.#raw.toBigInt(); } /** * @description Returns the BN representation of the number */ toBn() { return this.#raw.toBn(); } /** * @description Returns a hex string representation of the value. isLe returns a LE (number-only) representation */ toHex(isLe) { return this.#raw.toHex(isLe); } /** * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information */ toHuman(isExtended) { return this.#raw.toHuman(isExtended); } /** * @description Converts the Object to JSON, typically used for RPC transfers */ toJSON() { return this.#raw.toJSON(); } /** * @description Returns the number representation for the value */ toNumber() { return this.#raw.toNumber(); } /** * @description Returns the base runtime type name for this instance */ toRawType() { return `Compact<${this.registry.getClassName(this.#Type) || this.#raw.toRawType()}>`; } /** * @description Returns the string representation of the value */ toString() { return this.#raw.toString(); } /** * @description Encodes the value as a Uint8Array as per the SCALE specifications * @param isBare true when the value has none of the type-specific prefixes (internal) */ // eslint-disable-next-line @typescript-eslint/no-unused-vars toU8a(isBare) { return compactToU8a(this.#raw.toBn()); } /** * @description Returns the embedded [[UInt]] or [[Moment]] value */ unwrap() { return this.#raw; } }
JavaScript
class LocationMap extends Component{ // Map = ReactMapboxGl({ // accessToken: // 'undefined' // }); render(){ return( <section class="section map-section"> <div class="container"> <div class="row"> <div class="col-12"> <h4 class="section__title map-section__title">We Got you covered in these Four states</h4> <div id="map" class="map map-section__grid"> {/* <Map className="map map-section__grid" style="mapbox://styles/mapbox/streets-v9"> <Layer type="symbol" id="marker" layout={{ 'icon-image': 'marker-15' }}> <Feature coordinates={[-0.481747846041145, 51.3233379650232]} /> </Layer> </Map> */} </div> </div> </div> </div> </section> ) } }
JavaScript
class InboxPage extends Component { render() { return ( <Container> <Content style={{backgroundColor: 'white'}}> <List> <View style={{marginLeft: 20, marginTop: 25}}> <View style={{flex: 1, flexDirection: 'row'}}> <View style={{ width: 50, height: 50, backgroundColor:'#959595', marginTop: 5, borderRadius: 50 }} /> <View style={{flex: 1, flexDirection: 'column', marginLeft: 15}}> <View style={{flex: 1, flexDirection: 'row'}}> <Text style={{fontWeight: 'bold', marginBottom: 5}}>Gabriel</Text> <Text style={{position: 'absolute', right: 20, color: "#959595"}}>4 hours ago</Text> </View> <Text numberOfLines={2} style={{width: 280, overflow: 'hidden'}}>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tempor felis mauris, et dignissim lorem sagittis non.</Text> </View> </View> <View style={{flex: 1, flexDirection: 'row', marginTop: 25}}> <View style={{ width: 50, height: 50, backgroundColor:'#959595', marginTop: 5, borderRadius: 50 }} /> <View style={{flex: 1, flexDirection: 'column', marginLeft: 15}}> <View style={{flex: 1, flexDirection: 'row'}}> <Text style={{fontWeight: 'bold', marginBottom: 5}}>Nick</Text> <Text style={{position: 'absolute', right: 20, color: "#959595"}}>12 hours ago</Text> </View> <Text numberOfLines={2} style={{width: 280, overflow: 'hidden'}}>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tempor felis mauris, et dignissim lorem sagittis non.</Text> </View> </View> <View style={{flex: 1, flexDirection: 'row', marginTop: 25}}> <View style={{ width: 50, height: 50, backgroundColor:'#959595', marginTop: 5, borderRadius: 50 }} /> <View style={{flex: 1, flexDirection: 'column', marginLeft: 15}}> <View style={{flex: 1, flexDirection: 'row'}}> <Text style={{fontWeight: 'bold', marginBottom: 5}}>Max</Text> <Text style={{position: 'absolute', right: 20, color: "#959595"}}>1 day ago</Text> </View> <Text numberOfLines={2} style={{width: 280, overflow: 'hidden'}}>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tempor felis mauris, et dignissim lorem sagittis non.</Text> </View> </View> <View style={{flex: 1, flexDirection: 'row', marginTop: 25}}> <View style={{ width: 50, height: 50, backgroundColor:'#959595', marginTop: 5, borderRadius: 50 }} /> <View style={{flex: 1, flexDirection: 'column', marginLeft: 15}}> <View style={{flex: 1, flexDirection: 'row'}}> <Text style={{fontWeight: 'bold', marginBottom: 5}}>Christine</Text> <Text style={{position: 'absolute', right: 20, color: "#959595"}}>2 days ago</Text> </View> <Text numberOfLines={2} style={{width: 280, overflow: 'hidden'}}>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tempor felis mauris, et dignissim lorem sagittis non.</Text> </View> </View> </View> </List> </Content> </Container> ); } }
JavaScript
class NbLayoutScrollService { constructor() { this.scrollPositionReq$ = new Subject(); this.manualScroll$ = new Subject(); this.scroll$ = new Subject(); this.scrollable$ = new Subject(); } /** * Returns scroll position * * @returns {Observable<NbScrollPosition>} */ getPosition() { return Observable.create((observer) => { const listener = new Subject(); listener.subscribe(observer); this.scrollPositionReq$.next({ listener }); return () => listener.complete(); }); } /** * Sets scroll position * * @param {number} x * @param {number} y */ scrollTo(x = null, y = null) { this.manualScroll$.next({ x, y }); } /** * Returns a stream of scroll events * * @returns {Observable<any>} */ onScroll() { return this.scroll$.pipe(share()); } /** * @private * @returns Observable<NbScrollPosition>. */ onManualScroll() { return this.manualScroll$.pipe(share()); } /** * @private * @returns {Subject<any>} */ onGetPosition() { return this.scrollPositionReq$; } onScrollableChange() { return this.scrollable$.pipe(share()); } /** * @private * @param {any} event */ fireScrollChange(event) { this.scroll$.next(event); } scrollable(scrollable) { this.scrollable$.next(scrollable); } }
JavaScript
class configParser { /** * Creates an instance of configParser. * * @param {object} config A config object. * * @memberOf configParser */ constructor(config) { this.config = config; this.args = minimist(process.argv.slice(2), require('./cliOptions')); } /** * The active theme from configuration or command line. * * @readonly * * @memberOf configParser */ get activeTheme() { return this.args.theme || this.config.defaultTheme; } /** * Theme configuration for the active theme. * * @readonly * * @memberOf configParser */ get themeConfig() { return this.config.themes[this.activeTheme]; } /** * Whether or not production mode is enabled. * * @readonly * * @memberOf configParser */ get productionMode() { return this.args.production || process.env.NODE_ENV === 'production'; } }
JavaScript
class IndexOf extends AsyncObject { constructor (buf, value, byteOffset, encoding) { super(buf, value, byteOffset || 0, encoding || 'utf8') } syncCall () { return (buf, value, byteOffset, encoding) => { return buf.indexOf(value, byteOffset, encoding) } } }
JavaScript
class JSONSchemaValidator { constructor() { this.errors = [] } /** * 添加错误信息 * * @param {*} path * @param {*} key * @param {*} val * @memberof JSONSchemaValidator */ addError(path, key, val) { this.errors.push({ path, message: this.formatError(key, val) }) } resetError() { this.errors = [] } /** * 格式化错误信息 * @param {string} key * @param {any | array} error */ formatError(key, error) { return messages[ key ](error) } validate(instance, schema) { let res = validate(instance, schema) res.forEach(item => { this.addError.apply(this, item); }); return this.errors; } }
JavaScript
class ClientDetailPane extends React.Component { render() { const {client} = this.props const orgnrItem = ( <li className="list-group-item"> <small>Organization nr: </small> <a target="_blank" href={`https://w2.brreg.no/enhet/sok/detalj.jsp?orgnr=${client.org_nr}`}> {_.replace(client.org_nr, /(\d{3})(\d{3})(\d{3})/, '$1 $2 $3')} </a> </li> ) return( <div className="row align-items-center"> <div className="col"> <h2 className="text-primary">{client.name} <small className="text-dark"></small> </h2> <hr /> <div className="row"> <div className="col-md-6"> <p></p> </div> <div className="col-md-6"> <ul className="list-group"> {client.org_nr ? orgnrItem : null} </ul> </div> </div> </div> </div> ) } }
JavaScript
class UnionOrIntersectionType extends Type { constructor( flags ) { super( flags ); /** @type {?Array<Type>} */ this.types = null; // Constituent types this.propertyCache = new Map(); // Cache of resolved properties this.resolvedProperties = null; this.resolvedIndexType = null; this.resolvedBaseConstraint = null; this.couldContainTypeVariables = false; } getBaseConstraint() { const constraint = this.getResolvedBaseConstraint(); if ( constraint !== noConstraintType && constraint !== circularConstraintType ) return constraint; } isGenericObjectType() { return this.types.forEach( t => t.isGenericObjectType() ); } isGenericIndexType() { forEach( this.types, t => t.isGenericIndexType() ); } }
JavaScript
class ComponentReferenceLinker { constructor() { this._log = new Signale({ 'scope': 'Reference linker', }); this._placeholders = {}; this._codePlaceholders = {}; } async start() { this._log.start(`Inspecting documents in ${PAGES_SRC} ...`); return new Promise((resolve, reject) => { let stream = gulp.src(PAGES_SRC, {'read': true, 'base': './'}); stream = stream.pipe(through.obj((doc, encoding, callback) => { // this._log.await(`Checking ${doc.relative} ...`); stream.push(this._link(doc)); callback(); })); stream.pipe(gulp.dest('./')); stream.on('end', () => { this._log.complete('Linked all component references!'); resolve(); }); }); } _link(doc) { return this._check(doc); } _check(doc) { let content = doc.contents.toString(); /* eslint-disable max-len */ const codeExamples = content.match(/(<(amp-[^\s]+)(?:\s[^>]*)?>(.*?)<\/\2>|```html(.*?)*?```|Preview:(.*?)*?<\/amp-\w*(-\w*)*\>|\[sourcecode:html](.*?)*?\[\/sourcecode])/gsm); if (codeExamples !== null) { for (let i = 0; i < codeExamples.length; i++) { const codeExample = codeExamples[i]; content = content.replace(codeExample, this._createCodePlaceholder(codeExample)); } } // Cases /* eslint-disable max-len */ const cases = [ // content.match(/\[amp-\w*(-\w*)*\]\(\/docs\/reference\/components\/\w*-\w*(-\w*)*\.html\)/gm), // content.match(/\[`amp-\w*(-\w*)*\`]\(\/docs\/reference\/components\/\w*-\w*(-\w*)*\.html\)/gm), // content.match(/\[amp-\w*(-\w*)*]\(https:\/\/www.ampproject.org\/docs\/reference\/components\/\w*-\w*(-\w*)*\)/gm), // content.match(/\[\`amp-\w*(-\w*)*\`]\(https:\/\/www.ampproject.org\/docs\/reference\/components\/\w*-\w*(-\w*)*\)/gm), // content.match(/\[\`amp-\w*(-\w*)*\`]\(https:\/\/github.*\.md\)/gm), // content.match(/\[amp-\w*(-\w*)*.*]\(.*\)/gm), content.match(/\[(.*)?amp-\w*(-\w*)*.*]\(.*\)/gm), content.match(/\`<amp-\w*(-\w*)*>`/gm), content.match(/\`amp-\w*(-\w*)*`/gm), content.match(/amp-\w*(-\w*)*./gm), ]; /* eslint-enable max-len */ for (let i = 0; i < cases.length; i++) { const results = Array.from(new Set(cases[i])); for (let j = 0; j < results.length; j++) { const result = results[j]; if (result.slice(-1) === '/' || result.slice(-1) === '.') { continue; } else { const component = result.match(/amp-\w*(-\w*)*/g)[0]; const linkDescription = result.match(/(?<=\[)(.* )?amp-\w*(-\w*)*( .*)?(?=])/g); const description = ((linkDescription !== null) ? linkDescription[0].replace(component, `\`${component}\``) : `\`${component}\``); if (this._componentExist(component) === true) { while (content.includes(result)) { const placeholder = ((i === cases.length-1) ? this._createPlaceholder(component, description) + ' ' : this._createPlaceholder(component, description)); content = content.replace(result, placeholder); } } } } } for (const placeholder of Object.keys(this._placeholders)) { while (content.includes(placeholder)) { content = content.replace(placeholder, this._placeholders[placeholder]); } } for (const codePlaceholder of Object.keys(this._codePlaceholders)) { while (content.includes(codePlaceholder)) { content = content.replace(codePlaceholder, this._codePlaceholders[codePlaceholder]); } } doc.contents = Buffer.from(content); return doc; } _hash(str) { const hash = str.split('') .reduce((prevHash, currVal) => (((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0); this._log.error(hash); return hash; } _createPlaceholder(component, description) { const placeholder =`<!--${this._hash(description)}-->`; if (!this._placeholders[placeholder]) { this._placeholders[placeholder] = this._componentPath(component, description); } return placeholder; } _createCodePlaceholder(codeExample) { const codePlaceholder = `<!--${this._hash(codeExample)}-->`; if (!this._codePlaceholders[codePlaceholder]) { this._codePlaceholders[codePlaceholder] = codeExample; } return codePlaceholder; } _componentPath(component) { /* eslint-disable max-len */ const path = `({{g.doc('/content/amp-dev/documentation/components/reference/${component}.md', locale=doc.locale).url.path}})`; return `[\`${component}\`]${path}`; /* eslint-enable max-len */ } _componentExist(component) { const path = COMPONENTS_SRC + '/reference/' + component + '.md'; if (fs.existsSync(path)) { return true; } } }
JavaScript
class TransactionQueue { /** * Creates a TransactionQueue. * * @param pendingTransactions A map of sender to a list of their transactions, * sorted by nonce and without nonce gaps. * @param baseFee The base fee of the next block, if it's going to use EIP-1559 */ constructor(pendingTransactions, baseFee) { this._queuedTransactions = new Map(); this._heap = new heap_1.default((a, b) => decreasingOrderEffectiveMinerFeeComparator(a, b, baseFee)); for (const [address, txList] of pendingTransactions) { if (baseFee === undefined && txList.some((tx) => tx.data.type === 2)) { // eslint-disable-next-line @nomiclabs/only-hardhat-error throw new errors_1.InternalError("Trying to initialize and sort a mempool with an EIP-1559 tx but no base fee"); } const [firstTx, ...remainingTxs] = txList; this._heap.push(firstTx); this._queuedTransactions.set(address, remainingTxs); } } getNextTransaction() { if (this._lastTransactionSender !== undefined) { this._moveFirstEnqueuedTransactionToHeap(this._lastTransactionSender); } const nextTx = this._heap.pop(); if (nextTx === undefined) { return undefined; } this._lastTransactionSender = nextTx.data.getSenderAddress().toString(); return nextTx.data; } removeLastSenderTransactions() { if (this._lastTransactionSender === undefined) { // eslint-disable-next-line @nomiclabs/only-hardhat-error throw new errors_1.InternalError("TransactionQueue#removeLastSenderTransactions called before TransactionQueue#getNextTransaction"); } this._queuedTransactions.delete(this._lastTransactionSender); this._lastTransactionSender = undefined; } _moveFirstEnqueuedTransactionToHeap(sender) { const queue = this._queuedTransactions.get(sender); if (queue === undefined || queue.length === 0) { return; } const [first, ...rest] = queue; this._heap.push(first); this._queuedTransactions.set(sender, rest); } }
JavaScript
class Main { constructor () { this.configPath = null; } load (configPath) { this.configPath = configPath; return this; } run () { process.env.EG_CONFIG_DIR = this.configPath || process.env.EG_CONFIG_DIR; const config = require('./config'); // this is to init config before loading servers and plugins const plugins = pluginsLoader.load({ config }); const gateway = require('./gateway')({ plugins, config }); return Promise.all([gateway]); } }
JavaScript
class Search { /** * Create a search query * @param {string} query The search query */ constructor(query) { this.query = query; } /** * Get results by defined search query * @returns {Search} Returns this value */ async getResults() { try { const result = await axios(`https://api.spoonacular.com/recipes/complexSearch?apiKey=${apiKey}&query=${this.query}&addRecipeInformation=true`); this.result = result.data.results; return this; } catch (error) { throw error; } } }
JavaScript
class Container { constructor(registry, options = {}) { this.registry = registry; this.owner = options.owner || null; this.cache = dictionary(options.cache || null); this.factoryManagerCache = dictionary(options.factoryManagerCache || null); this.isDestroyed = false; if (DEBUG) { this.validationCache = dictionary(options.validationCache || null); } } /** @private @property registry @type Registry @since 1.11.0 */ /** @private @property cache @type InheritingDict */ /** @private @property validationCache @type InheritingDict */ /** Given a fullName return a corresponding instance. The default behavior is for lookup to return a singleton instance. The singleton is scoped to the container, allowing multiple containers to all have their own locally scoped singletons. ```javascript let registry = new Registry(); let container = registry.container(); registry.register('api:twitter', Twitter); let twitter = container.lookup('api:twitter'); twitter instanceof Twitter; // => true // by default the container will return singletons let twitter2 = container.lookup('api:twitter'); twitter2 instanceof Twitter; // => true twitter === twitter2; //=> true ``` If singletons are not wanted, an optional flag can be provided at lookup. ```javascript let registry = new Registry(); let container = registry.container(); registry.register('api:twitter', Twitter); let twitter = container.lookup('api:twitter', { singleton: false }); let twitter2 = container.lookup('api:twitter', { singleton: false }); twitter === twitter2; //=> false ``` @private @method lookup @param {String} fullName @param {Object} [options] @param {String} [options.source] The fullname of the request source (used for local lookup) @return {any} */ lookup(fullName, options) { assert('fullName must be a proper full name', this.registry.isValidFullName(fullName)); return lookup(this, this.registry.normalize(fullName), options); } /** A depth first traversal, destroying the container, its descendant containers and all their managed objects. @private @method destroy */ destroy() { destroyDestroyables(this); this.isDestroyed = true; } /** Clear either the entire cache or just the cache for a particular key. @private @method reset @param {String} fullName optional key to reset; if missing, resets everything */ reset(fullName) { if (fullName === undefined) { resetCache(this); } else { resetMember(this, this.registry.normalize(fullName)); } } /** Returns an object that can be used to provide an owner to a manually created instance. @private @method ownerInjection @returns { Object } */ ownerInjection() { return { [OWNER]: this.owner }; } /** Given a fullName, return the corresponding factory. The consumer of the factory is responsible for the destruction of any factory instances, as there is no way for the container to ensure instances are destroyed when it itself is destroyed. @public @method factoryFor @param {String} fullName @param {Object} [options] @param {String} [options.source] The fullname of the request source (used for local lookup) @return {any} */ factoryFor(fullName, options = {}) { let normalizedName = this.registry.normalize(fullName); assert('fullName must be a proper full name', this.registry.isValidFullName(normalizedName)); assert( 'EMBER_MODULE_UNIFICATION must be enabled to pass a namespace option to factoryFor', EMBER_MODULE_UNIFICATION || !options.namespace ); if (options.source || options.namespace) { normalizedName = this.registry.expandLocalLookup(fullName, options); if (!normalizedName) { return; } } return factoryFor(this, normalizedName, fullName); } }
JavaScript
class StateEmitter extends EventEmitter { /** * Creates an instance of StateEmitter * * @param {array} states * @memberof StateEmitter */ constructor(states) { super(); if (!Type.isArray(states) || !states.length) { throw new Error(`Expected states array, got ${ JSON.stringify(states) }`); } const invalid = states .filter((value) => !(Type.isString(value) || Type.isSymbol(value))); if (invalid.length) { throw new Error(`Expected states array to consist of strings or symbols, got ${ JSON.stringify(invalid) }`); } storage.set(this, { states }); } /** * Obtain the index of a state name * * @param {string} name * @return {number|undefined} index * @memberof StateEmitter */ index(name) { const { states } = storage.get(this); const index = states.indexOf(name); // eslint-disable-next-line no-undefined return index >= 0 ? index : undefined; } /** * Obtain the state at the given index * * @param {number} index * @return {string|symbol|undefined} state * @memberof StateEmitter */ state(index) { const { states } = storage.get(this); return states[index]; } /** * Normalize the state * * @param {string|symbol|number} state * @return {string|symbol|undefined} name * @memberof StateEmitter */ normalize(state) { const normal = Type.isNumber(state) ? this.state(state) : state; // verify whether the normal value is a string and recognized as state if (!((Type.isString(normal) || Type.isSymbol(normal)) && Type.isNumber(this.index(normal)))) { throw new Error(`Unknown state "${ JSON.stringify(state) }`); } return normal; } /** * Add a state listener * * @param {string|symbol|number} state * @param {function} listener * @return {StateEmitter} emitter * @memberof StateEmitter */ addListener(state, listener) { return super.addListener(this.normalize(state), listener); } /** * Emit a state event * * @param {string|symbol|number} state * @param {any} ...args * @return {boolean} emitted * @memberof StateEmitter */ emit(state, ...args) { return super.emit(this.normalize(state), ...args); } /** * Returns a copy of the array of listeners for given state * * @param {string|symbol|number} state * @return {array} listeners * @memberof StateEmitter */ listeners(state) { return super.listeners(this.normalize(state)); } /** * Remove a state listener * * @param {string|symbol|number} state * @param {any} ...args * @return {boolean} emitted * @memberof StateEmitter */ off(state, listener) { return super.removeListener(this.normalize(state), listener); } /** * Register a state listener * * @param {string|symbol|number} state * @param {function} listener * @return {boolean} emitted * @memberof StateEmitter */ on(state, listener) { return super.on(this.normalize(state), listener); } /** * Register a state listener which is removed after one emission * * @param {string|symbol|number} state * @param {function} listener * @return {boolean} emitted * @memberof StateEmitter */ once(state, listener) { return super.once(this.normalize(state), listener); } /** * Register a state listener to be emited first * * @param {string|symbol|number} state * @param {function} listener * @return {boolean} emitted * @memberof StateEmitter */ prependListener(state, listener) { return super.prependListener(this.normalize(state), listener); } /** * Register a state listener to be emited first and be removed after * one emission * * @param {string|symbol|number} state * @param {function} listener * @return {boolean} emitted * @memberof StateEmitter */ prependOnceListener(state, listener) { return super.prependOnceListener(this.normalize(state), listener); } /** * Remove all state listeners for given state * * @param {string|symbol|number} state * @return {boolean} emitted * @memberof StateEmitter */ removeAllListeners(state) { const args = [].concat(Type.isUndefined(state) ? [] : this.normalize(state)); return super.removeAllListeners.apply(this, args); } /** * Remove a state listener * * @param {string|symbol|number} state * @param {function} listener * @return {boolean} emitted * @memberof StateEmitter */ removeListener(state, listener) { return super.removeListener(this.normalize(state), listener); } }
JavaScript
class SerialConsoleConnector extends React.Component { state = { status: LOADING, passKeys: false }; onBackendDisconnected = () => { log('Backend has disconnected, pass the info to the UI component'); if (this.childSerialconsole) { this.childSerialconsole.onConnectionClosed( 'Reason for disconnect provided by backend.' ); } this.setState({ passKeys: false, status: DISCONNECTED // will close the terminal window }); }; onConnect = () => { log('SerialConsoleConnector.onConnect(), ', this.state); this.setConnected(); this.tellFairyTale(); }; onData = data => { log( 'UI terminal component produced data, i.e. a key was pressed, pass it to backend. [', data, ']' ); // Normally, the "data" shall be passed to the backend which might send them back via onData() call // Since there is no backend, let;s pass them to UI component immediately. if (this.state.passKeys) { this.onDataFromBackend(data); } }; onDataFromBackend = data => { log('Backend sent data, pass them to the UI component. [', data, ']'); if (this.childSerialconsole) { this.childSerialconsole.onDataReceived(data); } }; onDisconnect = () => { this.setState({ status: DISCONNECTED }); timeoutIds.forEach(id => clearTimeout(id)); }; onResize = (rows, cols) => { log( 'UI has been resized, pass this info to backend. [', rows, ', ', cols, ']' ); }; setConnected = () => { this.setState({ status: CONNECTED, passKeys: true }); }; tellFairyTale = () => { let time = 1000; timeoutIds.push( setTimeout( () => this.onDataFromBackend(' This is a mock terminal. '), time ) ); time += 1000; timeoutIds.push( setTimeout( () => this.onDataFromBackend(' Something is happening! '), time ) ); time += 1000; timeoutIds.push( setTimeout( () => this.onDataFromBackend(' Something is happening! '), time ) ); time += 1000; timeoutIds.push( setTimeout( () => this.onDataFromBackend(' Backend will be disconnected shortly. '), time ) ); time += 5000; timeoutIds.push(setTimeout(this.onBackendDisconnected, time)); }; render() { return ( <SerialConsole onConnect={this.onConnect} onDisconnect={this.onDisconnect} onResize={this.onResize} onData={this.onData} id="my-serialconsole" status={this.state.status} ref={c => { this.childSerialconsole = c; }} autoFit={this.props.autoFit} cols={this.props.cols} rows={this.props.rows} /> ); } }
JavaScript
class Response extends Body { /** * @param {?} responseOptions */ constructor(responseOptions) { super(); this._body = responseOptions.body; this.status = /** @type {?} */ ((responseOptions.status)); this.ok = (this.status >= 200 && this.status <= 299); this.statusText = responseOptions.statusText; this.headers = responseOptions.headers; this.type = /** @type {?} */ ((responseOptions.type)); this.url = /** @type {?} */ ((responseOptions.url)); } /** * @return {?} */ toString() { return `Response with status: ${this.status} ${this.statusText} for URL: ${this.url}`; } }
JavaScript
class VideoPlus extends LitElement { static get styles() { return css`:host {display: block;max-width: 1920px;background:#4d4d4d;overflow:hidden}` } static get properties() { return { name: { type: String }, rtsp: { type: String }, ws: { type: String }, poster: { type: String }, //videoEl: { type: HTMLCanvasElement }, } } constructor() { super() this.name = '' this.rtsp = '' this.ws = '' this.poster = '' this.player = null this.pState="play" this.width = 1920 this.height = 1080 this.loading = '' this.shotImg = '' //this.renderHeight = 'auto' } get canvasEl() { return this.shadowRoot.querySelector('#pcanvas') } get videoEl() { let video = this.shadowRoot.querySelector('#pvideo'); video.width = this.width video.height = this.height return video } get renderHeight(){ let rHeight = Math.round(this.offsetWidth / 16 *9)+'px'; this.setAttribute('style',`height:${rHeight}`); return rHeight } get state() {return this.pState} set state(nv){ this.pState = nv; } attributeChangedCallback(name,ov,nv){ if(ov && (nv != ov)){ console.log('attr changed:', name, ov); console.log(nv); let optMap = new Map([['rtsp','url'],['ws','socketurl']]) let newOpts = {} if(nv){ newOpts[optMap.get(name)] = nv } if(this.player){ this.player.stop() this.requestUpdate('state','playing') this.state = "playing" this.player = null setTimeout(()=>{ this.initPlayer(this.getOpts(newOpts)); },5) } } super.attributeChangedCallback(name, ov, nv); } update(changedProps) { super.update(changedProps); } overlayRenderer(){ let config={ canvas: this.canvasEl, video: this.videoEl, } return new H5SensePlayer.overlayRenderer(config); } getOpts(remoteOpt) { let opts = { url: this.rtsp, socketurl: this.ws, preferMode: "mse", container: this.videoEl, } if(!remoteOpt){ return opts } if(remoteOpt){ return Object.assign(opts,remoteOpt); } } onPlay() { if(this.player){ if(this.state == 'playing'){ this.player.play(); this.requestUpdate('state','pause') this.state = "pause" }else if(this.state == 'pause'){ this.player.stop() this.requestUpdate('state','playing') this.state = "playing" } }else{ this.initPlayer(this.getOpts()); } } initPlayer(options) { console.log(options) if (this.player) { this.player.stop(); this.player = null; } //this.overlayRenderer().restart(); this.player = new H5SensePlayer(options); this.player.play(); this.requestUpdate('state','pause') this.state = "pause" this.loading = 'isloading'; this.videoEl.onloadedmetadata = () =>{ debugger this.requestUpdate('loading','') this.loading = ''; this.requestUpdate('state','lod') this.state = "lod" } } connectedCallback() { super.connectedCallback(); window.addEventListener('resize:end', this._handleResize); } disconnectedCallback() { super.disconnectedCallback(); window.removeEventListener('resize:end', this._handleResize); } _handleResize = (ev) => { this.renderHeight; } screenshot(){ let shotCanvas = this.shadowRoot.querySelector('.screenshot'); console.log(shotCanvas) shotCanvas.style.display = "block"; this.shotImg = new Image(); this.shotImg.src = this.shadowRoot.querySelector('#pvideo').toDataURL("image/jpeg",1.0); //console.log(this.videoEl.toDataURL("image/png")) //return image; shotCanvas.appendChild(this.shotImg) // let offscreen = new OffscreenCanvas(256,256) // let gl = offscreen.getContext('webgl') // let bitmapImg = offscreen.transferToImageBitmap() // shotCanvas.transferFromImageBitmap(bitmapImg); //console.log(this.videoEl) //console.log(this.videoEl.getContext("2d").getImageData(0,0,this.videoEl.width,this.videoEl.height)) //shotCanvas.getContext("2d").drawImage(this.videoEl,this.videoEl.width,this.videoEl.height) } render() { const {name, state, poster,renderHeight,loading,shotImg, onPlay,screenshot} = this; return html` <style>${unsafeCSS(stylePlayer)}</style> <div class="s-player"> <canvas id="pcanvas" class="canvas"></canvas> <canvas id="pvideo"></canvas> <div class="video-title">${name}</div> <div class="masks masks-${state}" @click=${onPlay}> <img class="poster-img" src=${poster} alt=""> <i class="icono-${state}"></i> <slot>loading...</slot> </div> <div class="${loading}"><div class="load1"><div class="loader"></div></div></div> <div class="screenshot"> <i class="down">下载</i> </div> <div class="video-tool-bar"> <i class="icono-camera" title="截屏" @click=${screenshot}></i> </div> </div>` } }
JavaScript
class LinearMovementHandle extends BaseLinearMovementHandle { /** * Create a linear movement scene widget. * * @param {string} name - The name value. * @param {number} length - The length value. * @param {number} thickness - The thickness value. * @param {Color} color - The color value. */ constructor(name, length = 0.1, thickness = 0.003, color = new Color()) { super(name) this.colorParam.setValue(color) this.handleMat = new Material('handle', 'HandleShader') this.handleMat.getParameter('BaseColor').setValue(color) this.handleMat.getParameter('MaintainScreenSize').setValue(1) this.handleMat.getParameter('Overlay').setValue(0.9) const handleGeom = new Cylinder(thickness, length, 64) handleGeom.getParameter('BaseZAtZero').setValue(true) const tipGeom = new Cone(thickness * 4, thickness * 10, 64, true) const handle = new GeomItem('handle', handleGeom, this.handleMat) const tip = new GeomItem('tip', tipGeom, this.handleMat) const tipXfo = new Xfo() tipXfo.tr.set(0, 0, length) transformVertices(tipGeom, tipXfo) this.colorParam.on('valueChanged', () => { this.handleMat.getParameter('BaseColor').setValue(this.colorParam.getValue()) }) this.addChild(handle) this.addChild(tip) } /** * Applies a special shinning shader to the handle to illustrate interaction with it. */ highlight() { super.highlight() this.handleMat.getParameter('BaseColor').setValue(this.highlightColorParam.getValue()) } /** * Removes the shining shader from the handle. */ unhighlight() { super.unhighlight() this.handleMat.getParameter('BaseColor').setValue(this.colorParam.getValue()) } /** * Sets global xfo target parameter. * * @param {Parameter} param - The video param. * @param {boolean} track - The track param. */ setTargetParam(param, track = true) { this.param = param if (track) { const __updateGizmo = () => { this.getParameter('GlobalXfo').setValue(param.getValue()) } __updateGizmo() param.on('valueChanged', __updateGizmo) } } /** * Returns target's global xfo parameter. * * @return {Parameter} - returns handle's target global Xfo. */ getTargetParam() { return this.param ? this.param : this.getParameter('GlobalXfo') } /** * Handles the initially drag of the handle. * * @param {MouseEvent|TouchEvent|object} event - The event param. */ onDragStart(event) { this.grabPos = event.grabPos const param = this.getTargetParam() this.baseXfo = param.getValue() this.change = new ParameterValueChange(param) UndoRedoManager.getInstance().addChange(this.change) } /** * Handles drag action of the handle. * * @param {MouseEvent|TouchEvent|object} event - The event param. */ onDrag(event) { const dragVec = event.holdPos.subtract(this.grabPos) const newXfo = this.baseXfo.clone() newXfo.tr.addInPlace(dragVec) this.change.update({ value: newXfo, }) } /** * Handles the end of dragging the handle. * * @param {MouseEvent|TouchEvent|object} event - The event param. */ onDragEnd(event) { this.change = null } }
JavaScript
class ScheduleCreateOrUpdateParameters { /** * Create a ScheduleCreateOrUpdateParameters. * @member {string} name Gets or sets the name of the Schedule. * @member {string} [description] Gets or sets the description of the * schedule. * @member {date} startTime Gets or sets the start time of the schedule. * @member {date} [expiryTime] Gets or sets the end time of the schedule. * @member {object} [interval] Gets or sets the interval of the schedule. * @member {string} frequency Possible values include: 'OneTime', 'Day', * 'Hour', 'Week', 'Month' * @member {string} [timeZone] Gets or sets the time zone of the schedule. * @member {object} [advancedSchedule] Gets or sets the AdvancedSchedule. * @member {array} [advancedSchedule.weekDays] Days of the week that the job * should execute on. * @member {array} [advancedSchedule.monthDays] Days of the month that the * job should execute on. Must be between 1 and 31. * @member {array} [advancedSchedule.monthlyOccurrences] Occurrences of days * within a month. */ constructor() { } /** * Defines the metadata of ScheduleCreateOrUpdateParameters * * @returns {object} metadata of ScheduleCreateOrUpdateParameters * */ mapper() { return { required: false, serializedName: 'ScheduleCreateOrUpdateParameters', type: { name: 'Composite', className: 'ScheduleCreateOrUpdateParameters', modelProperties: { name: { required: true, serializedName: 'name', type: { name: 'String' } }, description: { required: false, serializedName: 'properties.description', type: { name: 'String' } }, startTime: { required: true, nullable: false, serializedName: 'properties.startTime', type: { name: 'DateTime' } }, expiryTime: { required: false, nullable: true, serializedName: 'properties.expiryTime', type: { name: 'DateTime' } }, interval: { required: false, serializedName: 'properties.interval', type: { name: 'Object' } }, frequency: { required: true, serializedName: 'properties.frequency', type: { name: 'String' } }, timeZone: { required: false, serializedName: 'properties.timeZone', type: { name: 'String' } }, advancedSchedule: { required: false, serializedName: 'properties.advancedSchedule', type: { name: 'Composite', className: 'AdvancedSchedule' } } } } }; } }
JavaScript
class GsWebSocket { constructor() { const protocol = (window.location.protocol === "https:") ? "wss://" : "ws://"; this.url = protocol + window.location.host + "/_ws/"; // Open WebSocket this._open(); // Configure events this.socket.addEventListener("open", () => { console.log("[WebSocket] Connection established"); }); this.socket.addEventListener("close", () => { console.log("[WebSocket] Connection closed, retrying connection in 1s..."); setTimeout(() => this._open(), 1000); }); this.socket.addEventListener("error", () => { console.log("[WebSocket] Connection errored, retrying connection in 1s..."); setTimeout(() => this._open(), 1000); }); } _open() { console.log(`[WebSocket] Connecting to ${this.url}...`); this.socket = new WebSocket(this.url); } /** * Send local WebRTC session description to remote. * @param {SessionDescription} localDescription WebRTC local SDP * @param {string} stream Name of the stream * @param {string} quality Requested quality */ sendLocalDescription(localDescription, stream, quality) { if (this.socket.readyState !== 1) { console.log("[WebSocket] Waiting for connection to send data..."); setTimeout(() => this.sendLocalDescription(localDescription, stream, quality), 100); return; } console.log(`[WebSocket] Sending WebRTC local session description for stream ${stream} quality ${quality}`); this.socket.send(JSON.stringify({ "webRtcSdp": localDescription, "stream": stream, "quality": quality })); } /** * Set callback function on new remote session description. * @param {Function} callback Function called when data is received */ onRemoteDescription(callback) { this.socket.addEventListener("message", (event) => { console.log("[WebSocket] Received WebRTC remote session description"); const sdp = new RTCSessionDescription(JSON.parse(event.data)); callback(sdp); }); } }
JavaScript
class DefaultNodeFactory extends react_diagrams_1.AbstractNodeFactory { constructor() { super("default"); } generateReactWidget(diagramEngine, node) { return React.createElement(DefaultNodeWidget_1.DefaultNodeWidget, { node: node, diagramEngine: diagramEngine }); } getNewInstance(initialConfig) { return new DefaultNodeModel_1.DefaultNodeModel(); } }
JavaScript
class CopyBacon { /** * @constructor * @return {void} */ constructor() { if (!this.setVars()) return; this.setEvents(); } /** * Init vars. * @return {boolean} If variables has been found */ setVars() { this.button = document.querySelector('[data-bacon-button]'); if (!this.button) return false; this.wrapper = document.querySelector('[data-bacon-wrapper]'); this.imageWrapper = document.querySelector('[data-bacon-image]'); this.image = this.imageWrapper.querySelector('img'); this.config = { imageSrc: this.image.src, }; return true; } /** * @return {void} Assigns events to found DOM elements */ setEvents() { this.button.addEventListener( 'click', this.copyImage.bind(this) ); } /** * @return {void} Copy image wrapper and create new image into it */ copyImage() { const container = this.imageWrapper.cloneNode(); const image = document.createElement('img'); const { imageSrc } = this.config; image.src = imageSrc; image.style = ` width: 100%; height: 100%; `; container.appendChild(image); this.wrapper.appendChild(container); } }
JavaScript
class SelectInstance { /** * @constructor * @param {HTMLDivElement} wrapper Custom select DOM Element * @return {void} */ constructor(wrapper) { if (!this.setVars(wrapper)) return; this.setEvents(); } /** * Init vars. * @param {HTMLDivElement} wrapper Custom select DOM Element * @return {boolean} If variables has been found */ setVars(wrapper) { this.select = wrapper; if (!this.select) return false; this.selectValue = this.select.querySelector('[data-select-value]'); this.selectItems = this.select.querySelectorAll('[data-select-item]'); return true; } /** * @return {void} Assigns events to found DOM elements */ setEvents() { this.selectValue.addEventListener( 'keydown', this.preventValue.bind(this) ); [...this.selectItems].forEach((item) => { item.addEventListener( 'click', this.chooseValue.bind(this) ); }); } /** * @return {void} Chooses value from select */ chooseValue({ target }) { const valueTrimmed = target .innerHTML .replace(/^(&nbsp;|\s)*/, '') .replace(/(&nbsp;|\s)*$/, ''); this.selectValue.value = valueTrimmed; } /** * @param {Event} e * @return {void} Prevents user for inserting value into select */ preventValue(e) { e.preventDefault(); } }
JavaScript
class Select { /** * @constructor * @return {void} */ constructor() { this.sections = document.querySelectorAll('[data-select]'); if (!this.sections.length) return; this.sections.forEach((section) => { new SelectInstance(section); }); } }
JavaScript
class Form { /** * @constructor * @return {void} */ constructor() { if (!this.setVars()) return; this.setEvents(); } /** * Init vars. * @return {boolean} If variables has been found */ setVars() { this.section = document.querySelector('[data-form-section]'); if (!this.section) return false; this.button = this.section.querySelector('[data-form-button]'); this.select = this.section.querySelectorAll('[data-select-item]'); this.inputs = this.section.querySelectorAll('[data-input]'); this.regex = { text: /^[a-zA-Z0-9]+/i, email: /\S+@\S+\.\S+/g, code: /^[0-9]+$/g, card: /^[0-9]{16}$/g, date: /^[0-9]{4}$/g, phone: /^[0-9]{6,}$/g, }; this.formData = {}; this.classes = { error: 'input--error', correct: 'input--correct', }; return true; } /** * @return {void} Assigns events to found DOM elements */ setEvents() { this.button.addEventListener( 'click', this.submitForm.bind(this) ); [...this.select].forEach((item) => { item.addEventListener( 'click', ({ target }) => this.validateInput( target.parentElement.parentElement.querySelector('input') ) ); }); [...this.inputs].forEach((input) => { this.buildFormData(input); input.addEventListener( 'input', ({ target }) => this.validateInput(target) ); }); } /** * @param {Event} e * @return {boolean} Validates and submits form */ submitForm(e) { e.preventDefault(); let formValid = true; const keys = Object.keys(this.formData); const keysLength = keys.length; for (let i = 0; i < keysLength; i++) { const { isValid } = this.formData[keys[i]]; if (!isValid) { formValid = false; this.validateInput( this.findInput(keys[i]) ); } } if (!formValid) return false; const data = {}; for (let i = 0; i < keysLength; i++) { data[keys[i]] = this.formData[keys[i]].value; } /* Current project setup does not allow for modern javascript syntax so I have abstained from implementing async/await function for API call and always returns true */ return true; } /** * @param {string} name Name attribute of the input * @return {HTMLInputElement | null} Finds input to validate */ findInput(name) { return [...this.inputs].find((input) => { return input.getAttribute('name') === name; }) || null; } /** * @param {HTMLInputElement} item * @return {void} Creates form data from inputs */ buildFormData(item) { const name = item.getAttribute('name'); this.formData[name] = { isValid: false, value: '', }; } /** * @param {HTMLInputElement | null} target * @return {void} Assigns validation to input */ validateInput(target) { if (!target) return false; const { error, correct } = this.classes; const type = target.getAttribute('data-input-type'); const name = target.getAttribute('name'); let { value } = target; switch (type) { case 'card': target.value = this.reformatInputValue(value, type); value = value.replace(/\s-\s/g, '').match(/.{1,4}/g) || []; if (value.length > 4) { value = value.splice(0, 4); } value = value.join(''); break; case 'date': target.value = this.reformatInputValue(value, type); value = target.value.replace(/\s\/\s/g, ''); break; case 'phone': target.value = this.reformatInputValue(value, type); value = value.replace(/\D/g, ''); break; } const isValid = value.match(this.regex[type]); if (isValid) { target.parentElement.classList.remove(error); target.parentElement.classList.add(correct); } else { target.parentElement.classList.remove(correct); target.parentElement.classList.add(error); } this.formData[name] = { isValid: !!isValid, value, }; } /** * @param {string} value value to be changed * @param {string} type input type * @return {string} Reformats card number */ reformatInputValue(value, type) { switch (type) { case 'card': let list = value.replace(/\s-\s/g, '').match(/.{1,4}/g); if (!list) return ''; if (list.length > 4) { list = list.splice(0, 4); } return list.join(' - '); case 'date': value = value.replace(/\D/g, ''); const dateLength = value.length; if (!dateLength) return 'MM / YY'; let startValue = ['M', 'M', 'Y', 'Y']; for (let i = 0; i < dateLength; i++) { startValue[i] = value[i]; } startValue = startValue.join(''); let [month, year] = startValue.replace(/\s\/\s/g, '').match(/.{1,2}/g); if (month > 12) { month = 12; } return [month, year].join(' / '); case 'phone': value = value.replace(/\D/g, ''); if (value.length > 10) return value; value = value.match(/.{1,3}/g); const phoneLength = value instanceof Array ? value.length: null; switch (phoneLength) { case 4: return value[3].length === 1 ? `(${value[0]}) ${value[1]} ${value[2].substring(0, 2)}${'' }-${value[2].substring(2, 3) + value[3]}` : `(${value[0]}) ${value[1]} ${value[2]}-${value[3]}`; case 3: return value[2].length === 3 ? `(${value[0]}) ${value[1]}${' ' }${value[2].substring(0, 2)}-${value[2].substring(2, 3)}` : `(${value[0]}) ${value[1]} ${value[2]}`; case 2: return `(${value[0]}) ${value[1]}`; case 1: return `(${value[0]})`; } return ''; } } }
JavaScript
class Core { /** * @return {void} */ constructor() { new Select(); new CopyBacon(); new Form(); } }
JavaScript
class BehaviorMoveTo { constructor(bot, targets) { this.stateName = 'moveTo'; this.active = false; /** * How close the bot should attempt to get to this location before * considering the goal reached. A value of 0 will mean the bot must * be inside the target position. */ this.distance = 0; this.bot = bot; this.targets = targets; const mcData = (0, minecraft_data_1.default)(bot.version); this.movements = new mineflayer_pathfinder_1.Movements(bot, mcData); } onStateEntered() { // @ts-expect-error this.bot.on('path_update', this.path_update); // @ts-expect-error this.bot.on('goal_reached', this.goal_reached); this.startMoving(); } onStateExited() { // @ts-expect-error this.bot.removeListener('path_update', this.path_update); // @ts-expect-error this.bot.removeListener('goal_reached', this.goal_reached); this.stopMoving(); } path_update(r) { if (r.status === 'noPath') { console.log('[MoveTo] No path to target!'); } } goal_reached() { if (index_1.globalSettings.debugMode) { console.log('[MoveTo] Target reached.'); } } /** * Sets the target block position to move to. If the bot * is currently moving, it will stop and move to here instead. * * If the bot is not currently in this behavior state, the entity * will still be assigned as the target position when this state * is entered. * * This method updates the target position. * * @param position - The position to move to. */ setMoveTarget(position) { if (this.targets.position === position) { return; } this.targets.position = position; this.restart(); } /** * Cancels the current path finding operation. */ stopMoving() { const pathfinder = this.bot.pathfinder; pathfinder.setGoal(null); } /** * Starts a new path finding operation. */ startMoving() { const position = this.targets.position; if (position == null) { if (index_1.globalSettings.debugMode) { console.log('[MoveTo] Target not defined. Skipping.'); } return; } if (index_1.globalSettings.debugMode) { console.log(`[MoveTo] Moving from ${this.bot.entity.position.toString()} to ${position.toString()}`); } const pathfinder = this.bot.pathfinder; let goal; if (this.distance === 0) { goal = new mineflayer_pathfinder_1.goals.GoalBlock(position.x, position.y, position.z); } else { goal = new mineflayer_pathfinder_1.goals.GoalNear(position.x, position.y, position.z, this.distance); } pathfinder.setMovements(this.movements); pathfinder.setGoal(goal); } /** * Stops and restarts this movement behavior. Does nothing if * this behavior is not active. */ restart() { if (!this.active) { return; } this.stopMoving(); this.startMoving(); } /** * Checks if the bot has finished moving or not. */ isFinished() { const pathfinder = this.bot.pathfinder; return !pathfinder.isMoving(); } /** * Gets the distance to the target position. * * @returns The distance, or 0 if no target position is assigned. */ distanceToTarget() { const position = this.targets.position; if (position == null) return 0; return this.bot.entity.position.distanceTo(position); } }
JavaScript
class GoogleClient { /** * @constructor Id & Secret (https://console.developers.google.com/apis/credentials) * @param {string} clientID Google Client id * @param {string} clientSecret Google Client Secret */ constructor(clientID, clientSecret) { this._id = clientID this._secret = clientSecret this._baseURL = `https://www.googleapis.com`, this._baseAuthURL = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${this._id}&response_type=token&prompt=consent` this.scopes = []; this.redirectURL = '' } /** * * @param {String | Array} scope Google Scopes (https://developers.google.com/identity/protocols/oauth2/scopes) */ async setScopes(scope) { if(!scope || typeof scope !== String && Array) throw Error("Please Write the scope in a string or array"); if(typeof scope === string){ return this.scopes.push(scope); } else if(typeof scope === Array){ return scope.forEach(x => this.scopes.push(x)); } else { throw Error("Unable to set scope. Please Try again or Contact the Devs"); } } /** * * @param {string} redirectURI Redirect Url after successfull Authorization * @param {String} login_hint Email adress or sub identifier for hint for the Google Authentication Server (https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow#oauth-2.0-endpoints) */ async generateUrl(redirectURI, login_hint = null) { if(typeof redirectURI !== string) throw Error("RedirectUri is not a string.."); if(!redirectURI) { if(this.redirectURL) redirectURI = this.redirectURL else throw Error("Please Provide a Redirect Url"); } this.redirectURL = redirectURI; return `${this._baseAuthURL}&redirect_uri=${this.redirectURL}&scope=${!this.scopes ? 'profile' : this.scopes.map(x=>x).join("%20")}${!login_hint ? '' : `&login_hint=${login_hint}`}` } /** * @param {string} code Access_Token */ async getData(code) { let returnobject = [] this.scopes.forEach(async(x) => { let request = await axios.default({ method: 'get', url: x + '?alt=json', headers: { 'Authorization': 'Bearer ' + code } }); returnobject.push(request.data); }); return returnobject } }
JavaScript
class Menu extends Component { render() { return ( <div className={classNames(styles.menu, { [styles.inDrawer]: this.props.inDrawer, })} > <div className={styles.closeWrapper}> <div className={styles.close} onClick={this.props.onClose}> &times; </div> </div> <Logo /> <div className={styles.menuItems}> <div className={styles.menuItem}> <Link to="/">Latest News</Link> </div> <div className={styles.menuItem}> <Link to="/introducing-majority/">About Majority</Link> </div> <div className={styles.menuItem}> <a href="http://eastbaydsa.org" target="_blank" rel="noopener noreferrer" > East Bay DSA </a> </div> </div> <img src={ebdsaLogo} alt="East Bay DSA" className={styles.ebdsaLogo} /> {/* <NewsletterSignup /> */} </div> ) } }