language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class SoccerClub { // constructor constructor (numberOfPlayers, division, version) { this.numberOfPlayers = numberOfPlayers; this.division = division; this.version = version; } // method printClubDetails() { // Template Literal - es6 feature console.log(`A club can have ${this.numberOfPlayers} players in the ${this.division} division of ${this.version} version.`); } }
JavaScript
class DynamitesSC extends SoccerClub { constructor(clubName, numberOfPlayers, division, version) { super(numberOfPlayers, division, version); this.clubName = clubName; } printDynamitesDetails(version) { console.log(`Clubname: ${this.clubName} from ${this.version} version.`); } }
JavaScript
class RichNode { constructor(content) { for( var key in content ) this[key] = content[key]; } get region() { const start = this.start; const end = this.end; return [ start, end || start ]; } set region( [start, end] ){ this.start = start; this.end = end; } get length() { const end = this.end || 0; const start = this.start || 0; const diff = Math.max( 0, end - start ); return diff; } isInRegion(start, end) { return start <= this.start && this.end <= end; } isPartiallyInRegion(start, end) { return ( this.start >= start && this.start < end ) || ( this.end > start && this.end <= end ); } isPartiallyOrFullyInRegion([start, end]) { if (start == undefined || end == undefined) return true; return (this.start >= start && this.start <= end) || (this.end >= start && this.end <= end) || (this.start <= start && end <= this.end); } partiallyOrFullyContainsRegion([start,end]) { return (positionInRange(start, this.region) || positionInRange(end, this.region)); } containsRegion(start, end) { return this.start <= start && end <= this.end; } isAncestorOf(richNode) { let node = richNode; while (node) { if ( this.domNode == node.domNode ) return true; node = node.parent; } return false; } isDescendentOf(richNode) { return richNode.isAncestorOf(this); } }
JavaScript
class Context { constructor({ parent = null, currentFunction = null, inLoop = false } = {}) { Object.assign(this, { parent, currentFunction, inLoop, locals: new Map(), }); } /* createChildContextForFunctionBody(currentFunction) { // When entering a new function, we're not in a loop anymore return new Context({ parent: this, currentFunction, inLoop: false }); } */ createChildContextForLoop() { // When entering a loop body, just set the inLoop field, retain others return new Context({ parent: this, currentFunction: this.currentFunction, inLoop: true }); } createChildContextForBlock() { // For a block, we have to retain both the function and loop settings. return new Context({ parent: this, currentFunction: this.currentFunction, inLoop: this.inLoop, }); } // Adds a variable or function to this context. add(declaration) { if (this.locals.has(declaration.id)) { throw new Error(`${declaration} already declared in this scope`); } this.locals.set(declaration.id, declaration); } lookup(id) { for (let context = this; context !== null; context = context.parent) { if (context.locals.has(id)) { return context.locals.get(id); } } throw new Error(`Identifier ${id} has not been declared`); } }
JavaScript
class PureItemRenderer extends PureComponent { render() { return itemRenderer(this.props); } }
JavaScript
class MovieService { // get movies static getMovies() { return new Promise(async (resolve, reject) => { try { const res = await axios.get(movies); const data = res.data; resolve( data.map(movie => ({ ...movie })) ); } catch (err) { reject(err) } }) } // add movie static addMovie(name, price) { return axios.post(movies, { name, price }) } // delete movie static deleteMovie(id) { return axios.delete(`${movies}${id}`) } }
JavaScript
class Texture extends ThreeDOMElement { constructor(onUpdate, threeTexture, gltfTexture = null, gltfSampler = null, gltfImage = null) { super(onUpdate, gltfTexture ? gltfTexture : {}, new Set(threeTexture ? [threeTexture] : [])); this[$sampler] = new Sampler(onUpdate, threeTexture, gltfSampler); this[$image] = new Image(onUpdate, threeTexture, gltfImage); } get name() { return this[$sourceObject].name || ''; } get sampler() { return this[$sampler]; } get source() { return this[$image]; } }
JavaScript
class Proc { /** * Constructor class */ constructor(apiKey, user, levelConcurrency) { this.levelConcurrency = levelConcurrency this.api = new Api(user, apiKey) } /** * Get the total of pages * @returns {Number} The total of pages */ async getTotalPages() { try { const resultJson = await this.api.apiReq() return resultJson.recenttracks['@attr'].totalPages } catch (error) { return Promise.reject(error.message || error) } } /** * Performs requests and return results * @returns {Object} The results object */ async process(start = 0, end) { try { let results = [] const totalPages = end || Number(await this.getTotalPages()) const levelConcurrency = Number(this.levelConcurrency) || totalPages const chunk = levelConcurrency >= totalPages - start ? 1 : (totalPages - start) % levelConcurrency !== 0 ? Math.floor((totalPages - start) / levelConcurrency) - 1 : (totalPages - start) / levelConcurrency let requests = [] let count = 0 for (let i of [ ...Array.from( { length: totalPages - start }, (value, key) => key + start ) ]) { count++ if (count < chunk) { requests.push(this.api.apiReq({ page: i })) } if (count >= chunk) { count = 0 requests.push(this.api.apiReq({ page: i })) const data = await Promise.all(requests) requests = [] results.push( ...data.map(page => { if ( page && page.recenttracks && typeof page.recenttracks === 'object' && page.recenttracks['@attr'] ) { delete page.recenttracks['@attr'] if (Array.isArray(page.recenttracks.track)) { if (page.recenttracks.track[0]['@attr']) { page.recenttracks.track.shift() } page.recenttracks.track.map(tr => { if (tr.date) { if (tr.date['#text']) { tr.timestamp = tr.date['#text'] delete tr.date } } }) return page.recenttracks.track } } }) ) } } return results } catch (error) { return Promise.reject(error.message || error) } } }
JavaScript
class Stock extends Product{ batches = []; status = undefined; /** * * @param stock * @constructor */ constructor(stock) { super(stock) if (typeof stock !== undefined) for (let prop in stock) if (stock.hasOwnProperty(prop)) this[prop] = stock[prop]; this.status = this.status || StockStatus.AVAILABLE; this.batches = this.batches.map(b => new Batch(b)); } getQuantity(){ return this.batches.reduce((sum, b) => sum + b.getQuantity(), 0); } /** * Validate if everything seems ok with the properties of this object. * @returns undefined if all ok. An array of errors if not all ok. */ validate() { return super.validate(); } }
JavaScript
class GetDocumentInformation { static async Run() { try { let fileInfo = new comparison_cloud.FileInfo(); fileInfo.filePath = "source_files/word/source.docx"; let request = new comparison_cloud.GetDocumentInfoRequest(fileInfo); let response = await infoApi.getDocumentInfo(request); console.log("GetDocumentInformation completed: " + response.pageCount); } catch (error) { console.log(error.message); } } }
JavaScript
class GitHubLogger { _log(message, type = 'notice', options = {}) { message = message.replace(/\n/g, '%0A'); const configs = Object.entries(options).map(([key, option]) => `${key}=${option}`).join(','); console.log((0, _base.stripAnsiEscapes)(`::${type} ${configs}::${message}`)); } debug(message, options) { this._log(message, 'debug', options); } error(message, options) { this._log(message, 'error', options); } notice(message, options) { this._log(message, 'notice', options); } warning(message, options) { this._log(message, 'warning', options); } }
JavaScript
class StickyTable extends PureComponent { static propTypes = { stickyHeaderCount: PropTypes.number, stickyColumnCount: PropTypes.number, onScroll: PropTypes.func }; static defaultProps = { stickyHeaderCount: 1, stickyColumnCount: 1 }; constructor(props) { super(props); this.index = index = index + 1; } /** * Get the column and header to render * @returns {undefined} */ render() { var {stickyColumnCount, stickyHeaderCount} = this.props; stickyColumnCount = Math.min(stickyColumnCount, 1); stickyHeaderCount = Math.min(stickyHeaderCount, 1); return ( <div className={`sticky-table sticky-table-${this.index}` + (this.props.className || '')}> <style> {` .sticky-table-${this.index} .sticky-table-row:nth-child(-n+${stickyHeaderCount}) .sticky-table-cell { position: -webkit-sticky; position: sticky; top: 0; z-index: 2; } .sticky-table-${this.index} .sticky-table-row .sticky-table-cell:nth-child(-n+${stickyColumnCount}) { position: -webkit-sticky; position: sticky; left: 0; z-index: 2; } .sticky-table-${this.index} .sticky-table-row:nth-child(-n+${stickyHeaderCount}) .sticky-table-cell:nth-child(-n+${stickyColumnCount}) { position: -webkit-sticky; position: sticky; top: 0; left: 0; z-index: 3; } `} </style> <Table> {this.props.children} </Table> </div> ); } }
JavaScript
class AuthPanel extends React.Component { constructor(props) { super(props); this.state = {} } render() { let {intl} =this.props return ( <div className="container-fluid ui-auth-panel clearfix"> <div className="row "> <div className="col-sm-6 ui-left-lpanel "> <div className="content-panel center-block"> <div className="company-short-name"> { t1(intl, "welcome_to") } { t(intl, "VietED") } </div> <div className="ui-logo-panel "> <img src={config.defaultLogo}/> </div> </div> </div> <div className="col-sm-6"> <div className="content-panel"> {this.props.children} </div> </div> </div> </div> ); } }
JavaScript
class MediaQueriesSplitter { static findNextNonCommentStylesheetRule(rules, currentIndex) { let nextRule = false; while (typeof rules[++currentIndex] !== 'undefined') { if (rules[currentIndex].type !== 'comment') { nextRule = rules[currentIndex]; break; } } return nextRule; } constructor({cssFile, prepareMediaQueries}) { this.contents = cssFile.contents.toString(); this.options = [...prepareMediaQueries.prepare()]; } static #generateOutputFiles( outputFiles ) { for (let filename in outputFiles) { outputFiles[filename] = cssStringify({ type: 'stylesheet', stylesheet: {rules: outputFiles[filename]} }); } return outputFiles; } handle() { let outputFiles = {}; let rules = cssParse(this.contents).stylesheet.rules; rules.forEach((rule, ruleIndex) => { let _rule = rule; // Check whether the current rule is a comment, keep it with the next non-comment rule (if there is any) if (rule.type === 'comment') { _rule = MediaQueriesSplitter.findNextNonCommentStylesheetRule(rules, ruleIndex); if (!_rule) { _rule = rule; } } // Only add the rule to the list if it's a @media rule, and if it's the matching rule. Or, add it if no specific media query was specified if (!Array.isArray(this.options)) { this.options = [this.options]; } this.options.forEach((option) => { if (!option.media || !option.filename) { return; } if (!Array.isArray(option.media)) { option.media = [option.media]; } option.media.every((optionMedia) => { let outputFile = '', isMediaWidthRule = false, ruleMediaMin = null, ruleMediaMax = null; if (_rule.type === 'media' && _rule.media) { ruleMediaMin = _rule.media.match(/\(min-width:\s*([0-9]+)px\)/); ruleMediaMax = _rule.media.match(/\(max-width:\s*([0-9]+)px\)/); if ((ruleMediaMin && ruleMediaMin[1]) || (ruleMediaMax && ruleMediaMax[1])) { isMediaWidthRule = true; ruleMediaMin = ruleMediaMin ? ruleMediaMin[1] : 0; ruleMediaMax = ruleMediaMax ? ruleMediaMax[1] : 0; } } if (typeof optionMedia === 'string') { if (optionMedia === 'all' || (optionMedia === 'none' && !isMediaWidthRule)) { outputFile = option.filename; } } else if (typeof optionMedia === 'object' && isMediaWidthRule) { let optionMediaMin = optionMedia.min ? parseInt(optionMedia.min, 10) : 0, optionMediaMinUntil = optionMedia.minUntil ? parseInt(optionMedia.minUntil, 10) : 0, optionMediaMax = optionMedia.max ? parseInt(optionMedia.max, 10) : 0; if (!optionMediaMinUntil && optionMediaMax) { optionMediaMinUntil = optionMediaMax; } try { let ruleMeetsOptionMediaMin = optionMediaMin ? ruleMediaMin && ruleMediaMin >= optionMediaMin : true, ruleMeetsOptionMediaMinUntil = optionMediaMinUntil && ruleMediaMin ? ruleMediaMin < optionMediaMinUntil : true, ruleMeetsOptionMediaMax = optionMediaMax && ruleMediaMax ? ruleMediaMax < optionMediaMax : true; if (ruleMeetsOptionMediaMin && ruleMeetsOptionMediaMinUntil && ruleMeetsOptionMediaMax) { outputFile = option.filename; } } catch (error) { } } if (outputFile) { if (typeof outputFiles[outputFile] === 'undefined') { outputFiles[outputFile] = []; } outputFiles[outputFile].push(rule); //Return false to break the loop, to prevent the current rule to be added to the same file multiple times return false; } return true; }); }); }); return MediaQueriesSplitter.#generateOutputFiles( outputFiles ); } }
JavaScript
class TodoForm extends React.Component { // Constructor with state constructor() { super(); this.state = { itemName: null }; } handleChanges = (e) => { // update state with each keystroke this.setState({ itemName: e.target.value }); }; handleAdd = (e) =>{ e.preventDefault(); this.props.addItem(this.state.itemName) this.setState({ itemName: '' }) } // class property to submit form render() { return ( <div className="App"> <form className='FormApp' onSubmit={this.handleAdd}> {/* This is an uncontrolled component 😬 We want it to be controlled by state */} <input value={this.state.itemName} onChange={this.handleChanges} type="text" name="item" /> <button >Add</button> </form> </div> ); } }
JavaScript
class ProductImages extends bookshelf.Model { /** * Get table name. */ get tableName() { return TABLE_NAME; } /** * One Product will be parent of every product images. */ product() { return this.belongsTo(Product); } }
JavaScript
class Portfolio { /** * Creates a new Portfolio web app with a number of comments specified by the user. */ constructor() { this.numComments = document.getElementById('count-options').value; this.visitLocs = { glacier: { lat: 48.760815, lng: -113.786722 }, edinburgh: { lat: 55.943914, lng: -3.21689 }, sanblas: { lat: 9.5702911, lng: -78.9272882 }, fjord: { lat: -45.4572629, lng: 167.2282707 } }; this.parkLocs = { 'Zion': { lat: 37.3220096, lng: -113.1833194 } , 'Rocky Mountain': { lat: 40.3503939, lng: -105.9566636 }, 'Grand Teton': { lat: 43.6594418, lng: -111.000682 }, 'Joshua Tree': { lat: 33.8987129, lng: -116.4211304}, }; } /** * Sets up the Portfolio by getting comment data from the servlet. */ async setup() { await this.getComments(); this.setupPlaceMaps(); this.setupParkMap(); this.setupFooter(); } /** * Sets up display of the footer (either a login link or comments form) based on the login status of the user. */ async setupFooter() { let path = '/login'; let res = await fetch(path); let loginStatus = await res.text(); /* If the user is logged in, hide the login link and display the comments form. */ if (loginStatus.trim() === 'true') { document.getElementById('login-footer').style.display = 'none'; document.getElementById('comments-footer').style.display = 'flex'; } else { // hide comments and show login if user is not logged in document.getElementById('login-link').href = loginStatus; document.getElementById('login-footer').display = 'flex'; document.getElementById('comments-footer').display = 'none'; } } /** * Removes all comments from the DOM. */ removeComments() { this.numComments = document.getElementById('count-options').value; let parentList = document.getElementById("comments"); parentList.innerHTML = ''; } /** * Creates an <li> element containing text. */ createListElement(text) { const liElement = document.createElement('li'); liElement.innerText = text; return liElement; } /** * Fetches content from the server, parses as JSON, and then adds the content to the page as a list element. */ async getComments() { let path = '/data?number=' + this.numComments; let res = await fetch(path); /* Check for errors in the HTTP response and alert the user. */ if (res.status === 404){ // empty datastore or too many comments requested return; } else if (res.status !== 200) { alert('Error generated in HTTP response from servlet'); } let comments = await res.json(); let parentList = document.getElementById("comments"); comments.forEach(comment => parentList.appendChild(this.createListElement(`${comment.text} posted by ${comment.email}`))); } /** * Deletes all comments from the datastore. */ async deleteComments() { let path = '/delete-data'; let res = await fetch(path, { method: 'POST' }); /* Check for errors in the HTTP response and alert the user. */ if (res.status !== 200) { alert('Error generated in HTTP response from servlet'); } } /** * Adds four maps to the page showing four places I really want to visit. */ setupPlaceMaps() { let mapOptions; for (let loc of Object.entries(this.visitLocs)) { mapOptions = { zoom: 8, center: loc[1] }; this.createMap(mapOptions, loc[0]); } } /** * Creates a map with pins of my favorite national parks. */ setupParkMap() { let usa = { lat: 44.0733586, lng: -97.5443135 }; let mapOptions = { zoom: 3, center: usa }; let map = this.createMap(mapOptions, 'parks'); for (const [name, position] of Object.entries(this.parkLocs)) { let marker = new google.maps.Marker({position, map}); let infowindow = new google.maps.InfoWindow({ content: name }); marker.addListener('click', function() { infowindow.open(map, marker); }); } } /** * Creates a single map with the given options. */ createMap(mapOptions, id) { const map = new google.maps.Map( document.getElementById(id), mapOptions); map.setTilt(45); return map; } }
JavaScript
class RadialTreeBrowser { constructor(selector) { this.selector = selector; this._init(); } _init() { this.svg = d3.select(this.selector); this.group = this.svg.append('g'); this.svg.attr('viewBox', `0 0 ${BOX_SIZE} ${BOX_SIZE}`); this.group.attr('class', 'radial-tree-browser'); this.group.call(this.dragHandler()); } clear() { this.group.selectAll('.edge').remove(); this.group.selectAll('.node').remove(); return this; } draw(view) { this.view = view; this.update(); this.drawEdges(this.view.root); this.drawNodes(this.view.root); } update() { this.clear(); this.drawEdges(this.view.root); this.drawNodes(this.view.root); } drawEdges(root) { this.group.selectAll('.edge') .data(links(root)) .enter().append('path') .attr('class', 'edge') .attr('d', d => { const s = d.source, t = d.target; return `M${s.x},${s.y}S${t.x},${s.y} ${t.x},${t.y}`; }); } drawNodes(root) { const nodes = this.group.selectAll('.node') .data(root.node.descendants()).enter().append('g') .attr('class', d => `node ${d.children ? 'internal' : 'leaf'}`) .attr('tabindex', 0) .attr('aria-label', d => d.text) .attr('aria-level', d => d.node && d.node.depth || 0) .attr('transform', d => `translate(${d.x} ${d.y})`); nodes.append('circle') .attr('r', 10); nodes.append('text') .attr('dy', '0.3rem') .attr('x', d => (d.x > BOX_SIZE / 2) ? 15 : -15) .attr('text-anchor', d => (d.x > BOX_SIZE / 2) ? 'start' : 'end') .attr('transform', labelRotation) .attr('opacity', hideTextAtBorder) .text(d => d.name); nodes .on('dblclick', this.clickHandler.bind(this)); } /** * As d3 has an issue with drag & click handling at the same time, we figure * out a doubleclick occured ourselves and trigger the onclick handler. **/ dragHandler() { let clickTimestamp = new Date().getTime(); const testDoubleClick = () => { const now = new Date().getTime(); const doubleClick = (now - clickTimestamp) <= 500; clickTimestamp = new Date().getTime(); return doubleClick; }; return d3.drag() .on('start', () => { this.view.actions.startDrag(d3.event); d3.event.sourceEvent.stopPropagation(); }) .on('drag', () => { this.view.actions.onDrag(d3.event); d3.event.sourceEvent.stopPropagation(); this.update(); }) .on('end', function() { if (testDoubleClick()) { this.clickHandler(d3.event); return ; } else { this.view.actions.endDrag(d3.event); d3.event.sourceEvent.stopPropagation(); this.update(); } d3.event.sourceEvent .target.parentElement.setAttribute('class', 'node selected'); }.bind(this)); } clickHandler(event) { console.debug('click'); this.view.actions.onClick(event, this.update.bind(this)); } }
JavaScript
class Specifications{ /** * Get information about current implementation */ static user() { return { general: { languages: navigator.languages, }, navigator: { userAgent: navigator.userAgent, appCodeName: navigator.appCodeName, appName: navigator.appName, appVersion: navigator.appVersion, buildId: navigator.buildID, doNotTrack: navigator.doNotTrack, plugins: Specifications.plugins(), }, services:{ websocket: Boolean(window.WebSocket), cookieEnabled: navigator.cookieEnabled, }, system: { oscpu: navigator.oscpu, platform: navigator.platform, }, screen: { resolution: screen.width + 'x' + screen.height, color_depth: screen.colorDepth + ' bits', window: window.innerWidth + 'x' + window.innerHeight, }, } } /** * Get list of plugins * @return {{}} */ static plugins(){ let res = {}; for (let i = 0; i < navigator.plugins.length; i++){ const plugin = navigator.plugins[i]; if (plugin) { res[plugin.name] = plugin.description; } } return res; } }
JavaScript
class Keys { /** * Generates a new keypair from the given curve. * * @param {Curve} curve * @returns {KeyPair} */ static generate(curve) { if (curve === undefined) { // eslint-disable-next-line no-param-reassign curve = Curve.getDefaultCurve(); } else if (!(curve instanceof Curve)) { // eslint-disable-next-line no-param-reassign curve = new Curve(curve); } if (curve.supported === false) { throw new Error('Unsupported curve: ' + curve.name); } // TODO: entropy? // eslint-disable-next-line new-cap const kp = new elliptic(curve.name).genKeyPair(); return new KeyPair( new PrivateKey( new BC(kp.getPrivate().toArray()), curve ), new PublicKey( new BC(kp.getPublic().getX().toArray()), new BC(kp.getPublic().getY().toArray()), curve) ); } /** * Creates a new keypair from the given private key. * * @param {PrivateKey} privateKey * @returns {KeyPair} */ static fromPrivateKey(privateKey) { if (privateKey.curve.supported === false) { throw new Error('Unsupported curve: ' + privateKey.curve.name); } const kp = elliptic(privateKey.curve.name).keyFromPrivate(privateKey.key.buffer); if (!privateKey.key.equals(new BC(kp.getPrivate().toArray()))) { throw new Error('Something went wrong, the imported private key does not equal the elliptic one'); } return new KeyPair( privateKey, new PublicKey( new BC(kp.getPublic().getX().toArray()), new BC(kp.getPublic().getY().toArray()), privateKey.curve) ); } /** * * @param keyPair * @param digest * @returns {{r: BC, s: BC}} */ static sign(keyPair, digest) { // create an ecpair const ecPair = elliptic(keyPair.curve.name).keyFromPrivate(keyPair.privateKey.key.buffer); const signature = ecPair.sign(digest.buffer, ecPair.getPrivate('hex'), 'hex', { canonical: false }); // Verify signature if (ecPair.verify(digest.buffer, signature.toDER()) === false) { throw Error('Unable to verify the sign result.'); } return { s: new BC(Buffer.from(signature.s.toArray())), r: new BC(Buffer.from(signature.r.toArray())) }; } }
JavaScript
class Employee { constructor(name, id, email){ //Validates constructor if (typeof name !== "string" || !name.trim().length) { throw new Error("Expected parameter 'name' to be a non-empty string"); } if (typeof id !== "number" || isNaN(id)) { throw new Error("Expected parameter 'id' to be a number"); } if (typeof email !== "string" || !email.trim().length) { throw new Error("Expected parameter 'email' to be a non-empty string"); } //Assigns object properties to constructor arguments this.name = name; this.id = id; this.email = email; this.role = 'Employee' } // Gets the employee name getName(){ return this.name; }; //Gets the employee ID getID(){ return this.id; }; //Gets the employee email getEmail(){ return this.email; }; //Gets the employee role getRole(){ return this.role; }; }
JavaScript
class CustomPaymentMethodService { // /** // * // * @param {object} payment The payment selected on checkout // * @param {object} data The bigcommerce CheckoutService data // * @param {object} response The response from create payment // */ // constructor(payment, data, response = '') { // this.payment = payment; // this.data = data; // this.response = response; // } static async fetchCustomPaymentMethods(storeProfile){ await fetch("https://bc-custom-payment.herokuapp.com/admin/payment-methods/get-all/" + storeProfile.storeHash) .then(res => res.json()) .then( (result) => { console.log(result); }, // Deal with error here so catch doesn't break component (error) => { } ) } // handlePayment(){ // console.log( // "Links:", // this.data.getConfig().links.orderConfirmationLink, // this.data.getConfig().links.checkoutLink, // this.data.getConfig().links.cartLink, // this.data.getConfig().links.siteLink, // ); // return new Promise((resolve, reject) => { // this.createPayment(this.payment, this.data) // .then(() => { // this.handleResponse(); // resolve(); // }) // .catch((err) => { // reject(err); // }); // }); // } // /** // * Send a POST request to the app to create the Payment. // */ // createPayment(payment, data){ // // Simple POST request with a JSON body using fetch // const requestOptions = { // method: 'POST', // headers: { 'Content-Type': 'application/json' }, // body: JSON.stringify({ // order_id: data.getOrder().orderId, // payment_method_config_id: payment.customMethodId, // items: data.getOrder().lineItems, // links: { // success: data.getConfig().links.orderConfirmationLink, // pending: data.getConfig().links.orderConfirmationLink, // failure: data.getConfig().links.orderConfirmationLink, // } // }) // }; // return new Promise((resolve, reject) => { // fetch("https://bc-custom-payment.herokuapp.com/admin/payments/" + data.getConfig().storeProfile.storeHash, requestOptions) // .then(response => response.json()) // .then(data => { // console.log('Return create payment: ', data); // this.response = data; // resolve(); // // if(typeof data.redirectUrl !== 'undefined'){ // // window.open(data.redirectUrl, '_blank'); // // resolve() // // } // }) // .catch(err => reject(err)) // }) // } // /** // * Method to handle the response received from the ajax call to the // * App to create a payment. // */ // handleResponse(){ // console.log(`Processing ${this.response.paymentType} payment...`); // switch(this.response.paymentType){ // case 'mercadopago': // this.handleMercadoPago(); // break; // default: // console.log(`Sorry, not a payment type.`); // } // } // handleMercadoPago(){ // if(typeof this.response.redirectUrl !== 'undefined'){ // window.open(this.response.redirectUrl, '_blank'); // } // } }
JavaScript
class Logger { #e = process.env.NODE_ENV #filename #id = Math.floor(Math.random() * 100) #dir = resolve(__dirname, '../../logs') #path #console /** * @param {String} filename The filename for the log file * @param {'info' | 'debug' | 'warn' | 'error' | 'fatal'} level The debug level */ constructor(filename, level = levels.info) { this.level = level this.#filename = `${filename}.${this.#e}.log` this.#dir = resolve(__dirname, '../../logs') this.#path = resolve(this.#dir, this.#filename) this.#refresh() this.#console = new console.Console(createWriteStream(this.#path, { flags: 'a' })) this.#console.log(`\n<<- ${new Date().toISOString()} =<< <||| ~@[${this.#id}] |||> >>= [${this.level}] ->>\n`) } #refresh() { if (this.#e === 'production') return true if (!existsSync(this.#dir)) mkdir(this.#dir, () => {}) if (!existsSync(this.#path)) this.#console = new console.Console(createWriteStream(this.#path, { flags: 'a' })) } /** * Logs a message <br> * Doesn't do anything in production environment * * @param {...String} msgs The messages to be logged * @public */ log(...msgs) { if (this.#refresh()) return const date = new Date().toISOString() const finalMsg = `${date}\t~@[${this.#id}]\t[${this.level}]\t${msgs.join(' ')}` switch (this.level) { case levels.info: this.#console.info(finalMsg) break case levels.debug: this.#console.debug(finalMsg) break case levels.warn: this.#console.warn(finalMsg) break case levels.error: case levels.fatal: this.#console.error(finalMsg, '\n') break default: this.#console.log(finalMsg) break } return this } /** * The default logger to be used */ static logger = new Logger('default') /** * The error logger to be used */ static error = new Logger('error', levels.error) static levels = levels static Logger = Logger /** * Custom logger * * @param {'info' | 'debug' | 'warn' | 'error' | 'fatal'} level The level to be logged * @param {...String} msgs The messages to log */ static log = (level, ...msgs) => { const logger = new Logger(['error', 'fatal'].includes(level) ? 'error' : 'default', level) logger.log(msgs) } }
JavaScript
class Installs extends Commands { /** * Fetches a list of WordPress installs in users wpengine accounts. * @returns Object * @since 1.0.0 */ listInstalls = async () => { const data = await fetch(`https://api.wpengineapi.com/v1/installs`, { method: 'GET', headers: { 'Authorization': this.auth.authorization }, }) const json = await data.json(); const accounts = json.results.map(data => { return { name: data.name, value: data.id }; }) return accounts; } newInstall = async () => { } installs = () => { // Add prompts here } }
JavaScript
class Countdown extends React.PureComponent { state = { time: 0 } /** * Set interval to update counter */ componentDidMount () { this.tick() } /** * Update countdown time when the date has changed. * * @param {object} nextProps */ componentWillReceiveProps (nextProps) { if (nextProps.targetDate !== this.props.targetDate) { this.tick(nextProps) } } /** * Stop ticking when it's not mounted anymore. */ componentWillUnmount () { clearTimeout(this.tickTimeout) } /** * Calculate time left. */ tick = (props) => { const { targetDate } = props || this.props this.countTime(targetDate) clearTimeout(this.tickTimeout) this.tickTimeout = setTimeout(this.tick, 300) } /** * Update time in state. * * @param {string} targetDate */ countTime (targetDate) { const convertedDate = Date.parse(targetDate) this.setState({ time: Math.max(0, convertedDate - Date.now()) }) } /** * Render countdown. * * @returns {React.Element} */ render () { const { time } = this.state const { render: Renderer, ...passedProps } = this.props const seconds = Math.floor((time / 1000) % 60) const minutes = Math.floor((time / 1000 / 60) % 60) const hours = Math.floor(time / (1000 * 60 * 60) % 24) const days = Math.floor(time / (1000 * 60 * 60 * 24)) const finished = time === 0 const countdownProps = { ...passedProps, time, days, hours, minutes, seconds, finished } return <Renderer {...countdownProps} /> } }
JavaScript
class WSServer { /** * construction of the WSServer * @param {Object} config configuration object * @param {...} */ constructor(config, bridge) { this.WebSocketServer = require('websocket').server; this.http = require('http'); this._bridge = bridge; this._config = config; this._handlers = new Map(); this._mnManager = MNManager.getInstance(); } /** * Start and initialize the Websocket endpoint of the Matrix MessagingNode. * */ start() { var httpServer = this.http.createServer(() => {}).listen( this._config.WS_PORT, () => { console.log("+[WSServer] [start] " + (new Date()) + " MatrixMN is listening on port " + this._config.WS_PORT); } ); let wsServer = new this.WebSocketServer({ httpServer: httpServer }); wsServer.on('request', (request) => { this._handleRequest(request); }); } _handleRequest(request) { let path = request.resourceURL.path; // console.log("+[WSServer] [_handleRequest] %s: received connection request from: %s origin: %s path: %s", (new Date()), request.remoteAddress, request.origin, path); if (request.resourceURL.path !== "/stub/connect") { request.reject(403, "Invalid request path!"); return; } let con = request.accept(null, request.origin); con.on('message', (msg) => { this._handleMessage(con, msg); }); con.on('close', () => { this._handleClose(con); }); } _handleMessage(con, msg) { let m; // console.log("+[WSServer] [_handleMessage] Connection received msg: %s", msg.utf8Data); if (msg.type === "utf8" && (msg.utf8Data.substr(0, 1) === "{")) m = JSON.parse(msg.utf8Data); // if its not a fresh connection the connection should have a runtimeURL injected if (con.runtimeURL) { let handler = this._handlers.get(con.runtimeURL); if (handler) { // check for disconnect command from stub with proper runtimeURL if ( m.cmd === "disconnect" && m.data.runtimeURL === con.runtimeURL) { console.log( "+[WSServer] [_handleMessage] DISCONNECT command from %s ", m.data.runtimeURL ); // cleanup handler and related resources handler.cleanup(); // remove all mappings of addresses to this handler this._mnManager.removeHandlerMappingsForRuntimeURL(con.runtimeURL); // remove handler from own housekeeping this._handlers.delete(con.runtimeURL); try { con.close(); } catch(e) {} } else handler.handleStubMessage(m, this); } else console.log("+[WSServer] [_handleMessage] no matching StubHandler found for runtimeURL %", con.runtimeURL); } else { // handle first message that was received via this websocket. if (m.cmd === "connect" && m.data.runtimeURL) { // use given runtimeURL as ID and inject it to the con object for later identification con.runtimeURL = m.data.runtimeURL; console.log("+[WSServer] [_handleMessage] external stub connection with runtimeURL %s", con.runtimeURL); this._createHandler(con.runtimeURL, con) .then(() => { this._sendResponse(con, 200, "Connection accepted!"); }); } else { this._sendResponse(con, 403, "Invalid handshake!"); con.close(); } } } /** * lazy creation of handlers * performs all actions to instantiate, initialize and register a handler, if necessary * returns existing instance otherwise */ _createHandler(runtimeURL, con) { return new Promise((resolve, reject) => { let handler = this._handlers.get(runtimeURL); if (handler) { // console.log("+[WSServer] [_createHandler] found existing handler"); handler.updateCon(con); resolve(handler); } else { // let userId = this._mnManager.createUserId(runtimeURL); let handler = new WSHandler(this._config, con); // perform handler initialization (creation and syncing of the intent) handler.initialize(this._bridge) .then(() => { this._handlers.set(runtimeURL, handler); // TODO: check why we need to set it twice - from -> to? console.log("+[WSServer] [_createHandler] created and initialized new WSHandler for runtimeURL %s", con.runtimeURL); // add mapping of given runtimeURL to this handler this._mnManager.addHandlerMapping(runtimeURL, handler); resolve(handler); // TODO: check where it is invoked from, maybe not needed to return the handler }) } }); } _sendResponse(con, code, msg) { con.send(JSON.stringify({ cmd: "connect", response: code, data: { msg: msg } })); } _handleClose(con) { console.log("+[WSServer] [_handleClose] closing connection to runtimeURL: " + con.runtimeURL); var handler = this._handlers.get(con.runtimeURL); if (handler) { handler.releaseCon(); } } }
JavaScript
class Hero2 extends Phaser.Sprite { constructor(game, x, y) { // call Phaser.Sprite constructor super(game, x, y, 'hero'); // Phaser: make the hero pinned to a specific coord this.anchor.set(0.5, 0.5); // Phaser: enable physics for this sprite this.game.physics.enable(this); // Phaser: make the body stay inside the screen bounds this.body.collideWorldBounds = true; } /* * add more public/private methods to the class down here */ // public custom method move(direction) { // Instead of acting directly on the position... // this.x += direction * 2.5; // 2.5 pixels each frame // ...affect the body (physics) of the sprite const SPEED = 200; this.body.velocity.x = direction * SPEED; } // public custom method jump() { const JUMP_SPEED = 600; let canJump = this.body.touching.down; if (canJump) { this.body.velocity.y = -JUMP_SPEED; } return canJump; }; // public custom method bounce() { const BOUNCE_SPEED = 200; this.body.velocity.y = -BOUNCE_SPEED; }; }
JavaScript
class BookController { /** * @description this method adds a new book to the database * * @param {object} req * @param {object} res * * @returns {object} add book message and book as payload */ static addBook(req, res) { bookModel.create(req.body).then((book) => { res.status(201).json({ message: 'Book created', payload: book }); }).catch((error) => { const messageObject = errorMessages(error); switch (messageObject.type) { case 'uniqueError': res.status(409).json({ message: messageObject.error }); break; default: res.status(500).json({ message: 'Internal server error' }); } }); } /** * @description This method deletes a book from the database * * @param {object} req request object * @param {object} res response object * * @returns {object} deleted book id and message */ static deleteBook(req, res) { const { id } = req.params; findOneResource(borrowedBookModel, { where: { bookId: id, returnStatus: false } }) .then((response) => { if (response !== null) { return res.status(422).json({ message: 'This book has been borrowed and cannot be deleted' }); } borrowedBookModel.destroy({ where: { id } }).then(() => { findOneResource(bookModel, { where: { id } }) .then((reply) => { if (!reply) { return res.status(404).json({ message: 'Book not found in the database' }); } return bookModel.destroy({ where: { id } }) .then(() => { res.status(200).json({ message: 'Book has been successfully deleted', bookId: id }); }); }); }).catch(() => { return res.status(500).json({ message: 'Internal service error' }); }); }); } /** * @description This method gets all the books in the database * * @param {object} req Request object * @param {object} res Response object * * @returns {object} All books in the library */ static getBooks(req, res) { findAllResources(bookModel, { include: { model: categoryModel } }).then((response) => { res.status(200).json({ books: response }); }).catch(() => { res.status(500).json({ message: 'Internal server error' }); }); } /** * @description This method gets all the borrowed books in the database * * @param {object} req Request object * @param {object} res Response object * * @returns {object} borrowedbooks */ static getBorrowedBooks(req, res) { findAllResources(borrowedBookModel, { include: { model: bookModel, include: { model: categoryModel } } }) .then((response) => { res.status(200).json({ books: response }); }).catch(() => { res.status(500).json({ message: 'Internal server error' }); }); } /** * @description This method gets a book by its Id * * @param {object} req Request object * @param {object} res Response object * * @returns {object} book payload */ static getBookById(req, res) { const { id } = req.body; findOneResource(bookModel, { where: { id } }) .then((book) => { if (!book) { return res.status(404).json({ message: 'This books is not available in our database' }); } return res.status(200).json({ payload: book }); }) .catch(() => { res.status(500).json({ message: 'Internal server error' }); }); } /** * @description This method edits or modifies a book in the database * * @param {object} req request object * @param {object} res response object * * @returns {object} Modified book */ static modifyBook(req, res) { const { id } = req.body; const query = { where: { id, visibility: true } }; const bookData = { pages: req.body.pages, author: req.body.author, year: req.body.year, title: req.body.title, categoryId: req.body.categoryId, description: req.body.description, quantity: req.body.quantity, imageUrl: req.body.imageUrl, PDFUrl: req.body.PDFUrl }; findOneResource(bookModel, query) .then((book) => { if (!book) return res.status(404).json({ message: 'Book not found' }); book.update(bookData) .then((updated) => { if (updated) { return findOneResource(bookModel, { where: { id: updated.id }, include: { model: categoryModel } }).then((response) => { res.status(200).json({ message: 'Book modified successfully', payload: response }); }); } }).catch((error) => { const messageObject = errorMessages(error); switch (messageObject.type) { case 'uniqueError': res.status(409).json({ message: messageObject.error }); break; default: res.status(500).json({ message: 'Internal server error' }); } }) .catch(() => res.status(500).json({ message: 'Internal server error' })); }); } /** * @description This method allows a user to borrow a book * * @param {object} req request object * @param {object} res response object * * @returns {object} response payload */ static borrowBook(req, res) { const { bookId, userId, expectedReturnDate } = req.body; const payload = { bookId, userId, expectedReturnDate }; borrowedBookModel.create(payload) .then((response) => { bookModel.update({ quantity: req.book.dataValues.quantity - 1 }, { where: { id: response.dataValues.bookId } }) .then((updateResponse) => { if (updateResponse) { return res.status(201).json({ message: 'You have successfully borrowed this book', returnDate: expectedReturnDate, bookBorrowed: response.dataValues }); } }); }) .catch(() => { res.status(500).json({ message: 'Internal server error' }); }); } /** * @description This method allows a user to return a borrowed book * * @param { object } req Requst body * @param { object } res Response body * * @returns { object } returns json object */ static returnBook(req, res) { const { userId, bookId } = req.body; const userIdInteger = parseInt(userId, 10); const bookIdInteger = parseInt(bookId, 10); findOneResource(borrowedBookModel, { where: { userId: userIdInteger, bookId: bookIdInteger, returnStatus: false } }) .then((response) => { if (response === null) { res.status(404).json({ message: 'This book is not in your latest borrow history' }); } else { borrowedBookModel.update({ returnStatus: true }, { where: { id: response.dataValues.id } }) .then((feedback) => { if (feedback) { findOneResourceById(bookModel, bookId) .then((foundBook) => { bookModel.update({ quantity: foundBook.dataValues.quantity + 1 }, { where: { id: bookId } }).then((updated) => { if (updated) { res.status(200).json({ message: 'Book has been returned' }); } }); }); } }) .catch(() => { res.status(500).json({ message: 'Internal server error' }); }); } }); } /** * @description This method adds a category to the database * * @param {object} req request body * @param {object} res response body * * @return {object} response object as categories */ static addCategory(req, res) { const { category } = req.body; categoryModel.create({ category }) .then((reply) => { if (reply) { findAllResources(categoryModel) .then((response) => { res.status(201).json({ message: 'Category created', payload: response }); }) .catch(() => { res.status(500).json({ message: 'Category could not be created' }); }); } }) .catch((error) => { const messageObject = errorMessages(error); switch (messageObject.type) { case 'uniqueError': res.status(409).json({ error: messageObject.error }); break; default: res.status(500).json({ error: 'Internal server error' }); } }); } /** * @description This method fetches all categories from the database * * @param { object } req request object * @param { object } res respones object * * @return { object } categories as payload */ static getCategories(req, res) { findAllResources(categoryModel) .then((categories) => { if (categories) { res.status(200).json({ categories }); } }) .catch(() => { res.status(500) .json({ message: 'Internal server error' }); }); } /** * @description Fetches the last 4 upload books as trending books * * @param { object } req request object * @param { object } res response object * * @return { object } trending books */ static fetchTrendingBooks(req, res) { findAllResources(bookModel, { limit: 4, order: [['createdAt', 'DESC']] }) .then((response) => { res.status(200).json({ trendingBooks: response }); }) .catch(() => { res.status(500).json({ message: 'Internal server error' }); }); } }
JavaScript
class Globie { constructor() { // BINDINGS this.onResize = this.onResize.bind(this); this.onReady = this.onReady.bind(this); this.handleScroll = this.handleScroll.bind(this); this.triggerFootTap = this.triggerFootTap.bind(this); this.runFootTap = this.runFootTap.bind(this); $(window).resize(this.onResize); $(document).ready(this.onReady); this.$globie = $('svg.globie'); this.footFrame = 1; this.footTapRate = 60; this.footTapNumber = this.footTapRate * (9 * 3); // 3 taps this.footTapDelay = 10000; // 10 secs this.bodyRotateRate = 30; } onResize() { } onReady() { this.setFootTap(); this.bindMouseMove(); this.bindScroll(); } bindScroll() { $(window).on('scroll', this.handleScroll); $('#project-wrapper').on('scroll', this.handleScroll); } handleScroll(event) { this.scrollTop = $(event.target).scrollTop(); this.rotateBody(); } rotateBody() { const scrollTop = this.scrollTop / this.bodyRotateRate; const frame = Math.floor(scrollTop % 24) + 1; this.$globie.find('g.show').removeClass('show'); this.$globie.find('g.body-' + frame + '').addClass('show'); } setFootTap() { // trigger foot tapping after tap delay setInterval(() => { this.triggerFootTap(); // cancel tapping after number of taps setTimeout(this.cancelFootTap.bind(this), this.footTapNumber); }, this.footTapDelay); } triggerFootTap() { this.tapTimeout = setTimeout(this.runFootTap, this.footTapRate); } runFootTap() { this.tapRequest = window.requestAnimationFrame(this.triggerFootTap); this.tapFoot(); } tapFoot() { // hide current foot frame and show next this.$globie.find('path.right-' + this.footFrame).removeClass('show'); this.footFrame = this.footFrame === 8 ? 1 : this.footFrame + 1; this.$globie.find('path.right-' + this.footFrame).addClass('show'); } cancelFootTap() { clearTimeout(this.tapTimeout); window.cancelAnimationFrame(this.tapRequest); // reset foot to first frame this.$globie.find('path.right-' + this.footFrame).removeClass('show'); this.footFrame = 1; this.$globie.find('path.right-1').addClass('show'); } bindMouseMove() { window.addEventListener('mousemove', this.cancelFootTap.bind(this)); } }
JavaScript
class UserStatsBans extends BitField { /** * @returns {STAT_INDICATIONS} */ get bansObject() { return UserStatsBans.toBansObject(this.bansString); } /** * @returns {string} */ get bansString() { return UserStatsBans.toBansString({ stars: this.STARS, diamonds: this.DIAMONDS, scoins: this.SCOINS, ucoins: this.UCOINS, demons: this.DEMONS, cp: this.CP, net: this.NET }); } /** * @description Whether the user is banned from the stars leaderboard * @type {boolean} * @param {boolean} bool */ get STARS() { return this.has(this.indicators.STARS); } set STARS(bool) { return this.resolveBitBoolean(this.indicators.STARS, bool); } /** * @description Whether the user is banned from the diamonds leaderboard * @type {boolean} * @param {boolean} bool */ get DIAMONDS() { return this.has(this.indicators.DIAMONDS); } set DIAMONDS(bool) { return this.resolveBitBoolean(this.indicators.DIAMONDS, bool); } /** * @description Whether the user is banned from the secret coins leaderboard * @type {boolean} * @param {boolean} bool */ get SCOINS() { return this.has(this.indicators.SCOINS); } set SCOINS(bool) { return this.resolveBitBoolean(this.indicators.SCOINS, bool); } /** * @description Whether the user is banned from the user coins leaderboard * @type {boolean} * @param {boolean} bool */ get UCOINS() { return this.has(this.indicators.UCOINS); } set UCOINS(bool) { return this.resolveBitBoolean(this.indicators.UCOINS, bool); } /** * @description Whether the user is banned from the demons leaderboard * @type {boolean} * @param {boolean} bool */ get DEMONS() { return this.has(this.indicators.DEMONS); } set DEMONS(bool) { return this.resolveBitBoolean(this.indicators.DEMONS, bool); } /** * @description Whether the user is banned from the creator points leaderboard * @type {boolean} * @param {boolean} bool */ get CP() { return this.has(this.indicators.CP); } set CP(bool) { return this.resolveBitBoolean(this.indicators.CP, bool); } /** * @description Whether the user is banned from the net score leaderboard * @type {boolean} */ get NET() { return Object.values(this.indicatorsObj()).includes(true); } /** * @description Performs adjustments based on an entered bit representation * * `NUMBER` - bit value * * `STRING` - hex * * `OBJECT` - stat, boolean paired bit object representation * @param {number|string|(Object<string, number>)|STAT_INDICATIONS} bit */ resolve(bit) { if (typeof bit === "string") this.resolve(UserStatsBans.toBansObject(bit)); else if (Object.prototype.toString.call(bit) === "[object Object]" && !Object.keys(bit).every(k => /^[0-9]{1,}$/.test(k))) this.resolve(Object.entries(bit).reduce((v, [stat, bool]) => { if (/^(stars?)$/i.test(stat)) v[this.indicators.STARS] = bool; if (/^(diamonds?)$/i.test(stat)) v[this.indicators.DIAMONDS] = bool; if (/^(scoins?|secretcoins?|secret coins?|coins?)$/i.test(stat)) v[this.indicators.SCOINS] = bool; if (/^(ucoins?|usercoins?|user coins?)$/i.test(stat)) v[this.indicators.UCOINS] = bool; if (/^(demons?)$/i.test(stat)) v[this.indicators.DEMONS] = bool; if (/^(cp|creatorpoints?|creator points?)$/i.test(stat)) v[this.indicators.CP] = bool; return v; }, {})); else super.resolve(bit); } }
JavaScript
class BigImageCarouselSketch { constructor(p5, surface, extraArgs) { this.p5 = p5; this.surface = surface; this.tiles = null; this.image_list_config = extraArgs; } preload() { var p5 = this.p5; this.backgroundColor = p5.color(120); this.tiles = []; for (let path in this.image_list_config) { let images = this.image_list_config[path]; for (let i in images) { // TODO(jgessner): switch to functional style. let image = images[i]; for (let x = 0; x < image.num_x_tiles; x++) { let tilePath = asset(path + image.name + '_tile-' + x + '_' + this.surface.virtualOffset.y + '.' + image.extension); this.tiles.push(p5.loadImage(tilePath)); } } } } setup() { var p5 = this.p5; p5.noFill(); p5.stroke(255, 0, 0); p5.strokeWeight(4); // Each instance will only ever draw images from one Y offset, but many X offsets. if (!this.tiles || !this.tiles.length) { return; } this.sum_tile_width = 0; for (let x = 0; x < this.tiles.length; x++) { this.sum_tile_width += this.tiles[x].width; } if (this.sum_tile_width < this.surface.wallRect.w) { let initial_sum_tile_width = this.sum_tile_width; while (this.sum_tile_width < this.surface.wallRect.w) { this.tiles = this.tiles.concat(this.tiles); this.sum_tile_width += initial_sum_tile_width; } } // Pre-draw the images off-screen so we don't need to load them or decode them while drawing. for (let i in this.tiles) { p5.image(this.tiles[i], -10000, -10000); } } draw(t) { var p5 = this.p5; if (this.tiles == null) { return; } if (this.surface.virtualOffset.y == null) { return; } // x_0 is the actual position that the first tile should be drawn at. // Make sure to draw integer pixel positions or performance will suffer. let x_0 = Math.floor((((t - this.surface.startTime) / 9) % (2*this.sum_tile_width)) - this.sum_tile_width); // for each iteration: // - translate x zero // - fit all of the tiles necessary into a given window (the overall width)) // states: // - only draw positive // - draw negative and positive // - // from all of the images, figure out the total width. That strip will be the thing that cycles. // if sum of all image widths > wall width, identify the starting let x_offset = x_0; // walk backwards through the list to draw the tail end until we have no more of it. // Draw the "positive" images. const screen_right_edge = this.surface.virtualRect.x + this.surface.virtualRect.w; for (let x = 0; x < this.tiles.length; x++) { let image = this.tiles[x]; let right_x = x_offset + image.width; // Do we need to draw this image? if ((x_offset >= this.surface.virtualRect.x && x_offset <= screen_right_edge) || (right_x >= this.surface.virtualRect.x && right_x < screen_right_edge)) { p5.image(image, x_offset, this.surface.virtualRect.y); } x_offset += image.width; } if (x_0 < 0) { // need to fill in images on the right. while (x_offset < this.surface.wallRect.w) { for (let x = 0; x < this.tiles.length; x++) { let image = this.tiles[x]; let right_x = x_offset + image.width; // Do we need to draw this image? if ((x_offset >= this.surface.virtualRect.x && x_offset <= screen_right_edge) || (right_x >= this.surface.virtualRect.x && right_x < screen_right_edge)) { p5.image(image, x_offset, this.surface.virtualRect.y); } x_offset += image.width; } } } if (x_0 > 0) { x_offset = x_0; for (let x = this.tiles.length - 1; x >= 0; x--) { let image = this.tiles[x]; x_offset -= image.width; let right_x = x_offset + image.width; // Do we need to draw this image? if ((x_offset >= this.surface.virtualRect.x && x_offset <= screen_right_edge) || (right_x >= this.surface.virtualRect.x && right_x < screen_right_edge)) { p5.image(image, x_offset, this.surface.virtualRect.y); } } } } }
JavaScript
class Header extends Component { render() { return <Navbar className={this.props.className} bg="light" expand="xs"> <h1>SIT-MapChecker</h1> <div> <div> <span className="switch-caption">Multiple Building Analyzer </span> <label name="multibuildingswitchSwitch" className="switch"> <input type="checkbox" onChange={this.props.toggleMultiBuilding} /> <span className="slider round"></span> </label> </div> <div> <span className="switch-caption">Accessibility: </span> <label name="accessibilitySwitch" className="switch"> <input type="checkbox" onChange={this.props.toggleAccessibilityMode} /> <span className="slider round"></span> </label> </div> </div> </Navbar>; } }
JavaScript
class ReactNipple extends Component { /* eslint-disable no-trailing-spaces */ /** * Component propTypes * * Any additional (unknown) props will be passed along as attributes of the created DOM element. * * @property {string} className - A css classname for the DOM element * @property {object} options - An object with nipplejs options, see https://github.com/yoannmoinet/nipplejs#options * @property {boolean} static - A shortcut for setting the options `{mode: 'static', position: {top: '50%', left: '50%'}}`. Will override values in the `options` object. * @property {function} onCreated - Callback that is invoked with the created instance * @property {function} onDestroy - Callback that is invoked with the instance that is going to be destroyed * @property {function} onStart - Callback for the 'start' event handler, see https://github.com/yoannmoinet/nipplejs#start * @property {function} onEnd - Callback for the 'end' event handler, see https://github.com/yoannmoinet/nipplejs#end * @property {function} onMove - Callback for the 'move' event handler, see https://github.com/yoannmoinet/nipplejs#move * @property {function} onDir - Callback for the 'dir' event handler, see https://github.com/yoannmoinet/nipplejs#dir * @property {function} onPlain - Callback for the 'plain' event handler, see https://github.com/yoannmoinet/nipplejs#plain * @property {function} onShown - Callback for the 'shown' event handler, see https://github.com/yoannmoinet/nipplejs#shown * @property {function} onHidden - Callback for the 'hidden' event handler, see https://github.com/yoannmoinet/nipplejs#hidden * @property {function} onPressure - Callback for the 'pressure' event handler, see https://github.com/yoannmoinet/nipplejs#pressure */ /* eslint-enable no-trailing-spaces */ static get propTypes() { return { className: PropTypes.string, options: PropTypes.shape({ color: PropTypes.string, size: PropTypes.integer, threshold: PropTypes.float, // before triggering a directional event fadeTime: PropTypes.integer, // transition time multitouch: PropTypes.bool, maxNumberOfNipples: PropTypes.number, // when multitouch, what is too many? dataOnly: PropTypes.bool, // no dom element whatsoever position: PropTypes.object, // preset position for 'static' mode mode: PropTypes.string, // 'dynamic', 'static' or 'semi' restJoystick: PropTypes.bool, restOpacity: PropTypes.number, // opacity when not 'dynamic' and rested catchDistance: PropTypes.number }), static: PropTypes.bool, onStart: PropTypes.func, onEnd: PropTypes.func, onMove: PropTypes.func, onDir: PropTypes.func, onPlain: PropTypes.func, onShown: PropTypes.func, onHidden: PropTypes.func, onPressure: PropTypes.func, onCreated: PropTypes.func, onDestroy: PropTypes.func }; } get ownProps() { return [ 'options', 'static', 'onStart', 'onEnd', 'onMove', 'onDir', 'onPlain', 'onShown', 'onHidden', 'onPressure', 'onCreated' ]; } get elementProps() { return Object.entries(this.props).reduce((result, [key, value]) => { if (this.ownProps.includes(key)) { return result; } result[key] = value; return result; }, {}); } componentDidUpdate(prevProps) { if (!isEqual(prevProps.options, this.props.options)) { this.destroyJoystick(); this.createJoystick(); } } render() { return ( <div {...this.elementProps} ref={this.handleElement} className={cx('ReactNipple', this.props.className)} /> ); } //----------------------------------- // // impl // //----------------------------------- @autobind handleElement(ref) { this._element = ref; if (ref) { this.createJoystick(this.props); } else if (this._element) { this.destroyJoystick(); } } createJoystick(props) { const options = { zone: this._element, ...props.options }; if (this.props.static) { options.mode = 'static'; options.position = { top: '50%', left: '50%' }; } const joystick = nipplejs.create(options); joystick.on('start', this.handleJoystickStart); joystick.on('end', this.handleJoystickEnd); joystick.on('move', this.handleJoystickMove); joystick.on('dir', this.handleJoystickDir); joystick.on('plain', this.handleJoystickPlain); joystick.on('shown', this.handleJoystickShown); joystick.on('hidden', this.handleJoystickHidden); joystick.on('pressure', this.handleJoystickPressure); this.joystick = joystick; if (props.onCreated) { props.onCreated(this.joystick); } } destroyJoystick() { if (this.joystick) { this.joystick.destroy(); this.joystick = undefined; } } invokeCallback(type, evt, data) { if (this.props[type]) { this.props[type](evt, data); } } @autobind handleJoystickStart(evt, data) { this.invokeCallback('onStart', evt, data); } @autobind handleJoystickEnd(evt, data) { this.invokeCallback('onEnd', evt, data); } @autobind handleJoystickMove(evt, data) { this.invokeCallback('onMove', evt, data); } @autobind handleJoystickDir(evt, data) { this.invokeCallback('onDir', evt, data); } @autobind handleJoystickPlain(evt, data) { this.invokeCallback('onPlain', evt, data); } @autobind handleJoystickShown(evt, data) { this.invokeCallback('onShown', evt, data); } @autobind handleJoystickHidden(evt, data) { this.invokeCallback('onHidden', evt, data); } @autobind handleJoystickPressure(evt, data) { this.invokeCallback('onPressure', evt, data); } }
JavaScript
class RotationalMotorEquation extends Equation { constructor(bodyA, bodyB, maxForce = 1e6) { super(bodyA, bodyB, -maxForce, maxForce) /** * World oriented rotational axis * @property {Vec3} axisA */ this.axisA = new Vec3() /** * World oriented rotational axis * @property {Vec3} axisB */ this.axisB = new Vec3() // World oriented rotational axis /** * Motor velocity * @property {Number} targetVelocity */ this.targetVelocity = 0 } computeB(h) { const a = this.a const b = this.b const bi = this.bi const bj = this.bj const axisA = this.axisA const axisB = this.axisB const GA = this.jacobianElementA const GB = this.jacobianElementB // g = 0 // gdot = axisA * wi - axisB * wj // gdot = G * W = G * [vi wi vj wj] // => // G = [0 axisA 0 -axisB] GA.rotational.copy(axisA) axisB.negate(GB.rotational) const GW = this.computeGW() - this.targetVelocity const GiMf = this.computeGiMf() const B = -GW * b - h * GiMf return B } }
JavaScript
class wanderState { constructor() { this.wanderDist = 0; this.dir = 0.8; } execute(me) { me.checkWalls(); if (me.jump > 0) { me.applyForce(gravity); me.velocity.add(me.acceleration); me.acceleration.set(0, 0); me.position.add(me.velocity); } else { if (this.wanderDist == 0) { this.wanderDist = int(random(50, 100)); this.dir = random([-0.8, 0.8]); } this.wanderDist--; me.position.add(this.dir, 0); if (me.position.x > 770 || me.position.x < 30 || !me.standing) { me.position.add(-this.dir * 5, 0); this.dir = -this.dir; this.wanderDist += 5; } } if ( dist(me.position.x, me.position.y, player.position.x, player.position.y) < 120 ) { me.changeState(1); } } } // wanderState
JavaScript
class chaseState { constructor() { this.onEdge = false; this.edge = ""; } execute(me) { if ( me.position.y - 10 > player.position.y + 35 && me.jump == 0 && player.jump == 0 && me.velocity.y == 0 ) { me.applyForce(jumpForce); me.jump = 1; } if (me.jump > 0) { me.applyForce(gravity); } if (me.position.x < player.position.x) { me.velocity.set(0.8, me.velocity.y); } else { me.velocity.set(-0.8, me.velocity.y); } me.velocity.add(me.acceleration); me.acceleration.set(0, 0); me.position.add(me.velocity); me.checkWalls(); if (!me.standing) { me.jump = 1; } if ( dist(me.position.x, me.position.y, player.position.x, player.position.y) > 120 ) { me.changeState(0); } } } // chaseState
JavaScript
class WebmWasmEngine extends RecordRTCEngine { /** * Setup recording engine. * * @param {LocalMediaStream} stream - Media stream to record. * @param {Object} mediaType - Object describing the media type of this * engine. * @param {Boolean} debug - Indicating whether or not debug messages should * be printed in the console. */ setup(stream, mediaType, debug) { // set options this.recorderType = RecordRTC.WebAssemblyRecorder; this.workerPath = this.videoWorkerURL; super.setup(stream, mediaType, debug); } }
JavaScript
class App extends Component { constructor(props) { super(props); this.state = DEFAULT_STATE; } /* Utilities */ setFilePath = file => { const { name, path } = file; this.setState({ filePath: path, fileName: name, cryptedFilePath: "", viewCode: 1 }); }; /* Event Handlers */ onAbort = () => this.setState(DEFAULT_STATE); onEncrypt = password => { const { filePath } = this.state; const encryptedFilePath = ipcRenderer.sendSync("encryptFileRequest", { filePath, password }); this.setState({ viewCode: 2, cryptedFilePath: encryptedFilePath }); }; onDecrypt = password => { const { filePath } = this.state; ipcRenderer.send("decryptFileRequest", { filePath, password }); ipcRenderer.on("decryptFileResponse", (event, arg) => { const { decryptedFilePath, error } = arg; if (!error) { this.setState({ viewCode: 2, cryptedFilePath: decryptedFilePath }); } else { this.setState({ viewCode: 3 }); } }); }; render() { const { cryptedFilePath, viewCode } = this.state; let filePath, fileName; if (remote.process.argv.length >= 2) { filePath = remote.process.argv[1]; let splitFilePath = filePath.split("/"); fileName = splitFilePath[splitFilePath.length - 1]; } else { filePath = this.state.filePath; fileName = this.state.fileName; } const fileIsEncrypted = filePath.endsWith(".dbolt"); let appBody; if (viewCode === 0) { appBody = <FileUpload setFilePath={this.setFilePath} />; } else if (viewCode === 1 && !fileIsEncrypted) { appBody = ( <CryptForm fileName={fileName} onSubmit={this.onEncrypt} onAbort={this.onAbort} /> ); } else if (viewCode === 1 && fileIsEncrypted) { appBody = ( <CryptForm fileName={fileName} onSubmit={this.onDecrypt} onAbort={this.onAbort} isDecryption={fileIsEncrypted} /> ); } else if (viewCode === 2) { appBody = ( <SuccessScreen onGoHome={() => this.setState({ viewCode: 0 })} filePath={cryptedFilePath} /> ); } else if (viewCode === 3) { appBody = ( <CryptForm fileName={fileName} onSubmit={this.onDecrypt} onAbort={this.onAbort} isDecryption={fileIsEncrypted} displayError={true} /> ); } return ( <div className="app"> <div className="titlebar" /> {appBody} </div> ); } }
JavaScript
class Bandwidther extends EventEmitter { /** * Constructor for the Bandwidther class. Does not validate input data * coherence. * @param {number} sessionId - The session id to perform the pings * @param {number} requestedBw - required bandwidth is in kbits/s * @param {number} negotiationBandwidth - Time to run the test in seconds * @param {Boolean} proactive - Tells teh bandwidther to be proactive */ constructor(sessionId, requestedBw, negotiationBandwidth, proactive) { super(); this.sessionId = sessionId; this.requestedBw = requestedBw; this.negotiationBandwidth = negotiationBandwidth; this.proactive = proactive; this.recieved = []; this.sequence = 0; this.localMeasurements = new Measure(); this.reportedMeasurements = new Measure(); // Generate the random payload. The size is 1000 bytes. const buffer = Buffer.alloc(1000); crypto.randomFillSync(buffer, 1000); this.body = buffer.toString('utf8'); // Fill the required timers for the bandwidth. this.timers = []; let msgPerSec = requestedBw / 8; for (let i = 1; i <= 1000; i++) { const intPart = Math.floor(msgPerSec * i * 0.001); if (intPart !== 0) { msgPerSec = msgPerSec - (intPart * 1000) / i; this.timers.push({ ms: i, times: intPart, }); if (msgPerSec === 0) { break; } } } this.timeoutId = undefined; } /** * Generates a new bandwidther with Client settings. * @param {number} sessionId - The session id to perform the pings * @param {number} requestedBw - required bandwidth is in kbits/s * @param {number} negotiationBandwidth - Time to run the test in seconds * @return {Bandwidther} */ static genClient(sessionId, requestedBw, negotiationBandwidth) { return new Bandwidther(sessionId, requestedBw, negotiationBandwidth, true); } /** * Generates a new bandwidther with Server settings. * @param {number} sessionId - The session id to perform the pings * @param {number} requestedBw - required bandwidth is in kbits/s * @param {number} negotiationBandwidth - Time to run the test in seconds * @return {Bandwidther} */ static genServer(sessionId, requestedBw, negotiationBandwidth) { return new Bandwidther(sessionId, requestedBw, negotiationBandwidth, false); } /** * Starts the measurement stage. * @return {Promise} On sucess the measures, on error the error */ measure() { return new Promise((resolve, reject) => { this.rejectCallback = reject; this.endFunc = () => { console.log('Calling end func'); this.localMeasurements.extractBandwidth(this.recieved, this.requestedBw); this.recieved = []; this.sequence = 0; setImmediate(resolve, { local: this.localMeasurements, remote: this.reportedMeasurements, }); }; this.intervaFunc = (count) => { for (let i = 0; i < count; i++) { const headers = { 'Stage': '1', 'Session-Id': this.sessionId, 'Sequence-Number': this.sequence, 'Measurements': this.localMeasurements.toHeader(), }; this.emit('message', Request.genReq( 'BWIDTH', 'q4s://www.example.com', headers)); this.sequence++; } if (Date.now() > this.endTime) { this.timers.forEach((timer, i, arr) => { if (timer.intervalId) { clearInterval(timer.intervalId); arr[i].intervalId = undefined; } }); this.timeoutId = setTimeout(this.endFunc, 300); } }; if (this.proactive) { this.timers.forEach((timer, i, arr) => { arr[i].intervalId = setInterval(this.intervaFunc, timer.ms, timer.times); }); this.endTime = Date.now() + this.negotiationBandwidth * 1000; } }); } /** * Adds a request to the current measurement. This should only be called * during a measurement * @param {Request} req - The recieved request. * @param {Number} time - The time in miliseconds since epoch. */ req(req, time) { if (!this.proactive) { this.proactive = true; this.timers.forEach((timer, i, arr) => { arr[i].intervalId = setInterval(this.intervaFunc, timer.ms, timer.times); }); this.endTime = Date.now() + this.negotiationBandwidth * 1000; } if (req.headers['Sequence-Number']) { this.recieved.push(parseInt(req.headers['Sequence-Number'])); } if (req.headers.Measurements) { this.reportedMeasurements.fromHeader(req.headers.Measurements); } this.localMeasurements.extractBandwidth(this.recieved, this.requestedBw); if (this.timeoutId) { clearTimeout(this.timeoutId); this.timeoutId = setTimeout(this.endFunc, 300); } } /** * Cancel communication */ cancel() { this.timers.forEach((timer, i, arr) => { if (timer.intervalId) { clearInterval(timer.intervalId); arr[i].intervalId = undefined; } }); if (this.timeoutId) { clearTimeout(this.timeoutId); this.timeoutId = undefined; } this.recieved = []; this.sequence = 0; this.rejectCallback(); } }
JavaScript
class SemiCircle extends Primitive { /** * @param {Number} radius - The radius of the circle this class will be drawing a section of. * @param {Number} offset - The offset, in radians, from which the section should start drawing. * @param {Number} angle - The angle length, in radians, of the section to draw. * @param {Object} options - The rendering options for this object. * @constructor */ constructor(radius, offset, angle, options) { super(options); this.mRadius = radius; this.mOffset = offset; this.mAngle = angle; this.size.set(radius * 2, radius * 2); } /** * Destroys this object. Called automatically when the reference count of this object reaches zero. * * @method destroy */ destroy() { delete this.mRadius; delete this.mOffset; delete this.mAngle; super.destroy(); } /** * The radius of the circle this class will be drawing a section of. * * @type {Number} */ get radius() { return this.mRadius; } /** * @param {Number} value - The new radius of the circle this class will be drawing a section of. */ set radius(value) { if (value !== this.mRadius) { this.mRadius = value; this.size.set(this.mRadius * 2, this.mRadius * 2); this.needsRedraw(); } } /** * The offset, in radians, from which the section should start drawing. * * @type {Number} */ get offset() { return this.mOffset; } /** * @param {Number} value - The new offset, in radians, from which the section should start drawing. */ set offset(value) { if (value !== this.mOffset) { this.mOffset = value; this.needsRedraw(); } } /** * The angle length, in radians, of the section to draw. * * @type {Number} */ get angle() { return this.mAngle; } /** * @param {Number} value - The new angle length, in radians, of the section to draw. */ set angle(value) { if (value !== this.mAngle) { this.mAngle = value; this.needsRedraw(); } } /** * Renders the path of this shape to the context. * * @method _renderPath * @param {CanvasRenderingContext2D} context - The canvas context in which the drawing operations will be performed. * @param {Object} options - The rendering options for this shape. * @private */ _renderPath(context, options) { let radius = this.mRadius; if (options.strokeType) { if (options.strokeType === SemiCircle.STROKE_INNER) { radius -= options.stroke * 0.5; } else if (options.strokeType === SemiCircle.STROKE_OUTER) { radius += options.stroke * 0.5; } } radius = Math.max(radius, 0); context.beginPath(); context.arc(this.mRadius, this.mRadius, radius, INITIAL_OFFSET + this.mOffset, INITIAL_OFFSET + this.mOffset + this.mAngle, false); if (options.closePath) { context.closePath(); } } }
JavaScript
class Logo extends React.Component { render(){ return( <View style = {styles.container}> <Image style = {styles.image} source = {require('../images/Parking_Reservation_Logo.png')}/> <Text style = {styles.logoText}>Parking Reservation</Text> </View> ) } }
JavaScript
class CommonListView extends BasicView { /** * @param {!ListDataHandler} dataHandler * @param {string} optionTag */ constructor(dataHandler, optionTag) { super(); /** @private @const {!ListDataHandler} */ this.dataHandler_ = dataHandler; /** @private @const {string} */ this.optionTag_ = optionTag; /** * @private @const {function(!listitems.Params): !googSoy.data.SanitizedHtml} */ this.template_ = listitems; /** * @private @type {!Array<function(!Element): ?Promise<undefined>>} */ this.listeners_ = []; /** * @private @type {number} The number of batch of data has been loaded into the view. */ this.batch_ = 0; /** @private {?Element} The container for all list items. */ this.container_ = null; /** @private @const {function(): ?Promise<undefined>} */ this.bindedScrollHandler_ = this.loadNextBatch_.bind(this); /** @private @const {function(number): ?Promise<undefined>} */ this.bindedDataLoader_ = this.renderNextBatch_.bind(this); /** @private @const {function(!JsactionActionFlow): ?Promise<undefined>} */ this.bindedSelectorHandler_ = this.changeSort_.bind(this); /** @private {number} Number of items to be added for each load. */ this.itemsPerBatch_ = 18; /** @private {string} The id of the last item in the list. */ this.idOfLastItem_ = EMPTY_STRING; /** @private {string} The sort parameter for the query. */ this.sortBy_ = Array.from(SORT_PARAMS_MAP)[0][0]; /** @private {string} The sort order for the query. */ this.sortOrder_ = ASCENDING; /** @private {?Element} */ this.sortBySelector_ = null; /** @private {?Element} */ this.sortOrderSelector_ = null; /** @private {?Element} */ this.statusBar_ = null; /** @private {?number} */ this.totalItemsNumber_ = 0; /** @private {boolean} */ this.isLoading_ = false; /** @private @const {!JsactionEventContract} */ this.eventContract_ = new JsactionEventContract(); /** @private @const {!JsactionDispatcher} */ this.dispatcher_ = new JsactionDispatcher(); /** @private @const {function(!JsactionActionFlow): ?Promise<undefined>} */ this.bindedOnclickHandler_ = this.handleOnclickEvent_.bind(this); /** @private {?Element} */ this.scrollDiv_ = null; } /** * Sets up the event handlers for elements in the list. * @private */ initJsaction_() { // Events will be handled for all elements under this container. this.eventContract_.addContainer( /** @type {!Element} */ (super.getCurrentContentElement())); // Register the event types we care about. this.eventContract_.addEvent('click'); this.eventContract_.addEvent('dblclick'); this.eventContract_.addEvent('change'); this.eventContract_.dispatchTo( this.dispatcher_.dispatch.bind(this.dispatcher_)); this.dispatcher_.registerHandlers( 'commonlistview', // the namespace null, // handler object { // action map 'clickAction': this.bindedOnclickHandler_, 'doubleClickAction': this.bindedOnclickHandler_, 'change' : this.bindedSelectorHandler_ }); } /** * Handles click and double click events on navbar. * @param {!JsactionActionFlow} flow Contains the data related to the action. * and more. See actionflow.js. * @private */ async handleOnclickEvent_(flow) { this.listeners_.forEach(async (listener) => { await listener(/** @type {!Element} */ (flow.node())); }); } /** * Loads the first two batches of list item to page. */ async renderView() { super.setCurrentContent(commonlistview({ pagetype: this.optionTag_, sortParams: SORT_PARAMS_MAP, asc: ASCENDING, desc: DESCENDING})); super.resetAndUpdate(); this.initJsaction_(); // tableContainer.innerHTML = commonlistview({pagetype: this.optionTag_}); this.container_ = googDom.getElement(ITEM_CONTAINER_ID); this.sortBySelector_ = googDom.getElement(SORT_BY_SELECTOR_ID); this.sortBySelector_.value = this.sortBy_; this.sortOrderSelector_ = googDom.getElement(SORT_ORDER_SELECTOR_ID); this.sortOrderSelector_.value = this.sortOrder_; window.addEventListener('scroll', this.bindedScrollHandler_); this.scrollDiv_ = googDom.getElement('scroll-div'); this.scrollDiv_.addEventListener('scroll', this.bindedScrollHandler_); try { this.totalItemsNumber_ = await this.dataHandler_.getTotalNumber(); this.setHeight_(); if (isNaN(this.totalItemsNumber_)) { throw new Error(ISNAN_ERROR); } await this.renderNextBatch_(this.itemsPerBatch_ * 2); this.batch_ = 2; while (this.scrollDiv_.scrollHeight <= this.scrollDiv_.clientHeight) { await this.renderNextBatch_(this.itemsPerBatch_); } } catch(e) { console.log(e); throw e; } } /** * Changes the sort values for the query and * rerenders using the new query parameters. * @param {!JsactionActionFlow} flow Contains the data related to the action of * changing sort params. * @private */ async changeSort_(flow) { this.sortBy_ = googDom.getElement(SORT_BY_SELECTOR_ID).value; this.sortOrder_ = googDom.getElement(SORT_ORDER_SELECTOR_ID).value; this.batch_ = 0; this.listeners_.forEach(async (listener) => { await listener(/** @type {!Element} */ (flow.node())); }); } /** @private Preset the hight of the list. */ setHeight_() { this.container_.style.height = `${ITEM_HEIGHT * this.totalItemsNumber_}px`; } /** * Loads the next batch of data and render to the view. * @param {number} numberOfItems The number of objects to be loaded from server. * @private */ async renderNextBatch_(numberOfItems) { try { this.isLoading_ = true; const dataBatch = await this.dataHandler_.getNextBatch( this.optionTag_, this.batch_, numberOfItems, this.idOfLastItem_, this.sortBy_, this.sortOrder_); const dataList = dataBatch ? dataBatch[ITEM] : undefined; if (!dataBatch || !dataList || dataList.length == 0) { this.isLoading_ = false; return; } this.idOfLastItem_ = dataList ? dataList[dataList.length - 1][0] : EMPTY_STRING; this.container_.innerHTML += this.template_({batchofitems: dataBatch}); this.batch_ += 1; } catch (e) { console.log(e); throw e; } finally { this.isLoading_ = false; } } /** * Checks if the page is about to reach the bottom, * if so, load one more batch of data. * @private */ async loadNextBatch_() { if (this.isLoading_) { return; } const scrolledHeight = this.scrollDiv_.scrollTop; const innerHeight = this.scrollDiv_.clientHeight; const threshold = (this.batch_ - 1) * this.itemsPerBatch_ * ITEM_HEIGHT; while (scrolledHeight + innerHeight > threshold && this.batch_ * this.itemsPerBatch_ < this.totalItemsNumber_) { try { await this.bindedDataLoader_(this.itemsPerBatch_); } catch (e) { console.log(e); throw e; } } } /** * Registers a listener for jsaction. * @param {function(!Element): ?Promise<undefined>} listener */ registerListener(listener) { this.listeners_.push(listener); } /** * Before the currently view is removed, call this function to remove * scroll event handler. */ removeScrollHandler() { this.container_.removeEventListener('scroll', this.bindedScrollHandler_); } }
JavaScript
class TDClient { constructor(apikey, options) { this.options = options || {}; this.options.apikey = apikey; this.options.host = this.options.host || 'api.treasuredata.com'; this.options.protocol = this.options.protocol || 'https'; this.options.headers = this.options.headers || {}; this.baseUrl = `${this.options.protocol}://${this.options.host}`; } /** * Return the list of all databases belongs to given account * @param {function} callback - Callback function which receives * error object and results object * @example * // Results object * {name: 'db1', count: 1, created_at: 'XXX', * updated_at: 'YYY', organization: null, * permission: 'administrator'} */ listDatabases(callback) { this._request("/v3/database/list", { method: 'GET', json: true }, callback); } /** * Delete the given named database * @param {string} db - The name of database * @param {function} callback - Callback function which receives * error object and results object */ deleteDatabase(db, callback) { this._request("/v3/database/delete/" + qs.escape(db), { method: 'POST', json: true }, callback); } /** * Create the given named database * @param {string} db - The name of database * @param {function} callback - Callback function which receives * error object and results object */ createDatabase(db, callback) { this._request("/v3/database/create/" + qs.escape(db), { method: 'POST', json: true }, callback); } /** * Return the list of all tables belongs to given database * @param {string} db - The name of database * @param {function} callback - Callback function which receives * error object and results object */ listTables(db, callback) { this._request("/v3/table/list/" + qs.escape(db), { json: true }, callback); } /** * Create log type table in the given database * @param {string} db - The name of database * @param {string} table - The name of table * @param {function} callback - Callback function which receives * error object and results object */ createLogTable(db, table, callback) { this.createTable(db, table, 'log', callback); } /** * Create item type table in the given database * @deprecated * @param {string} db - The name of database * @param {string} table - The name of table * @param {function} callback - Callback function which receives * error object and results object */ createItemTable(db, table, callback) { this.createTable(db, table, 'item', callback); } /** * Create table in given database * @param {string} db - The name of database * @param {string} table - The name of table * @param {string} type - The type of table ('log' or 'item') * @param {function} callback - Callback function which receives * error object and results object */ createTable(db, table, type, callback) { this._request("/v3/table/create/" + qs.escape(db) + "/" + qs.escape(table) + "/" + qs.escape(type), { method: 'POST', json: true }, callback); } /** * Swap the content of two tables * @param {string} db - The name of database * @param {string} table1 - The first table * @param {string} table2 - The second table * @param {function} callback - Callback function which receives * error object and results object */ swapTable(db, table1, table2, callback) { this._request("/v3/table/swap/" + qs.escape(db) + "/" + qs.escape(table1) + "/" + qs.escape(table2), { method: 'POST', json: true }, callback); } updateSchema(db, table, schema_json, callback) { this._request("/v3/table/update-schema/" + qs.escape(db) + "/" + qs.escape(table), { method: 'POST', body: schema_json, json: true }, callback); } deleteTable(db, table, callback) { this._request("/v3/table/delete/" + qs.escape(db) + "/" + qs.escape(table), { method: 'POST', json: true }, callback); } tail(db, table, count, to, from, callback) { if (typeof count === 'function') { callback = count; count = null; } else if (typeof to === 'function') { callback = to; to = null; } else if (typeof from === 'function') { callback = from; from = null; } let params = { // format: 'msgpack' }; if (count) { params.count = count; } if (to) { params.to = to; } if (from) { params.from = from; } this._request("/v3/table/tail/" + qs.escape(db) + "/" + qs.escape(table), { method: 'GET', qs: params }, callback); } /** * Return the list of all jobs run by your account * @param {string} from - The start of the range of list * @param {string} to - The end of the range of list * @param {string} status - The status of returned jobs * @param {function} callback - Callback function which receives * error object and results object * */ listJobs(from, to, status, conditions, callback) { if (typeof from === 'function') { callback = from; from = 0; } else if (typeof to === 'function') { callback = to; to = null; } else if (typeof status === 'function') { callback = status; status = null; } else if (typeof conditions === 'function') { callback = conditions; conditions = null; } let params = { from: from }; if (to) { params.to = to; } if (status) { params.status = status; } if (conditions) { params.conditions = conditions; } this._request("/v3/job/list/", { qs: params, json: true }, callback); } /** * Returns the status and logs of a given job * @param {string} job_id - The job id * @param {function} callback - Callback function which receives * error object and results object * */ showJob(job_id, callback) { this._request("/v3/job/show/" + qs.escape(job_id), { json: true }, callback); } /** * Returns the result of a specific job. * @param {string} job_id - The job id * @param {string} format - Format to receive data back in, defaults * to tsv * @param {function} callback - Callback function which receives * error object and results object */ jobResult(job_id, format, callback) { let opts = { method: 'GET', qs: { format: 'tsv' } }; if (typeof format === 'function') { callback = format; }else{ opts.qs.format = format; } this._request("/v3/job/result/" + qs.escape(job_id), opts, callback); } /** * Kill the currently running job * @param {string} job_id - the job id * @param {function} callback - Callback function which receives * error object and results object */ kill(job_id, callback) { this._request("/v3/job/kill/" + qs.escape(job_id), { method: 'POST', json: true }, callback); } /** * Submit Hive type job * @param {string} db - The name of database * @param {string} query - The Hive query which run on given database * @param {object} opts - Supported options are `result`, * `priority` and `retry_limit` * @param {function} callback - Callback function which receives * error object and results object * * @see {@link https://docs.treasuredata.com/categories/hive} */ hiveQuery(db, query, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } this._query(db, 'hive', query, opts, callback) } /** * Submit Presto type job * @param {string} db - The name of database * @param {string} query - The Presto query which run on given database * @param {object} opts - Supported options are `result`, * `priority` and `retry_limit` * @param {function} callback - Callback function which receives * error object and results object * * @see {@link https://docs.treasuredata.com/categories/presto} */ prestoQuery(db, query, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } this._query(db, 'presto', query, opts, callback) } // Export API export(db, table, storage_type, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } opts.storage_type = storage_type; this._request("/v3/export/run/" + qs.escape(db) + "/" + qs.escape(table), { method: 'POST', body: opts, json: true }, callback); } /** * Create scheduled job * * @param {string} name - The name of scheduled job * @param {object} opts - Supported options are `cron` and `query`. * @param {function} callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/categories/scheduled-job} * */ createSchedule(name, opts, callback) { if (!opts.cron || !opts.query) { return callback(new Error('opts.cron and opts.query is required!'), {}); } opts.type = 'hive'; this._request("/v3/schedule/create/" + qs.escape(name), { method: 'POST', body: opts, json: true }, callback); } /** * Delete scheduled job * * @param {string} name - The name of scheduled job * @param {function} callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/categories/scheduled-job} * */ deleteSchedule(name, callback) { this._request("/v3/schedule/delete/" + qs.escape(name), { method: 'POST', json: true }, callback); } /** * Show the list of scheduled jobs * * @param {function} callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/categories/scheduled-job} * */ listSchedules(callback) { this._request("/v3/schedule/list", { method: 'GET', json: true }, callback); } /** * Update the scheduled job * * @param {string} name - The name of scheduled job * @param {object} params - Updated content * @param {function} callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/categories/scheduled-job} */ updateSchedule(name, params, callback) { this._request("/v3/schedule/update/" + qs.escape(name), { body: params, method: 'POST', json: true }, callback); } history(name, from, to, callback) { if (typeof from === 'function') { callback = from; from = 0; } else if (typeof from === 'function') { callback = to; to = null; } let params = {}; if (from) { params.from = from; } if (to) { params.to = to; } this._request("/v3/schedule/history/" + qs.escape(name), { method: 'GET', qs: params, json: true }, callback); } runSchedule(name, time, num, callback) { if (typeof num === 'function') { callback = num; num = null; } let params = {}; if (num) { params.num = num; } this._request("/v3/schedule/run/" + qs.escape(name) + "/" + qs.escape(time), { method: 'POST', qs: params, json: true }, callback); } // Import API import(db, table, format, stream, size, unique_id, callback) { if (typeof unique_id === 'function') { callback = unique_id; unique_id = null; } let path; if (unique_id) { path = "/v3/table/import_with_id/" + qs.escape(db) + "/" + qs.escape(table) + "/" + qs.escape(unique_id) + "/" + qs.escape(format); } else { path = "/v3/table/import/" + qs.escape(db) + "/" + qs.escape(table) + "/" + qs.escape(format); } this._put(path, { method: 'PUT', headers: { 'Content-Type': 'application/octet-stream', 'Content-Length': size } }, stream, callback); } // Result API listResult(callback) { this._request("/v3/result/list", { json: true }, callback); } createResult(name, url, callback) { this._request("/v3/result/create/" + qs.escape(name), { method: 'POST', body: { 'url': url }, json: true }, callback); } deleteResult(name, url, callback) { this._request("/v3/result/delete/" + qs.escape(name), { method: 'POST', body: { 'url': url }, json: true }, callback); } // Server Status API serverStatus(callback) { this._request("/v3/system/server_status", { json: true }, callback); } // Bulk import APIs /** * Create bulk import session * @param {string} name - The session name * @param {string } db - Database name where data is imported * @param {string } table - Table name where data is imported * @param {function} callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/articles/bulk-import} */ createBulkImport(name, db, table, callback) { this._request('/v3/bulk_import/create/' + qs.escape(name) + '/' + qs.escape(db) + '/' + qs.escape(table), { method: 'POST', json: true }, callback); } /** * Delete bulk import session * @param {string} name - The session name * @param {function} callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/articles/bulk-import} */ deleteBulkImport(name, callback) { this._request('/v3/bulk_import/delete/' + qs.escape(name), { method: 'POST', json: true }, callback); } /** * Show the information about specified bulk import session * @param {string} name - The session name * @param {function} callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/articles/bulk-import} */ showBulkImport(name, callback) { this._request('/v3/bulk_import/show/' + qs.escape(name), { method: 'GET', json: true }, callback); } /** * Show the list of all bulk import sessions * @param {function} callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/articles/bulk-import} */ listBulkImports(callback) { this._request('/v3/bulk_import/list', { method: 'GET', json: true }, callback); } /** * Show the list of all partitions of specified bulk import session * @param {function} callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/articles/bulk-import} */ listBulkImportParts(name, callback) { this._request('/v3/bulk_import/list_parts/' + qs.escape(name), { method: 'GET', json: true }, callback); } /** * Upload a partition file for the specified bulk import session * @param {string} name - The bulk import session name * @param {string} partName - The partition name * @param {stream.Readable} stream - Readable stream that reads partition file * @param {function} callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/articles/bulk-import} * @example * var stream = fs.createReadStream('part_file.msgpack.gz'); * client.bulkImportUploadPart('bulk_import_session', 'part1', stream, function(err, results) { * // Obtain bulk import uploading result * }); */ bulkImportUploadPart(name, partName, stream, callback) { this._put('/v3/bulk_import/upload_part/' + qs.escape(name) + '/' + qs.escape(partName), {json: true}, stream, callback); } /** * Delete specified partition from given bulk import session * @param {string} name - The bulk import session name * @param {string} partName - The partition name * @param {function} callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/articles/bulk-import} */ bulkImportDeletePart(name, partName, callback) { this._request('/v3/bulk_import/delete_part/' + qs.escape(name) + '/' + qs.escape(partName), { method: 'POST', json: true }, callback); } /** * Run the job for processing partition files inside Treasure Data service * @param {string} name - The bulk import session name * @param callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/articles/bulk-import} */ performBulkImport(name, callback) { this._request('/v3/bulk_import/perform/' + qs.escape(name), { method: 'POST', json: true }, callback) } /** * Confirm the bulk import session is finished successfully * @param {string} name - The bulk import session name * @param callback - Callback function which receives * error object and results object * @see {@link https://docs.treasuredata.com/articles/bulk-import} */ commitBulkImport(name, callback) { this._request('/v3/bulk_import/commit/' + qs.escape(name), { method: 'POST', json: true }, callback) } /** * _query: Protected method * @protected */ _query(db, query_type, q, opts, callback) { opts.query = q; this._request("/v3/job/issue/" + query_type + "/" + qs.escape(db), { method: 'POST', body: opts, json: true }, callback); } /** * _request: Protected method * @protected */ _request(path, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options.uri = this.baseUrl + path; options.headers = { 'Authorization': 'TD1 ' + this.options.apikey }; // Merge custom headers options.headers = merge(options.headers, this.options.headers); callback = callback; request(options, (err, res, body) => { if (err) { return callback(err, undefined); } if (res.statusCode < 200 || res.statusCode > 299) { return callback(new Error((body && body.error) || 'HTTP ' + res.statusCode), body || {}); } callback(null, body || {}); }); } /** * _put: Protected method * @protected */ _put(path, options, stream, callback) { options.uri = this.baseUrl + path; options.headers = { 'Authorization': 'TD1 ' + this.options.apikey }; stream.pipe(request.put(options, (err, res, body) => { if (err) { return callback(err, undefined); } if (res.statusCode < 200 || res.statusCode > 299) { return callback(new Error((body && body.error) || 'HTTP ' + res.statusCode), body || {}); } callback(null, body || {}); })); } }
JavaScript
class GameMenu extends GameTheme { constructor(scene, orchestrator) { super('menu.xml', scene, orchestrator); } /** * @method initInterface * * Add the board size and player type choosing to the dat.gui interface */ initInterface() { let gui = this.scene.interface.gui; const MINBOARDSIZE = 4; const MAXBOARDSIZE = 14; this.boardFolder = gui.addFolder('Board'); this.boardFolder.add(this.orchestrator, 'boardHeight', MINBOARDSIZE, MAXBOARDSIZE).name('Height').step(1); this.boardFolder.add(this.orchestrator, 'boardWidth', MINBOARDSIZE, MAXBOARDSIZE).name('Width').step(1); this.boardFolder.open(); this.playerFolder = gui.addFolder('Player'); this.playerFolder.add(this.orchestrator, 'player1', {'Human': 'P', 'Computer Lv1': 1, 'Computer Lv2': 2}).name('Player 1'); this.playerFolder.add(this.orchestrator, 'player2', {'Human': 'P', 'Computer Lv1': 1, 'Computer Lv2': 2}).name('Player 2'); this.playerFolder.open(); } /** * @method destroyInterface * * Remove the board size and player type interface from dat.gui */ destroyInterface() { let gui = this.scene.interface.gui; gui.removeFolder(this.boardFolder); gui.removeFolder(this.playerFolder); } /** * @method onGraphLoaded * * Same as game theme's on graph loaded but adds extra interface elements. */ onGraphLoaded() { super.onGraphLoaded(); this.scene.interface.setActiveCamera(); this.initInterface(); this.cameraState = 'menu'; } }
JavaScript
class Article extends Component { constructor(props) { super(props); this.state = { selectedImageId: props.data.images ? props.data.images.edges[0].node.id : '' // counter: 1, // isCartOpen: false }; } handleThumbnailClick = id => { this.setState({ selectedImageId: id }); }; // incrementCounter = () => { // this.setState({ // counter: ++this.state.counter, // }) // } // decrementCounter = () => { // this.setState({ // counter: this.state.counter === 0 ? 0 : --this.state.counter, // }) // } handleOpenCart = () => { this.setState({ isCartOpen: true }); }; closeCart = () => { this.setState({ isCartOpen: false }); }; render() { const { data: { post, images } } = this.props; const selectedImage = images.edges.filter( x => x.node.id === this.state.selectedImageId )[0]; return ( <div> {/* <Cart post={post} image={images.edges[0].node} isCartOpen={this.state.isCartOpen} closeCart={this.closeCart} /> */} article {/* <Header /> <ThreePanes> <ArticleWrapper> <ArticleImageWrapper> <Image fluid={selectedImage.node.localFile.childImageSharp.fluid} /> </ArticleImageWrapper> </ArticleWrapper> <ArticleDetails> <ArticleMiniatures> {images.edges.map(x => ( <Miniature key={x.node.id} onClick={() => this.handleThumbnailClick(x.node.id)} style={{ opacity: this.state.selectedImageId === x.node.id ? 1 : 0.3 }} > <Image fixed={x.node.localFile.childImageSharp.fixed} /> </Miniature> ))} </ArticleMiniatures> <Details> <h2>Vestes & Qqch</h2> <h3>{post.title.replace(/^\d+__/g, '')}</h3> <p>{post.content.match(/(?<=<p>).*?(?=<\/p>)/g)[0]}</p> <div className='horizontalSep' /> <AddToCart> <p className='articlePrice'>{`${ post.content.match(/(?<=<p>).*?(?=<\/p>)/g)[1] } DA`}</p> <button onClick={this.handleOpenCart} className='addToCart__button' > Ajouter au panier </button> </AddToCart> </Details> </ArticleDetails> </ThreePanes> <Footer /> */} </div> ); } }
JavaScript
class Header extends Component { render() { console.log("Header", this.props.userInfo) return ( <div className={style.dadContainer}> <section className={style.sectionStyle}> <div className={style.imgContainer}> <FirebaseImage fbref={this.props.userInfo.avatar} /> </div> <div className={style.infoContainer}> <h3>{this.props.userInfo.name}</h3> <p>{this.props.userInfo.email}</p> <div/> </div> </section> <div className={style.menuContainer}> <Menu mode="horizontal" defaultSelectedKeys={[this.props.active]}> <Menu.Item key="_01"> <Link to="Profile">My Classes</Link> </Menu.Item> <Menu.Item key="_02"> <Link to="favorites">Favorites</Link> </Menu.Item> <Menu.Item key="_03"> <Link to="payments">Payments</Link> </Menu.Item> <Menu.Item key="_04"> <Link to="editProfile">Edit Profile</Link> </Menu.Item> </Menu> </div> </div> ) } }
JavaScript
class Dashboard extends Component { componentDidMount() { this.props.fetchSurveys(); } render() { return ( <div> <SurveyList /> <div className='fixed-action-btn'> <Link to='/surveys/new' className='btn-floating btn-large red'> <i className='large material-icons'>add</i> </Link> </div> </div> ); } }
JavaScript
class App extends React.Component { constructor (props) { super(props); this.listeners = []; this.observers = []; this.state = { user: {}, events: props.events, rules: props.rules, characters: props.characters }; this.setUser = this.setUser.bind(this); this.logout = this.logout.bind(this); this.subscribeService = this.subscribeService.bind(this); this.loadService = this.loadService.bind(this); this.recordCreate = this.recordCreate.bind(this); this.recordUpdate = this.recordUpdate.bind(this); this.recordPatch = this.recordPatch.bind(this); this.recordDelete = this.recordDelete.bind(this); this.getCharacter = this.getCharacter.bind(this); this.renderHome = this.renderHome.bind(this); this.renderLogin = this.renderLogin.bind(this); this.renderUser = this.renderUser.bind(this); this.renderCharacter = this.renderCharacter.bind(this); this.renderAdminEvents = this.renderAdminEvents.bind(this); this.renderAdminRules = this.renderAdminRules.bind(this); } componentDidMount() { api.getUser().then((user) => this.setState({user: user})); } componentWillUnmount() { this.listeners.forEach(service => { api.service(service).removeListener('created'); api.service(service).removeListener('updated'); api.service(service).removeListener('removed'); }); this.listeners = []; this.observers = []; } setUser(user) { return new Promise(resolve => this.setState({user: user}, resolve)); } logout() { api.logout(); return new Promise(resolve => this.setState({user: {}}, resolve)); } subscribeService(service, observer = () => null) { this.observers.push({service: service, func: observer}); return () => this.observers = this.observers.filter(item => ( !(item.service == service && item.func == observer) )); } loadService(service, reload = false) { if(-1 == this.listeners.indexOf(service)) { this.listeners.push(service); api.service(service).on('created', record => { this.setState((prevState, props) => { let nextState = Object.assign({}, prevState); nextState[service] = prevState[service].concat(record); return nextState; }, () => { api.setServiceData(service, this.state[service]); this.observers.filter(observer => observer.service == service) .forEach(observer => observer.func({type: 'created', data: record})); }); }); api.service(service).on('updated', record => { const previous = Object.assign({}, this.state.rules.filter(rule => rule._id == record._id)[0]); this.setState((prevState, props) => { let nextState = Object.assign({}, prevState); let index = prevState[service].map(item => item._id).indexOf(record._id); nextState[service][index] = Object.assign({}, record); return nextState; }, () => { api.setServiceData(service, this.state[service]); this.observers.filter(observer => observer.service == service) .forEach(observer => observer.func({type: 'updated', data: record, previous: previous})); }); }); api.service(service).on('removed', record => { this.setState((prevState, props) => { let nextState = Object.assign({}, prevState); nextState[service] = prevState[service].filter(item => item._id != record._id); return nextState; }, () => { api.setServiceData(service, this.state[service]); this.observers.filter(observer => observer.service == service) .forEach(observer => observer.func({type: 'removed', data: record})); }); }); } return api.getServiceData(service, reload).then(data => { this.setState((prevState, props) => { let nextState = Object.assign({}, prevState); nextState[service] = data; return nextState; }); }); } recordCreate(service, record, callback) { return api.service(service).create(record, callback); } recordUpdate(service, record, callback) { return api.service(service).update(record._id, record, callback); } recordPatch(service, id = null, data, query = {}, callback) { return api.service(service).patch(id, data, {query: query}, callback); } recordDelete(service, id = null, query = {}, callback) { return api.service(service).remove(id, {query: query}, callback); } getCharacter(id) { if(!id) Promise.reject(new Error('No ID provided')); return Promise.resolve() .then(() => { if(!this.state.user.hasOwnProperty('_id')) return api.getUser().then((user) => this.setUser(user)); }) .then(() => { if(!this.state.user.hasOwnProperty('_id')) throw new Error('Not signed in'); let character = this.state.characters.filter(c => c._id == id); if(character.length == 0) throw new Error('Character not found'); character = character[0]; if(character._player != this.state.user._id && !this.state.user.canManageCharacters) throw new Error('Not your character'); return character; }); } renderHome(props) { return <Home {...props} events={this.state.events} loadService={this.loadService} />; } renderLogin(props) { return <Login {...props} api={api} user={this.state.user} setUser={this.setUser} />; } renderUser(props) { return <User {...props} api={api} user={this.state.user} setUser={this.setUser} logout={this.logout} characters={this.state.characters.filter(c => c._player == this.state.user._id)} subscribeService={this.subscribeService} loadService={this.loadService} />; } renderCharacter(props) { return <Character {...props} user={this.state.user} logout={this.logout} rules={this.state.rules} getCharacter={this.getCharacter} subscribeService={this.subscribeService} loadService={this.loadService} create={this.recordCreate} update={this.recordUpdate} patch={this.recordPatch} remove={this.recordDelete} />; } renderAdminEvents(props) { return <AdminEvents {...props} user={this.state.user} logout={this.logout} events={this.state.events} subscribeService={this.subscribeService} loadService={this.loadService} create={this.recordCreate} update={this.recordUpdate} patch={this.recordPatch} remove={this.recordDelete} />; } renderAdminRules(props) { return <AdminRules {...props} user={this.state.user} logout={this.logout} rules={this.state.rules} subscribeService={this.subscribeService} loadService={this.loadService} create={this.recordCreate} update={this.recordUpdate} patch={this.recordPatch} remove={this.recordDelete} />; } render() { return ( <ThemeProvider theme={theme}> <div> <Route path='/admin' component={AdminNavigation} /> <Switch> <Route exact path='/' render={this.renderHome} /> <Route path='/register' render={this.renderLogin} /> <Route exact path='/login' render={this.renderLogin} /> <Route path='/login/reset/:token' render={this.renderLogin} /> <Route exact path='/account' render={this.renderUser} /> <Route path='/account/verify/:token' render={this.renderUser} /> <Route exact path='/character' render={this.renderCharacter} /> <Route exact path='/character/:id' render={this.renderCharacter} /> <Route path='/character/link/:link' render={this.renderCharacter} /> <Route exact path='/admin' component={AdminDashboard} /> <Route exact path='/admin/events' render={this.renderAdminEvents} /> <Route path='/admin/events/:id' render={this.renderAdminEvents} /> <Route exact path='/admin/rules' render={this.renderAdminRules} /> <Route path='/admin/rules/:id' render={this.renderAdminRules} /> <Route exact path='/admin/characters' component={PageNotFound} /> <Route path='/admin/characters/:id' component={PageNotFound} /> </Switch> <NotificationListDisplay /> </div> </ThemeProvider> ); } }
JavaScript
class Measure { constructor(scalar, magnitude, unit) { if (typeof scalar != 'number') { throw 'Invalid scalar given: ' + scalar; } if (typeof magnitude != 'object' || magnitude.constructor.name != 'Magnitude') { throw 'Invalid magnitude given: ' + magnitude; } if (typeof unit != 'object' || unit.constructor.name != 'Unit') { throw 'Invalid unit given: ' + unit; } this.scalar = scalar; this.magnitude = magnitude || Magnitude.UNIT; this.unit = unit; } identical(other) { return this.scalar === other.scalar && this.magnitude === other.magnitude && this.unit === other.unit; } equals(other) { const thisUnit = this.convertToUnit(); const otherUnit = other.convertToUnit(); return thisUnit.scalar === otherUnit.scalar && thisUnit.magnitude === otherUnit.magnitude && thisUnit.unit === otherUnit.unit; } convertTo(mag) { return new Measure(mag.from(this.scalar, this.magnitude), mag, this.unit); } convertToUnit() { return this.convertTo(Magnitude.UNIT); } toString() { let s = ''; s += this.scalar; s += this.magnitude.abbrev; s += this.unit.abbrev; return s; } }
JavaScript
class ShExClass { constructor (shexco, shm, shext, shexen) { this.shexco = shexco; this.shm = shm; this.shexat = new ShExAttributes(shext, this.shm, this.shexco, shexen); } /** * Genera el equivalente ShEx dada una clase * @param element Clase XMI * @returns {string} Equivalente ShEx */ classToShEx(element) { //Si está registrada como componente, no hacemos nada //Se generará dentro de la pertinente clase if(this.shm.getSubSet(element.$["xmi:id"]) !== undefined) { return ""; } let header = IRIManager.getShexTerm(element.$.name); let content = ""; let brackets = false; //Se crea herencia if(element.generalization) { brackets = true; //En el caso de que sea una shapeAnd let created = false; if(element.ownedAttribute) { for(let i = 0; i < element.ownedAttribute.length; i++) { if(element.ownedAttribute[i].$.name === "AND") { header += this.shexat.generalizationToShEx(element.generalization, "AND"); created = true; break; } else if(element.ownedAttribute[i].$.name === "OR") { header += this.shexat.generalizationToShEx(element.generalization, "OR"); created = true; break; } } } //Shape NOT if(element.generalization.length === 1 && element.generalization[0].$.name === "NOT") { brackets = false; content += this.shexat.generalizationToShEx(element.generalization, "NOT"); } else if(!element.ownedAttribute || !created) { content += this.shexat.generalizationToShEx(element.generalization); } } let attributes = element.ownedAttribute; if(!attributes) { attributes = []; if(!element.generalization) { brackets = true; } } //Se crean los atributos de la clase let ats = this.shexat.attributesToShEx(attributes, brackets); content += ats.content; header += ats.header; //Durante la generación de atributos se determina si son necesarias lalves brackets = ats.brackets; //Añadimos a la cabecera restricciones encontradas header += this.shexco.getConstraints(element); if(brackets) { return header + " {" + content + "\n}\n\n" } else { return header + content + "\n\n" } } }
JavaScript
class NewScheduledWithProfileApiModel { static getAttributeTypeMap() { return NewScheduledWithProfileApiModel.attributeTypeMap; } }
JavaScript
class Context { async _init() { LOG('init context') } /** * Extract matches from the string using `replace` and return an object with keys. * @param {string} s String to find matches in * @param {RegExp} re Regular Expression * @param {string[]} keys The sequence of keys corresponding to the matches. * @return {Object.<string, string>} The parsed matches in a hash. * @example * * export default { * context: Context, * async 'matches the badge snippet'({ getMatches }) { * const p = 'documentary' * const g = `%NPM: ${p}%` * const { pack } = getMatches(g, badgeRe, ['pack']) * equal(pack, p) * }, * } */ getMatches(s, re, keys) { const m = [] s.replace(re, (match, ...args) => { const o = {} const p = args.slice(0, args.length - 2) for (let i = 0; i < p.length; i++) { const a = p[i] const c = keys[i] if (c && a) o[c] = a } m.push(o) }) return m } /** * Example method. */ example() { return 'OK' } /** * Path to the fixture file. */ get FIXTURE() { return resolve(FIXTURE, 'test.txt') } get SNAPSHOT_DIR() { return resolve(__dirname, '../snapshot') } async _destroy() { LOG('destroy context') } }
JavaScript
class SendIRCConnection extends TwitchIRCConnection { /** * @param {AppUser} appUser * @constructor */ constructor(appUser) { super(appUser); this.connection_.onmessage = this.onMessage_.bind(this); } /** * @param {object} event event triggered by the Websocket connection * @private */ onMessage_(event) { let messages = event.data.split('\n'); for (let i = 0; i < messages.length; i++) { let msg = messages[i]; if (msg.length <= 1) { continue; } if (msg.startsWith('PING :tmi.twitch.tv')) { this.connection_.send('PONG :tmi.twitch.tv'); } } } }
JavaScript
class BaseWalkStrategy { /** * Create a new instance of BaseWalkStrategy. * @param nodes The nodes to iterate through. * @param blacklistLimit The number of failures before a node is blacklisted. */ constructor(nodes, blacklistLimit) { if (!nodes || nodes.length === 0) { throw new Error("You must supply at least one node to the strategy"); } this._allNodes = nodes; this._usableNodes = nodes.slice(); this._blacklistLimit = blacklistLimit; this._blacklistNodes = {}; } /** * The total number of nodes configured for the strategy. * @returns The total number of nodes. */ totalUsable() { return this._usableNodes.length; } /** * Blacklist the current node, so it doesn't get used again once limit is reached. */ blacklist() { if (this._blacklistLimit) { const current = this.current(); if (current) { if (!this._blacklistNodes[current.provider]) { this._blacklistNodes[current.provider] = 1; } else { this._blacklistNodes[current.provider]++; } if (this._blacklistNodes[current.provider] >= this._blacklistLimit) { const idx = this._usableNodes.indexOf(current); if (idx >= 0) { this._usableNodes.splice(idx, 1); } } // If there are no usable nodes left then reset the blacklists if (this._usableNodes.length === 0) { this._blacklistNodes = {}; this._usableNodes = this._allNodes.slice(); } } } } /** * Get the list of nodes that have not been blacklisted. * @returns The non blacklisted nodes. */ getUsableNodes() { return this._usableNodes; } }
JavaScript
class Util extends null { /** * Flatten an object. Any properties that are collections will get converted to an array of keys. * @param {Object} obj The object to flatten. * @param {...Object<string, boolean|string>} [props] Specific properties to include/exclude. * @returns {Object} */ static flatten(obj, ...props) { if (!isObject(obj)) return obj; const objProps = Object.keys(obj) .filter(k => !k.startsWith('_')) .map(k => ({ [k]: true })); props = objProps.length ? Object.assign(...objProps, ...props) : Object.assign({}, ...props); const out = {}; for (let [prop, newProp] of Object.entries(props)) { if (!newProp) continue; newProp = newProp === true ? prop : newProp; const element = obj[prop]; const elemIsObj = isObject(element); const valueOf = elemIsObj && typeof element.valueOf === 'function' ? element.valueOf() : null; // If it's a Collection, make the array of keys if (element instanceof Collection) out[newProp] = Array.from(element.keys()); // If the valueOf is a Collection, use its array of keys else if (valueOf instanceof Collection) out[newProp] = Array.from(valueOf.keys()); // If it's an array, flatten each element else if (Array.isArray(element)) out[newProp] = element.map(e => Util.flatten(e)); // If it's an object with a primitive `valueOf`, use that value else if (typeof valueOf !== 'object') out[newProp] = valueOf; // If it's a primitive else if (!elemIsObj) out[newProp] = element; } return out; } /** * Options for splitting a message. * @typedef {Object} SplitOptions * @property {number} [maxLength=2000] Maximum character length per message piece * @property {string|string[]|RegExp|RegExp[]} [char='\n'] Character(s) or Regex(es) to split the message with, * an array can be used to split multiple times * @property {string} [prepend=''] Text to prepend to every piece except the first * @property {string} [append=''] Text to append to every piece except the last */ /** * Splits a string into multiple chunks at a designated character that do not exceed a specific length. * @param {string} text Content to split * @param {SplitOptions} [options] Options controlling the behavior of the split * @returns {string[]} */ static splitMessage(text, { maxLength = 2_000, char = '\n', prepend = '', append = '' } = {}) { text = Util.verifyString(text); if (text.length <= maxLength) return [text]; let splitText = [text]; if (Array.isArray(char)) { while (char.length > 0 && splitText.some(elem => elem.length > maxLength)) { const currentChar = char.shift(); if (currentChar instanceof RegExp) { splitText = splitText.flatMap(chunk => chunk.match(currentChar)); } else { splitText = splitText.flatMap(chunk => chunk.split(currentChar)); } } } else { splitText = text.split(char); } if (splitText.some(elem => elem.length > maxLength)) throw new RangeError('SPLIT_MAX_LEN'); const messages = []; let msg = ''; for (const chunk of splitText) { if (msg && (msg + char + chunk + append).length > maxLength) { messages.push(msg + append); msg = prepend; } msg += (msg && msg !== prepend ? char : '') + chunk; } return messages.concat(msg).filter(m => m); } /** * Options used to escape markdown. * @typedef {Object} EscapeMarkdownOptions * @property {boolean} [codeBlock=true] Whether to escape code blocks or not * @property {boolean} [inlineCode=true] Whether to escape inline code or not * @property {boolean} [bold=true] Whether to escape bolds or not * @property {boolean} [italic=true] Whether to escape italics or not * @property {boolean} [underline=true] Whether to escape underlines or not * @property {boolean} [strikethrough=true] Whether to escape strikethroughs or not * @property {boolean} [spoiler=true] Whether to escape spoilers or not * @property {boolean} [codeBlockContent=true] Whether to escape text inside code blocks or not * @property {boolean} [inlineCodeContent=true] Whether to escape text inside inline code or not */ /** * Escapes any Discord-flavour markdown in a string. * @param {string} text Content to escape * @param {EscapeMarkdownOptions} [options={}] Options for escaping the markdown * @returns {string} */ static escapeMarkdown( text, { codeBlock = true, inlineCode = true, bold = true, italic = true, underline = true, strikethrough = true, spoiler = true, codeBlockContent = true, inlineCodeContent = true, } = {}, ) { if (!codeBlockContent) { return text .split('```') .map((subString, index, array) => { if (index % 2 && index !== array.length - 1) return subString; return Util.escapeMarkdown(subString, { inlineCode, bold, italic, underline, strikethrough, spoiler, inlineCodeContent, }); }) .join(codeBlock ? '\\`\\`\\`' : '```'); } if (!inlineCodeContent) { return text .split(/(?<=^|[^`])`(?=[^`]|$)/g) .map((subString, index, array) => { if (index % 2 && index !== array.length - 1) return subString; return Util.escapeMarkdown(subString, { codeBlock, bold, italic, underline, strikethrough, spoiler, }); }) .join(inlineCode ? '\\`' : '`'); } if (inlineCode) text = Util.escapeInlineCode(text); if (codeBlock) text = Util.escapeCodeBlock(text); if (italic) text = Util.escapeItalic(text); if (bold) text = Util.escapeBold(text); if (underline) text = Util.escapeUnderline(text); if (strikethrough) text = Util.escapeStrikethrough(text); if (spoiler) text = Util.escapeSpoiler(text); return text; } /** * Escapes code block markdown in a string. * @param {string} text Content to escape * @returns {string} */ static escapeCodeBlock(text) { return text.replaceAll('```', '\\`\\`\\`'); } /** * Escapes inline code markdown in a string. * @param {string} text Content to escape * @returns {string} */ static escapeInlineCode(text) { return text.replace(/(?<=^|[^`])`(?=[^`]|$)/g, '\\`'); } /** * Escapes italic markdown in a string. * @param {string} text Content to escape * @returns {string} */ static escapeItalic(text) { let i = 0; text = text.replace(/(?<=^|[^*])\*([^*]|\*\*|$)/g, (_, match) => { if (match === '**') return ++i % 2 ? `\\*${match}` : `${match}\\*`; return `\\*${match}`; }); i = 0; return text.replace(/(?<=^|[^_])_([^_]|__|$)/g, (_, match) => { if (match === '__') return ++i % 2 ? `\\_${match}` : `${match}\\_`; return `\\_${match}`; }); } /** * Escapes bold markdown in a string. * @param {string} text Content to escape * @returns {string} */ static escapeBold(text) { let i = 0; return text.replace(/\*\*(\*)?/g, (_, match) => { if (match) return ++i % 2 ? `${match}\\*\\*` : `\\*\\*${match}`; return '\\*\\*'; }); } /** * Escapes underline markdown in a string. * @param {string} text Content to escape * @returns {string} */ static escapeUnderline(text) { let i = 0; return text.replace(/__(_)?/g, (_, match) => { if (match) return ++i % 2 ? `${match}\\_\\_` : `\\_\\_${match}`; return '\\_\\_'; }); } /** * Escapes strikethrough markdown in a string. * @param {string} text Content to escape * @returns {string} */ static escapeStrikethrough(text) { return text.replaceAll('~~', '\\~\\~'); } /** * Escapes spoiler markdown in a string. * @param {string} text Content to escape * @returns {string} */ static escapeSpoiler(text) { return text.replaceAll('||', '\\|\\|'); } /** * @typedef {Object} FetchRecommendedShardsOptions * @property {number} [guildsPerShard=1000] Number of guilds assigned per shard * @property {number} [multipleOf=1] The multiple the shard count should round up to. (16 for large bot sharding) */ /** * Gets the recommended shard count from Discord. * @param {string} token Discord auth token * @param {FetchRecommendedShardsOptions} [options] Options for fetching the recommended shard count * @returns {Promise<number>} The recommended number of shards */ static async fetchRecommendedShards(token, { guildsPerShard = 1_000, multipleOf = 1 } = {}) { if (!token) throw new DiscordError('TOKEN_MISSING'); const response = await fetch(RouteBases.api + Routes.gatewayBot(), { method: 'GET', headers: { Authorization: `Bot ${token.replace(/^Bot\s*/i, '')}` }, }); if (!response.ok) { if (response.status === 401) throw new DiscordError('TOKEN_INVALID'); throw response; } const { shards } = await response.json(); return Math.ceil((shards * (1_000 / guildsPerShard)) / multipleOf) * multipleOf; } /** * Parses emoji info out of a string. The string must be one of: * * A UTF-8 emoji (no id) * * A URL-encoded UTF-8 emoji (no id) * * A Discord custom emoji (`<:name:id>` or `<a:name:id>`) * @param {string} text Emoji string to parse * @returns {APIEmoji} Object with `animated`, `name`, and `id` properties * @private */ static parseEmoji(text) { if (text.includes('%')) text = decodeURIComponent(text); if (!text.includes(':')) return { animated: false, name: text, id: null }; const match = text.match(/<?(?:(a):)?(\w{2,32}):(\d{17,19})?>?/); return match && { animated: Boolean(match[1]), name: match[2], id: match[3] ?? null }; } /** * Resolves a partial emoji object from an {@link EmojiIdentifierResolvable}, without checking a Client. * @param {EmojiIdentifierResolvable} emoji Emoji identifier to resolve * @returns {?RawEmoji} * @private */ static resolvePartialEmoji(emoji) { if (!emoji) return null; if (typeof emoji === 'string') return /^\d{17,19}$/.test(emoji) ? { id: emoji } : Util.parseEmoji(emoji); const { id, name, animated } = emoji; if (!id && !name) return null; return { id, name, animated: Boolean(animated) }; } /** * Shallow-copies an object with its class/prototype intact. * @param {Object} obj Object to clone * @returns {Object} * @private */ static cloneObject(obj) { return Object.assign(Object.create(obj), obj); } /** * Sets default properties on an object that aren't already specified. * @param {Object} def Default properties * @param {Object} given Object to assign defaults to * @returns {Object} * @private */ static mergeDefault(def, given) { if (!given) return def; for (const key in def) { if (!Object.hasOwn(given, key) || given[key] === undefined) { given[key] = def[key]; } else if (given[key] === Object(given[key])) { given[key] = Util.mergeDefault(def[key], given[key]); } } return given; } /** * Options used to make an error object. * @typedef {Object} MakeErrorOptions * @property {string} name Error type * @property {string} message Message for the error * @property {string} stack Stack for the error */ /** * Makes an Error from a plain info object. * @param {MakeErrorOptions} obj Error info * @returns {Error} * @private */ static makeError(obj) { const err = new Error(obj.message); err.name = obj.name; err.stack = obj.stack; return err; } /** * Makes a plain error info object from an Error. * @param {Error} err Error to get info from * @returns {MakeErrorOptions} * @private */ static makePlainError(err) { return { name: err.name, message: err.message, stack: err.stack, }; } /** * Moves an element in an array *in place*. * @param {Array<*>} array Array to modify * @param {*} element Element to move * @param {number} newIndex Index or offset to move the element to * @param {boolean} [offset=false] Move the element by an offset amount rather than to a set index * @returns {number} * @private */ static moveElementInArray(array, element, newIndex, offset = false) { const index = array.indexOf(element); newIndex = (offset ? index : 0) + newIndex; if (newIndex > -1 && newIndex < array.length) { const removedElement = array.splice(index, 1)[0]; array.splice(newIndex, 0, removedElement); } return array.indexOf(element); } /** * Verifies the provided data is a string, otherwise throws provided error. * @param {string} data The string resolvable to resolve * @param {Function} [error] The Error constructor to instantiate. Defaults to Error * @param {string} [errorMessage] The error message to throw with. Defaults to "Expected string, got <data> instead." * @param {boolean} [allowEmpty=true] Whether an empty string should be allowed * @returns {string} */ static verifyString( data, error = Error, errorMessage = `Expected a string, got ${data} instead.`, allowEmpty = true, ) { if (typeof data !== 'string') throw new error(errorMessage); if (!allowEmpty && data.length === 0) throw new error(errorMessage); return data; } /** * Can be a number, hex string, an RGB array like: * ```js * [255, 0, 255] // purple * ``` * or one of the following strings: * - `Default` * - `White` * - `Aqua` * - `Green` * - `Blue` * - `Yellow` * - `Purple` * - `LuminousVividPink` * - `Fuchsia` * - `Gold` * - `Orange` * - `Red` * - `Grey` * - `Navy` * - `DarkAqua` * - `DarkGreen` * - `DarkBlue` * - `DarkPurple` * - `DarkVividPink` * - `DarkGold` * - `DarkOrange` * - `DarkRed` * - `DarkGrey` * - `DarkerGrey` * - `LightGrey` * - `DarkNavy` * - `Blurple` * - `Greyple` * - `DarkButNotBlack` * - `NotQuiteBlack` * - `Random` * @typedef {string|number|number[]} ColorResolvable */ /** * Resolves a ColorResolvable into a color number. * @param {ColorResolvable} color Color to resolve * @returns {number} A color */ static resolveColor(color) { if (typeof color === 'string') { if (color === 'Random') return Math.floor(Math.random() * (0xffffff + 1)); if (color === 'Default') return 0; color = Colors[color] ?? parseInt(color.replace('#', ''), 16); } else if (Array.isArray(color)) { color = (color[0] << 16) + (color[1] << 8) + color[2]; } if (color < 0 || color > 0xffffff) throw new RangeError('COLOR_RANGE'); else if (Number.isNaN(color)) throw new TypeError('COLOR_CONVERT'); return color; } /** * Sorts by Discord's position and id. * @param {Collection} collection Collection of objects to sort * @returns {Collection} */ static discordSort(collection) { const isGuildChannel = collection.first() instanceof GuildChannel; return collection.sorted( isGuildChannel ? (a, b) => a.rawPosition - b.rawPosition || Number(BigInt(a.id) - BigInt(b.id)) : (a, b) => a.rawPosition - b.rawPosition || Number(BigInt(b.id) - BigInt(a.id)), ); } /** * Sets the position of a Channel or Role. * @param {Channel|Role} item Object to set the position of * @param {number} position New position for the object * @param {boolean} relative Whether `position` is relative to its current position * @param {Collection<string, Channel|Role>} sorted A collection of the objects sorted properly * @param {Client} client The client to use to patch the data * @param {string} route Route to call PATCH on * @param {string} [reason] Reason for the change * @returns {Promise<Channel[]|Role[]>} Updated item list, with `id` and `position` properties * @private */ static async setPosition(item, position, relative, sorted, client, route, reason) { let updatedItems = [...sorted.values()]; Util.moveElementInArray(updatedItems, item, position, relative); updatedItems = updatedItems.map((r, i) => ({ id: r.id, position: i })); await client.rest.patch(route, { body: updatedItems, reason }); return updatedItems; } /** * Alternative to Node's `path.basename`, removing query string after the extension if it exists. * @param {string} path Path to get the basename of * @param {string} [ext] File extension to remove * @returns {string} Basename of the path * @private */ static basename(path, ext) { const res = parse(path); return ext && res.ext.startsWith(ext) ? res.name : res.base.split('?')[0]; } /** * The content to have all mentions replaced by the equivalent text. * @param {string} str The string to be converted * @param {TextBasedChannels} channel The channel the string was sent in * @returns {string} */ static cleanContent(str, channel) { str = str .replace(/<@!?[0-9]+>/g, input => { const id = input.replace(/<|!|>|@/g, ''); if (channel.type === ChannelType.DM) { const user = channel.client.users.cache.get(id); return user ? `@${user.username}` : input; } const member = channel.guild.members.cache.get(id); if (member) { return `@${member.displayName}`; } else { const user = channel.client.users.cache.get(id); return user ? `@${user.username}` : input; } }) .replace(/<#[0-9]+>/g, input => { const mentionedChannel = channel.client.channels.cache.get(input.replace(/<|#|>/g, '')); return mentionedChannel ? `#${mentionedChannel.name}` : input; }) .replace(/<@&[0-9]+>/g, input => { if (channel.type === ChannelType.DM) return input; const role = channel.guild.roles.cache.get(input.replace(/<|@|>|&/g, '')); return role ? `@${role.name}` : input; }); return str; } /** * The content to put in a code block with all code block fences replaced by the equivalent backticks. * @param {string} text The string to be converted * @returns {string} */ static cleanCodeBlockContent(text) { return text.replaceAll('```', '`\u200b``'); } }
JavaScript
class Remove extends PureComponent { static propTypes = { /** @ignore */ accountName: PropTypes.string.isRequired, /** @ignore */ deleteAccount: PropTypes.func.isRequired, /** @ignore */ history: PropTypes.object.isRequired, /** @ignore */ generateAlert: PropTypes.func.isRequired, /** @ignore */ t: PropTypes.func.isRequired, }; state = { removeConfirm: false, }; /** * Remove account from wallet state and seed vault * @param {string} Password - Plain text account password * @returns {undefined} */ removeAccount = async (password) => { const { accountName, history, t, generateAlert, deleteAccount } = this.props; this.setState({ removeConfirm: false, }); try { await removeSeed(password, accountName); deleteAccount(accountName); history.push('/wallet/'); generateAlert('success', t('settings:accountDeleted'), t('settings:accountDeletedExplanation')); } catch (err) { generateAlert( 'error', t('changePassword:incorrectPassword'), t('changePassword:incorrectPasswordExplanation'), ); return; } }; render() { const { t, accountName } = this.props; const { removeConfirm, vault } = this.state; if (removeConfirm && !vault) { return ( <ModalPassword isOpen inline onSuccess={(password) => this.removeAccount(password)} onClose={() => this.setState({ removeConfirm: false })} category="negative" content={{ title: t('deleteAccount:enterPassword'), confirm: t('accountManagement:deleteAccount'), }} /> ); } return ( <div> <Info> <p>{t('deleteAccount:yourSeedWillBeRemoved')}</p> </Info> <Button variant="negative" onClick={() => this.setState({ removeConfirm: !removeConfirm })}> {t('accountManagement:deleteAccount')} </Button> <Confirm isOpen={removeConfirm} category="negative" content={{ title: `Are you sure you want to delete ${accountName}?`, //FIXME message: t('deleteAccount:yourSeedWillBeRemoved'), cancel: t('cancel'), confirm: t('accountManagement:deleteAccount'), }} onCancel={() => this.setState({ removeConfirm: false })} onConfirm={() => this.removeAccount()} /> </div> ); } }
JavaScript
class XliffParser { constructor() { this._locale = null; } parse(xliff, url) { this._unitMlString = null; this._msgIdToHtml = {}; const xml = new XmlParser().parse(xliff, url, false); this._errors = xml.errors; ml.visitAll(this, xml.rootNodes, null); return { msgIdToHtml: this._msgIdToHtml, errors: this._errors, locale: this._locale, }; } visitElement(element, context) { switch (element.name) { case _UNIT_TAG: this._unitMlString = null; const idAttr = element.attrs.find((attr) => attr.name === 'id'); if (!idAttr) { this._addError(element, `<${_UNIT_TAG}> misses the "id" attribute`); } else { const id = idAttr.value; if (this._msgIdToHtml.hasOwnProperty(id)) { this._addError(element, `Duplicated translations for msg ${id}`); } else { ml.visitAll(this, element.children, null); if (typeof this._unitMlString === 'string') { this._msgIdToHtml[id] = this._unitMlString; } else { this._addError(element, `Message ${id} misses a translation`); } } } break; // ignore those tags case _SOURCE_TAG: case _SEGMENT_SOURCE_TAG: break; case _TARGET_TAG: const innerTextStart = element.startSourceSpan.end.offset; const innerTextEnd = element.endSourceSpan.start.offset; const content = element.startSourceSpan.start.file.content; const innerText = content.slice(innerTextStart, innerTextEnd); this._unitMlString = innerText; break; case _FILE_TAG: const localeAttr = element.attrs.find((attr) => attr.name === 'target-language'); if (localeAttr) { this._locale = localeAttr.value; } ml.visitAll(this, element.children, null); break; default: // TODO(vicb): assert file structure, xliff version // For now only recurse on unhandled nodes ml.visitAll(this, element.children, null); } } visitAttribute(attribute, context) { } visitText(text, context) { } visitComment(comment, context) { } visitExpansion(expansion, context) { } visitExpansionCase(expansionCase, context) { } _addError(node, message) { this._errors.push(new I18nError(node.sourceSpan, message)); } }
JavaScript
class XmlToI18n { convert(message, url) { const xmlIcu = new XmlParser().parse(message, url, true); this._errors = xmlIcu.errors; const i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ? [] : [].concat(...ml.visitAll(this, xmlIcu.rootNodes)); return { i18nNodes: i18nNodes, errors: this._errors, }; } visitText(text, context) { return new i18n.Text(text.value, text.sourceSpan); } visitElement(el, context) { if (el.name === _PLACEHOLDER_TAG) { const nameAttr = el.attrs.find((attr) => attr.name === 'id'); if (nameAttr) { return new i18n.Placeholder('', nameAttr.value, el.sourceSpan); } this._addError(el, `<${_PLACEHOLDER_TAG}> misses the "id" attribute`); return null; } if (el.name === _MARKER_TAG) { return [].concat(...ml.visitAll(this, el.children)); } this._addError(el, `Unexpected tag`); return null; } visitExpansion(icu, context) { const caseMap = {}; ml.visitAll(this, icu.cases).forEach((c) => { caseMap[c.value] = new i18n.Container(c.nodes, icu.sourceSpan); }); return new i18n.Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan); } visitExpansionCase(icuCase, context) { return { value: icuCase.value, nodes: ml.visitAll(this, icuCase.expression), }; } visitComment(comment, context) { } visitAttribute(attribute, context) { } _addError(node, message) { this._errors.push(new I18nError(node.sourceSpan, message)); } }
JavaScript
class ObapPercentageSparkline extends ObapElement { static get styles() { return [css` :host { --obap-percentage-sparkline-selected-color: var(--obap-primary-color, #5c6bc0); --obap-percentage-sparkline-unselected-color: var(--obap-on-primary-color, #FFFFFF); display: block; width: 200px; height: 20px; } :host([hidden]) { display: none !important; } :host([disabled]) { pointer-events: none; } .container { position: relative; padding: 0; margin: 0; width: 100%; height: 100%; background: var(--obap-percentage-sparkline-unselected-color); } .bar { position: relative; height: 100%; background: var(--obap-percentage-sparkline-selected-color); } .label { position: absolute; left: 0; top: 0; display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%; height: 100%; font-weight: 500; } `]; } static get properties() { return { value: { type: Number, attribute: 'value' } } } constructor() { super(); this.value = 0; } render() { const val = `${Math.min(Math.max(this.value, 0), 100)}%` const barStyle = `width: ${val};`; const labelStyle = ` background: linear-gradient(90deg, var(--obap-percentage-sparkline-unselected-color) 0%, var(--obap-percentage-sparkline-unselected-color) ${val}, var(--obap-percentage-sparkline-selected-color) ${val}, var(--obap-percentage-sparkline-selected-color) 100%); background-clip: text; -webkit-background-clip: text; -webkit-text-fill-color: transparent; `; return html` <div class="container"> <div class="bar" style="${barStyle}"></div> <div class="label" style="${labelStyle}">${val}</div> </div> `; } }
JavaScript
class SpyLocation { constructor() { this.urlChanges = []; this._history = [new LocationState('', '', null)]; this._historyIndex = 0; /** * \@internal */ this._subject = new EventEmitter(); /** * \@internal */ this._baseHref = ''; /** * \@internal */ this._platformStrategy = (/** @type {?} */ (null)); /** * \@internal */ this._platformLocation = (/** @type {?} */ (null)); /** * \@internal */ this._urlChangeListeners = []; } /** * @param {?} url * @return {?} */ setInitialPath(url) { this._history[this._historyIndex].path = url; } /** * @param {?} url * @return {?} */ setBaseHref(url) { this._baseHref = url; } /** * @return {?} */ path() { return this._history[this._historyIndex].path; } /** * @return {?} */ getState() { return this._history[this._historyIndex].state; } /** * @param {?} path * @param {?=} query * @return {?} */ isCurrentPathEqualTo(path, query = '') { /** @type {?} */ const givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path; /** @type {?} */ const currPath = this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path(); return currPath == givenPath + (query.length > 0 ? ('?' + query) : ''); } /** * @param {?} pathname * @return {?} */ simulateUrlPop(pathname) { this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'popstate' }); } /** * @param {?} pathname * @return {?} */ simulateHashChange(pathname) { // Because we don't prevent the native event, the browser will independently update the path this.setInitialPath(pathname); this.urlChanges.push('hash: ' + pathname); this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'hashchange' }); } /** * @param {?} url * @return {?} */ prepareExternalUrl(url) { if (url.length > 0 && !url.startsWith('/')) { url = '/' + url; } return this._baseHref + url; } /** * @param {?} path * @param {?=} query * @param {?=} state * @return {?} */ go(path, query = '', state = null) { path = this.prepareExternalUrl(path); if (this._historyIndex > 0) { this._history.splice(this._historyIndex + 1); } this._history.push(new LocationState(path, query, state)); this._historyIndex = this._history.length - 1; /** @type {?} */ const locationState = this._history[this._historyIndex - 1]; if (locationState.path == path && locationState.query == query) { return; } /** @type {?} */ const url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push(url); this._subject.emit({ 'url': url, 'pop': false }); } /** * @param {?} path * @param {?=} query * @param {?=} state * @return {?} */ replaceState(path, query = '', state = null) { path = this.prepareExternalUrl(path); /** @type {?} */ const history = this._history[this._historyIndex]; if (history.path == path && history.query == query) { return; } history.path = path; history.query = query; history.state = state; /** @type {?} */ const url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push('replace: ' + url); } /** * @return {?} */ forward() { if (this._historyIndex < (this._history.length - 1)) { this._historyIndex++; this._subject.emit({ 'url': this.path(), 'state': this.getState(), 'pop': true }); } } /** * @return {?} */ back() { if (this._historyIndex > 0) { this._historyIndex--; this._subject.emit({ 'url': this.path(), 'state': this.getState(), 'pop': true }); } } /** * @param {?} fn * @return {?} */ onUrlChange(fn) { this._urlChangeListeners.push(fn); this.subscribe((/** * @param {?} v * @return {?} */ v => { this._notifyUrlChangeListeners(v.url, v.state); })); } /** * \@internal * @param {?=} url * @param {?=} state * @return {?} */ _notifyUrlChangeListeners(url = '', state) { this._urlChangeListeners.forEach((/** * @param {?} fn * @return {?} */ fn => fn(url, state))); } /** * @param {?} onNext * @param {?=} onThrow * @param {?=} onReturn * @return {?} */ subscribe(onNext, onThrow, onReturn) { return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn }); } /** * @param {?} url * @return {?} */ normalize(url) { return (/** @type {?} */ (null)); } }
JavaScript
class MockLocationStrategy extends LocationStrategy { constructor() { super(); this.internalBaseHref = '/'; this.internalPath = '/'; this.internalTitle = ''; this.urlChanges = []; /** * \@internal */ this._subject = new EventEmitter(); this.stateChanges = []; } /** * @param {?} url * @return {?} */ simulatePopState(url) { this.internalPath = url; this._subject.emit(new _MockPopStateEvent(this.path())); } /** * @param {?=} includeHash * @return {?} */ path(includeHash = false) { return this.internalPath; } /** * @param {?} internal * @return {?} */ prepareExternalUrl(internal) { if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) { return this.internalBaseHref + internal.substring(1); } return this.internalBaseHref + internal; } /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ pushState(ctx, title, path, query) { // Add state change to changes array this.stateChanges.push(ctx); this.internalTitle = title; /** @type {?} */ const url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; /** @type {?} */ const externalUrl = this.prepareExternalUrl(url); this.urlChanges.push(externalUrl); } /** * @param {?} ctx * @param {?} title * @param {?} path * @param {?} query * @return {?} */ replaceState(ctx, title, path, query) { // Reset the last index of stateChanges to the ctx (state) object this.stateChanges[(this.stateChanges.length || 1) - 1] = ctx; this.internalTitle = title; /** @type {?} */ const url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; /** @type {?} */ const externalUrl = this.prepareExternalUrl(url); this.urlChanges.push('replace: ' + externalUrl); } /** * @param {?} fn * @return {?} */ onPopState(fn) { this._subject.subscribe({ next: fn }); } /** * @return {?} */ getBaseHref() { return this.internalBaseHref; } /** * @return {?} */ back() { if (this.urlChanges.length > 0) { this.urlChanges.pop(); this.stateChanges.pop(); /** @type {?} */ const nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : ''; this.simulatePopState(nextUrl); } } /** * @return {?} */ forward() { throw 'not implemented'; } /** * @return {?} */ getState() { return this.stateChanges[(this.stateChanges.length || 1) - 1]; } }
JavaScript
class MockPlatformLocation { /** * @param {?=} config */ constructor(config) { this.baseHref = ''; this.hashUpdate = new Subject(); this.urlChanges = [{ hostname: '', protocol: '', port: '', pathname: '/', search: '', hash: '', state: null }]; if (config) { this.baseHref = config.appBaseHref || ''; /** @type {?} */ const parsedChanges = this.parseChanges(null, config.startUrl || 'http://<empty>/', this.baseHref); this.urlChanges[0] = Object.assign({}, parsedChanges); } } /** * @return {?} */ get hostname() { return this.urlChanges[0].hostname; } /** * @return {?} */ get protocol() { return this.urlChanges[0].protocol; } /** * @return {?} */ get port() { return this.urlChanges[0].port; } /** * @return {?} */ get pathname() { return this.urlChanges[0].pathname; } /** * @return {?} */ get search() { return this.urlChanges[0].search; } /** * @return {?} */ get hash() { return this.urlChanges[0].hash; } /** * @return {?} */ get state() { return this.urlChanges[0].state; } /** * @return {?} */ getBaseHrefFromDOM() { return this.baseHref; } /** * @param {?} fn * @return {?} */ onPopState(fn) { // No-op: a state stack is not implemented, so // no events will ever come. } /** * @param {?} fn * @return {?} */ onHashChange(fn) { this.hashUpdate.subscribe(fn); } /** * @return {?} */ get href() { /** @type {?} */ let url = `${this.protocol}//${this.hostname}${this.port ? ':' + this.port : ''}`; url += `${this.pathname === '/' ? '' : this.pathname}${this.search}${this.hash}`; return url; } /** * @return {?} */ get url() { return `${this.pathname}${this.search}${this.hash}`; } /** * @private * @param {?} state * @param {?} url * @param {?=} baseHref * @return {?} */ parseChanges(state, url, baseHref = '') { // When the `history.state` value is stored, it is always copied. state = JSON.parse(JSON.stringify(state)); return Object.assign({}, parseUrl(url, baseHref), { state }); } /** * @param {?} state * @param {?} title * @param {?} newUrl * @return {?} */ replaceState(state, title, newUrl) { const { pathname, search, state: parsedState, hash } = this.parseChanges(state, newUrl); this.urlChanges[0] = Object.assign({}, this.urlChanges[0], { pathname, search, hash, state: parsedState }); } /** * @param {?} state * @param {?} title * @param {?} newUrl * @return {?} */ pushState(state, title, newUrl) { const { pathname, search, state: parsedState, hash } = this.parseChanges(state, newUrl); this.urlChanges.unshift(Object.assign({}, this.urlChanges[0], { pathname, search, hash, state: parsedState })); } /** * @return {?} */ forward() { throw new Error('Not implemented'); } /** * @return {?} */ back() { /** @type {?} */ const oldUrl = this.url; /** @type {?} */ const oldHash = this.hash; this.urlChanges.shift(); /** @type {?} */ const newHash = this.hash; if (oldHash !== newHash) { scheduleMicroTask((/** * @return {?} */ () => this.hashUpdate.next((/** @type {?} */ ({ type: 'hashchange', state: null, oldUrl, newUrl: this.url }))))); } } /** * @return {?} */ getState() { return this.state; } }
JavaScript
class XAPI extends EventEmitter { /** * @param {Backend} backend - Backend connected to an XAPI instance. * @param {object} options - XAPI object options. * @param {function} options.feedbackInterceptor - Feedback interceptor. */ constructor(backend, options = {}) { super(); /** @type {Backend} */ this.backend = backend; /** @ignore */ this.requestId = 1; /** @ignore */ this.requests = {}; /** * Interface to XAPI feedback registration. * @type {Feedback} */ this.feedback = new Feedback(this, options.feedbackInterceptor); /** * Interface to XAPI configurations. * @type {Config} */ this.config = new Config(this); /** * Interface to XAPI events. * @type {Event} */ this.event = new Event(this); /** * Interface to XAPI statuses. * @type {Status} */ this.status = new Status(this); // Restrict object mutation Object.defineProperties(this, { config: { writable: false }, event: { writable: false }, feedback: { writable: false }, status: { writable: false }, }); Object.seal(this); backend .on('close', () => { this.emit('close'); }) .on('error', (error) => { this.emit('error', error); }) .on('ready', () => { this.emit('ready'); }) .on('data', this.handleResponse.bind(this)); } /** * Close the XAPI connection. * * @return {XAPI} - XAPI instance.. */ close() { this.backend.close(); return this; } /** * Executes the command specified by the given path. * * @example * // Space delimited * xapi.command('Presentation Start'); * * // Slash delimited * xapi.command('Presentation/Start'); * * // Array path * xapi.command(['Presentation', 'Start']); * * // With parameters * xapi.command('Presentation Start', { PresentationSource: 1 }); * * // Multi-line * xapi.command('UserInterface Extensions Set', { ConfigId: 'example' }, ` * <Extensions> * <Version>1.1</Version> * <Panel item="1" maxOccurrence="n"> * <Icon>Lightbulb</Icon> * <Type>Statusbar</Type> * <Page item="1" maxOccurrence="n"> * <Name>Foo</Name> * <Row item="1" maxOccurrence="n"> * <Name>Bar</Name> * <Widget item="1" maxOccurrence="n"> * <WidgetId>widget_3</WidgetId> * <Type>ToggleButton</Type> * </Widget> * </Row> * </Page> * </Panel> * </Extensions> * `); * * @param {Array|string} path - Path to command node. * @param {Object} [params] - Object containing named command arguments. * @param {string} [body] - Multi-line body for commands requiring it. * @return {Promise} - Resolved with the command response when ready. */ command(path, params, body = '') { const apiPath = normalizePath(path).join('/'); const method = `xCommand/${apiPath}`; return this.execute(method, !body ? params : Object.assign({ body }, params)); } /** @private */ handleResponse(response) { const { id, method } = response; if (method === 'xFeedback/Event') { log.debug('feedback:', response); this.feedback.dispatch(response.params); } else { if ({}.hasOwnProperty.call(response, 'result')) { log.debug('result:', response); const { resolve } = this.requests[id]; resolve(response.result); } else { log.debug('error:', response); const { reject } = this.requests[id]; reject(response.error); } delete this.requests[id]; } } /** @private */ nextRequestId() { const requestId = this.requestId; this.requestId += 1; return requestId.toString(); } /** * Execute the given JSON-RPC request on the backend. * * @example * xapi.execute('xFeedback/Subscribe', { * Query: ['Status', 'Audio'], * }); * * @param {String} method - Name of RPC method to invoke. * @param {Object} [params] - Parameters to add to the request. * @return {Promise} - Resolved with the command response. */ execute(method, params) { return new Promise((resolve, reject) => { const id = this.nextRequestId(); const request = rpc.createRequest(id, method, params); this.backend.execute(request); this.requests[id] = { resolve, reject }; }); } }
JavaScript
class Polaroid extends Component { constructor( props ) { super( props ); this.state = { height: '100%', width: 'auto', touched: false, exit: false }; } componentDidMount() { const self = this; if ( this.props.image ) { const image = new Image(); image.src = this.props.image; image.onload = function loadImage() { if ( this.height > this.width ) { self.setFormat( 'high' ); } else self.setFormat( 'wide' ); }; } } setFormat( type ) { let width = '100%'; let height = 'auto'; if ( type === 'wide' ) { width = 'auto'; height = '100%'; } this.setState({ width: width, height: height }); } remove = ( evt ) => { evt.stopPropagation(); this.setState({ exit: true }); } trigger = () => { if ( this.props.onClick !== noop ) { this.props.onClick( this.props.id ); } } touch = () => { this.setState({ touched: true }); } untouch = () => { this.setState({ touched: false }); } render() { const format = this.state.width + ' ' + this.state.height; const background = { backgroundImage: 'url(' + this.props.image + ')', backgroundSize: format, backgroundPosition: 'center' }; let imageClass = 'polaroid'; if ( this.props.onClick !== noop ) { imageClass += ' clickable-polaroid'; } if ( this.state.exit === true ) { imageClass += ' polaroid-exit'; } let innerImage = 'polaroid-image'; if ( this.state.touched === true ) { innerImage = 'polaroid-image polaroid-touched'; } const out = <div id={this.props.id} role="button" tabIndex={0} onMouseOver={this.touch} onFocus={this.touch} onMouseOut={this.untouch} onBlur={this.untouch} onClick={this.trigger} onKeyPress={this.trigger} style={this.props.style} className={imageClass} > <div className="polaroid-wrapper"> {this.props.stain ? <div className="polaroid-stain" /> : null} <div style={background} className={innerImage} /> {this.props.showPin ? <div className="polaroid-pin" /> : null} {this.props.removable ? <button onClick={this.remove} className="pin-image-map" /> : null } </div> </div>; if ( this.props.draggable ) { return <ReactDraggable>{out}</ReactDraggable>; } return out; } }
JavaScript
class SpreadsheetSettingsWidgetTextFieldSpreadsheetDateFormatPattern extends SpreadsheetSettingsWidgetTextField { placeholder() { return "Enter pattern"; } size() { return 20; } maxLength() { return 255; } stringToValue(string) { var value; switch(string.length) { case 0: value = null; break; default: value = SpreadsheetDateFormatPattern.fromJson(string); break; } return value; } }
JavaScript
class GanacheGasMultiplierProvider extends MultipliedGasEstimationProvider { constructor(provider) { super(provider, exports.GANACHE_GAS_MULTIPLIER); } async request(args) { const isGanache = await this._isGanache(); if (args.method === "eth_estimateGas" && isGanache) { const params = this._getParams(args); return this._getMultipliedGasEstimation(params); } return this._wrappedProvider.request(args); } async _isGanache() { if (this._cachedIsGanache === undefined) { const clientVersion = (await this._wrappedProvider.request({ method: "web3_clientVersion", })); this._cachedIsGanache = clientVersion.includes("TestRPC"); } return this._cachedIsGanache; } }
JavaScript
class TripledocProfile extends LitElement { static get properties() { return { message: { type: String }, name: {type: String}, profile: {type: Object} }; } constructor() { super(); this.message = 'Hello world! From minimal-element'; this.name = "unknown" this.profile = {name:"", friends: []} this.ns = new Namespaces() this.th = new TripledocHelper() } firstUpdated(changedProperties) { var app = this; this.agent = new HelloAgent(this.name); this.agent.receive = function(from, message) { if (message.hasOwnProperty("action")){ switch(message.action) { case "uriChanged": app.uriChanged(message.uri) break; default: console.log("Unknown action ",message) } } }; } render() { const friendList = (friends) => html` friendList (${friends.length})<br> <ul> ${friends.map((f) => html` <li> <button @click=${this.clickFriend} uri=${f} >${f}</button> </li> `)} </ul> `; return html` <h1>${this.name}</h1> <p>Name : ${this.profile.name}</p> <p> ${friendList(this.profile.friends)} </p> <p>Storage : <button @click=${this.clickFolder} uri=${this.profile.storage} >${this.profile.storage}</button></p> `; } uriChanged(uri){ console.log(uri) this.th.getProfileFromCard(uri).then( p =>{ console.log(p) this.profile = p; // this.name = profile.name; // this.friends = profile.friends; },err => { console.log(err) } ) } clickFriend(event) { var uri = event.target.getAttribute("uri"); var message = {action:"updateUriInput", uri:uri} this.agent.send('Browser', message); } clickFolder(event) { var uri = event.target.getAttribute("uri"); var message = {action:"exploreFolder", uri:uri} this.agent.send('Explorer', message); } }
JavaScript
class UserIP extends LitElement { // a convention I enjoy so you can change the tag name in 1 place static get tag() { return 'user-ip'; } // HTMLElement life-cycle, built in; use this for setting defaults constructor() { super(); // default values this.ip = null; this.location = null; // variables can be stored on "this" as the class we're working on is like a // Java or other Object Oriented Programming Language // so for this one, we're storing a reference to the API endpoint // so that if it ever changed it would be easier to update this.ipLookUp = 'https://ip-fast.com/api/ip/?format=json&location=True'; // messed around for a bit and noticed that changing location=false // to location=true the country and city data s being retreived and saved somehwere } // properties that you wish to use as data in HTML, CSS, and the updated life-cycle static get properties() { return { ip: { type: String, reflect: true }, location: {type: String, reflect: true}, //line above is used to create the location variable }; } // updated fires every time a property defined above changes // this allows you to react to variables changing and use javascript to perform logic updated(changedProperties) { // this is looping over an array of values that's keyed by property name == the old value // this is because you could always write this.whatever if "whatever" is the property name in question changedProperties.forEach((oldValue, propName) => { // see if the current property that we know changed, is called ip // also see if it has ANY value. We benefit from JS being lazy typed here because null // (our default value) will fail this test but ANY VALUE will pass it if (propName === 'ip' && this[propName]) { // JS is driven heavily by user events like click, hover, focus, keydown, etc // but you can also generate any custom event you want at any time of any name! // in this case, when the value of ip changes, I'm going to emit a "ip-changed" event // this way of other parts of the application want to know that ip changed in this element // then it can react to it accordingly const evt = new CustomEvent('ip-changed', { // send the event up in the HTML document bubbles: true, // move up out of custom tags (that have a shadowRoot) and regular HTML tags composed: true, // other developers / code is allowed to tell this event to STOP going up in the DOM cancelable: true, // the payload of data to fire internal to the document // this structure can be whatever you want in detail, a lot of times // I either make detail : this // or detail.value = whatever the important value is to send detail: { value: this.ip, value: this.location, //not sure if this does anything }, }); // this actually fires the event up from this tag in the page based on criteria above this.dispatchEvent(evt); } }); } // Lit life-cycle; this fires the 1st time the element is rendered on the screen // this is a sign it is safe to make calls to this.shadowRoot firstUpdated(changedProperties) { // "super" is a reserved word so that objects made before us can run THEIR version of this method // for example, if LitElement had a firstUpdated on it's class, we are extending from LitElement // at the top of this class so it's important we run LitElement's code... THEN ours here if (super.firstUpdated) { super.firstUpdated(changedProperties); } // go get an IP address based on the user generating a request // to this cool, simple, annonymous IP returnings service // sanity check that this wasn't set previously if (this.ip === null) { this.updateUserIP(); } if(this.location === null) { this.updateUserIP(); }//adding this shows the location on the first loines at the top but orverrides what was highlighted in orange } /** * Async, so run this code in order though in this example * it'll run regardless since we're not doing other actions */ async updateUserIP() { return fetch(this.ipLookUp) .then(resp => { if (resp.ok) { return resp.json(); } return false; }) .then(data => { this.ip = data.ip; return data; }) .then(data =>{ this.location = data.latitude+", "+data.country; return data; }); } // styles that ONLY APPLY TO THIS CODE BLOCK // this capability is called ShadowRoot and // it ensures that the code in the render() method // will be the only thing to get these styles applied // certain things can go in but the styles can't bleed out static get styles() { return [ css` /* :host is a special selector meaning the stlyes to apply to the tag itself, like defaults */ :host { display: block; } /* an unorder list is a ul tag */ ul { margin: 0 8px; list-style-type: square; font-size: 20px; } /* a list item in an ul or ol */ li { margin: 0; padding: 0; } .ipaddress { /* This is a CSS variable meaning code external to this can style using this variable in CSS */ font-style: var(--user-ip-ipaddress-font-style, italic); } `, ]; } // this serves very little purpose but at least we're rendering the info render() { return html` <ul> <li><strong class="ipaddress">IP address:</strong> ${this.ip}</li> <li><strong class="ipaddress">Location:</strong> ${this.location}</li> </ul>`; } }
JavaScript
class CommandoClient extends discord.Client { /** * Options for a CommandoClient * @typedef {ClientOptions} CommandoClientOptions * @property {string} [commandPrefix=!] - Default command prefix * @property {number} [commandEditableDuration=30] - Time in seconds that command messages should be editable * @property {boolean} [nonCommandEditable=true] - Whether messages without commands can be edited to a command * @property {boolean} [unknownCommandResponse=true] - Whether the bot should respond to an unknown command * @property {string|string[]|Set<string>} [owner] - ID of the bot owner's Discord user, or multiple IDs * @property {string} [invite] - Invite URL to the bot's support server */ /** * @param {CommandoClientOptions} [options] - Options for the client */ constructor(options = {}) { if(typeof options.commandPrefix === 'undefined') options.commandPrefix = '!'; if(options.commandPrefix === null) options.commandPrefix = ''; if(typeof options.commandEditableDuration === 'undefined') options.commandEditableDuration = 30; if(typeof options.nonCommandEditable === 'undefined') options.nonCommandEditable = true; if(typeof options.unknownCommandResponse === 'undefined') options.unknownCommandResponse = true; super(options); /** * The client's command registry * @type {CommandRegistry} */ this.registry = new CommandRegistry(this); /** * The client's command dispatcher * @type {CommandDispatcher} */ this.dispatcher = new CommandDispatcher(this, this.registry); /** * The client's setting provider * @type {?SettingProvider} */ this.provider = null; /** * Shortcut to use setting provider methods for the global settings * @type {GuildSettingsHelper} */ this.settings = new GuildSettingsHelper(this, null); /** * Internal global command prefix, controlled by the {@link CommandoClient#commandPrefix} getter/setter * @type {?string} * @private */ this._commandPrefix = null; // Set up command handling const msgErr = err => { this.emit('error', err); }; this.on('message', message => { this.dispatcher.handleMessage(message).catch(msgErr); }); this.on('messageUpdate', (oldMessage, newMessage) => { this.dispatcher.handleMessage(newMessage, oldMessage).catch(msgErr); }); // Fetch the owner(s) if(options.owner) { this.once('ready', () => { if(options.owner instanceof Array || options.owner instanceof Set) { for(const owner of options.owner) { this.users.fetch(owner).catch(err => { this.emit('warn', `Unable to fetch owner ${owner}.`); this.emit('error', err); }); } } else { this.users.fetch(options.owner).catch(err => { this.emit('warn', `Unable to fetch owner ${options.owner}.`); this.emit('error', err); }); } }); } } /** * Global command prefix. An empty string indicates that there is no default prefix, and only mentions will be used. * Setting to `null` means that the default prefix from {@link CommandoClient#options} will be used instead. * @type {string} * @emits {@link CommandoClient#commandPrefixChange} */ get commandPrefix() { if(typeof this._commandPrefix === 'undefined' || this._commandPrefix === null) return this.options.commandPrefix; return this._commandPrefix; } set commandPrefix(prefix) { this._commandPrefix = prefix; this.emit('commandPrefixChange', null, this._commandPrefix); } /** * Owners of the bot, set by the {@link CommandoClientOptions#owner} option * <info>If you simply need to check if a user is an owner of the bot, please instead use * {@link CommandoClient#isOwner}.</info> * @type {?Array<User>} * @readonly */ get owners() { if(!this.options.owner) return null; if(typeof this.options.owner === 'string') return [this.users.get(this.options.owner)]; const owners = []; for(const owner of this.options.owner) owners.push(this.users.get(owner)); return owners; } /** * Checks whether a user is an owner of the bot (in {@link CommandoClientOptions#owner}) * @param {UserResolvable} user - User to check for ownership * @return {boolean} */ isOwner(user) { if(!this.options.owner) return false; user = this.users.resolve(user); if(!user) throw new RangeError('Unable to resolve user.'); if(typeof this.options.owner === 'string') return user.id === this.options.owner; if(this.options.owner instanceof Array) return this.options.owner.includes(user.id); if(this.options.owner instanceof Set) return this.options.owner.has(user.id); throw new RangeError('The client\'s "owner" option is an unknown value.'); } /** * Sets the setting provider to use, and initialises it once the client is ready * @param {SettingProvider|Promise<SettingProvider>} provider Provider to use * @return {Promise<void>} */ async setProvider(provider) { provider = await provider; this.provider = provider; if(this.readyTimestamp) { this.emit('debug', `Provider set to ${provider.constructor.name} - initialising...`); await provider.init(this); this.emit('debug', 'Provider finished initialisation.'); return undefined; } this.emit('debug', `Provider set to ${provider.constructor.name} - will initialise once ready.`); await new Promise(resolve => { this.once('ready', () => { this.emit('debug', `Initialising provider...`); resolve(provider.init(this)); }); }); /** * Emitted upon the client's provider finishing initialisation * @event CommandoClient#providerReady * @param {SettingProvider} provider - Provider that was initialised */ this.emit('providerReady', provider); this.emit('debug', 'Provider finished initialisation.'); return undefined; } async destroy() { await super.destroy(); if(this.provider) await this.provider.destroy(); } }
JavaScript
class MemoryConfigReader { /** * Creates a new instance of config reader. * * @param config (optional) component configuration parameters */ constructor(config = null) { this._config = new pip_services_commons_node_1.ConfigParams(); this._config = config; } /** * Configures component by passing configuration parameters. * * @param config configuration parameters to be set. */ configure(config) { this._config = config; } /** * Reads configuration and parameterize it with given values. * * @param correlationId (optional) transaction id to trace execution through call chain. * @param parameters values to parameters the configuration or null to skip parameterization. * @param callback callback function that receives configuration or error. */ readConfig(correlationId, parameters, callback) { if (parameters != null) { let config = new pip_services_commons_node_1.ConfigParams(this._config).toString(); let template = handlebars.compile(config); config = template(parameters); callback(null, pip_services_commons_node_1.ConfigParams.fromString(config)); } else { let config = new pip_services_commons_node_1.ConfigParams(this._config); ; callback(null, config); } } }
JavaScript
class AlertHelper extends Helper { /** * Construct Alert Helper class */ constructor () { // Run super super(); // Bind private methods this._emitAlert = this._emitAlert.bind(this); // Bind public methods this.user = this.user.bind(this); this.socket = this.socket.bind(this); this.session = this.session.bind(this); } /** * Emits an alert * * @param {string} socketType * @param {*} socketReceiver * @param {string} type * @param {string} message * @param {object} opts * @param {string} medium * * @private * * @async */ async _emitAlert (socketType, socketReceiver, type, message, opts = {}, medium = 'helper') { // Create alert object const data = { 'type' : type, 'opts' : opts, 'done' : false, 'medium' : medium }; // Add message to data opts data.opts.text = message; // Run alert compile hook await this.eden.hook('alert.compile', data); // Create alert const alert = new Alert(data); // Check socket type if (socketType === 'user') { // Set user alert.set('user', socketReceiver); } else if (socketType === 'socket') { // Set session alert.set('session', socketReceiver.request.cookie[config.get('session.key') || 'eden.session.id']); } else { // Set session alert.set('session', socketReceiver); } // Save alert if (opts && opts.save) { // Save alert await alert.save(); } else if (socketType === 'socket') { // Emit to socket socketReceiver.emit('alert', data); } else { // Emit to redis socket[socketType](socketReceiver, 'alert', data); } } /** * Emits to user * * @param {user} user * @param {string} type * @param {string} message * @param {object} opts * @param {string} medium * * @async */ async user (user, type, message, opts = {}, medium = 'helper') { // Emit alert to user await this._emitAlert('user', user, type, message, opts, medium); } /** * Emits to socket * * @param {socket} socket * @param {string} type * @param {string} message * @param {object} opts * @param {string} medium * * @async */ async socket (socket, type, message, opts = {}, medium = 'helper') { // Emit alert to socket await this._emitAlert('socket', socket, type, message, opts, medium); } /** * Emits to session * * @param {String} session * @param {String} type * @param {string} message * @param {object} opts * @param {string} medium * * @async */ async session (session, type, message, opts = {}, medium = 'helper') { // Emit alert to session await this._emitAlert('session', session, type, message, opts, medium); } }
JavaScript
class Target extends EventEmitter { /** * @param {Runtime} runtime Reference to the runtime. * @param {?Blocks} blocks Blocks instance for the blocks owned by this target. * @constructor */ constructor (runtime, blocks) { super(); if (!blocks) { blocks = new Blocks(runtime); } /** * Reference to the runtime. * @type {Runtime} */ this.runtime = runtime; /** * A unique ID for this target. * @type {string} */ this.id = uid(); /** * Blocks run as code for this target. * @type {!Blocks} */ this.blocks = blocks; /** * Dictionary of variables and their values for this target. * Key is the variable id. * @type {Object.<string,*>} */ this.variables = {}; /** * Dictionary of comments for this target. * Key is the comment id. * @type {Object.<string,*>} */ this.comments = {}; /** * Dictionary of custom state for this target. * This can be used to store target-specific custom state for blocks which need it. * TODO: do we want to persist this in SB3 files? * @type {Object.<string,*>} */ this._customState = {}; /** * Currently known values for edge-activated hats. * Keys are block ID for the hat; values are the currently known values. * @type {Object.<string, *>} */ this._edgeActivatedHatValues = {}; } /** * Called when the project receives a "green flag." * @abstract */ onGreenFlag () {} /** * Return a human-readable name for this target. * Target implementations should override this. * @abstract * @returns {string} Human-readable name for the target. */ getName () { return this.id; } /** * Update an edge-activated hat block value. * @param {!string} blockId ID of hat to store value for. * @param {*} newValue Value to store for edge-activated hat. * @return {*} The old value for the edge-activated hat. */ updateEdgeActivatedValue (blockId, newValue) { const oldValue = this._edgeActivatedHatValues[blockId]; this._edgeActivatedHatValues[blockId] = newValue; return oldValue; } hasEdgeActivatedValue (blockId) { return this._edgeActivatedHatValues.hasOwnProperty(blockId); } /** * Clear all edge-activaed hat values. */ clearEdgeActivatedValues () { this._edgeActivatedHatValues = {}; } /** * Look up a variable object, first by id, and then by name if the id is not found. * Create a new variable if both lookups fail. * @param {string} id Id of the variable. * @param {string} name Name of the variable. * @return {!Variable} Variable object. */ lookupOrCreateVariable (id, name) { let variable = this.lookupVariableById(id); if (variable) return variable; variable = this.lookupVariableByNameAndType(name, Variable.SCALAR_TYPE); if (variable) return variable; // No variable with this name exists - create it locally. const newVariable = new Variable(id, name, Variable.SCALAR_TYPE, false); this.variables[id] = newVariable; return newVariable; } /** * Look up a broadcast message object with the given id and return it * if it exists. * @param {string} id Id of the variable. * @param {string} name Name of the variable. * @return {?Variable} Variable object. */ lookupBroadcastMsg (id, name) { let broadcastMsg; if (id) { broadcastMsg = this.lookupVariableById(id); } else if (name) { broadcastMsg = this.lookupBroadcastByInputValue(name); } else { log.error('Cannot find broadcast message if neither id nor name are provided.'); } if (broadcastMsg) { if (name && (broadcastMsg.name.toLowerCase() !== name.toLowerCase())) { log.error(`Found broadcast message with id: ${id}, but` + `its name, ${broadcastMsg.name} did not match expected name ${name}.`); } if (broadcastMsg.type !== Variable.BROADCAST_MESSAGE_TYPE) { log.error(`Found variable with id: ${id}, but its type ${broadcastMsg.type}` + `did not match expected type ${Variable.BROADCAST_MESSAGE_TYPE}`); } return broadcastMsg; } } /** * Look up a broadcast message with the given name and return the variable * if it exists. Does not create a new broadcast message variable if * it doesn't exist. * @param {string} name Name of the variable. * @return {?Variable} Variable object. */ lookupBroadcastByInputValue (name) { const vars = this.variables; for (const propName in vars) { if ((vars[propName].type === Variable.BROADCAST_MESSAGE_TYPE) && (vars[propName].name.toLowerCase() === name.toLowerCase())) { return vars[propName]; } } } /** * Look up a variable object. * Search begins for local variables; then look for globals. * @param {string} id Id of the variable. * @param {string} name Name of the variable. * @return {!Variable} Variable object. */ lookupVariableById (id) { // If we have a local copy, return it. if (this.variables.hasOwnProperty(id)) { return this.variables[id]; } // If the stage has a global copy, return it. if (this.runtime && !this.isStage) { const stage = this.runtime.getTargetForStage(); if (stage && stage.variables.hasOwnProperty(id)) { return stage.variables[id]; } } } /** * Look up a variable object by its name and variable type. * Search begins with local variables; then global variables if a local one * was not found. * @param {string} name Name of the variable. * @param {string} type Type of the variable. Defaults to Variable.SCALAR_TYPE. * @param {?bool} skipStage Optional flag to skip checking the stage * @return {?Variable} Variable object if found, or null if not. */ lookupVariableByNameAndType (name, type, skipStage) { if (typeof name !== 'string') return; if (typeof type !== 'string') type = Variable.SCALAR_TYPE; skipStage = skipStage || false; for (const varId in this.variables) { const currVar = this.variables[varId]; if (currVar.name === name && currVar.type === type) { return currVar; } } if (!skipStage && this.runtime && !this.isStage) { const stage = this.runtime.getTargetForStage(); if (stage) { for (const varId in stage.variables) { const currVar = stage.variables[varId]; if (currVar.name === name && currVar.type === type) { return currVar; } } } } return null; } /** * Look up a list object for this target, and create it if one doesn't exist. * Search begins for local lists; then look for globals. * @param {!string} id Id of the list. * @param {!string} name Name of the list. * @return {!Varible} Variable object representing the found/created list. */ lookupOrCreateList (id, name) { let list = this.lookupVariableById(id); if (list) return list; list = this.lookupVariableByNameAndType(name, Variable.LIST_TYPE); if (list) return list; // No variable with this name exists - create it locally. const newList = new Variable(id, name, Variable.LIST_TYPE, false); this.variables[id] = newList; return newList; } /** * Creates a variable with the given id and name and adds it to the * dictionary of variables. * @param {string} id Id of variable * @param {string} name Name of variable. * @param {string} type Type of variable, '', 'broadcast_msg', or 'list' * @param {boolean} isCloud Whether the variable to create has the isCloud flag set. * Additional checks are made that the variable can be created as a cloud variable. */ createVariable (id, name, type, isCloud) { if (!this.variables.hasOwnProperty(id)) { const newVariable = new Variable(id, name, type, false); if (isCloud && this.isStage && this.runtime.canAddCloudVariable()) { newVariable.isCloud = true; this.runtime.addCloudVariable(); this.runtime.ioDevices.cloud.requestCreateVariable(newVariable); } this.variables[id] = newVariable; } } /** * Creates a comment with the given properties. * @param {string} id Id of the comment. * @param {string} blockId Optional id of the block the comment is attached * to if it is a block comment. * @param {string} text The text the comment contains. * @param {number} x The x coordinate of the comment on the workspace. * @param {number} y The y coordinate of the comment on the workspace. * @param {number} width The width of the comment when it is full size * @param {number} height The height of the comment when it is full size * @param {boolean} minimized Whether the comment is minimized. */ createComment (id, blockId, text, x, y, width, height, minimized) { if (!this.comments.hasOwnProperty(id)) { const newComment = new Comment(id, text, x, y, width, height, minimized); if (blockId) { newComment.blockId = blockId; const blockWithComment = this.blocks.getBlock(blockId); if (blockWithComment) { blockWithComment.comment = id; } else { log.warn(`Could not find block with id ${blockId } associated with commentId: ${id}`); } } this.comments[id] = newComment; } } /** * Renames the variable with the given id to newName. * @param {string} id Id of variable to rename. * @param {string} newName New name for the variable. */ renameVariable (id, newName) { if (this.variables.hasOwnProperty(id)) { const variable = this.variables[id]; if (variable.id === id) { const oldName = variable.name; variable.name = newName; if (this.runtime) { if (variable.isCloud && this.isStage) { this.runtime.ioDevices.cloud.requestRenameVariable(oldName, newName); } const blocks = this.runtime.monitorBlocks; blocks.changeBlock({ id: id, element: 'field', name: variable.type === 'list' ? 'LIST' : 'VARIABLE', value: id }, this.runtime); const monitorBlock = blocks.getBlock(variable.id); if (monitorBlock) { this.runtime.requestUpdateMonitor(Map({ id: id, params: blocks._getBlockParams(monitorBlock) })); } } } } } /** * Removes the variable with the given id from the dictionary of variables. * @param {string} id Id of variable to delete. */ deleteVariable (id) { if (this.variables.hasOwnProperty(id)) { // Get info about the variable before deleting it const deletedVariableName = this.variables[id].name; const deletedVariableWasCloud = this.variables[id].isCloud; delete this.variables[id]; if (this.runtime) { if (deletedVariableWasCloud && this.isStage) { this.runtime.ioDevices.cloud.requestDeleteVariable(deletedVariableName); this.runtime.removeCloudVariable(); } this.runtime.monitorBlocks.deleteBlock(id); this.runtime.requestRemoveMonitor(id); } } } /** * Remove this target's monitors from the runtime state and remove the * target-specific monitored blocks (e.g. local variables, global variables for the stage, x-position). * NOTE: This does not delete any of the stage monitors like backdrop name. */ deleteMonitors () { this.runtime.requestRemoveMonitorByTargetId(this.id); let targetSpecificMonitorBlockIds; if (this.isStage) { // This only deletes global variables and not other stage monitors like backdrop number. targetSpecificMonitorBlockIds = Object.keys(this.variables); } else { targetSpecificMonitorBlockIds = Object.keys(this.runtime.monitorBlocks._blocks) .filter(key => this.runtime.monitorBlocks._blocks[key].targetId === this.id); } for (const blockId of targetSpecificMonitorBlockIds) { this.runtime.monitorBlocks.deleteBlock(blockId); } } /** * Create a clone of the variable with the given id from the dictionary of * this target's variables. * @param {string} id Id of variable to duplicate. * @param {boolean=} optKeepOriginalId Optional flag to keep the original variable ID * for the duplicate variable. This is necessary when cloning a sprite, for example. * @return {?Variable} The duplicated variable, or null if * the original variable was not found. */ duplicateVariable (id, optKeepOriginalId) { if (this.variables.hasOwnProperty(id)) { const originalVariable = this.variables[id]; const newVariable = new Variable( optKeepOriginalId ? id : null, // conditionally keep original id or generate a new one originalVariable.name, originalVariable.type, originalVariable.isCloud ); if (newVariable.type === Variable.LIST_TYPE) { newVariable.value = originalVariable.value.slice(0); } else { newVariable.value = originalVariable.value; } return newVariable; } return null; } /** * Duplicate the dictionary of this target's variables as part of duplicating. * this target or making a clone. * @param {object=} optBlocks Optional block container for the target being duplicated. * If provided, new variables will be generated with new UIDs and any variable references * in this blocks container will be updated to refer to the corresponding new IDs. * @return {object} The duplicated dictionary of variables */ duplicateVariables (optBlocks) { let allVarRefs; if (optBlocks) { allVarRefs = optBlocks.getAllVariableAndListReferences(); } return Object.keys(this.variables).reduce((accum, varId) => { const newVariable = this.duplicateVariable(varId, !optBlocks); accum[newVariable.id] = newVariable; if (optBlocks && allVarRefs) { const currVarRefs = allVarRefs[varId]; if (currVarRefs) { this.mergeVariables(varId, newVariable.id, currVarRefs); } } return accum; }, {}); } /** * Post/edit sprite info. * @param {object} data An object with sprite info data to set. * @abstract */ postSpriteInfo () {} /** * Retrieve custom state associated with this target and the provided state ID. * @param {string} stateId - specify which piece of state to retrieve. * @returns {*} the associated state, if any was found. */ getCustomState (stateId) { return this._customState[stateId]; } /** * Store custom state associated with this target and the provided state ID. * @param {string} stateId - specify which piece of state to store on this target. * @param {*} newValue - the state value to store. */ setCustomState (stateId, newValue) { this._customState[stateId] = newValue; } /** * Call to destroy a target. * @abstract */ dispose () { this._customState = {}; if (this.runtime) { this.runtime.removeExecutable(this); } } // Variable Conflict Resolution Helpers /** * Get the names of all the variables of the given type that are in scope for this target. * For targets that are not the stage, this includes any target-specific * variables as well as any stage variables unless the skipStage flag is true. * For the stage, this is all stage variables. * @param {string} type The variable type to search for; defaults to Variable.SCALAR_TYPE * @param {?bool} skipStage Optional flag to skip the stage. * @return {Array<string>} A list of variable names */ getAllVariableNamesInScopeByType (type, skipStage) { if (typeof type !== 'string') type = Variable.SCALAR_TYPE; skipStage = skipStage || false; const targetVariables = Object.values(this.variables) .filter(v => v.type === type) .map(variable => variable.name); if (skipStage || this.isStage || !this.runtime) { return targetVariables; } const stage = this.runtime.getTargetForStage(); const stageVariables = stage.getAllVariableNamesInScopeByType(type); return targetVariables.concat(stageVariables); } /** * Merge variable references with another variable. * @param {string} idToBeMerged ID of the variable whose references need to be updated * @param {string} idToMergeWith ID of the variable that the old references should be replaced with * @param {?Array<Object>} optReferencesToUpdate Optional context of the change. * Defaults to all the blocks in this target. * @param {?string} optNewName New variable name to merge with. The old * variable name in the references being updated should be replaced with this new name. * If this parameter is not provided or is '', no name change occurs. */ mergeVariables (idToBeMerged, idToMergeWith, optReferencesToUpdate, optNewName) { const referencesToChange = optReferencesToUpdate || // TODO should there be a separate helper function that traverses the blocks // for all references for a given ID instead of doing the below..? this.blocks.getAllVariableAndListReferences()[idToBeMerged]; VariableUtil.updateVariableIdentifiers(referencesToChange, idToMergeWith, optNewName); } /** * Share a local variable (and given references for that variable) to the stage. * @param {string} varId The ID of the variable to share. * @param {Array<object>} varRefs The list of variable references being shared, * that reference the given variable ID. The names and IDs of these variable * references will be updated to refer to the new (or pre-existing) global variable. */ shareLocalVariableToStage (varId, varRefs) { if (!this.runtime) return; const variable = this.variables[varId]; if (!variable) { log.warn(`Cannot share a local variable to the stage if it's not local.`); return; } const stage = this.runtime.getTargetForStage(); // If a local var is being shared with the stage, // sharing will make the variable global, resulting in a conflict // with the existing local variable. Preemptively Resolve this conflict // by renaming the new global variable. // First check if we've already done the local to global transition for this // variable. If we have, merge it with the global variable we've already created. const varIdForStage = `StageVarFromLocal_${varId}`; let stageVar = stage.lookupVariableById(varIdForStage); // If a global var doesn't already exist, create a new one with a fresh name. // Use the ID we created above so that we can lookup this new variable in the // future if we decide to share this same variable again. if (!stageVar) { const varName = variable.name; const varType = variable.type; const newStageName = `Stage: ${varName}`; stageVar = this.runtime.createNewGlobalVariable(newStageName, varIdForStage, varType); } // Update all variable references to use the new name and ID this.mergeVariables(varId, stageVar.id, varRefs, stageVar.name); } /** * Share a local variable with a sprite, merging with one of the same name and * type if it already exists on the sprite, or create a new one. * @param {string} varId Id of the variable to share * @param {Target} sprite The sprite to share the variable with * @param {Array<object>} varRefs A list of all the variable references currently being shared. */ shareLocalVariableToSprite (varId, sprite, varRefs) { if (!this.runtime) return; if (this.isStage) return; const variable = this.variables[varId]; if (!variable) { log.warn(`Tried to call 'shareLocalVariableToSprite' with a non-local variable.`); return; } const varName = variable.name; const varType = variable.type; // Check if the receiving sprite already has a variable of the same name and type // and use the existing variable, otherwise create a new one. const existingLocalVar = sprite.lookupVariableByNameAndType(varName, varType); let newVarId; if (existingLocalVar) { newVarId = existingLocalVar.id; } else { const newVar = new Variable(null, varName, varType); newVarId = newVar.id; sprite.variables[newVarId] = newVar; } // Merge with the local variable on the new sprite. this.mergeVariables(varId, newVarId, varRefs); } /** * Given a list of variable referencing fields, shares those variables with * the target with the provided id, resolving any variable conflicts that arise * using the following rules: * * If this target is the stage, exit. There are no conflicts that arise * from sharing variables from the stage to another sprite. The variables * already exist globally, so no further action is needed. * * If a variable being referenced is a global variable, do nothing. The * global variable already exists so no further action is needed. * * If a variable being referenced is local, and * 1) The receiving target is a sprite: * create a new local variable or merge with an existing local variable * of the same name and type. Update all the referencing fields * for the original variable to reference the new variable. * 2) The receiving target is the stage: * Create a new global variable with a fresh name and update all the referencing * fields to reference the new variable. * * @param {Array<object>} blocks The blocks containing * potential conflicting references to variables. * @param {Target} receivingTarget The target receiving the variables */ resolveVariableSharingConflictsWithTarget (blocks, receivingTarget) { if (this.isStage) return; // Get all the variable references in the given list of blocks const allVarListRefs = this.blocks.getAllVariableAndListReferences(blocks); // For all the variables being referenced, check for which ones are local // to this target, and resolve conflicts based on whether the receiving target // is a sprite (with a conflicting local variable) or whether it is // the stage (which cannot have local variables) for (const varId in allVarListRefs) { const currVar = this.variables[varId]; if (!currVar) continue; // The current variable is global, there shouldn't be any conflicts here, skip it. // Get the list of references for the current variable id const currVarListRefs = allVarListRefs[varId]; if (receivingTarget.isStage) { this.shareLocalVariableToStage(varId, currVarListRefs); } else { this.shareLocalVariableToSprite(varId, receivingTarget, currVarListRefs); } } } /** * Fixes up variable references in this target avoiding conflicts with * pre-existing variables in the same scope. * This is used when uploading this target as a new sprite into an existing * project, where the new sprite may contain references * to variable names that already exist as global variables in the project * (and thus are in scope for variable references in the given sprite). * * If this target has a block that references an existing global variable and that * variable *does not* exist in this target (e.g. it was a global variable in the * project the sprite was originally exported from), merge the variables. This entails * fixing the variable references in this sprite to reference the id of the pre-existing global variable. * * If this target has a block that references an existing global variable and that * variable does exist in the target itself (e.g. it's a local variable in the sprite being uploaded), * then the local variable is renamed to distinguish itself from the pre-existing variable. * All blocks that reference the local variable will be updated to use the new name. */ // TODO (#1360) This function is too long, add some helpers for the different chunks and cases... fixUpVariableReferences () { if (!this.runtime) return; // There's no runtime context to conflict with if (this.isStage) return; // Stage can't have variable conflicts with itself (and also can't be uploaded) const stage = this.runtime.getTargetForStage(); if (!stage || !stage.variables) return; const renameConflictingLocalVar = (id, name, type) => { const conflict = stage.lookupVariableByNameAndType(name, type); if (conflict) { const newName = StringUtil.unusedName( `${this.getName()}: ${name}`, this.getAllVariableNamesInScopeByType(type)); this.renameVariable(id, newName); return newName; } return null; }; const allReferences = this.blocks.getAllVariableAndListReferences(); const unreferencedLocalVarIds = []; if (Object.keys(this.variables).length > 0) { for (const localVarId in this.variables) { if (!this.variables.hasOwnProperty(localVarId)) continue; if (!allReferences[localVarId]) unreferencedLocalVarIds.push(localVarId); } } const conflictIdsToReplace = Object.create(null); const conflictNamesToReplace = Object.create(null); // Cache the list of all variable names by type so that we don't need to // re-calculate this in every iteration of the following loop. const varNamesByType = {}; const allVarNames = type => { const namesOfType = varNamesByType[type]; if (namesOfType) return namesOfType; varNamesByType[type] = this.runtime.getAllVarNamesOfType(type); return varNamesByType[type]; }; for (const varId in allReferences) { // We don't care about which var ref we get, they should all have the same var info const varRef = allReferences[varId][0]; const varName = varRef.referencingField.value; const varType = varRef.type; if (this.lookupVariableById(varId)) { // Found a variable with the id in either the target or the stage, // figure out which one. if (this.variables.hasOwnProperty(varId)) { // If the target has the variable, then check whether the stage // has one with the same name and type. If it does, then rename // this target specific variable so that there is a distinction. const newVarName = renameConflictingLocalVar(varId, varName, varType); if (newVarName) { // We are not calling this.blocks.updateBlocksAfterVarRename // here because it will search through all the blocks. We already // have access to all the references for this var id. allReferences[varId].map(ref => { ref.referencingField.value = newVarName; return ref; }); } } } else { // We didn't find the referenced variable id anywhere, // Treat it as a reference to a global variable (from the original // project this sprite was exported from). // Check for whether a global variable of the same name and type exists, // and if so, track it to merge with the existing global in a second pass of the blocks. const existingVar = stage.lookupVariableByNameAndType(varName, varType); if (existingVar) { if (!conflictIdsToReplace[varId]) { conflictIdsToReplace[varId] = existingVar.id; } } else { // A global variable with the same name did not already exist, // create a new one such that it does not conflict with any // names of local variables of the same type. const allNames = allVarNames(varType); const freshName = StringUtil.unusedName(varName, allNames); stage.createVariable(varId, freshName, varType); if (!conflictNamesToReplace[varId]) { conflictNamesToReplace[varId] = freshName; } } } } // Rename any local variables that were missed above because they aren't // referenced by any blocks for (const id in unreferencedLocalVarIds) { const varId = unreferencedLocalVarIds[id]; const name = this.variables[varId].name; const type = this.variables[varId].type; renameConflictingLocalVar(varId, name, type); } // Handle global var conflicts with existing global vars (e.g. a sprite is uploaded, and has // blocks referencing some variable that the sprite does not own, and this // variable conflicts with a global var) // In this case, we want to merge the new variable referenes with the // existing global variable for (const conflictId in conflictIdsToReplace) { const existingId = conflictIdsToReplace[conflictId]; const referencesToUpdate = allReferences[conflictId]; this.mergeVariables(conflictId, existingId, referencesToUpdate); } // Handle global var conflicts existing local vars (e.g a sprite is uploaded, // and has blocks referencing some variable that the sprite does not own, and this // variable conflcits with another sprite's local var). // In this case, we want to go through the variable references and update // the name of the variable in that reference. for (const conflictId in conflictNamesToReplace) { const newName = conflictNamesToReplace[conflictId]; const referencesToUpdate = allReferences[conflictId]; referencesToUpdate.map(ref => { ref.referencingField.value = newName; return ref; }); } } }
JavaScript
class DateTime { constructor (ctx) { this.ctx = ctx this.w = ctx.w this.months31 = [1, 3, 5, 7, 8, 10, 12] this.months30 = [2, 4, 6, 9, 11] this.daysCntOfYear = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] } isValidDate (date) { return !isNaN(this.parseDate(date)) } getUTCTimeStamp (dateStr) { return new Date(new Date(dateStr).toUTCString().substr(0, 25)).getTime() // return new Date(new Date(dateStr).setMinutes(new Date().getTimezoneOffset())) } parseDate (dateStr) { const parsed = Date.parse(dateStr) if (!isNaN(parsed)) { return this.getUTCTimeStamp(dateStr) } let output = Date.parse(dateStr.replace(/-/g, '/').replace(/[a-z]+/gi, ' ')) output = this.getUTCTimeStamp(output) return output } // https://stackoverflow.com/a/11252167/6495043 treatAsUtc (dateStr) { let result = new Date(dateStr) result.setMinutes(result.getMinutes() - result.getTimezoneOffset()) return result } // http://stackoverflow.com/questions/14638018/current-time-formatting-with-javascript#answer-14638191 formatDate (date, format, utc = true, convertToUTC = true) { const locale = this.w.globals.locale let MMMM = ['\x00', ...locale.months] let MMM = ['\x01', ...locale.shortMonths] let dddd = ['\x02', ...locale.days] let ddd = ['\x03', ...locale.shortDays] function ii (i, len) { let s = i + '' len = len || 2 while (s.length < len) s = '0' + s return s } if (convertToUTC) { date = this.treatAsUtc(date) } let y = utc ? date.getUTCFullYear() : date.getFullYear() format = format.replace(/(^|[^\\])yyyy+/g, '$1' + y) format = format.replace(/(^|[^\\])yy/g, '$1' + y.toString().substr(2, 2)) format = format.replace(/(^|[^\\])y/g, '$1' + y) let M = (utc ? date.getUTCMonth() : date.getMonth()) + 1 format = format.replace(/(^|[^\\])MMMM+/g, '$1' + MMMM[0]) format = format.replace(/(^|[^\\])MMM/g, '$1' + MMM[0]) format = format.replace(/(^|[^\\])MM/g, '$1' + ii(M)) format = format.replace(/(^|[^\\])M/g, '$1' + M) let d = utc ? date.getUTCDate() : date.getDate() format = format.replace(/(^|[^\\])dddd+/g, '$1' + dddd[0]) format = format.replace(/(^|[^\\])ddd/g, '$1' + ddd[0]) format = format.replace(/(^|[^\\])dd/g, '$1' + ii(d)) format = format.replace(/(^|[^\\])d/g, '$1' + d) let H = utc ? date.getUTCHours() : date.getHours() format = format.replace(/(^|[^\\])HH+/g, '$1' + ii(H)) format = format.replace(/(^|[^\\])H/g, '$1' + H) let h = H > 12 ? H - 12 : H === 0 ? 12 : H format = format.replace(/(^|[^\\])hh+/g, '$1' + ii(h)) format = format.replace(/(^|[^\\])h/g, '$1' + h) let m = utc ? date.getUTCMinutes() : date.getMinutes() format = format.replace(/(^|[^\\])mm+/g, '$1' + ii(m)) format = format.replace(/(^|[^\\])m/g, '$1' + m) let s = utc ? date.getUTCSeconds() : date.getSeconds() format = format.replace(/(^|[^\\])ss+/g, '$1' + ii(s)) format = format.replace(/(^|[^\\])s/g, '$1' + s) let f = utc ? date.getUTCMilliseconds() : date.getMilliseconds() format = format.replace(/(^|[^\\])fff+/g, '$1' + ii(f, 3)) f = Math.round(f / 10) format = format.replace(/(^|[^\\])ff/g, '$1' + ii(f)) f = Math.round(f / 10) format = format.replace(/(^|[^\\])f/g, '$1' + f) let T = H < 12 ? 'AM' : 'PM' format = format.replace(/(^|[^\\])TT+/g, '$1' + T) format = format.replace(/(^|[^\\])T/g, '$1' + T.charAt(0)) let t = T.toLowerCase() format = format.replace(/(^|[^\\])tt+/g, '$1' + t) format = format.replace(/(^|[^\\])t/g, '$1' + t.charAt(0)) let tz = -date.getTimezoneOffset() let K = utc || !tz ? 'Z' : tz > 0 ? '+' : '-' if (!utc) { tz = Math.abs(tz) let tzHrs = Math.floor(tz / 60) let tzMin = tz % 60 K += ii(tzHrs) + ':' + ii(tzMin) } format = format.replace(/(^|[^\\])K/g, '$1' + K) let day = (utc ? date.getUTCDay() : date.getDay()) + 1 format = format.replace(new RegExp(dddd[0], 'g'), dddd[day]) format = format.replace(new RegExp(ddd[0], 'g'), ddd[day]) format = format.replace(new RegExp(MMMM[0], 'g'), MMMM[M]) format = format.replace(new RegExp(MMM[0], 'g'), MMM[M]) format = format.replace(/\\(.)/g, '$1') return format } getTimeUnitsfromTimestamp (minX, maxX) { let w = this.w if (w.config.xaxis.min !== undefined) { minX = w.config.xaxis.min } if (w.config.xaxis.max !== undefined) { maxX = w.config.xaxis.max } let minYear = new Date(minX).getFullYear() let maxYear = new Date(maxX).getFullYear() let minMonth = new Date(minX).getMonth() let maxMonth = new Date(maxX).getMonth() let minDate = new Date(minX).getDate() let maxDate = new Date(maxX).getDate() let minHour = new Date(minX).getHours() let maxHour = new Date(maxX).getHours() let minMinute = new Date(minX).getMinutes() let maxMinute = new Date(maxX).getMinutes() return { minMinute, maxMinute, minHour, maxHour, minDate, maxDate, minMonth, maxMonth, minYear, maxYear } } isLeapYear (year) { return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0) } calculcateLastDaysOfMonth (month, year, subtract) { const days = this.determineDaysOfMonths(month, year) // whatever days we get, subtract the number of days asked return days - subtract } determineDaysOfYear (year) { let days = 365 if (this.isLeapYear(year)) { days = 366 } return days } determineRemainingDaysOfYear (year, month, date) { let dayOfYear = this.daysCntOfYear[month] + date if (month > 1 && this.isLeapYear()) dayOfYear++ return dayOfYear } determineDaysOfMonths (month, year) { let days = 30 month = Utils.monthMod(month) switch (true) { case this.months30.indexOf(month) > -1: if (month === 2) { if (this.isLeapYear(year)) { days = 29 } else { days = 28 } } break case this.months31.indexOf(month) > -1: days = 31 break default: days = 31 break } return days } }
JavaScript
class ContentCards { /** * Create a ContentCards instance * @param {object} appboy - Appboy SDK instance * @param {object[]} appboy.cards * @param {object} opts - Options * @param {string[]} opts.enabledCardTypes * @property {string[]} this.enabledCardTypes * @property {object} this.appboy * @property {object[]} this.cards * @property {object} this.titleCard */ constructor (appboy = {}, opts = {}) { const { cards = [] } = appboy; const { enabledCardTypes = [] } = opts; this.enabledCardTypes = enabledCardTypes.length ? enabledCardTypes : defaultEnabledCardTypes; this.appboy = appboy; this.rawCards = cards; this.cards = cards.map(transformCardData); this.groups = []; this.titleCard = {}; } /** * Outputs results * @returns {object} output * @returns {object} output.titleCard * @returns {object[]} output.cards */ output () { return { titleCard: this.titleCard, cards: this.cards, groups: this.groups, rawCards: this.rawCards }; } /** * Orders card by `order` value. * Example value: cards.extras.order = 'Numeric string' * @property {Object[]} this.cards * @returns {ContentCards} */ orderCardsByOrderValue () { this.cards.sort(( { order: a = DEFAULT_ORDER_VALUE }, { order: b = DEFAULT_ORDER_VALUE } ) => ( +a - +b )); return this; } /** * Orders card by `update` value. * Example value: cards.updated = 'Date string' * @property {Object[]} this.cards * @returns {ContentCards} */ orderCardsByUpdateValue () { this.cards = orderBy(this.cards, 'updated'); return this; } /** * Groups cards by preceding title cards (Header_Card). * Accounts for Terms_And_Conditions_Card for backwards compatibility. * @property {Object[]} this.cards * @returns {ContentCards} */ arrangeCardsByTitles () { this.groups = this.cards.reduce((acc, card) => { const { type } = card; if (type && (startsWith(type, 'Header_Card') || startsWith(type, 'Terms_And_Conditions_Card'))) { return [...acc, { ...card, cards: [] }]; } if (!acc.length) { return [{ title: '', cards: [card] }]; } acc[acc.length - 1].cards.push(card); return acc; }, []); return this; } /** * Finds and segregates a title card * @property {Object[]} this.cards * @property {Object} this.titleCard * @returns {ContentCards} */ getTitleCard () { const index = findIndex( this.cards, card => card.type === 'Terms_And_Conditions_Card' && card.url && card.pinned ); const [titleCard] = index > -1 ? this.cards.splice(index, 1) : [{}]; this.titleCard = titleCard; return this; } /** * Filters out card types based on `enabledCardTypes` and display times * @property {Object[]} this.cards * @returns {ContentCards} */ filterCards (brands) { this.cards = this.cards .sort(({ order: a }, { order: b }) => +a - +b) .filter(({ type }) => (type ? this.enabledCardTypes.includes(type) : false)) .filter(card => isCardCurrentlyActive(card, brands)); return this; } /** * Removes duplicate content cards. * There's a bug in Braze where duplicate content cards end up being displayed twice * This is being fix so in the mean time this function removes cards that have the same title and * card type it also orders the cards by the last updated date. * @property {Object[]} this.cards * @returns {ContentCards} */ removeDuplicateContentCards () { this.cards = orderBy(this.cards, 'updated').filter((contentCard, index, item) => index === findIndex( item, card => card.title === contentCard.title && card.type === contentCard.type )); return this; } }
JavaScript
class View extends PureComponent { static propTypes = { data: PropTypes.shape( settingsShape ).isRequired, message: PropTypes.string, handleFormSubmit: PropTypes.func.isRequired, handleChange: PropTypes.func.isRequired, }; handleSettingChange = this.handleSettingChange.bind( this ); render() { const { data: { voiceControl }, message, handleFormSubmit } = this.props; return ( <div> <aside className="secondaryInfoContainer beforePrimary"> <p id="ratingHelpsDiscoverability" className="secondaryInfo"> <Trans i18nKey="ratingHelpsDiscoverability.message"> <a href={ getUrl( `EXTENSION_RATE_${ browserNameForRating }` ) } className="secondaryInfoLink" >.</a> </Trans> </p> </aside> <form id="settingsForm"> <fieldset className="pwFormGroup"> <legend className="pwFormGroupCaption"> <h3 className="pwFormGroupCaptionHeading"> { t( `voiceControlSettings` ) } </h3> </legend> { settingsToViewProperties.get( `voiceControl` ).map( setting => <Setting key={ setting.settingName } data={ setting } settingGroupName="voiceControl" savedValue={ voiceControl[ setting.settingName ] } handleChange={ this.handleSettingChange } /> ) } <p className="pwText"> <Trans i18nKey="voiceControlSettingsCommands.message"> <a href={ getUrl( `EXTENSION_COMMANDS` ) }>.</a> <a href={ getUrl( `EXTENSION_COMMANDS_EXAMPLES` ) }>.</a> </Trans> </p> </fieldset> <div className="pwFormControls"> <button className="pwCta" title={ t( `saveSettingsTooltip` ) } onClick={ handleFormSubmit } > { t( `saveSettings` ) } </button> <p id="settingsFormMessage" className="pwText" role="status" aria-live="polite" hidden={ ! utils.isNonEmptyString( message ) } > { message } </p> </div> </form> <aside className="secondaryInfoContainer"> <Links links={ helpfulLinks } /> </aside> <aside className="secondaryInfoContainer"> <h6 id="sisterProjectsHeading"> { t( `sisterProjects` ) } </h6> <Links links={ sisterProjects } referrer={ queryParameterRefValue } /> </aside> <aside id="copyright"> <p id="copyrightText"> { t( `swagbucksCopyright` ) } </p> </aside> </div> ); } /** * Propagate a setting change to the parent component. * * @param {Event} event */ handleSettingChange( event ) { const { name, value } = event.target; this.props.handleChange( name, value ); } }
JavaScript
class TileConfig { /** * @param {TileSystem} tileSystem - tileSystem * @param {Extent} fullExtent - fullExtent of the tile layer * @param {Size} tileSize - tile size */ constructor(tileSystem, fullExtent, tileSize) { this.tileSize = tileSize; this.fullExtent = fullExtent; this.prepareTileInfo(tileSystem, fullExtent); } prepareTileInfo(tileSystem, fullExtent) { if (isString(tileSystem)) { tileSystem = TileSystem[tileSystem.toLowerCase()]; } else if (Array.isArray(tileSystem)) { tileSystem = new TileSystem(tileSystem); } if (!tileSystem) { throw new Error('Invalid TileSystem'); } this.tileSystem = tileSystem; //自动计算transformation const a = fullExtent['right'] > fullExtent['left'] ? 1 : -1, b = fullExtent['top'] > fullExtent['bottom'] ? -1 : 1, c = tileSystem['origin']['x'], d = tileSystem['origin']['y']; this.transformation = new Transformation([a, b, c, d]); } /** * Get index of point's tile * @param {Point} point - transformed point, this.transformation.transform(pCoord) * @param {Number} res - current resolution * @return {Object} tile index */ getTileIndex(point, res) { const tileSystem = this.tileSystem, tileSize = this['tileSize'], delta = 1E-7; const tileX = Math.floor(delta + point.x / (tileSize['width'] * res)); const tileY = -Math.floor(delta + point.y / (tileSize['height'] * res)); return { 'x': tileSystem['scale']['x'] * tileX, 'y': tileSystem['scale']['y'] * tileY }; } /** * Get tile index and offset from tile's northwest * @param {Coordinate} pCoord - projected coordinate * @param {Number} res - current resolution * @return {Object} tile index and offset */ getCenterTile(pCoord, res) { const tileSystem = this.tileSystem, tileSize = this['tileSize']; const point = this.transformation.transform(pCoord, 1); let tileIndex = this.getTileIndex(point, res); const tileLeft = tileIndex['x'] * tileSize['width']; const tileTop = tileIndex['y'] * tileSize['height']; const offsetLeft = point.x / res - tileSystem['scale']['x'] * tileLeft; const offsetTop = point.y / res + tileSystem['scale']['y'] * tileTop; //如果x方向为左大右小 if (tileSystem['scale']['x'] < 0) { tileIndex['x'] -= 1; } //如果y方向上大下小 if (tileSystem['scale']['y'] > 0) { tileIndex['y'] -= 1; } //有可能tileIndex超出世界范围 tileIndex = this.getNeighorTileIndex(tileIndex['x'], tileIndex['y'], 0, 0, true); return { 'x': tileIndex['x'], 'y': tileIndex['y'], 'offset': new Point(offsetLeft, offsetTop) }; } /** * Get neibor's tile index * @param {Number} tileX * @param {Number} tileY * @param {Number} offsetX * @param {Number} offsetY * @param {Number} zoomLevel * @return {Object} tile's neighbor index */ getNeighorTileIndex(tileX, tileY, offsetX, offsetY, res, isRepeatWorld) { const tileSystem = this.tileSystem; let x = (tileX + tileSystem['scale']['x'] * offsetX); let y = (tileY - tileSystem['scale']['y'] * offsetY); const idx = x; const idy = y; if (isRepeatWorld) { //caculate tile index to request in url in repeated world. const ext = this._getTileFullIndex(res); if (x < ext['xmin']) { x = ext['xmax'] - (ext['xmin'] - x) % (ext['xmax'] - ext['xmin']); if (x === ext['xmax']) { x = ext['xmin']; } } else if (x >= ext['xmax']) { x = ext['xmin'] + (x - ext['xmin']) % (ext['xmax'] - ext['xmin']); } if (y >= ext['ymax']) { y = ext['ymin'] + (y - ext['ymin']) % (ext['ymax'] - ext['ymin']); } else if (y < ext['ymin']) { y = ext['ymax'] - (ext['ymin'] - y) % (ext['ymax'] - ext['ymin']); if (y === ext['ymax']) { y = ext['ymin']; } } } return { // tile index to request in url 'x': x, 'y': y, // real tile index 'idx' : idx, 'idy' : idy }; } _getTileFullIndex(res) { const ext = this.fullExtent; const transformation = this.transformation; const nwIndex = this.getTileIndex(transformation.transform(new Coordinate(ext['left'], ext['top']), 1), res); const seIndex = this.getTileIndex(transformation.transform(new Coordinate(ext['right'], ext['bottom']), 1), res); return new Extent(nwIndex, seIndex); } /** * Get tile's south west's projected coordinate * @param {Number} tileX * @param {Number} tileY * @param {Number} res * @return {Object} */ getTileProjectedSw(tileX, tileY, res) { const tileSystem = this.tileSystem; const tileSize = this['tileSize']; const y = tileSystem['origin']['y'] + tileSystem['scale']['y'] * (tileY + (tileSystem['scale']['y'] === 1 ? 0 : 1)) * (res * tileSize['height']); const x = tileSystem['scale']['x'] * (tileX + (tileSystem['scale']['x'] === 1 ? 0 : 1)) * res * tileSize['width'] + tileSystem['origin']['x']; return [x, y]; } /** * Get tile's extent * @param {Number} tileX * @param {Number} tileY * @param {Number} res * @return {Extent} */ getTilePrjExtent(tileX, tileY, res) { const tileSize = this['tileSize'], sw = new Coordinate(this.getTileProjectedSw(tileX, tileY, res)); const sx = this.transformation.matrix[0], sy = this.transformation.matrix[1]; const x = sw.x + sx * (res * tileSize['width']), y = sw.y - sy * (res * tileSize['height']); return new Extent(sw, new Coordinate(x, y)); } }
JavaScript
class PathTesselator extends Tesselator { constructor({data, getGeometry, positionFormat, fp64}) { super({ data, getGeometry, fp64, positionFormat, attributes: { startPositions: {size: 3}, endPositions: {size: 3}, leftPositions: {size: 3}, rightPositions: {size: 3}, startEndPositions64XyLow: {size: 4, fp64Only: true}, neighborPositions64XyLow: {size: 4, fp64Only: true} } }); } /* Getters */ get(attributeName) { return this.attributes[attributeName]; } /* Implement base Tesselator interface */ getGeometrySize(path) { return Math.max(0, this.getPathLength(path) - 1); } /* eslint-disable max-statements, complexity */ updateGeometryAttributes(path, context) { const { attributes: { startPositions, endPositions, leftPositions, rightPositions, startEndPositions64XyLow, neighborPositions64XyLow }, fp64 } = this; const numPoints = context.geometrySize + 1; if (numPoints < 2) { // ignore invalid path return; } const isPathClosed = this.isClosed(path); let startPoint = this.getPointOnPath(path, 0); let endPoint = this.getPointOnPath(path, 1); let prevPoint = isPathClosed ? this.getPointOnPath(path, numPoints - 2) : startPoint; let nextPoint; for (let i = context.vertexStart, ptIndex = 1; ptIndex < numPoints; i++, ptIndex++) { if (ptIndex + 1 < numPoints) { nextPoint = this.getPointOnPath(path, ptIndex + 1); } else { nextPoint = isPathClosed ? this.getPointOnPath(path, 1) : endPoint; } startPositions[i * 3] = startPoint[0]; startPositions[i * 3 + 1] = startPoint[1]; startPositions[i * 3 + 2] = startPoint[2] || 0; endPositions[i * 3] = endPoint[0]; endPositions[i * 3 + 1] = endPoint[1]; endPositions[i * 3 + 2] = endPoint[2] || 0; leftPositions[i * 3] = prevPoint[0]; leftPositions[i * 3 + 1] = prevPoint[1]; leftPositions[i * 3 + 2] = prevPoint[2] || 0; rightPositions[i * 3] = nextPoint[0]; rightPositions[i * 3 + 1] = nextPoint[1]; rightPositions[i * 3 + 2] = nextPoint[2] || 0; if (fp64) { startEndPositions64XyLow[i * 4] = fp64LowPart(startPoint[0]); startEndPositions64XyLow[i * 4 + 1] = fp64LowPart(startPoint[1]); startEndPositions64XyLow[i * 4 + 2] = fp64LowPart(endPoint[0]); startEndPositions64XyLow[i * 4 + 3] = fp64LowPart(endPoint[1]); neighborPositions64XyLow[i * 4] = fp64LowPart(prevPoint[0]); neighborPositions64XyLow[i * 4 + 1] = fp64LowPart(prevPoint[1]); neighborPositions64XyLow[i * 4 + 2] = fp64LowPart(nextPoint[0]); neighborPositions64XyLow[i * 4 + 3] = fp64LowPart(nextPoint[1]); } prevPoint = startPoint; startPoint = endPoint; endPoint = nextPoint; } } /* eslint-enable max-statements, complexity */ /* Utilities */ getPathLength(path) { if (Number.isFinite(path[0])) { // flat format return path.length / this.positionSize; } return path.length; } getPointOnPath(path, index) { if (Number.isFinite(path[0])) { // flat format const {positionSize} = this; // TODO - avoid creating new arrays when using binary return [ path[index * positionSize], path[index * positionSize + 1], positionSize === 3 ? path[index * positionSize + 2] : 0 ]; } return path[index]; } isClosed(path) { const numPoints = this.getPathLength(path); const firstPoint = this.getPointOnPath(path, 0); const lastPoint = this.getPointOnPath(path, numPoints - 1); return ( firstPoint[0] === lastPoint[0] && firstPoint[1] === lastPoint[1] && firstPoint[2] === lastPoint[2] ); } }
JavaScript
class Event { /** * Constructor * * @param {String} name * @param {*} context */ constructor(name, context) { Object.defineProperty(this, "name", { value: name, enumerable: true, configurable: false, writable: false, }); Object.defineProperty(this, "context", { value: context, enumerable: true, configurable: false, writable: false, }); weakmap.set(this, { isCanceled: false }); } /** * Retrieve an events cancelation state * * @returns {Boolean} */ get isCanceled() { return weakmap.get(this).isCanceled; } /** * Cancel an events processing immediately */ cancel() { weakmap.get(this).isCanceled = true; } }
JavaScript
class Command { /** * Setup command line interface using commander. * * @param {array} argv * Raw array of command line arguments. * @param {string} outputDir * Working directory: process.cwd(). */ constructor(argv, outputDir) { argv = argv || []; this._outputDir = outputDir || ''; this._program = program; this._program.version(config.version); this._program.usage('[options] <filename>'); this._program.description(config.description); let options = this._options(); for (let i = 0, len = options.length; i < len; i++) { this._program.option( options[i].name, options[i].desc + ' (default: ' + options[i].value + ').', options[i].callback, options[i].value ); } this._program.parse(argv); } /** * Starts the tileset slicing process. * * @return {boolean} * True, if process could be started. */ run() { if (typeof this._program.args[0] === 'undefined') { console.log('No input image defined.'); return false; } let slicer = new Slicer(); let slicerConfig = {}; for (let key of Object.keys(defaults)) { slicerConfig[key] = this._program[key]; } let filepath = this._program.args[0]; slicer.slice(filepath, slicerConfig, (error, tiles) => { if (error) { throw error; } this._index = 0; this._tiles = tiles; this._process(); }); return true; } /** * Returns the full path of a single tile. * * @param {number} i * Index of the tile. * * @return {string} * Full path of single tile. */ tilePath(i) { return path.resolve(this.outputDir(), 'tile-' +i + '.png'); } /** * Returns the full output directory path. * * @return {string} * Output directory. */ outputDir() { return path.resolve(this._outputDir, this._program.output); } /** * Array of options for the command line interface. * * @return {Array} * Array of command line options. * * @private */ _options() { return [ { name: '-o, --output <directory>', desc: 'Output directory', callback: (value) => { return value; }, value: this._outputDir }, { name: '-f, --format <format>', desc: 'Output format', callback: (value) => { return value; }, value: defaults.format }, { name: '-w, --tileWidth <n>', desc: 'Tile width', callback: parseFloat, value: defaults.tileWidth }, { name: '-h, --tileHeight <n>', desc: 'Tile height', callback: parseFloat, value: defaults.tileHeight }, { name: '-x, --startX <n>', desc: 'Start x-position for slicer', callback: parseFloat, value: defaults.startX }, { name: '-y, --startY <n>', desc: 'Start y-position for slicer', callback: parseFloat, value: defaults.startY }, { name: '--paddingX <n>', desc: 'Padding between tiles', callback: parseFloat, value: defaults.paddingX }, { name: '--paddingY <n>', desc: 'Padding between tiles', callback: parseFloat, value: defaults.paddingY } ]; } /** * Processes the next tile in the queue. * * @private */ _process() { let tile = this._tiles[this._index] || null; if (!tile) { console.log(this._index + ' tiles have been created.'); return; } let filepath = this.tilePath(this._index); tile.writeFile(filepath, this._program.format, {}, error => { if (error) { throw error; } this._index++; this._process(); }); } }
JavaScript
class Widget { /** @constructs Widget and initializes its root. */ constructor(widgetRoot = null) { /** @member {HTMLElement} */ this._root = widgetRoot; /** @member {Property[]}*/ this.properties = []; } /** Widget's visual root. * @type {HTMLElement} */ get root() { return this._root; } set root(r) { this._root = r; } /** @returns {Widget} */ static fromRoot(root) { let w = new Widget(); w.root = root; return w; } /** Creates a {@see Widget} from the specified React component. */ static react(reactComponent) { let widget = Widget.fromRoot(ui.div()); ReactDOM.render(reactComponent, widget.root); return widget; } }
JavaScript
class Filter extends Widget { constructor() { super(ui.div()); /** @member {DataFrame} */ this.dataFrame = null; } }
JavaScript
class Accordion extends DartWidget { /** @constructs Accordion */ constructor(d) { super(d); } /** Creates a new instance of Accordion */ static create() { return toJs(grok_Accordion()); } /** @type {AccordionPane[]} */ get panes() { return grok_TabControlBase_Get_Panes(this.d).map(toJs); } /** Returns a pane with the specified name. * @param {string} name * @returns {AccordionPane} */ getPane(name) { return toJs(grok_TabControlBase_GetPane(this.d, name)); } addPane(name, getContent, expanded = false, before = null) { return toJs(grok_Accordion_AddPane(this.d, name, getContent, expanded, before !== null ? before.d : null)); } }
JavaScript
class AccordionPane { constructor(d) { this.d = d; } /** Expanded state * @type {boolean} */ get expanded() { return grok_AccordionPane_Get_Expanded(this.d); } set expanded(v) { return grok_AccordionPane_Set_Expanded(this.d, v); } /** @type {string} */ get name() { return grok_AccordionPane_Get_Name(this.d); } set name(name) { return grok_AccordionPane_Set_Name(this.d, name); } }
JavaScript
class Menu { constructor(d) { this.d = d; } static create() { return toJs(grok_Menu()); } /** Creates a popup menu. * @returns {Menu} */ static popup() { return toJs(grok_Menu_Context()); } /** Finds a child menu item with the specified text. * @param {string} text * @returns {Menu} */ find(text) { return toJs(grok_Menu_Find(this.d, text)); } /** Removes a child menu item with the specified text. * @param {string} text */ remove(text) { grok_Menu_Remove(this.d, text); } /** Removes all child menu items. */ clear() { grok_Menu_Clear(this.d); } /** Adds a menu group with the specified text. * @param {string} text * @returns {Menu} */ group(text) { return toJs(grok_Menu_Group(this.d, text)); } /** Adds a menu group with the specified text and handler. * @param {string} text * @param {Function} onClick - callback with no parameters * @returns {Menu} */ item(text, onClick) { return toJs(grok_Menu_Item(this.d, text, onClick)); } /** For each item in items, adds a menu group with the specified text and handler. * Returns this. * @param {string[]} items * @param {Function} onClick - a callback with one parameter * @returns {Menu} */ items(items, onClick) { return toJs(grok_Menu_Items(this.d, items, onClick)); } /** Adds a separator line. * @returns {Menu} */ separator() { return toJs(grok_Menu_Separator(this.d)); } /** Shows the menu. * @returns {Menu} */ show() { return toJs(grok_Menu_Show(this.d)); } }
JavaScript
class Balloon { /** Shows information message (green background) */ info(s) { grok_Balloon(s, 'info'); } /** Shows information message (red background) */ error(s) { grok_Balloon(s, 'error'); } }
JavaScript
class InputBase { constructor(d, onChanged = null) { this.d = d; if (onChanged != null) this.onChanged((_) => onChanged(this.value)); } get root() { return grok_InputBase_Get_Root(this.d); }; get caption() { return grok_InputBase_Get_Caption(this.d); }; get format() { return grok_InputBase_Get_Format(this.d); } ; get captionLabel() { return grok_InputBase_Get_CaptionLabel(this.d); }; get input() { return grok_InputBase_Get_Input(this.d); }; get nullable() { return grok_InputBase_Get_Nullable(this.d); }; set nullable(v) { return grok_InputBase_Set_Nullable(this.d, v); }; get value() { return grok_InputBase_Get_Value(this.d); }; set value(x) { return grok_InputBase_Set_Value(this.d, x); }; get stringValue() { return grok_InputBase_Get_StringValue(this.d); }; set stringValue(s) { return grok_InputBase_Set_StringValue(this.d, s); }; get readOnly() { return grok_InputBase_Get_ReadOnly(this.d); }; set readOnly(v) { return grok_InputBase_Set_ReadOnly(this.d, v); }; get enabled() { return grok_InputBase_Get_Enabled(this.d); }; set enabled(v) { return grok_InputBase_Set_Enabled(this.d, v); }; /// Occurs when [value] is changed, either by user or programmatically. onChanged(callback) { return _sub(grok_InputBase_OnChanged(this.d, callback)); } /// Occurs when [value] is changed by user. onInput(callback) { return _sub(grok_InputBase_OnInput(this.d, callback)); } save() { return grok_InputBase_Save(this.d); }; load(s) { return grok_InputBase_Load(this.d, s); }; init() { return grok_InputBase_Init(this.d); }; fireChanged() { return grok_InputBase_FireChanged(this.d); }; addCaption(caption) { grok_InputBase_AddCaption(this.d, caption); }; addPatternMenu(pattern) { grok_InputBase_AddPatternMenu(this.d, pattern); } setTooltip(msg) { grok_InputBase_SetTooltip(this.d, msg); }; static forProperty(property) { return toJs(grok_InputBase_ForProperty(property.d)); } }
JavaScript
class TreeViewNode { /** @constructs {TreeView} */ constructor(d) { this.d = d; } /** Creates new nodes tree * @returns {TreeViewNode} */ static tree() { return toJs(grok_TreeViewNode_Tree()); } /** Visual root. * @type {HTMLElement} */ get root() { return grok_TreeViewNode_Root(this.d); } /** Caption label. * @type {HTMLElement} */ get captionLabel() { grok_TreeViewNode_CaptionLabel(this.d); } /** Check box. * @type {null|HTMLElement} */ get checkBox() { return grok_TreeViewNode_CheckBox(this.d); } /** Returns 'true' if checked * @returns {boolean} */ get checked() { return grok_TreeViewNode_Get_Checked(this.d); } set checked(checked) { return grok_TreeViewNode_Set_Checked(this.d, checked); } /** Returns node text. * @returns {string} */ get text() { return grok_TreeViewNode_Text(this.d); } /** Node value. * @type {Object} */ get value() { return grok_TreeViewNode_Get_Value(this.d) }; set value(v) { grok_TreeViewNode_Set_Value(this.d, v) }; /** Gets all node items. * @returns {Array<TreeViewNode>} */ get items() { return grok_TreeViewNode_Items(this.d).map(i => toJs(i)); } /** Add new group to node. * @param {string} text * @param {Object} value * @param {boolean} expanded * @returns {TreeViewNode} */ group(text, value = null, expanded = true) { return toJs(grok_TreeViewNode_Group(this.d, text, value, expanded)); } /** Add new item to node. * @param {string} text * @param {Object} value * @returns {TreeViewNode} */ item(text, value = null) { return toJs(grok_TreeViewNode_Item(this.d, text, value)); } /** Enables checkbox on node * @param {boolean} checked */ enableCheckBox(checked = false) { grok_TreeViewNode_EnableCheckBox(this.d, checked); } }
JavaScript
class Client extends abstract_client_1.AbstractClient { constructor(clientConfig) { super("iotcloud.tencentcloudapi.com", "2021-04-08", clientConfig); } /** * 本接口(GetCOSURL)用于获取固件存储在COS的URL */ async GetCOSURL(req, cb) { return this.request("GetCOSURL", req, cb); } /** * 本接口(ReplaceTopicRule)用于修改替换规则 */ async ReplaceTopicRule(req, cb) { return this.request("ReplaceTopicRule", req, cb); } /** * 发布RRPC消息 */ async PublishRRPCMessage(req, cb) { return this.request("PublishRRPCMessage", req, cb); } /** * 设置设备上报的日志级别 */ async UpdateDeviceLogLevel(req, cb) { return this.request("UpdateDeviceLogLevel", req, cb); } /** * 本接口(DescribeGatewayBindDevices)用于获取网关绑定的子设备列表 */ async DescribeGatewayBindDevices(req, cb) { return this.request("DescribeGatewayBindDevices", req, cb); } /** * 获取日志内容列表 */ async ListLogPayload(req, cb) { return this.request("ListLogPayload", req, cb); } /** * 本接口(UpdateTopicPolicy)用于更新Topic信息 */ async UpdateTopicPolicy(req, cb) { return this.request("UpdateTopicPolicy", req, cb); } /** * 查询固件信息 */ async DescribeFirmware(req, cb) { return this.request("DescribeFirmware", req, cb); } /** * 本接口(DescribeDeviceShadow)用于查询虚拟设备信息。 */ async DescribeDeviceShadow(req, cb) { return this.request("DescribeDeviceShadow", req, cb); } /** * 本接口(DescribeDevice)用于查看设备信息 */ async DescribeDevice(req, cb) { return this.request("DescribeDevice", req, cb); } /** * 发布广播消息 */ async PublishBroadcastMessage(req, cb) { return this.request("PublishBroadcastMessage", req, cb); } /** * 启用或者禁用设备 */ async UpdateDeviceAvailableState(req, cb) { return this.request("UpdateDeviceAvailableState", req, cb); } /** * 本接口(DescribeProduct)用于查看产品详情 */ async DescribeProduct(req, cb) { return this.request("DescribeProduct", req, cb); } /** * 本接口(CreateTopicRule)用于创建一个规则 */ async CreateTopicRule(req, cb) { return this.request("CreateTopicRule", req, cb); } /** * 重试设备升级任务 */ async RetryDeviceFirmwareTask(req, cb) { return this.request("RetryDeviceFirmwareTask", req, cb); } /** * 本接口(CreateTopicPolicy)用于创建一个Topic */ async CreateTopicPolicy(req, cb) { return this.request("CreateTopicPolicy", req, cb); } /** * 更新产品的私有CA */ async UpdateProductPrivateCA(req, cb) { return this.request("UpdateProductPrivateCA", req, cb); } /** * 查询私有CA绑定的产品列表 */ async DescribePrivateCABindedProducts(req, cb) { return this.request("DescribePrivateCABindedProducts", req, cb); } /** * 本接口(BatchUpdateFirmware)用于批量更新设备固件 */ async BatchUpdateFirmware(req, cb) { return this.request("BatchUpdateFirmware", req, cb); } /** * 本接口(CreateProduct)用于创建一个新的物联网通信产品 */ async CreateProduct(req, cb) { return this.request("CreateProduct", req, cb); } /** * 本接口(GetUserResourceInfo)用于查询用户资源使用信息。 */ async GetUserResourceInfo(req, cb) { return this.request("GetUserResourceInfo", req, cb); } /** * 批量设置产品禁用状态 */ async SetProductsForbiddenStatus(req, cb) { return this.request("SetProductsForbiddenStatus", req, cb); } /** * 查询产品绑定的CA证书 */ async DescribeProductCA(req, cb) { return this.request("DescribeProductCA", req, cb); } /** * 获取证书认证类型设备的私钥,刚生成或者重置设备后仅可调用一次 */ async DescribeDeviceClientKey(req, cb) { return this.request("DescribeDeviceClientKey", req, cb); } /** * 本接口(DescribeProducts)用于列出产品列表。 */ async DescribeProducts(req, cb) { return this.request("DescribeProducts", req, cb); } /** * 本接口(CreateMultiDevicesTask)用于创建产品级别的批量创建设备任务 */ async CreateMultiDevicesTask(req, cb) { return this.request("CreateMultiDevicesTask", req, cb); } /** * 查询资源推送任务列表 */ async DescribeResourceTasks(req, cb) { return this.request("DescribeResourceTasks", req, cb); } /** * 查询固件升级任务统计信息 */ async DescribeFirmwareTaskStatistics(req, cb) { return this.request("DescribeFirmwareTaskStatistics", req, cb); } /** * 删除产品的私有CA证书 */ async DeleteProductPrivateCA(req, cb) { return this.request("DeleteProductPrivateCA", req, cb); } /** * 查询推送资源任务统计信息 */ async DescribePushResourceTaskStatistics(req, cb) { return this.request("DescribePushResourceTaskStatistics", req, cb); } /** * 本接口(DescribeProductTask)用于查看产品级别的任务信息 */ async DescribeProductTask(req, cb) { return this.request("DescribeProductTask", req, cb); } /** * 本接口(DeleteDevice)用于删除物联网通信设备。 */ async DeleteDevice(req, cb) { return this.request("DeleteDevice", req, cb); } /** * 批量启用或者禁用设备 */ async UpdateDevicesEnableState(req, cb) { return this.request("UpdateDevicesEnableState", req, cb); } /** * 本接口(ListFirmwares)用于获取固件列表 */ async ListFirmwares(req, cb) { return this.request("ListFirmwares", req, cb); } /** * 获取设备上报的日志 */ async ListSDKLog(req, cb) { return this.request("ListSDKLog", req, cb); } /** * 本接口(DescribeProductResource)用于查询产品资源详情。 */ async DescribeProductResource(req, cb) { return this.request("DescribeProductResource", req, cb); } /** * 编辑固件信息 */ async EditFirmware(req, cb) { return this.request("EditFirmware", req, cb); } /** * 本接口(CreateDevice)用于新建一个物联网通信设备。 */ async CreateDevice(req, cb) { return this.request("CreateDevice", req, cb); } /** * 本接口(DescribeDeviceResource)用于查询设备资源详情。 */ async DescribeDeviceResource(req, cb) { return this.request("DescribeDeviceResource", req, cb); } /** * 本接口(PublishMessage)用于向某个主题发消息。 */ async PublishMessage(req, cb) { return this.request("PublishMessage", req, cb); } /** * 查询固件升级任务状态分布 */ async DescribeFirmwareTaskDistribution(req, cb) { return this.request("DescribeFirmwareTaskDistribution", req, cb); } /** * 创建私有CA证书 */ async CreatePrivateCA(req, cb) { return this.request("CreatePrivateCA", req, cb); } /** * 本接口(DeleteProduct)用于删除一个物联网通信产品 */ async DeleteProduct(req, cb) { return this.request("DeleteProduct", req, cb); } /** * 更新私有CA证书 */ async UpdatePrivateCA(req, cb) { return this.request("UpdatePrivateCA", req, cb); } /** * 本接口(DownloadDeviceResource)用于下载设备资源 */ async DownloadDeviceResource(req, cb) { return this.request("DownloadDeviceResource", req, cb); } /** * 删除私有CA证书 */ async DeletePrivateCA(req, cb) { return this.request("DeletePrivateCA", req, cb); } /** * 重置设备的连接状态 */ async ResetDeviceState(req, cb) { return this.request("ResetDeviceState", req, cb); } /** * 查询固件升级任务详情 */ async DescribeFirmwareTask(req, cb) { return this.request("DescribeFirmwareTask", req, cb); } /** * 本接口(UploadFirmware)用于上传设备固件信息 */ async UploadFirmware(req, cb) { return this.request("UploadFirmware", req, cb); } /** * 本接口(DescribeDeviceResources)用于查询设备资源列表。 */ async DescribeDeviceResources(req, cb) { return this.request("DescribeDeviceResources", req, cb); } /** * 更新产品动态注册的配置 */ async UpdateProductDynamicRegister(req, cb) { return this.request("UpdateProductDynamicRegister", req, cb); } /** * 本接口(ListLog)用于查看日志信息 */ async ListLog(req, cb) { return this.request("ListLog", req, cb); } /** * 查询固件升级任务的设备列表 */ async DescribeFirmwareTaskDevices(req, cb) { return this.request("DescribeFirmwareTaskDevices", req, cb); } /** * 取消设备升级任务 */ async CancelDeviceFirmwareTask(req, cb) { return this.request("CancelDeviceFirmwareTask", req, cb); } /** * 本接口(EnableTopicRule)用于启用规则 */ async EnableTopicRule(req, cb) { return this.request("EnableTopicRule", req, cb); } /** * 本接口(BindDevices)用于网关设备批量绑定子设备 */ async BindDevices(req, cb) { return this.request("BindDevices", req, cb); } /** * 本接口(CreateTaskFileUrl)用于获取产品级任务文件上传链接 */ async CreateTaskFileUrl(req, cb) { return this.request("CreateTaskFileUrl", req, cb); } /** * 本接口(UnbindDevices)用于网关设备批量解绑子设备 */ async UnbindDevices(req, cb) { return this.request("UnbindDevices", req, cb); } /** * 查询私有化CA信息 */ async DescribePrivateCA(req, cb) { return this.request("DescribePrivateCA", req, cb); } /** * 本接口(DescribeProductTasks)用于查看产品级别的任务列表 */ async DescribeProductTasks(req, cb) { return this.request("DescribeProductTasks", req, cb); } /** * 本接口(DescribeDevices)用于查询物联网通信设备的设备列表。 */ async DescribeDevices(req, cb) { return this.request("DescribeDevices", req, cb); } /** * 本接口(GetAllVersion)用于获取所有的版本列表 */ async GetAllVersion(req, cb) { return this.request("GetAllVersion", req, cb); } /** * 本接口(DisableTopicRule)用于禁用规则 */ async DisableTopicRule(req, cb) { return this.request("DisableTopicRule", req, cb); } /** * 本接口(UpdateDeviceShadow)用于更新虚拟设备信息。 */ async UpdateDeviceShadow(req, cb) { return this.request("UpdateDeviceShadow", req, cb); } /** * 查询固件升级任务列表 */ async DescribeFirmwareTasks(req, cb) { return this.request("DescribeFirmwareTasks", req, cb); } /** * 本接口(DescribeProductResources)用于查询产品资源列表。 */ async DescribeProductResources(req, cb) { return this.request("DescribeProductResources", req, cb); } /** * 本接口(DeleteDeviceResource)用于删除设备资源 */ async DeleteDeviceResource(req, cb) { return this.request("DeleteDeviceResource", req, cb); } /** * 查询私有CA证书列表 */ async DescribePrivateCAs(req, cb) { return this.request("DescribePrivateCAs", req, cb); } /** * 本接口(UpdateDevicePSK)用于更新设备的PSK */ async UpdateDevicePSK(req, cb) { return this.request("UpdateDevicePSK", req, cb); } /** * 本接口(DeleteTopicRule)用于删除规则 */ async DeleteTopicRule(req, cb) { return this.request("DeleteTopicRule", req, cb); } }
JavaScript
class DbQueryResultCache { // ------------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------------- constructor(connection) { this.connection = connection; const { schema } = this.connection.driver.options; const database = this.connection.driver.database; const cacheOptions = typeof this.connection.options.cache === "object" ? this.connection.options.cache : {}; const cacheTableName = cacheOptions.tableName || "query-result-cache"; this.queryResultCacheDatabase = database; this.queryResultCacheSchema = schema; this.queryResultCacheTable = this.connection.driver.buildTableName(cacheTableName, schema, database); } // ------------------------------------------------------------------------- // Public Methods // ------------------------------------------------------------------------- /** * Creates a connection with given cache provider. */ async connect() { } /** * Disconnects with given cache provider. */ async disconnect() { } /** * Creates table for storing cache if it does not exist yet. */ async synchronize(queryRunner) { queryRunner = this.getQueryRunner(queryRunner); const driver = this.connection.driver; const tableExist = await queryRunner.hasTable(this.queryResultCacheTable); // todo: table name should be configurable if (tableExist) return; await queryRunner.createTable(new Table_1.Table({ database: this.queryResultCacheDatabase, schema: this.queryResultCacheSchema, name: this.queryResultCacheTable, columns: [ { name: "id", isPrimary: true, isNullable: false, type: driver.normalizeType({ type: driver.mappedDataTypes.cacheId, }), generationStrategy: driver.options.type === "spanner" ? "uuid" : "increment", isGenerated: true, }, { name: "identifier", type: driver.normalizeType({ type: driver.mappedDataTypes.cacheIdentifier, }), isNullable: true, }, { name: "time", type: driver.normalizeType({ type: driver.mappedDataTypes.cacheTime, }), isPrimary: false, isNullable: false, }, { name: "duration", type: driver.normalizeType({ type: driver.mappedDataTypes.cacheDuration, }), isPrimary: false, isNullable: false, }, { name: "query", type: driver.normalizeType({ type: driver.mappedDataTypes.cacheQuery, }), isPrimary: false, isNullable: false, }, { name: "result", type: driver.normalizeType({ type: driver.mappedDataTypes.cacheResult, }), isNullable: false, }, ], })); } /** * Caches given query result. * Returns cache result if found. * Returns undefined if result is not cached. */ getFromCache(options, queryRunner) { queryRunner = this.getQueryRunner(queryRunner); const qb = this.connection .createQueryBuilder(queryRunner) .select() .from(this.queryResultCacheTable, "cache"); if (options.identifier) { return qb .where(`${qb.escape("cache")}.${qb.escape("identifier")} = :identifier`) .setParameters({ identifier: this.connection.driver.options.type === "mssql" ? new MssqlParameter_1.MssqlParameter(options.identifier, "nvarchar") : options.identifier, }) .getRawOne(); } else if (options.query) { if (this.connection.driver.options.type === "oracle") { return qb .where(`dbms_lob.compare(${qb.escape("cache")}.${qb.escape("query")}, :query) = 0`, { query: options.query }) .getRawOne(); } return qb .where(`${qb.escape("cache")}.${qb.escape("query")} = :query`) .setParameters({ query: this.connection.driver.options.type === "mssql" ? new MssqlParameter_1.MssqlParameter(options.query, "nvarchar") : options.query, }) .getRawOne(); } return Promise.resolve(undefined); } /** * Checks if cache is expired or not. */ isExpired(savedCache) { const duration = typeof savedCache.duration === "string" ? parseInt(savedCache.duration) : savedCache.duration; return ((typeof savedCache.time === "string" ? parseInt(savedCache.time) : savedCache.time) + duration < new Date().getTime()); } /** * Stores given query result in the cache. */ async storeInCache(options, savedCache, queryRunner) { const shouldCreateQueryRunner = queryRunner === undefined || (queryRunner === null || queryRunner === void 0 ? void 0 : queryRunner.getReplicationMode()) === "slave"; if (queryRunner === undefined || shouldCreateQueryRunner) { queryRunner = this.connection.createQueryRunner("master"); } let insertedValues = options; if (this.connection.driver.options.type === "mssql") { // todo: bad abstraction, re-implement this part, probably better if we create an entity metadata for cache table insertedValues = { identifier: new MssqlParameter_1.MssqlParameter(options.identifier, "nvarchar"), time: new MssqlParameter_1.MssqlParameter(options.time, "bigint"), duration: new MssqlParameter_1.MssqlParameter(options.duration, "int"), query: new MssqlParameter_1.MssqlParameter(options.query, "nvarchar"), result: new MssqlParameter_1.MssqlParameter(options.result, "nvarchar"), }; } if (savedCache && savedCache.identifier) { // if exist then update const qb = queryRunner.manager .createQueryBuilder() .update(this.queryResultCacheTable) .set(insertedValues); qb.where(`${qb.escape("identifier")} = :condition`, { condition: insertedValues.identifier, }); await qb.execute(); } else if (savedCache && savedCache.query) { // if exist then update const qb = queryRunner.manager .createQueryBuilder() .update(this.queryResultCacheTable) .set(insertedValues); if (this.connection.driver.options.type === "oracle") { qb.where(`dbms_lob.compare("query", :condition) = 0`, { condition: insertedValues.query, }); } else { qb.where(`${qb.escape("query")} = :condition`, { condition: insertedValues.query, }); } await qb.execute(); } else { // Spanner does not support auto-generated columns if (this.connection.driver.options.type === "spanner" && !insertedValues.id) { insertedValues.id = (0, uuid_1.v4)(); } // otherwise insert await queryRunner.manager .createQueryBuilder() .insert() .into(this.queryResultCacheTable) .values(insertedValues) .execute(); } if (shouldCreateQueryRunner) { await queryRunner.release(); } } /** * Clears everything stored in the cache. */ async clear(queryRunner) { return this.getQueryRunner(queryRunner).clearTable(this.queryResultCacheTable); } /** * Removes all cached results by given identifiers from cache. */ async remove(identifiers, queryRunner) { await Promise.all(identifiers.map((identifier) => { const qb = this.getQueryRunner(queryRunner).manager.createQueryBuilder(); return qb .delete() .from(this.queryResultCacheTable) .where(`${qb.escape("identifier")} = :identifier`, { identifier, }) .execute(); })); } // ------------------------------------------------------------------------- // Protected Methods // ------------------------------------------------------------------------- /** * Gets a query runner to work with. */ getQueryRunner(queryRunner) { if (queryRunner) return queryRunner; return this.connection.createQueryRunner(); } }
JavaScript
class Button extends me.GUI_Object { /** * constructor */ constructor(x, y) { super(x, y, { image: stuff.texture, region : "shadedDark36.png" }); this.setOpacity(0.25); this.anchorPoint.set(0, 0); } /** * function called when the object is clicked on */ onClick(event) { this.setOpacity(0.5); me.input.triggerKeyEvent(me.input.KEY.SPACE, true); return false; } /** * function called when the object is clicked on */ onRelease(event) { this.setOpacity(0.25); me.input.triggerKeyEvent(me.input.KEY.SPACE, false); return false; } }
JavaScript
class Joypad extends me.GUI_Object { /** * constructor */ constructor(x, y) { super(x, y, { // background "fix" part of the joypad image: stuff.texture, region : "shadedDark07.png", anchorPoint : new me.Vector2d(0, 0) }); // mobile part of the joypad this.pad = new me.Sprite(x, y, { image: stuff.texture, region : "shadedDark01.png", anchorPoint : new me.Vector2d(0, 0) }); // default relative position from the back of the joypad this.relative = new me.Vector2d( this.width / 2 - this.pad.width / 2, this.height / 2 - this.pad.height /2 ); // offset by which the joypad move when pressed/moved this.joypad_offset = new me.Vector2d(); // default opacity this.setOpacity(0.25); // cursors status // TODO make it configurable this.cursors = { up: false, down: false, left: false, right: false }; // register on the pointermove event me.input.registerPointerEvent('pointermove', this, this.pointerMove.bind(this)); } onDestroyEvent() { // release register event event me.input.releasePointerEvent("pointermove", this); } /** * pointermove function */ pointerMove(event) { if (this.released === false) { var x = event.gameScreenX + (event.width / 2); var y = event.gameScreenY + (event.height / 2); // pointerMove is a global on the viewport, so check for coordinates if (this.getBounds().contains(x, y)) { // if any direction is active, update it if necessary if (this.cursors.left === true || this.cursors.right === true) { this.checkDirection.call(this, x, y); } } else { // release keys/joypad if necessary this.onRelease.call(this, event); } } } // update the cursors value and trigger key event checkDirection(x, y) { if (x - this.pos.x < this.width / 2) { if (this.cursors.left === false) { me.input.triggerKeyEvent(me.input.KEY.LEFT, true); this.cursors.left = true; this.joypad_offset.x = -((this.width / 2 - (x - this.pos.x)) % this.pad.width / 4); } // release the right key if it was pressed if (this.cursors.right === true) { me.input.triggerKeyEvent(me.input.KEY.RIGHT, false); this.cursors.right = false; } } if (x - this.pos.x > this.width / 2) { if (this.cursors.right === false) { me.input.triggerKeyEvent(me.input.KEY.RIGHT, true); this.cursors.right = true; this.joypad_offset.x = +(((x - this.pos.x) - this.width / 2) % this.pad.width / 4); } // release the left key is it was pressed if (this.cursors.left === true) { me.input.triggerKeyEvent(me.input.KEY.LEFT, false); this.cursors.left = false; } } } /** * function called when the object is clicked on */ onClick(event) { var x = event.gameScreenX + (event.width / 2); var y = event.gameScreenY + (event.height / 2); this.setOpacity(0.50); this.checkDirection.call(this, x, y); return false; } /** * function called when the object is release or cancelled */ onRelease(event) { this.setOpacity(0.25); if (this.cursors.left === true) { me.input.triggerKeyEvent(me.input.KEY.LEFT, false); this.cursors.left = false; } if (this.cursors.right === true) { me.input.triggerKeyEvent(me.input.KEY.RIGHT, false); this.cursors.right = false; } this.joypad_offset.set(0, 0); return false; } /** * extend the draw function */ draw(renderer) { // call the super constructor super.draw(renderer); this.pad.pos.setV(this.pos).add(this.relative).add(this.joypad_offset); this.pad.draw(renderer); } }
JavaScript
class VirtualJoypad extends me.Container { constructor() { // call the constructor super(); // persistent across level change this.isPersistent = true; // Use screen coordinates this.floating = true; // make sure our object is always draw first this.z = Infinity; // give a name this.name = "VirtualJoypad"; // instance of the virtual joypad this.joypad = new Joypad( 50, me.game.viewport.height - 200 ); // instance of the button this.button = new Button( me.game.viewport.width - 150, me.game.viewport.height - 150 ); this.addChild(this.joypad); this.addChild(this.button); // re-position the button in case of // size/orientation change var self = this; me.event.on( me.event.VIEWPORT_ONRESIZE, function (width, height) { self.button.pos.set( width - 150, height - 150, self.button.pos.z ) } ); } }
JavaScript
class MetadataIntegrityException extends BaseException { constructor(code, config) { super(code, MetadataIntegrityException.codes[code], { className: 'MetadataIntegrityException' }); } static codes = { /** * ### Entity name is required. * * This error is thrown when you try to create an entity, and the description object you used does not contain a `name` param. * @example * new Entity({}); * * @attribute MIE001 */ 'MIE001': 'Entity name is required', /** * ### Entity name must be a String. * * Thrown when you try to set a non-string value as entity name. * * @example * new Entity({ name: 123 }); * * @attribute MIE002 */ 'MIE002': 'Entity name must be a string', /** * ### Entity name must comply with the specification. * * All entity names must comply with a specification: They must start by an A-Z or an underscore, and contain only letters, numbers, hyphens and underscores. * @example * new Entity({ name: '1abc' }) * @example * new Entity({ name: '-abc' }) * @example * new Entity({ name: 'abc$' }) * * @attribute MIE003 */ 'MIE003': 'Entity name must comply with the specification', /** * ### Entity name must have between 2 a 64 characters. * * All Metadatio entities must comply with these length requirements to be valid. * @example * new Entity({ name: 'a' }) * @example * new Entity({ name: 'a..za..za..za..z' }) // More than 64 characters :) * * @attribute MIE004 */ 'MIE004': 'Entity name must have between 2 a 64 characters', /** * ### Entity fields must be instances of field. * * This error occurs when you try to append a non-Field object as entity's field. * @example * new Entity({ ... fields: [{...}] }) * @example * someEntity.addField({}) * * @attribute MIE005 */ 'MIE005': 'Entity fields must be instances of field', /** * ### A field already exist with name {{name}}, and 'overwrite' flag has not been set. * * When you append a field to an entity, an existence verification is done on the field name. The {{#crossLink Entity/addField:method}}addField{{/crossLink}} method contains an optional `overwrite` flag - that bypasses this verification process. If you don't set the flag, you will get this error. * @example * const entity = new Entity({ ... fields: [new Field({ name: 'foo'})] }) * @example * entity.addField(new Field({ name: 'foo' })) * * @attribute MIE006 */ 'MIE006': 'A field already exist with name {{name}}, and \'overwrite\' flag has not been set', /** * ### Field name is required. * * This error is thrown when you try to create an field, and the description object you used does not contain a `name` param. * @example * new Field({}) * * @attribute MIF001 */ 'MIF001': 'Field name is required', /** * ### Field name must be a string. * * This error is thrown when you set a non-string value as field name * @example * new Field({ name: 123, ... }) * * @attribute MIF002 */ 'MIF002': 'Field name must be a string', /** * ### Field name must comply with the specification. * * As entities, all field names must comply with the specification -i.e. must start by an A-Z or an underscore, and contain only letters, numbers, hyphens and underscores. * @example * new Field({ name: '1abc', ... }) * @example * new Field({ name: '-abc', ... }) * @example * new Field({ name: 'abc$', ... }) * * @attribute MIF003 */ 'MIF003': 'Field name must comply with the specification', /** * ### Field name must have between 2 and 64 characters. * * All field names lengths must be between defined bounds * @example * new Field({ name: 'a', ... }) * @example * new Field({ name: 'a..za..za..za..z', ... }) // More than 64 characters :D * * @attribute MIF004 */ 'MIF004': 'Field name must have between 2 and 64 characters', /** * ### Data type is not defined. * * This exception is thrown when you define a field without a data type. Data typing your fields is essential for proper working, and thus not assigning it will result in this error. * @example * new Field({ name: 'foo' }) * * @attribute MIF005 */ 'MIF005': 'Data type is not defined', /** * ### Data type is invalid. * * This exception occurs when you set an invalid data type to a field. Data types can only be String, Number, Boolean, Date, and references to other entities * @example * new Field({ name: 'foo', dataType: 'wrong' }) * * @attribute MIF006 */ 'MIF006': 'Data type is invalid', /** * ### Multiplicity is neither \'one\' nor \'many\'. * * You will get this error if you setup a multiplicity for an entity that is neither 'one' nor 'many'. The {{#crossLink Field/multiplicity:property}}multiplicity{{/crossLink}} is optional, and by default is set to 'one'. * @example * new Field({ ... multiplicity: 'wrong' }) * * @attribute MIF007 */ 'MIF007': 'Multiplicity is neither \'one\' nor \'many\'', /** * ### Validator name must be given, and be a string. * * When you attach validators to a field, you must define a *string* name for the validator - for logging purposes. When you associate a validator to a field without a name set - or with a name that is not a string -, you will get this error. * @example * someField.addValidator(null, new Validator(...)) * @example * someField.addValidator(123, new Validator(...)) * * @attribute MIV001 */ 'MIV001': 'Validator name must be given, and be a string', /** * ### Validators must be instances of \'Validator\'. * * Every time you include a validator to a field, the value you set as validator is checked, to verify that it is an instance of {{#crossLink Validator}}Validator{{/crossLink}}. If that's not the case, this exception is thrown. * @example * new Field({ ... validators: { 'pattern': {} } }) * @example * someField.addValidator('pattern', {}); * * @attribute MIV002 */ 'MIV002': 'Validators must be instances of \'Validator\'', /** * ### A validator already exists with name {{name}} and 'overwrite' flag has not been set. * * When you include a validator to a field at runtime, a name verification is launched. If the validator name you set already exists, and you haven't set the `overwrite` flag, this error will occur. * @example * const someField = new Field({ ... validators: { 'pattern': ... } } }); * @example * someField.addValidator('pattern': new Validator(...)); * * @attribute MIV003 */ 'MIV003': 'A validator already exists with name {{name}} and \'overwrite\' flag has not been set' }; }
JavaScript
class MediaBaseViewer extends BaseViewer { /** @property {Object} - Keeps track of the different media metrics */ metrics = { [MEDIA_METRIC.bufferFill]: 0, [MEDIA_METRIC.duration]: 0, [MEDIA_METRIC.lagRatio]: 0, [MEDIA_METRIC.seeked]: false, [MEDIA_METRIC.totalBufferLag]: 0, [MEDIA_METRIC.watchLength]: 0, }; /** @property {number} - Number of times refreshing token has been retried for unauthorized error */ retryTokenCount = 0; /** * @inheritdoc */ constructor(options) { super(options); // Bind context for callbacks this.containerClickHandler = this.containerClickHandler.bind(this); this.errorHandler = this.errorHandler.bind(this); this.handleAutoplay = this.handleAutoplay.bind(this); this.handleRate = this.handleRate.bind(this); this.handleTimeupdateFromMediaControls = this.handleTimeupdateFromMediaControls.bind(this); this.loadeddataHandler = this.loadeddataHandler.bind(this); this.mediaendHandler = this.mediaendHandler.bind(this); this.pauseHandler = this.pauseHandler.bind(this); this.playingHandler = this.playingHandler.bind(this); this.processBufferFillMetric = this.processBufferFillMetric.bind(this); this.processMetrics = this.processMetrics.bind(this); this.progressHandler = this.progressHandler.bind(this); this.resetPlayIcon = this.resetPlayIcon.bind(this); this.seekHandler = this.seekHandler.bind(this); this.setAutoplay = this.setAutoplay.bind(this); this.setRate = this.setRate.bind(this); this.setTimeCode = this.setTimeCode.bind(this); this.setVolume = this.setVolume.bind(this); this.handleLoadStart = this.handleLoadStart.bind(this); this.handleCanPlay = this.handleCanPlay.bind(this); this.toggleMute = this.toggleMute.bind(this); this.togglePlay = this.togglePlay.bind(this); this.updateVolumeIcon = this.updateVolumeIcon.bind(this); this.restartPlayback = this.restartPlayback.bind(this); window.addEventListener('beforeunload', this.processMetrics); } /** * @inheritdoc */ setup() { if (this.isSetup) { return; } // Call super() to set up common layout super.setup(); // Media Wrapper this.wrapperEl = this.createViewer(document.createElement('div')); this.wrapperEl.className = CSS_CLASS_MEDIA; // Media Container this.mediaContainerEl = this.wrapperEl.appendChild(document.createElement('div')); this.mediaContainerEl.setAttribute('tabindex', '-1'); this.mediaContainerEl.className = CSS_CLASS_MEDIA_CONTAINER; this.mediaContainerEl.addEventListener('click', this.containerClickHandler); this.loadTimeout = 100000; this.oldVolume = DEFAULT_VOLUME; this.pauseListener = null; this.startTimeInSeconds = this.getStartTimeInSeconds(this.startAt); } /** * Converts a value and unit to seconds * * @param {Object} startAt - the unit and value that describes where to start the preview * @return {number} a time in seconds */ getStartTimeInSeconds(startAt = {}) { let convertedValue = INITIAL_TIME_IN_SECONDS; const value = getProp(startAt, 'value'); const unit = getProp(startAt, 'unit'); if (!value || !unit) { return INITIAL_TIME_IN_SECONDS; } if (unit === SECONDS_UNIT_NAME) { convertedValue = parseFloat(value, 10); if (Number.isNaN(convertedValue) || convertedValue < 0) { // Negative values aren't allowed, start from beginning return INITIAL_TIME_IN_SECONDS; } } else if (unit === TIMESTAMP_UNIT_NAME) { convertedValue = this.convertTimestampToSeconds(value); } else { console.error('Invalid unit for start:', unit); // eslint-disable-line no-console } return convertedValue; } /** * [destructor] * * @override * @return {void} */ destroy() { // Attempt to process the playback metrics at whatever point of playback has occurred // before we destroy the viewer this.processMetrics(); // Best effort to emit current media metrics as page unloads window.removeEventListener('beforeunload', this.processMetrics); if (this.controls && this.controls.destroy) { this.controls.destroy(); } if (this.mediaControls) { this.mediaControls.removeAllListeners(); this.mediaControls.destroy(); } // Try catch is needed due to weird behavior when src is removed try { if (this.mediaEl) { this.removeEventListenersForMediaElement(); this.removePauseEventListener(); this.mediaEl.removeAttribute('src'); this.mediaEl.load(); } if (this.mediaContainerEl) { this.mediaContainerEl.removeChild(this.mediaEl); this.mediaContainerEl.removeEventListener('click', this.containerClickHandler); } } catch (e) { // do nothing } super.destroy(); } /** * Loads a media source. * * @override * @return {Promise} Promise to load representations */ load() { super.load(); this.addEventListenersForMediaLoad(); const template = this.options.representation.content.url_template; this.mediaUrl = this.createContentUrlWithAuthParams(template); this.mediaEl.addEventListener('error', this.errorHandler); this.mediaEl.setAttribute('title', this.options.file.name); if (Browser.isIOS()) { // iOS doesn't fire loadeddata event until some data loads // Adding autoplay prevents this but won't actually autoplay the video. // https://webkit.org/blog/6784/new-video-policies-for-ios/ this.mediaEl.autoplay = true; } return this.getRepStatus() .getPromise() .then(() => { this.startLoadTimer(); this.mediaEl.src = this.mediaUrl; }) .catch(this.handleAssetError); } /** * Add event listeners to the media element related to loading of data * @return {void} */ addEventListenersForMediaLoad() { this.mediaEl.addEventListener('canplay', this.handleCanPlay); this.mediaEl.addEventListener('loadedmetadata', this.loadeddataHandler); this.mediaEl.addEventListener('loadstart', this.handleLoadStart); } /** * Click handler for media container * * @private * @return {void} */ containerClickHandler() { this.mediaContainerEl.classList.remove(CLASS_ELEM_KEYBOARD_FOCUS); } /** * Handler for meta data load for the media element. * * @protected * @emits load * @return {void} */ loadeddataHandler() { if (this.destroyed) { return; } // If it's already loaded, this handler should be triggered by refreshing token, // so we want to continue playing from the previous time, and don't need to load UI again. if (this.loaded) { this.play(this.currentTime); this.retryTokenCount = 0; return; } if (this.getViewerOption('useReactControls')) { this.loadUIReact(); } else { this.loadUI(); } if (this.isAutoplayEnabled()) { this.autoplay(); } this.setMediaTime(this.startTimeInSeconds); this.resize(); this.handleVolume(); this.loaded = true; this.emit(VIEWER_EVENT.load); // Make media element visible after resize this.showMedia(); if (this.options.autoFocus) { this.mediaContainerEl.focus(); } } /** * Makes media wrapper (and contents) visible. * * @protected * @return {void} */ showMedia() { this.wrapperEl.classList.add(CLASS_IS_VISIBLE); } /** * Determain whether is an expired token error * * @protected * @param {Object} details - error details * @return {bool} */ isExpiredTokenError({ details }) { return ( !isEmpty(details) && details.error_code === MediaError.MEDIA_ERR_NETWORK && details.error_message.includes(MEDIA_TOKEN_EXPIRE_ERROR) ); } /** * Restart playback using new token * * @protected * @param {string} newToken - new token * @return {void} */ restartPlayback(newToken) { const { currentTime } = this.mediaEl; this.currentTime = currentTime; this.options.token = newToken; this.mediaUrl = this.createContentUrlWithAuthParams(this.options.representation.content.url_template); this.mediaEl.src = this.mediaUrl; } /** * Handle expired token error * * @protected * @param {PreviewError} error * @return {boolean} True if it is a token error and is handled */ handleExpiredTokenError(error) { if (this.isExpiredTokenError(error)) { if (this.retryTokenCount >= MAX_RETRY_TOKEN) { const tokenError = new PreviewError( ERROR_CODE.TOKEN_NOT_VALID, null, { silent: true }, 'Reach refreshing token limit for unauthorized error.', ); this.triggerError(tokenError); } else { this.options .refreshToken() .then(this.restartPlayback) .catch(e => { const tokenError = new PreviewError( ERROR_CODE.TOKEN_NOT_VALID, null, { silent: true }, e.message, ); this.triggerError(tokenError); }); this.retryTokenCount += 1; } return true; } return false; } /** * Handles media element loading errors. * * @private * @param {Error} err - error object * @emits error * @return {void} */ errorHandler(err) { // eslint-disable-next-line console.error(err); const errorCode = getProp(err, 'target.error.code'); const errorMessage = getProp(err, 'target.error.message'); const errorDetails = errorCode ? { error_code: errorCode, error_message: errorMessage } : {}; const error = new PreviewError(ERROR_CODE.LOAD_MEDIA, __('error_refresh'), errorDetails); if (this.handleExpiredTokenError(error)) { return; } if (!this.isLoaded()) { this.handleDownloadError(error, this.mediaUrl); } else { this.triggerError(error); } } /** * Handler for playback rate * * @private * @emits ratechange * @return {void} */ handleRate() { const speed = this.cache.get(MEDIA_SPEED_CACHE_KEY) - 0; if (speed && this.mediaEl.playbackRate !== speed && this.mediaEl.playbackRate > 0) { this.emit('ratechange', speed); } this.mediaEl.playbackRate = speed; if (this.controls) { this.renderUI(); } } /** * Handler for volume * * @private * @emits volume * @return {void} */ handleVolume() { const volume = this.cache.has(MEDIA_VOLUME_CACHE_KEY) ? this.cache.get(MEDIA_VOLUME_CACHE_KEY) : DEFAULT_VOLUME; if (volume !== 0) { this.oldVolume = volume; } if (this.mediaEl.volume !== volume) { this.debouncedEmit('volume', volume); this.mediaEl.volume = volume; } if (this.controls) { this.renderUI(); } } /** * Handler for autoplay * * @private * @emits autoplay * @return {void} */ handleAutoplay() { this.emit('autoplay', this.isAutoplayEnabled()); if (this.controls) { this.renderUI(); } } /** * Handler for autoplay failure * Overridden in child class * * @protected */ handleAutoplayFail = () => {}; /** * Autoplay the media * * @private * @return {Promise} */ autoplay() { return this.play().catch(error => { if (error.message === PLAY_PROMISE_NOT_SUPPORTED) { // Fallback to traditional autoplay tag if mediaEl.play does not return a promise this.mediaEl.autoplay = true; } else { this.handleAutoplayFail(); } }); } /** * Determines if autoplay is enabled * * @protected * @return {boolean} Indicates if autoplay is enabled */ isAutoplayEnabled() { return this.cache.get(MEDIA_AUTOPLAY_CACHE_KEY) === 'Enabled'; } /** * Resize handler * * @private * @return {Function} debounced resize handler */ debouncedEmit = debounce((event, data) => { this.emit(event, data); }, EMIT_WAIT_TIME_IN_MILLIS); /** * Loads the controls * * @protected * @return {void} */ loadUI() { this.mediaControls = new MediaControls(this.mediaContainerEl, this.mediaEl, this.cache); this.addEventListenersForMediaControls(); this.addEventListenersForMediaElement(); } /** * Loads the React controls * * @protected * @return {void} */ loadUIReact() { if (!this.cache.has(MEDIA_AUTOPLAY_CACHE_KEY)) { this.cache.set(MEDIA_AUTOPLAY_CACHE_KEY, 'Disabled'); } if (!this.cache.has(MEDIA_SPEED_CACHE_KEY)) { this.cache.set(MEDIA_SPEED_CACHE_KEY, '1.0'); } this.addEventListenersForMediaElement(); } /** * Render and/or updated the controls * * @protected * @return {void} */ renderUI() {} /** * Handles timeupdate event for MediaControls * * @protected * @param {number} time - Time in seconds * @return {void} */ handleTimeupdateFromMediaControls(time) { this.removePauseEventListener(); this.setMediaTime(time); } /** * Adds event listeners to the media controls. * Makes changes to the media element. * * @protected * @return {void} */ addEventListenersForMediaControls() { this.mediaControls.addListener('timeupdate', this.handleTimeupdateFromMediaControls); this.mediaControls.addListener('volumeupdate', this.setVolume); this.mediaControls.addListener('toggleplayback', this.togglePlay); this.mediaControls.addListener('togglemute', this.toggleMute); this.mediaControls.addListener('ratechange', this.handleRate); this.mediaControls.addListener('autoplaychange', this.handleAutoplay); } /** * Return the current cached media play rate as a string * * @protected * @return {string} */ getRate() { return this.cache.get(MEDIA_SPEED_CACHE_KEY) || '1.0'; } /** * Updates time code. * * @private * @return {void} */ setTimeCode() { if (this.mediaControls) { this.mediaControls.setTimeCode(this.mediaEl.currentTime); } else { this.renderUI(); } } /** * Updates media element's time * * @private * @param {double} time - Time in seconds * @return {void} */ setMediaTime(time) { if (this.mediaEl && time >= 0 && time <= this.mediaEl.duration) { this.mediaEl.currentTime = time; } if (this.controls) { this.renderUI(); } } /** * Updates autoplay * * @protected * @param {boolean} autoplay - True if enabled * @return {void} */ setAutoplay(autoplay) { this.cache.set(MEDIA_AUTOPLAY_CACHE_KEY, autoplay ? 'Enabled' : 'Disabled', true); this.handleAutoplay(); } /** * Updates play rate * * @protected * @param {string} rate - New play rate * @return {void} */ setRate(rate) { this.cache.set(MEDIA_SPEED_CACHE_KEY, rate, true); this.handleRate(); } /** * Updates volume * * @protected * @param {number} volume - Must be a number between [0,1], per HTML5 spec * @return {void} */ setVolume(volume) { this.cache.set(MEDIA_VOLUME_CACHE_KEY, volume, true); this.handleVolume(); } /** * Updates volume icon. * * @private * @return {void} */ updateVolumeIcon() { if (this.mediaControls) { this.mediaControls.updateVolumeIcon(this.mediaEl.volume); } else { this.renderUI(); } } /** * Shows the pause icon. * Hides the loading indicator. * Updates volume. * Updates speed. * * @private * @return {void} */ playingHandler() { if (this.mediaControls) { this.mediaControls.showPauseIcon(); } else { this.renderUI(); } this.hideLoadingIcon(); this.handleRate(); this.handleVolume(); this.emit('play'); } /** * Updates progress. * * @private * @return {void} */ progressHandler() { if (this.mediaControls) { this.mediaControls.updateProgress(); } else { this.renderUI(); } } /** * Shows the play icon. * * @private * @return {void} */ pauseHandler() { if (this.mediaControls) { this.mediaControls.showPlayIcon(); } else { this.renderUI(); } } /** * Emits the seek event and hides the loading icon. * * @private * @emits seeked * @return {void} */ seekHandler() { this.hideLoadingIcon(); this.metrics[MEDIA_METRIC.seeked] = true; this.debouncedEmit('seeked', this.mediaEl.currentTime); } /** * Emits the previewnextfile event if autoplay is enabled. * * @private * @emits previewnextfile * @return {void} */ mediaendHandler() { this.resetPlayIcon(); this.processMetrics(); if (this.isAutoplayEnabled()) { this.emit(VIEWER_EVENT.mediaEndAutoplay); } } /** * Abstract. Must be implemented to process end of playback metrics * @emits MEDIA_METRIC_EVENTS.endPlayback * @return {void} */ processMetrics() {} /** * Shows the play button in media content. * * @private * @return {void} */ showPlayButton() { if (this.playButtonEl) { this.playButtonEl.classList.remove(CLASS_HIDDEN); } } /** * Hides the play button in media content. * * @private * @return {void} */ hidePlayButton() { if (this.playButtonEl) { this.playButtonEl.classList.add(CLASS_HIDDEN); } } /** * Resets the play icon and time. * * @private * @return {void} */ resetPlayIcon() { if (this.mediaControls) { this.mediaControls.setTimeCode(0); } else { this.setMediaTime(0); this.renderUI(); } this.hideLoadingIcon(); this.pauseHandler(); } /** * Removes pause event listener if it exists * * @private * @return {void} */ removePauseEventListener() { if (this.mediaEl && this.pauseListener) { this.mediaEl.removeEventListener('timeupdate', this.pauseListener); } } /** * Validates time parameter * * @private * @param {number} time - time for media * @return {boolean} - true if time is valid */ isValidTime(time) { return typeof time === 'number' && time >= 0 && time <= this.mediaEl.duration; } /** * Play media, optionally from start time to end time * * @param {number} start - start time in seconds * @param {number} end - end time in seconds * @emits play * @return {Promise} */ play(start, end) { const hasValidStart = this.isValidTime(start); const hasValidEnd = this.isValidTime(end); this.removePauseEventListener(); if (hasValidStart) { if (hasValidEnd && start < end) { this.pause(end); } // Start playing media from <start> time this.setMediaTime(start); } if (arguments.length === 0 || hasValidStart) { // Play may return a promise depending on browser support. This promise // will resolve when playback starts. // https://webkit.org/blog/7734/auto-play-policy-changes-for-macos/ const playPromise = this.mediaEl.play(); this.handleRate(); this.handleVolume(); return playPromise && typeof playPromise.then === 'function' ? playPromise : Promise.reject(new Error(PLAY_PROMISE_NOT_SUPPORTED)); } return Promise.resolve(); } /** * Pause media * * @param {number} time - time at which media is paused * @param {boolean} [userInitiated] - True if user input initiated the pause * @emits pause * @return {void} */ pause(time, userInitiated = false) { const hasValidTime = this.isValidTime(time); // Remove eventListener because segment completed playing or user paused manually this.removePauseEventListener(); if (hasValidTime) { this.pauseListener = () => { if (this.mediaEl.currentTime > time) { this.pause(); } }; this.mediaEl.addEventListener('timeupdate', this.pauseListener); } else { this.mediaEl.pause(); this.emit('pause', { userInitiated, }); } } /** * Toggle playback * * @protected * @return {void} */ togglePlay() { if (this.mediaEl.paused) { this.play(); } else { this.pause(undefined, true); } } /** * Toggle mute * * @protected * @return {void} */ toggleMute() { if (this.mediaEl.volume) { this.oldVolume = this.mediaEl.volume; this.cache.set(MEDIA_VOLUME_CACHE_KEY, 0, true); } else { this.cache.set(MEDIA_VOLUME_CACHE_KEY, this.oldVolume, true); } this.handleVolume(); } /** * Hides the loading indicator * * @protected * @return {void} */ hideLoadingIcon() { if (this.containerEl) { this.containerEl.classList.remove(CLASS_IS_BUFFERING); } } /** * Shows the loading indicator * * @protected * @return {void} */ showLoadingIcon() { if (this.containerEl && this.mediaEl && !this.mediaEl.paused && !this.mediaEl.ended) { this.containerEl.classList.add(CLASS_IS_BUFFERING); this.hidePlayButton(); } } /** * Adds event listeners to the media element. * Makes changes to the media controls. * * @protected * @return {void} */ addEventListenersForMediaElement() { this.mediaEl.addEventListener('ended', this.mediaendHandler); this.mediaEl.addEventListener('pause', this.pauseHandler); this.mediaEl.addEventListener('playing', this.playingHandler); this.mediaEl.addEventListener('progress', this.progressHandler); this.mediaEl.addEventListener('seeked', this.seekHandler); this.mediaEl.addEventListener('timeupdate', this.setTimeCode); this.mediaEl.addEventListener('volumechange', this.updateVolumeIcon); } /** * Removes event listeners to the media element * @return {void} */ removeEventListenersForMediaElement() { this.mediaEl.removeEventListener('canplay', this.handleCanPlay); this.mediaEl.removeEventListener('ended', this.mediaendHandler); this.mediaEl.removeEventListener('error', this.errorHandler); this.mediaEl.removeEventListener('loadeddata', this.loadeddataHandler); this.mediaEl.removeEventListener('loadstart', this.handleLoadStart); this.mediaEl.removeEventListener('pause', this.pauseHandler); this.mediaEl.removeEventListener('playing', this.playingHandler); this.mediaEl.removeEventListener('progress', this.progressHandler); this.mediaEl.removeEventListener('seeked', this.seekHandler); this.mediaEl.removeEventListener('timeupdate', this.setTimeCode); this.mediaEl.removeEventListener('volumechange', this.updateVolumeIcon); } /** * Callback from the 'loadstart' event from the media element. Triggers a timer to measure the initial buffer fill. * @return {void} */ handleLoadStart() { const tag = this.createTimerTag(MEDIA_METRIC.bufferFill); Timer.start(tag); } /** * Callback from the 'canplay' event from the media element. The first time this event is triggered we * calculate the initial buffer fill time. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplay_event} * @emits MEDIA_METRIC_EVENTS.bufferFill * @return {void} */ handleCanPlay() { const tag = this.createTimerTag(MEDIA_METRIC.bufferFill); Timer.stop(tag); // Only interested in the first event after 'loadstart' to determine the buffer fill this.mediaEl.removeEventListener('canplay', this.handleCanPlay); this.processBufferFillMetric(); } /** * Abstract. Processes the buffer fill metric which represents the initial buffer time before playback begins * @emits MEDIA_METRIC_EVENTS.bufferFill * @return {void} */ processBufferFillMetric() {} /** * Seeks forwards/backwards from current point * * @private * @param {number} increment - Increment in seconds. Negative to seek backwards, positive to seek forwards * @return {void} */ quickSeek(increment) { let newTime = this.mediaEl.currentTime + increment; this.removePauseEventListener(); // Make sure it's within bounds newTime = Math.max(0, Math.min(newTime, this.mediaEl.duration)); this.setMediaTime(newTime); } /** * Increases volume by a small increment * * @private * @return {void} */ increaseVolume() { let newVol = Math.round((this.mediaEl.volume + MEDIA_VOLUME_INCREMENT) * 100) / 100; newVol = Math.min(1, newVol); this.setVolume(newVol); } /** * Decreases volume by a small increment * * @private * @return {void} */ decreaseVolume() { let newVol = Math.round((this.mediaEl.volume - MEDIA_VOLUME_INCREMENT) * 100) / 100; newVol = Math.max(0, newVol); this.setVolume(newVol); } /** * Handles keyboard events for media * * @protected * @param {string} key - keydown key * @return {boolean} consumed or not */ onKeydown(key) { if (this.mediaControls) { return this.handleKeydown(key); } if (this.controls) { return this.handleKeydownReact(key); } return false; // Return false if controls are not ready } handleKeydown(key) { switch (key.toLowerCase()) { case 'tab': case 'shift+tab': this.mediaContainerEl.classList.add(CLASS_ELEM_KEYBOARD_FOCUS); this.mediaControls.show(); return false; // So that tab can proceed to do its default behavior of going to the next element case 'space': case 'k': this.togglePlay(); break; case 'arrowleft': if (this.mediaControls.isVolumeScrubberFocused()) { this.decreaseVolume(); } else { this.quickSeek(-5); } break; case 'j': this.quickSeek(-10); break; case 'arrowright': if (this.mediaControls.isVolumeScrubberFocused()) { this.increaseVolume(); } else { this.quickSeek(5); } break; case 'l': this.quickSeek(10); break; case '0': case 'home': this.setMediaTime(0); break; case 'arrowup': if (this.mediaControls.isTimeScrubberFocused()) { this.quickSeek(5); } else { this.increaseVolume(); } break; case 'arrowdown': if (this.mediaControls.isTimeScrubberFocused()) { this.quickSeek(-5); } else { this.decreaseVolume(); } break; case 'shift+>': this.mediaControls.increaseSpeed(); break; case 'shift+<': this.mediaControls.decreaseSpeed(); break; case 'f': case 'shift+f': this.mediaControls.toggleFullscreen(); break; case 'm': case 'shift+m': this.toggleMute(); break; case 'c': case 'shift+c': this.mediaControls.toggleSubtitles(); break; default: return false; } this.mediaControls.show(); return true; } handleKeydownReact(key) { switch (key.toLowerCase()) { case 'space': case 'k': this.togglePlay(); break; case 'arrowleft': this.quickSeek(-5); break; case 'j': this.quickSeek(-10); break; case 'arrowright': this.quickSeek(5); break; case 'l': this.quickSeek(10); break; case '0': case 'home': this.setMediaTime(0); this.renderUI(); break; case 'arrowup': this.increaseVolume(); break; case 'arrowdown': this.decreaseVolume(); break; case 'm': case 'shift+m': this.toggleMute(); break; default: return false; } return true; } /** * Converts from a youtube style timestamp to seconds * * @param {string} timestamp - the youtube style timestamp eg. "1h2m3s" * @return {number} - the time in seconds */ convertTimestampToSeconds(timestamp) { let timeInSeconds = INITIAL_TIME_IN_SECONDS; // Supports optional decimal points const TIMESTAMP_REGEX = /^([0-9]+(\.[0-9]*)?[smh]?){1,3}$/; const HOUR_REGEX = /[0-9]+(\.[0-9]*)?h/; const MINUTE_REGEX = /[0-9]+(\.[0-9]*)?m/; const SECOND_REGEX = /[0-9]+(\.[0-9]*)?s/; if (!timestamp || !TIMESTAMP_REGEX.test(timestamp)) { return timeInSeconds; } // Gets the first match for all the units const hours = HOUR_REGEX.exec(timestamp); const minutes = MINUTE_REGEX.exec(timestamp); const seconds = SECOND_REGEX.exec(timestamp); /** * Validates a substring match and converts to float * * @param {string} match - the timestamp substring e.g. 1h, 2m, or 3s * @return {number} - the number for the given unit */ const getValueOfMatch = match => { // Strip off unit (h, m, s) and convert to float const parsedMatch = parseFloat(match[0].slice(0, -1), 10); return Number.isNaN(parsedMatch) ? 0 : parsedMatch; }; if (hours) { timeInSeconds += ONE_HOUR_IN_SECONDS * getValueOfMatch(hours); } if (minutes) { timeInSeconds += ONE_MINUTE_IN_SECONDS * getValueOfMatch(minutes); } if (seconds) { timeInSeconds += getValueOfMatch(seconds); } return timeInSeconds; } /** * Overrides the base method * * @override * @return {Array} - the array of metric names to be emitted only once */ getMetricsWhitelist() { return [MEDIA_METRIC_EVENTS.bufferFill, MEDIA_METRIC_EVENTS.endPlayback]; } /** * Utility to create a Timer tag name * @param {string} tagName - tag name */ createTimerTag(tagName) { return Timer.createTag(this.options.file.id, tagName); } }
JavaScript
class MakeNunjucks extends Command { /** * @return {String} The command signature */ static get signature () { return ` make:nunjucks { name: Name of the view } { -l, --layout=@value: Define a layout to extend } ` } /** * @return {String} The command description */ static get description () { return 'Make a nunjucks view file' } /** * Handle method executed by ace * * @param {String} args.name Name of the view file * @param {String} options.layout Define a layout to extend * @return {void} */ async handle ({ name }, { layout }) { try { await this.ensureInProjectRoot() return await this.generateBlueprint(name, layout) } catch ({ message }) { this.error(message) } } /** * Ensures the command is executed within the * project root * * @throws {Error} If not in app root * @return {void} */ async ensureInProjectRoot () { const acePath = path.join(process.cwd(), 'ace') const exists = await this.pathExists(acePath) if (!exists) { throw new Error(`Make sure you are inside an Adonisjs app to run the make nunjucks command`) } } /** * Generate nunjucks file * * @param {String} name template filename * @param {String} [layout] layout to extend in nunjucks file * @return {String} Created file path */ async generateBlueprint (name, layout) { const templateFile = path.join(__dirname, './nunjucks.mustache') const filePath = path.join(process.cwd(), 'resources/views', name.toLowerCase().replace(/view/ig, '').replace(/\./g, '/')) + '.html' const data = { layout: layout && typeof (layout) === 'string' ? layout.replace('.html', '') : null } const templateContents = await this.readFile(templateFile, 'utf-8') await this.generateFile(filePath, templateContents, data) const createdFile = filePath.replace(process.cwd(), '').replace(path.sep, '') console.info(`${this.icon('success')} ${this.chalk.green('create')} ${createdFile}`) return createdFile } }
JavaScript
class VideoPlayer extends IntersectionObserverMixin( MediaBehaviorsVideo(SchemaBehaviors(SimpleColors)) ) { /* REQUIRED FOR TOOLING DO NOT TOUCH */ /** * Store tag name to make it easier to obtain directly. * @notice function name must be here for tooling to operate correctly */ static get tag() { return "video-player"; } constructor() { super(); this.crossorigin = "anonymous"; this.dark = false; this.darkTranscript = false; this.disableInteractive = false; this.hideTimestamps = false; this.hideTranscript = false; this.lang = "en"; this.learningMode = false; this.linkable = false; this.preload = "metadata"; this.sources = []; this.stickyCorner = "top-right"; this.tracks = []; this.setSourceData(); this.observer.observe(this, { childList: true, subtree: false, }); } /** * life cycle, element is removed from the DOM */ disconnectedCallback() { if (this.observer && this.observer.disconnect) this.observer.disconnect(); super.disconnectedCallback(); } /** * gets the HTML5 `audio` or `video` children * @readonly * @returns {object} HTML template */ get html5() { return html` ${this.sourceData .filter((item) => item.type !== "youtube") .map((sd) => { html` <source .src="${sd.src || undefined}" .type="${sd.type || undefined}" /> `; })} ${this.trackData.map((track) => { `<track .src="${track.src || undefined}" .kind="${track.kind || undefined}" .label="${track.label || undefined}" .srclang="${track.lang || undefined}" />`; })} `; } /** * Computes whether uses iframe * @readonly * @returns {Boolean} */ get iframed() { // make sure we take into account sandboxing as well // so that we can manage state effectively if ( this.sourceData && this.sourceData.length > 0 && this.sourceData[0] !== undefined && window.MediaBehaviors.Video._sourceIsIframe(this.sourceData[0].src) && !this.sandboxed ) { return true; } return false; } /** * Determines if compatible with `a11y-media-player` * @readonly * @returns {Boolean} */ get isA11yMedia() { if ( !this.sandboxed && (this.sourceType == "youtube" || this.sourceType == "local" || this.sourceData.length < 1) ) { return true; } return false; } /** * mutation observer for tabs * @readonly * @returns {object} */ get observer() { let callback = () => this.setSourceData(); return new MutationObserver(callback); } /** * Compute sandboxed status * @readonly * @returns {Boolean} */ get sandboxed() { // we have something that would require an iframe // see if we have a local system that would want to sandbox instead if ( this.sourceData && this.sourceData.length > 0 && typeof this.sourceData[0] !== undefined && window.MediaBehaviors.Video._sourceIsIframe(this.sourceData[0].src) ) { // fake creation of a webview element to see if it's valid // or not. let test = document.createElement("webview"); // if this function exists it means that our deploy target // is in a sandboxed environment and is not able to run iframe // content with any real stability. This is beyond edge case but // as this is an incredibly useful tag we want to make sure it // can mutate to work in chromium and android environments // which support such sandboxing if (typeof test.reload === "function") { return true; } } return false; } /** * Gets cleaned source list from source and sources properties * @readonly * @returns {Array} Eg. `[{ "src": "path/to/media.mp3", "type": "audio/mp3"}]` */ get sourceProperties() { let temp = typeof this.sources === "string" ? JSON.parse(this.sources) : this.sources.slice(); if (this.source) temp.unshift({ src: this.source }); if (temp && temp.length > 0) temp.forEach((item) => { item.type = item.type || this._computeMediaType(item.src); item.src = this._computeSRC(item.src, item.type); }); return temp; } /** * Gets cleaned track list from track and tracks properties * @readonly * @returns {Array} Eg. `[{ "src": "path/to/track.vtt", "label": "English", "srclang": "en", "kind": "subtitles"}]` */ get trackProperties() { let temp = typeof this.tracks === "string" ? JSON.parse(this.tracks) : this.tracks.slice(); if (this.track) temp.unshift({ src: this.track }); if (temp && temp.length > 0) temp.forEach((item) => { item.srclang = item.srclang || this.lang; item.kind = item.kind || "subtitles"; item.label = item.label || item.kind || item.lang; }); return temp; } /** * Source properties and slotted sources * @readonly * @returns {Array} List of source objects */ get sourceData() { let temp = this.sourceProperties.slice(), slotted = this.querySelectorAll("video source, audio source, iframe"); slotted.forEach((slot) => { this.sources.unshift({ src: slot.src, type: slot.type || this._computeMediaType(slot.src), }); }); return temp; } get audioOnly() { let videos = this.sourceData.filter( (item) => item.type.indexOf("audio") > -1 ); return videos.length > 1; } get standAlone() { return ( this.trackData === undefined || this.trackData === null || this.trackData.length < 1 ); } /** * Gets type of source based on src attribute * @returns {String} `local`, `vimeo`, `youtube`, etc. */ get sourceType() { if ( this.sourceData && this.sourceData.length > 0 && this.sourceData[0] !== undefined && typeof this.sourceData[0].src !== typeof undefined ) { return window.MediaBehaviors.Video.getVideoType(this.sourceData[0].src); } else { return null; } } /** * Gets cleaned track list * @readonly * @returns {Array} Eg. `[{ "src": "path/to/track.vtt", "label": "English", "srclang": "en", "kind": "subtitles",}]` */ get trackData() { let temp = typeof this.tracks === "string" ? JSON.parse(this.tracks).slice() : this.tracks.slice(), slotted = this.querySelectorAll("video track, audio track"); slotted.forEach((slot) => { let track = { src: slot.src }; if (slot.lang) track.lang = slot.lang; if (slot.srclang) track.srclang = slot.srclang; if (slot.label) track.label = slot.label; if (slot.kind) track.kind = slot.kind; this.tracks.unshift(track); slot.remove(); }); if (this.track !== undefined && this.track !== null && this.track !== "") temp.push({ src: this.track, srclang: this.lang, label: this.lang === "en" ? "English" : this.lang, kind: "subtitles", }); return temp; } /** * Gets Youtube ID from source string * @readonly * @returns {String} */ get youtubeId() { if ( this.sourceData && this.sourceData[0] && this.sourceType === "youtube" ) { return this._computeSRC(this.sourceData[0].src).replace( /.*\/embed\//, "" ); } return; } /** * gets an id for a11y-media-player * @readonly * @returns {string} an id for player */ get playerId() { return `${this.id || this.schemaResourceID}-media`; } /** * Compute media type based on source, i.e. 'audio/wav' for '.wav' */ _computeMediaType(source) { let audio = ["aac", "flac", "mp3", "oga", "wav"], video = ["mov", "mp4", "ogv", "webm"], type = "", findType = (text, data) => { data.forEach((item) => { if ( type === "" && typeof source !== undefined && source !== null && source.toLowerCase().indexOf("." + item) > -1 ) { type = text + "/" + item; } }); }; findType("audio", audio); findType("video", video); return type; } /** * Compute src from type / source combo. * Type is set by source so this ensures a waterfall * of valid values. */ _computeSRC(source, type) { if (source !== null && typeof source !== undefined) { // ensure that this is a valid url / cleaned up a bit type = type || window.MediaBehaviors.Video.getVideoType(source); source = window.MediaBehaviors.Video.cleanVideoSource(source, type); if (type == "vimeo") { if (this.vimeoTitle) { source += "?title=1"; } else { source += "?title=0"; } if (this.vimeoByline) { source += "&byline=1"; } else { source += "&byline=0"; } if (this.vimeoPortrait) { source += "&portrait=1"; } else { source += "&portrait=0"; } } else if (type == "dailymotion") { source += "&ui-start-screen-info=false"; source += "&ui-logo=false"; source += "&sharing-enable=false"; source += "&endscreen-enable=false"; } } return source; } /** * Implements haxHooks to tie into life-cycle if hax exists. */ haxHooks() { return { postProcessNodeToContent: "haxpostProcessNodeToContent", }; } /** * postProcesshaxNodeToContent - clean up so we don't have empty array data */ haxpostProcessNodeToContent(content) { content = content.replace(' sources="[]",', ""); content = content.replace(' tracks="[]",', ""); return content; } /** * triggers an update of sourceData property when slot changes * * @memberof VideoPlayer */ setSourceData() { let temp = this.source; this.source = ""; this.source = temp; } }
JavaScript
class AssetOverview extends PureComponent { static propTypes = { /** * Map of accounts to information objects including balances */ accounts: PropTypes.object, /** /* navigation object required to access the props /* passed by the parent component */ navigation: PropTypes.object, /** * Object that represents the asset to be displayed */ asset: PropTypes.object, /** * AVAX to current currency conversion rate */ conversionRate: PropTypes.number, /** * Currency code of the currently-active currency */ currentCurrency: PropTypes.string, /** * A string that represents the selected address */ selectedAddress: PropTypes.string, /** * Start transaction with asset */ newAssetTransaction: PropTypes.func, /** * An object containing token balances for current account and network in the format address => balance */ tokenBalances: PropTypes.object, /** * An object containing token exchange rates in the format address => exchangeRate */ tokenExchangeRates: PropTypes.object, /** * Action that toggles the receive modal */ toggleReceiveModal: PropTypes.func, /** * Primary currency, either AVAX or Fiat */ primaryCurrency: PropTypes.string }; onReceive = () => { const { asset } = this.props; this.props.toggleReceiveModal(asset); }; onSend = async () => { const { asset } = this.props; if (asset.isETH) { this.props.newAssetTransaction(getEther()); this.props.navigation.navigate('SendFlowView'); } else { this.props.newAssetTransaction(asset); this.props.navigation.navigate('SendFlowView'); } }; renderLogo = () => { const { asset: { address, image, logo, isETH } } = this.props; if (isETH) { return <Image source={ethLogo} style={styles.ethLogo} />; } const watchedAsset = image !== undefined; return logo || image ? ( <AssetIcon watchedAsset={watchedAsset} logo={image || logo} /> ) : ( <Identicon address={address} /> ); }; render() { const { accounts, asset: { address, isETH = undefined, decimals, symbol }, primaryCurrency, selectedAddress, tokenExchangeRates, tokenBalances, conversionRate, currentCurrency } = this.props; let mainBalance, secondaryBalance; const itemAddress = safeToChecksumAddress(address); let balance, balanceFiat; if (isETH) { balance = renderFromWei(accounts[selectedAddress] && accounts[selectedAddress].balance); balanceFiat = weiToFiat(hexToBN(accounts[selectedAddress].balance), conversionRate, currentCurrency); } else { const exchangeRate = itemAddress in tokenExchangeRates ? tokenExchangeRates[itemAddress] : undefined; balance = itemAddress in tokenBalances ? renderFromTokenMinimalUnit(tokenBalances[itemAddress], decimals) : 0; balanceFiat = balanceToFiat(balance, conversionRate, exchangeRate, currentCurrency); } // choose balances depending on 'primaryCurrency' if (primaryCurrency === 'AVAX') { mainBalance = `${balance} ${symbol}`; secondaryBalance = balanceFiat; } else { mainBalance = !balanceFiat ? `${balance} ${symbol}` : balanceFiat; secondaryBalance = !balanceFiat ? balanceFiat : `${balance} ${symbol}`; } return ( <View style={styles.wrapper} testID={'token-asset-overview'}> <View style={styles.assetLogo}>{this.renderLogo()}</View> <View style={styles.balance}> <Text style={styles.amount} testID={'token-amount'}> {mainBalance} </Text> <Text style={styles.amountFiat}>{secondaryBalance}</Text> </View> <AssetActionButtons leftText={strings('asset_overview.send_button').toUpperCase()} testID={'token-send-button'} middleText={strings('asset_overview.receive_button').toUpperCase()} onLeftPress={this.onSend} onMiddlePress={this.onReceive} middleType={'receive'} /> </View> ); } }
JavaScript
class Overview extends React.Component { constructor() { super() // this.store = { // type: 'tree', // root: { // name: 'A', // expanded: true, // children: [{ // name: 'B', // expanded: true, // children: [{ // name: 'D', // leaf: true // }, { // name: 'E', // leaf: true // }] // }, { // name: 'C', // leaf: true // }] // } // } this.treestore3 = { type: 'tree', proxy: { type: 'ajax', url: datafolder + 'sunburst.json', reader: { type: 'json', rootProperty: 'children' }, root: { text: 'A', expanded: true } }, } this.treestore2 = Ext.create('Ext.data.TreeStore', { proxy: { type: 'ajax', url: datafolder + 'sunburst.json', reader: { type: 'json', rootProperty: 'children' } }, autoLoad: true, root: { text: 'A', expanded: true } }); this.treestore = Ext.create('Ext.data.TreeStore', { proxy: { type: 'ajax', url: datafolder + 'treemap.json', reader: { type: 'json', rootProperty: 'children' } }, autoLoad: true, root: { text: 'A', expanded: true } }); // this.store2 = { // autoLoad: true, // proxy: { // type: 'ajax', // url: datafolder + 'treemap.json' // } // } } getNodeValue(record) { // The value in your data to derive the size of the tile from. return record.get('age'); } tooltipRenderer (component, tooltip, node) { tooltip.setHtml(node.data.get('name')); } render() { return ( <ExtD3_sunburst fitToParent padding={16} store={this.treestore2} tooltip={this.tooltipRenderer} nodeValue={this.getNodeValue} > </ExtD3_sunburst> ) } }
JavaScript
class IcrpgCharacterSheet extends ActorSheet { /** @override */ static get defaultOptions() { return mergeObject(super.defaultOptions, { classes: ["icrpg", "sheet", "actor"], template: "systems/icrpg/templates/actor/character-sheet.html", width: 400, height: 520, tabs: [{ navSelector: ".sheet-tabs", contentSelector: ".sheet-body", initial: "attributes" }], dragDrop: [{ dragSelector: ".items-list .item", dropSelector: null }] }); } /* -------------------------------------------- */ /** @override */ getData() { const data = super.getData(); data.dtypes = ["String", "Number", "Boolean"]; //for (let attr of Object.values(data.data.attributes)) { // attr.isCheckbox = attr.dtype === "Boolean"; //} return data; } /* -------------------------------------------- */ /** @override */ activateListeners(html) { super.activateListeners(html); // Everything below here is only needed if the sheet is editable if (!this.options.editable) return; // Item controls html.find(".items").on("click", ".item-control", this._onClickItemControl.bind(this)); html.find(".items").on("change", "input[name='equipped']", this._onClickItemFilter.bind(this)); // Rollable abilities. html.find('.rollable').click(this._onRoll.bind(this)); } /* -------------------------------------------- */ setPosition(options = {}) { const position = super.setPosition(options); const sheetHeader = this.element.find(".sheet-header"); const sheetBody = this.element.find(".sheet-body"); const bodyHeight = position.height - sheetHeader[0].clientHeight - 99; sheetBody.css("height", bodyHeight); return position; } /* -------------------------------------------- */ /** * Listen for click events on an attribute control to modify the composition of attributes in the sheet * @param {MouseEvent} event The originating left click event * @private */ async _onClickItemControl(event) { event.preventDefault(); const header = event.currentTarget; const action = header.dataset.action; // Create new item if (action === "create") { // Get the type of item to create. const type = header.dataset.type; // Grab any data associated with this control. const data = duplicate(header.dataset); // Initialize a default name. const name = `New ${type.capitalize()}`; // Prepare the item object. const itemData = { name: name, type: type, data: data }; // Remove the type from the dataset since it's in the itemData.type prop. delete itemData.data["type"]; // Finally, create the item! this.actor.createOwnedItem(itemData); } else if (action === "equip") { const li = $(header).parents(".item"); const item = this.actor.getOwnedItem(li.data("itemId")); await item.update({ "data.equipped": !item.data.data.equipped }); } else if (action === "edit") { const li = $(header).parents(".item"); const item = this.actor.getOwnedItem(li.data("itemId")); item.sheet.render(true); } else if (action === "delete") { const li = $(header).parents(".item"); const item = this.actor.getOwnedItem(li.data("itemId")); const itemTypeCapitalized = item.type.charAt(0).toUpperCase() + item.type.slice(1); let d = Dialog.confirm({ title: game.i18n.localize("ICRPG.Delete" + itemTypeCapitalized), content: "<p>" + game.i18n.localize("ICRPG.AreYouSure") + "</p>", yes: () => { this.actor.deleteOwnedItem(li.data("itemId")); li.slideUp(200, () => this.render(false)); }, no: () => { return; }, defaultYes: false }); } } /* -------------------------------------------- */ /** * Handle clickable rolls. * @param {Event} event The originating click event * @private */ _onRoll(event) { event.preventDefault(); const element = event.currentTarget; const dataset = element.dataset; if (dataset.roll) { let roll = new Roll(dataset.roll, this.actor.data.data); let label = dataset.label ? `${game.i18n.localize("ICRPG.Rolling")} ${dataset.label}` : ''; roll.roll().toMessage({ speaker: ChatMessage.getSpeaker({ actor: this.actor }), flavor: label }); } } /* -------------------------------------------- */ /** * Listen for click events on a filter to modify the item list in the sheet * @param {MouseEvent} event The originating left click event * @private */ async _onClickItemFilter(event) { event.stopPropagation(); const el_filters = document.querySelectorAll(".items input[name='equipped']"), el_filterable = document.querySelectorAll(".items .item[data-filterable], .items .item-description[data-filterable]"); // Filter checked inputs const el_checked = [...el_filters].filter(el => el.checked && el.value); // Collect checked inputs values to array const filters = [...el_checked].map(el => el.value); // Get elements to filter const el_filtered = [...el_filterable].filter(el => { const props = el.getAttribute('data-filterable').trim().split(/\s+/); return filters.every(fi => props.includes(fi)) }); // Hide all el_filterable.forEach(el => el.classList.add('is-hidden')); // Show filtered el_filtered.forEach(el => el.classList.remove('is-hidden')); } /* -------------------------------------------- */ }
JavaScript
class Base { constructor(client) { /** * The client that instantiated this * @name Base#client * @type {Client} * @readonly */ Object.defineProperty(this, 'client', { value: client }); } _clone() { return Object.assign(Object.create(this), this); } _patch(data) { return data; } _update(data) { const clone = this._clone(); this._patch(data); return clone; } toJSON(...props) { return flatten(this, ...props); } valueOf() { return this.id; } }