language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class ProjectChartComponent extends ChartComponent { /** * When column is clicked, select this note in the parent component. */ handleClick (evt) { const element = this.state.chart.getElementAtEvent(evt)[0] if (element !== undefined) { this.props.select_note(element._index) } } /** * Configure chart element before data is loaded. */ componentDidMount () { const options = { scales: { xAxes: [{ stacked: true, type: 'time', time: { unit: 'day' }, ticks: { max: moment().toDate(), min: moment().subtract(14, 'd').toDate() }, gridLines: { display: false } }], yAxes: [{ stacked: true, ticks: { startAtZero: true, stepSize: 0.25, callback: value => value.toFixed(2), padding: 5 }, gridLines: { drawBorder: false } }] }, onClick: this.handleClick.bind(this) } this.createChart('bar', {}, options) } render () { if (this.state) { // Load data passed in through props const chart = this.state.chart chart.data = this.props.data try { chart.update() } catch (err) { if (process.env.JEST_WORKER_ID !== undefined) { // Running under JEST - test mode // TODO: Updating chart is known failure in test mode - investigate console.error(err) } else { throw err } } } return super.render() } }
JavaScript
class Bullet extends GameObject { /** * Contructs base bullet * * @param {Vector} location Location to spawn bullet on * @param {Vector} velocity Base velocity vector of this bullet */ constructor(location, velocity) { super(location, Vector.multiply(Vector.normalize(velocity), BULLET_SPEED), Vector.copyArray(BULLET_SHAPE), BULLET_COLOR, ObjectTypes.BULLET, 0) } /** * Handles situation, when game object leaves the bounds of game board * * @param {Dictionary} bounds Dictionary containing canvas warping bounds */ handleBorderCross(_) { this.toDispose = true } /** * Handles the collision with other game object * * @param {GameObject} other Game object this game object collided with */ handleCollision(other) { if(other.type != ObjectTypes.BULLET) { this.toDispose = true } } }
JavaScript
class BotForm extends React.Component { fixValuesBeforeSubmit = formValues => { return { name: formValues.name, protocol: formValues.protocol, }; }; requestPermission = async (accountId, botId, resourcePrefix, methods) => { const permissionsUrl = accountId ? `${ROOT_URL}/accounts/${accountId}/bots/${botId}/permissions` : `${ROOT_URL}/bots/${botId}/permissions`; const responsePermissions = await fetchAuth(permissionsUrl, { headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, method: 'POST', body: JSON.stringify({ resource_prefix: resourcePrefix, methods: methods, }), }); handleFetchErrors(responsePermissions); }; afterSubmit = async response => { // if we have created a new bot, we should assign it appropriate permissions too: const { accountId, botId } = this.props.match.params; const editing = Boolean(botId); if (!editing && accountId) { // only if we are creating an account bot, do we assign permissions const responseJson = await response.json(); const newId = responseJson.id; // assign permissions to bot: await this.requestPermission(accountId, newId, `accounts/${accountId}/values`, ['POST', 'PUT']); await this.requestPermission(accountId, newId, `accounts/${accountId}/entities`, ['GET']); await this.requestPermission(accountId, newId, `accounts/${accountId}/credentials`, ['GET']); await this.requestPermission(accountId, newId, `accounts/${accountId}/sensors`, ['GET']); } const redirectTo = accountId ? `/accounts/${accountId}/bots` : '/bots'; return redirectTo; }; render() { const { accountId, botId } = this.props.match.params; const editing = Boolean(botId); const resource = accountId ? editing ? `accounts/${accountId}/bots/${botId}` : `accounts/${accountId}/bots` : editing ? `bots/${botId}` : `bots`; return ( <BotFormRender initialFormValues={{}} editing={editing} resource={resource} afterSubmit={this.afterSubmit} fixValuesBeforeSubmit={this.fixValuesBeforeSubmit} /> ); } }
JavaScript
class ArrowKeyNavigation { constructor(index) { this.index = index; } resetIndex() { this.index = 0; } /* Figures out which element is next, based on the key pressed * * current index and total number of items. Then calls focus function */ arrowNavigation(key) { if (this.index === undefined) this.index = 0; // Start at beginning else if (key === 37) { // Left --> Previous this.index -= 1; } else if (key === 38) { // Up --> Previous this.index = ArrowKeyNavigation.goToPrevious(this.index); } else if (key === 39) { // Right --> Next this.index += 1; } else if (key === 40) { // Down --> Next this.index = ArrowKeyNavigation.goToNext(this.index); } /* Ensure the index is within bounds, then focus element */ this.index = ArrowKeyNavigation.getSafeElementIndex(this.index); ArrowKeyNavigation.selectItemByIndex(this.index).focus(); } /* Returns the number of visible items / results */ static getNumResults() { return document.getElementsByClassName('item').length; } /* Returns the index for an element, ensuring that it's within bounds */ static getSafeElementIndex(index) { const numResults = ArrowKeyNavigation.getNumResults(); if (index < 0) return numResults - 1; else if (index >= numResults) return 0; return index; } /* Selects a given element, by it's ID. If out of bounds, returns element 0 */ static selectItemByIndex(index) { return (index >= 0 && index <= ArrowKeyNavigation.getNumResults()) ? document.getElementsByClassName('item')[index] : [document.getElementsByClassName('item')]; } /* Returns the index of the first cell in the previous/ above row */ static findPreviousRow(startingIndex) { const isSameRow = (indx, pos) => ArrowKeyNavigation.selectItemByIndex(indx).offsetTop === pos; const checkPreviousIndex = (currentIndex, yPos) => { if (currentIndex >= ArrowKeyNavigation.getNumResults()) return checkPreviousIndex(0, yPos); else if (isSameRow(currentIndex, yPos)) return checkPreviousIndex(currentIndex - 1, yPos); return currentIndex; }; const position = ArrowKeyNavigation.selectItemByIndex(startingIndex).offsetTop; return checkPreviousIndex(startingIndex, position); } /* Moves to the cell directly above the current */ static goToPrevious(startingIndex) { const isBelow = (start, end) => (ArrowKeyNavigation.selectItemByIndex(start).offsetTop < ArrowKeyNavigation.selectItemByIndex(end).offsetTop); const nextIndex = ArrowKeyNavigation.findPreviousRow(startingIndex); const count = nextIndex - startingIndex; const rowLen = nextIndex - ArrowKeyNavigation.findNextRow(startingIndex) + 1; const adjustment = isBelow(startingIndex, nextIndex) ? 0 : rowLen - count; return nextIndex + adjustment; } /* Returns the index of the first cell in the next/ below row */ static findNextRow(startingIndex) { const isSameRow = (indx, pos) => ArrowKeyNavigation.selectItemByIndex(indx).offsetTop === pos; const checkNextIndex = (currentIndex, yPos) => { if (currentIndex >= ArrowKeyNavigation.getNumResults()) return checkNextIndex(0, yPos); else if (isSameRow(currentIndex, yPos)) return checkNextIndex(currentIndex + 1, yPos); return currentIndex; }; const position = ArrowKeyNavigation.selectItemByIndex(startingIndex).offsetTop; return checkNextIndex(startingIndex, position); } /* Moves to the cell directly below the current */ static goToNext(startingIndex) { const isAbove = (start, end) => (ArrowKeyNavigation.selectItemByIndex(start).offsetTop > ArrowKeyNavigation.selectItemByIndex(end).offsetTop); const nextIndex = ArrowKeyNavigation.findNextRow(startingIndex); const count = nextIndex - startingIndex; const rowLen = nextIndex - ArrowKeyNavigation.findPreviousRow(startingIndex) - 1; const adjustment = isAbove(startingIndex, nextIndex) ? 0 : rowLen - count; return nextIndex + adjustment; } }
JavaScript
class BigIntHelper { /** * Load 3 bytes from array as bigint. * @param data The input array. * @param byteOffset The start index to read from. * @returns The bigint. */ static read3(data, byteOffset) { const v0 = (data[byteOffset + 0] + (data[byteOffset + 1] << 8) + (data[byteOffset + 2] << 16)) >>> 0; return bigInt(v0); } /** * Load 4 bytes from array as bigint. * @param data The input array. * @param byteOffset The start index to read from. * @returns The bigint. */ static read4(data, byteOffset) { const v0 = (data[byteOffset + 0] + (data[byteOffset + 1] << 8) + (data[byteOffset + 2] << 16) + (data[byteOffset + 3] << 24)) >>> 0; return bigInt(v0); } /** * Load 8 bytes from array as bigint. * @param data The data to read from. * @param byteOffset The start index to read from. * @returns The bigint. */ static read8(data, byteOffset) { const v0 = (data[byteOffset + 0] + (data[byteOffset + 1] << 8) + (data[byteOffset + 2] << 16) + (data[byteOffset + 3] << 24)) >>> 0; const v1 = (data[byteOffset + 4] + (data[byteOffset + 5] << 8) + (data[byteOffset + 6] << 16) + (data[byteOffset + 7] << 24)) >>> 0; return bigInt(v1).shiftLeft(BigIntHelper.BIG_32).or(v0); } /** * Convert a big int to bytes. * @param value The bigint. * @param data The buffer to write into. * @param byteOffset The start index to write from. */ static write8(value, data, byteOffset) { const v0 = Number(value.and(BigIntHelper.BIG_32_MASK)); const v1 = Number(value.shiftRight(BigIntHelper.BIG_32).and(BigIntHelper.BIG_32_MASK)); data[byteOffset] = v0 & 0xff; data[byteOffset + 1] = (v0 >> 8) & 0xff; data[byteOffset + 2] = (v0 >> 16) & 0xff; data[byteOffset + 3] = (v0 >> 24) & 0xff; data[byteOffset + 4] = v1 & 0xff; data[byteOffset + 5] = (v1 >> 8) & 0xff; data[byteOffset + 6] = (v1 >> 16) & 0xff; data[byteOffset + 7] = (v1 >> 24) & 0xff; } /** * Generate a random bigint. * @returns The bitint. */ static random() { return BigIntHelper.read8(RandomHelper.generate(8), 0); } }
JavaScript
class Triangle extends Plane { constructor(A, B, C) { // points A,B,C defining triangle (ABC) // we also define all the variables for planar functions super(Vector.fromPoints(A, B), Vector.fromPoints(A, C), A); this.A = A; this.B = B; this.C = C; } isPointInTriangle(point) { if (!this.isValidPlane) return false; //if (!this.isCoplanar(point)) return false; already check in isOnSameSide return Line.isOnSameSide(point, this.A, this.B, this.C) && Line.isOnSameSide(point, this.B, this.A, this.C) && Line.isOnSameSide(point, this.C, this.A, this.B); } getArea() { if (!this.isValidPlane) return NaN; return this.vector1.cross(this.vector2).getNorm() / 2; } isRightInA() { if (!this.isValidPlane) return false; return this.vector1.dot(this.vector2) == 0; } getAngles() { // definition from https://en.wikipedia.org/wiki/Triangle using thm d' Al Kashi const a = Vector.fromPoints(this.B, this.C).getNorm(); const b = this.vector2.getNorm(); const c = this.vector1.getNorm(); const aSqr = a * a; const bSqr = b * b; const cSqr = c * c; // alpha, beta, gamma are the angles originating from their corresponing point (alpha, A), (beta,B), (gamma,C) const alpha = Math.acos((bSqr + cSqr - aSqr) / (2 * b * c)); const beta = Math.acos((aSqr + cSqr - bSqr) / (2 * a * c)); const gamma = Math.acos((aSqr + bSqr - cSqr) / (2 * a * b)); return { alpha, beta, gamma } } }
JavaScript
class LocationWidget extends WidgetFrame { constructor(app, options) { super(app, options); this.app = app; this.setWidgetContent(); this.bindEvents(); } setWidgetContent() { this.$widgetInstance.addClass('locationwidget'); this.$widgetInstance.find('.skywaycesium-widget-content').append(LocationWidgetHtml); } bindEvents() { var self = this; this.$widgetInstance.find('#btnLocate').click(function () { self._locate(5000); }); } _locate(height) { var lng = Number(this.$widgetInstance.find('input.lng').val()); var lat = Number(this.$widgetInstance.find('input.lat').val()); if (comLib.isNumbr(lng) && comLib.isNumbr(lat)) { this.app.zoomToPoints([[lng, lat, height]], 'FLY'); this.app.drawBillboard( [Cesium.Cartographic.fromDegrees(lng, lat)], COLLECTIONNAME.LOCATION, { clampToGround: true, iconUrl: 'entityicon/loc.png' }); } } }
JavaScript
class ChannelHub extends EventEmitter { constructor() { super(); this.setMaxListeners(0); this.nodeChannels = {}; // a map of {channelName: [serverIds]} this.clientChannels = {}; // a map of {channelName: [clientIds]} } // Getter for returning the complete list of all channels. get channels() { let res = [], m = {}, nChannels = Object.keys(this.nodeChannels), cChannels = Object.keys(this.clientChannels); for (let i = 0, len = nChannels.length; i < len; i++) { let c = nChannels[i]; if (m[c]) continue; m[c] = true; res.push(c); } for (let j = 0, jlen = cChannels.length; j < jlen; j++) { let c = cChannels[j]; if (m[c]) continue; res.push(c); m[c] = true; } return res; } /** * Subscribes the specified server id to the specified channel. * If the channel does not exist, auto-create it * @Arguments * sid - the server id to use * channel - the channel name * */ subscribeNode(sid, channel) { if (typeof this.nodeChannels[channel] === 'undefined') { this.nodeChannels[channel] = []; this.emit('channel.add', channel); } let cidx = this.nodeChannels[channel].indexOf(sid); if (cidx === -1) { this.nodeChannels[channel].push(sid); this.emit('node.join', channel, sid); } } /** * Unsubscribes the given server id from the specified channel * @Arguments * sid - the server id to use * channel - the channel name * */ unsubscribeNode(sid, channel) { if (typeof this.nodeChannels[channel] === 'undefined') return; let cidx = this.nodeChannels[channel].indexOf(sid); if (cidx !== -1) { this.nodeChannels[channel].splice(cidx, 1); this.emit('node.leave', channel, sid); } if (this.nodeChannels[channel].length === 0) { delete this.nodeChannels[channel]; this.emit('channel.remove', channel); } } /** * Verifies if the specified node is in a channel * @Arguments * sid - the server id to use * channel - the channel name * */ isNodeSubscribed(sid, channel) { if (typeof this.nodeChannels[channel] === 'undefined') return false; let idx = this.nodeChannels[channel].indexOf(sid); return (idx !== -1); } /** * Returns an array with all the node's active subscriptions * @Arguments * sid - the server id to use * */ getNodeSubscriptions(sid) { let items = []; let channels = Object.keys(this.nodeChannels); for (let i = 0, len = channels.length; i < len; i++) { let c = channels[i]; if (this.nodeChannels[c].indexOf(sid) !== -1) { items.push(c); } } return items; } /** * Completely removes a node from all channels * @Arguments * sid - the server id to use * */ removeNode(sid) { let channels = Object.keys(this.nodeChannels); for (let i = 0, len = channels.length; i < len; i++) { let c = channels[i]; this.unsubscribeNode(sid, c); } return true; } /** * Subscribes a client to a channel. * If the channel does not exist, auto-create it. * This operation also requires the source node (that owns the client) * @Arguments * sid - the server id that has the client * cid - the client id * channel - the target channel * */ subscribeClient(sid, cid, channel) { this.subscribeNode(sid, channel); if (typeof this.clientChannels[channel] === 'undefined') { this.clientChannels[channel] = []; } let idx = this.clientChannels[channel].indexOf(cid); if (idx === -1) { this.clientChannels[channel].push(cid); this.emit('client.join', channel, cid); } return true; } /** * Unsubscribes the given client id from the specified channel * @Arguments * - cid - the client id to use * - channel - the channel name * */ unsubscribeClient(cid, channel) { if (typeof this.clientChannels[channel] === 'undefined') return false; let cidx = this.clientChannels[channel].indexOf(cid); if (cidx === -1) return false; this.clientChannels[channel].splice(cidx, 1); this.emit('client.leave', channel, cid); if (this.clientChannels[channel].length === 0) { delete this.clientChannels[channel]; this.removeChannel(channel); } return true; } /** * Checks if a client is subscribed to a specific channel * @Arguments * cid - the client id to use * channel - the channel name * */ isClientSubscribed(cid, channel) { if (typeof this.clientChannels[channel] === 'undefined') return false; let idx = this.clientChannels[channel].indexOf(cid); return (idx !== -1); } /** * Completely removes a client from all channels * @Arguments * cid - the client id to use * */ removeClient(sid) { let channels = Object.keys(this.clientChannels); for (let i = 0, len = channels.length; i < len; i++) { let c = channels[i]; this.unsubscribeClient(sid, c); } return true; } /** * Returns an array with all the client's active subscriptions * @Arguments * cid - the client id to use * */ getClientSubscriptions(cid) { let items = []; let channels = Object.keys(this.clientChannels); for (let i = 0, len = channels.length; i < len; i++) { let c = channels[i]; if (this.clientChannels[c].indexOf(cid) !== -1) { items.push(c); } } return items; } /** * Destroys a channel * */ removeChannel(channel) { if (typeof this.nodeChannels[channel] !== 'undefined') { let len = this.nodeChannels[channel].length - 1; while (len >= 0) { let sid = this.nodeChannels[channel][len]; this.unsubscribeNode(sid, channel); len = (this.nodeChannels[channel] || []).length - 1; } } if (typeof this.clientChannels[channel] !== 'undefined') { let len = this.clientChannels[channel].length - 1; while (len >= 0) { let cid = this.clientChannels[channel][len]; this.unsubscribeClient(cid, channel); len = (this.clientChannels[channel] || []).length - 1; } } } /** * Sends a message to the specified channel * @Arguments * - channel -> the channel string to send to * - message -> the message that we need to send * - senderSid -> the sender server id to use * - opt.nodes -> if set to true, send to individual nodes * - opt.broadcast -> if set to false, do not broadcast * * */ sendMessage(channel, message, senderSid, opt = {}) { if (typeof message === 'object' && message) message = JSON.stringify(message); let hasNodes = false, hasClients = false; if (typeof this.nodeChannels[channel] !== 'undefined') { hasNodes = true; if (opt.nodes !== true) { for (let i = 0, len = this.nodeChannels[channel].length; i < len; i++) { let sid = this.nodeChannels[channel][i]; this.emit('node.message', channel, sid, message); } } } else if (opt.broadcast !== false) { // we need to broadcast the message. this.emit('node.broadcast', channel, message); } if (typeof this.clientChannels[channel] !== 'undefined') { hasClients = true; for (let i = 0, len = this.clientChannels[channel].length; i < len; i++) { let cid = this.clientChannels[channel][i]; this.emit('client.message', channel, cid, message); } } if (!hasNodes && !hasClients) return false; if (!senderSid || (senderSid && this.isNodeSubscribed(senderSid, channel))) { this.emit('channel.message', channel, message); } return true; } }
JavaScript
class ExternalAppId { /** * Create a ExternalAppId. * @member {string} [externalId] The identifier for external apps that map to * an App Center app */ constructor() { } /** * Defines the metadata of ExternalAppId * * @returns {object} metadata of ExternalAppId * */ mapper() { return { required: false, serializedName: 'ExternalAppId', type: { name: 'Composite', className: 'ExternalAppId', modelProperties: { externalId: { required: false, serializedName: 'external_id', type: { name: 'String' } } } } }; } }
JavaScript
class CreateKbInputDTO { /** * Create a CreateKbInputDTO. * @property {array} [qnaList] List of QNA to be added to the index. Ids are * generated by the service and should be omitted. * @property {array} [urls] List of URLs to be added to knowledgebase. * @property {array} [files] List of files to be added to knowledgebase. */ constructor() { } /** * Defines the metadata of CreateKbInputDTO * * @returns {object} metadata of CreateKbInputDTO * */ mapper() { return { required: false, serializedName: 'CreateKbInputDTO', type: { name: 'Composite', className: 'CreateKbInputDTO', modelProperties: { qnaList: { required: false, serializedName: 'qnaList', type: { name: 'Sequence', element: { required: false, serializedName: 'QnADTOElementType', type: { name: 'Composite', className: 'QnADTO' } } } }, urls: { required: false, serializedName: 'urls', type: { name: 'Sequence', element: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, files: { required: false, serializedName: 'files', type: { name: 'Sequence', element: { required: false, serializedName: 'FileDTOElementType', type: { name: 'Composite', className: 'FileDTO' } } } } } } }; } }
JavaScript
class Settings { constructor () { this.locale = "en", this.dateFormat = "fi", this.timeFormat = "24h", this.mapLegend = new MapLegend() } /** * Save the application's settings. */ save () { i18n.locale = this.locale localStorage.setItem(keyLocale, this.locale) localStorage.setItem(keyDateFormat, this.dateFormat) localStorage.setItem(keyTimeFormat, this.timeFormat) localStorage.setItem(keyMapLegend, this.mapLegend) } /** * Load the application's settings. */ load () { this.locale = localStorage.getItem(keyLocale) || this.locale i18n.locale = this.locale this.dateFormat = localStorage.getItem(keyDateFormat) || this.dateFormat this.timeFormat = localStorage.getItem(keyTimeFormat) || this.timeFormat let savedMapLegend = localStorage.getItem(keyMapLegend) if (savedMapLegend) { try { savedMapLegend = JSON.parse(savedMapLegend) const savedBars = savedMapLegend.map(savedBar => JSON.parse(savedBar)) if (savedBars.length > 0) { this.mapLegend.clear() savedBars.forEach(savedBar => { this.mapLegend.addBar(new MapLegendBar(savedBar.threshold, savedBar.color)) }) } } catch { localStorage.removeItem(keyMapLegend) } } } }
JavaScript
class CreatedReadStream extends AsyncObject { constructor (path, options) { super(path, options || { flags: 'r', encoding: null, fd: null, mode: 0o666, autoClose: true, highWaterMark: 64 * 1024 }) } syncCall () { return (path, options) => { return fs.createReadStream(path, options) } } }
JavaScript
class FullNode extends Node { constructor(dbPath, { protocolClass = LiteProtocol, initPeerUrls = [], port, debug } = {}) { super(NODE_TYPE, dbPath, port, protocolClass, initPeerUrls, debug); this.timer = setInterval(() => { console.log(`Right now, there are ${this.peers().length} connected peers (full & thin).`); // TODO this.debugInfo(); }, 20000); } static get nodeType() { return NODE_TYPE; } close() { clearInterval(this.timer); super.close(); } // TODO debugInfo() { console.log('<<<<< debug start >>>>>'); let peerUrls = this.peers().map(peer => peer.url); console.log(peerUrls); console.log('<<<<<< debug end >>>>>>'); } }
JavaScript
class Select extends React.Component { constructor(props) { super(props); this.rest = omit(props, ['onChange', 'onBlur', 'onValueChange', 'onTouch', 'value', 'values', 'dataSource']); this.onChange = this.onChange.bind(this); this.onBlur = this.onBlur.bind(this); } shouldComponentUpdate(nextProps, nextState) { return this.props.multiple ? deepEqual(nextProps.values, this.props.values) === false : nextProps.value !== this.props.value; } hasOnValueChangeSubscriber() { return isFunction(this.props.onValueChange); } hasOnTouchSubscriber() { return isFunction(this.props.onTouch); } raiseValueChanged(value) { this.props.onValueChange(this.props.name, value); } raiseTouched() { this.props.onTouch(this.props.name); } onChange(event) { if (this.hasOnValueChangeSubscriber()) { if (this.props.multiple) { let values = []; let options = event.target.options; for (let i = 0; i < options.length; i++) { let option = options[i]; if (option.selected) { values.push(option.value); } } this.raiseValueChanged(values); } else { let value = event.target.options[event.target.selectedIndex].value; this.raiseValueChanged(value); } } } onBlur() { if (this.hasOnTouchSubscriber()) { this.raiseTouched(); } } render() { let selectedValues = this.props.multiple ? this.props.values : this.props.value; return ( <select value={selectedValues} onChange={this.onChange} onBlur={this.onBlur} {...this.rest}> {this.props.dataSource.map((dataItem, i) => { return <option key={i} value={dataItem}>{dataItem}</option>; })} </select> ); } }
JavaScript
class AccessController { /** * Check origin, protocol and configuration and initialize controller. * @param {string} unusedOrigin * @param {string} unusedProtocl * @param {!JsonObject} unusedConfig * @return {!Promise|undefined} */ connect(unusedOrigin, unusedProtocl, unusedConfig) {} /** * Authorize document. * @return {!Promise<!JsonObject>} */ authorize() {} /** * Pingback document view. * @return {!Promise} */ pingback() {} }
JavaScript
class StyleBase { /** * Make a style * @param {Stroke=} base Original style * @param {string=} color Default color */ constructor(base, color) { this._style = base ? base._style : color; this._color = base ? base._color : color; this._rgb = base ? base._rgb : null; this._hsl = base ? base._hsl : null; this._gradType = base ? base._gradType : null; this._gradParams = base ? base._gradParams : null; this._gradColors = base ? [...base._gradColors] : []; this._alpha = base ? base._alpha : 1; this._composition = base ? base._composition : 'source-over'; this._shadow = base ? new Shadow(base._shadow) : new Shadow(); } /** * Reset * @param {string} color Color * @return {StyleBase} This style */ reset(color) { this._style = color; this._color = color; this._rgb = null; this._hsl = null; this._gradType = null; this._gradParams = null; this._gradColors = []; this._alpha = 1; this._composition = 'source-over'; this._shadow = new Shadow(); return this; } /** * Set the color name * @param {string=} color Color name * @param {number=} [opt_alpha=1] Alpha 0-1 * @return {string|StyleBase} Color or this style */ color(color, opt_alpha = 1) { if (arguments.length === 0) return this._color; checkColor(color); if (opt_alpha === 1) { this._clear(); this._color = color; this._style = this._color; } else { if (Number.isNaN(opt_alpha)) throw new RangeError('STYLE::color: The alpha value seem to be wrong.'); const vs = convertColorToRgb(color, opt_alpha); this.rgb(...vs); } return this; } /** * Set RGB(A) * @param {number=} r Red 0-255 * @param {number=} g Green 0-255 * @param {number=} b Blue 0-255 * @param {number=} [opt_alpha=1] Alpha 0-1 * @return {Array<number>|StyleBase} RGB or this style */ rgb(r, g, b, opt_alpha = 1) { if (arguments.length === 0) return this._rgb; this._clear(); // Round r and g and b to integers this._rgb = [Math.round(r), Math.round(g), Math.round(b), opt_alpha]; this._style = `rgba(${this._rgb.join(', ')})`; return this; } /** * Set HSL(A) * @param {number=} h Hue 0-360 * @param {number=} s Saturation 0-100 * @param {number=} l Lightness 0-100 * @param {number=} [opt_alpha=1] Alpha 0-1 * @return {Array<number>|StyleBase} HSL or this style */ hsl(h, s, l, opt_alpha = 1) { if (arguments.length === 0) return this._hsl; this._clear(); this._hsl = [h, s, l, opt_alpha]; this._style = `hsla(${h}, ${s}%, ${l}%, ${opt_alpha})`; return this; } /** * Lighten the color * @param {number} [opt_rate=10] Rate % * @return {StyleBase} This style */ lighten(opt_rate = 10) { if (this._color) { this._rgb = convertColorToRgb(this._color); } const p = opt_rate / 100; if (this._rgb) { const [r, g, b] = this._rgb; this._rgb[0] = Math.round(r + (255 - r) * p); this._rgb[1] = Math.round(g + (255 - g) * p); this._rgb[2] = Math.round(b + (255 - b) * p); this._style = `rgba(${this._rgb.join(', ')})`; } else if (this._hsl) { const [h, s, l, av] = this._hsl; this._hsl[2] = l + (100 - l) * p; this._style = `hsla(${h}, ${s}%, ${this._hsl[2]}%, ${av})`; } return this; } /** * Darken the color * @param {number} [opt_rate=10] Rate % * @return {StyleBase} This style */ darken(opt_rate = 10) { if (this._color) { this._rgb = convertColorToRgb(this._color); } const p = opt_rate / 100; if (this._rgb) { const [r, g, b] = this._rgb; this._rgb[0] = Math.round(r * (1.0 - p)); this._rgb[1] = Math.round(g * (1.0 - p)); this._rgb[2] = Math.round(b * (1.0 - p)); this._style = `rgba(${this._rgb.join(', ')})`; } else if (this._hsl) { const [h, s, l, av] = this._hsl; this._hsl[2] = l * (1.0 - p); this._style = `hsla(${h}, ${s}%, ${this._hsl[2]}%, ${av})`; } return this; } /** * Set the gradation * - Linear ('linear', [Start coordinates x, y], [End coordinates x, y]) * - Radial ('radial', [1st center coordinates x、y], [Start radius, End radius], <[2nd center coordinates x, y]>) * - Others ('type') * @param {string} type Type ('linear', 'radial', Others) * @param {Array<number>} xy1_dir [Start coordinates x, y], or [1st center coordinates x、y] * @param {Array<number>} xy2_rs [End coordinates x, y], or [Start radius, End radius] * @param {Array<number>=} xy2 [2nd center coordinates x、y] * @return {Array|StyleBase} Gradation setting or this style */ gradation(type, xy1_dir, xy2_rs, xy2) { if (arguments.length === 0) { return this._gradParams ? [this._gradType, ...this._gradParams] : [this._gradType]; } if (!['linear', 'radial', 'vertical', 'horizontal', 'vector', 'inner', 'outer', 'diameter', 'radius'].includes(type)) { throw new Error('STYLE::gradation: The type of gradation is incorrect.'); } this._clear(); this._gradType = type; if (type === 'linear') { this._gradParams = [xy1_dir[0], xy1_dir[1], xy2_rs[0], xy2_rs[1]]; } else if (type === 'radial') { if (xy2 === undefined) { this._gradParams = [xy1_dir[0], xy1_dir[1], xy2_rs[0], xy1_dir[0], xy1_dir[1], xy2_rs[1]]; } else { this._gradParams = [xy1_dir[0], xy1_dir[1], xy2_rs[0], xy2[0], xy2[1], xy2_rs[1]]; } } return this; } /** * Add a color name to the gradation * @param {string} color Color name * @param {number=} [opt_alpha=1] Alpha 0-1 * @return {StyleBase} This style */ addColor(color, opt_alpha = 1) { // Disable caching this._style = null; checkColor(color); if (opt_alpha === 1) { this._gradColors.push(color); } else { if (Number.isNaN(opt_alpha)) throw new RangeError('STYLE::addColor: The alpha value seem to be wrong.'); const vs = convertColorToRgb(color, opt_alpha); this.addRgb(...vs); } return this; } /** * Add RGB(A) to the gradation * @param {number} r Red 0-255 * @param {number} g Green 0-255 * @param {number} b Blue 0-255 * @param {number=} [opt_alpha=1] Alpha 0-1 * @return {StyleBase} This style */ addRgb(r, g, b, opt_alpha = 1) { // Disable caching this._style = null; // Round r and g and b to integers r = Math.round(r), g = Math.round(g), b = Math.round(b); // If the alpha is not assigned if (opt_alpha === 1) { this._gradColors.push(`rgb(${r}, ${g}, ${b})`); } else { this._gradColors.push(`rgba(${r}, ${g}, ${b}, ${opt_alpha})`); } return this; } /** * Add HSL(A) to the gradation * @param {number} h Hue 0-360 * @param {number} s Saturation 0-100 * @param {number} l Lightness 0-100 * @param {number=} [opt_alpha=1] Alpha 0-1 * @return {StyleBase} This style */ addHsl(h, s, l, opt_alpha = 1) { // Disable caching this._style = null; // If the alpha is not assigned if (opt_alpha === 1) { this._gradColors.push(`hsl(${h}, ${s}%, ${l}%)`); } else { this._gradColors.push(`hsla(${h}, ${s}%, ${l}%, ${opt_alpha})`); } return this; } /** * Set alpha * @param {number=} alpha Alpha * @param {string=} op Arithmetic symbol * @return {number|StyleBase} Alpha or this style */ alpha(alpha, op) { if (alpha === undefined) return this._alpha; if (op === undefined) { this._alpha = alpha; } else { switch (op) { case '+': this._alpha += alpha; break; case '-': this._alpha -= alpha; break; case '*': this._alpha *= alpha; break; case '/': this._alpha /= alpha; break; } } return this; } /** * Set composition (composition method) * @param {string=} composition Composition * @return {string|StyleBase} Composition or this style */ composition(composition) { if (composition === undefined) return this._composition; this._composition = composition; return this; } /** * Set shadow * @param {number?} blur Blur amount * @param {string?} color Color * @param {number?} x Shadow offset x * @param {number?} y Shadow offset y * @return {Shadow|StyleBase} Shadow or this style */ shadow(blur, color, x, y) { if (blur === undefined) return this._shadow.get(); if (blur === false || blur === null) { this._shadow.clear(); } else { this._shadow.set(blur, color, x, y); } return this; } /** * Clear settings (used only in the library) * @private */ _clear() { this._style = null; this._color = null; this._rgb = null; this._hsl = null; this._gradType = null; this._gradParams = null; this._gradColors = []; this._gradBsCache = null; } /** * Make the style (used only in the library) * @private * @param {Paper|CanvasRenderingContext2D} ctx Paper or canvas context * @param {Array<number>} gradArea Gradation area * @return {string} Style string */ _makeStyle(ctx, gradArea) { this._gradOpt = {}; // When gradation if (this._gradType !== null) { if (this._style === null || (this._gradType !== 'linear' && this._gradType !== 'radial')) { this._style = this._makeGrad(ctx, gradArea, this._gradType, this._gradParams, this._gradColors, this._gradOpt); } } return this._style; } /** * Make a gradation (used only in the library) * @private * @param {Paper|CanvasRenderingContext2D} ctx Paper or canvas context * @param {dict} bs Bounds * @param {string} type Type * @param {Array} params Parameters * @param {Array<string>} cs Colors * @param {dict} opt Options * @return {string} String of style */ _makeGrad(ctx, bs, type, params, cs, opt) { if (cs.length === 0) return 'Black'; if (cs.length === 1) return cs[0]; let style; switch (type) { case 'linear': style = ctx.createLinearGradient.apply(ctx, params); break; case 'vertical': case 'horizontal': case 'vector': default: style = ctx.createLinearGradient.apply(ctx, this._makeLinearGradParams(ctx, type, bs)); break; case 'radial': style = ctx.createRadialGradient.apply(ctx, params); break; case 'inner': case 'outer': case 'diameter': case 'radius': style = ctx.createRadialGradient.apply(ctx, this._makeRadialGradParams(ctx, type, bs, opt)); break; } for (let i = 0, I = cs.length; i < I; i += 1) { style.addColorStop(i / (I - 1), cs[i]); } return style; } /** * Make linear gradation parameters (used only in the library) * @private * @param {Paper|CanvasRenderingContext2D} ctx Paper or canvas context * @param {string} type Type * @param {dict} bs Bounds * @return {Array<number>} Linear gradation parameters */ _makeLinearGradParams(ctx, type, bs) { const ERROR_STR = 'STYLE::_makeLinerGradParams: Gradation bounds are not correct.'; if (type === 'vertical') { if (bs && (bs.left == null || bs.top == null || bs.right == null || bs.bottom == null)) throw new Error(ERROR_STR); if (bs) return [bs.left, bs.top, bs.left, bs.bottom]; else return [0, 0, 0, ctx.canvas.height]; } else if (type === 'horizontal') { if (bs && (bs.left == null || bs.top == null || bs.right == null || bs.bottom == null)) throw new Error(ERROR_STR); if (bs) return [bs.left, bs.top, bs.right, bs.top]; else return [0, 0, ctx.canvas.width, 0]; } else { // type === 'vector' if (bs && (bs.fromX == null || bs.fromY == null || bs.toX == null || bs.toY == null)) throw new Error(ERROR_STR); if (bs) return [bs.fromX, bs.fromY, bs.toX, bs.toY]; else return [0, 0, ctx.canvas.width, ctx.canvas.height]; } } /** * Make radial gradation parameters (used only in the library) * @private * @param {Paper|CanvasRenderingContext2D} ctx Paper or canvas context * @param {string} type Type * @param {dict} bs Bounds * @param {dict} opt Options * @return {Array<number>} Radial gradation parameters */ _makeRadialGradParams(ctx, type, bs, opt) { const SQRT2 = 1.41421356237; const cw = ctx.canvas.width, ch = ctx.canvas.height; const bb = bs ? bs : { left: 0, top: 0, right: cw, bottom: ch, fromX: 0, fromY: 0, toX: cw, toY: ch }; const _f = (x0, y0, x1, y1) => { return { w: Math.abs(x0 - x1), h: Math.abs(y0 - y1), cx: (x0 + x1) / 2, cy: (y0 + y1) / 2 }; }; let r, p; if (type === 'inner' || type === 'outer') { p = _f(bb.left, bb.top, bb.right, bb.bottom); opt.scale = ((p.w < p.h) ? [p.w / p.h, 1] : [1, p.h / p.w]); opt.center = [p.cx, p.cy]; r = ((p.w < p.h) ? p.h : p.w) / 2; if (type === 'outer') r *= SQRT2; } else { // type === 'diameter' || type === 'radius' p = _f(bb.fromX, bb.fromY, bb.toX, bb.toY); r = Math.sqrt(p.w * p.w + p.h * p.h); if (type === 'diameter') { r /= 2; } else { // type === 'radius' p.cx = bb.fromX; p.cy = bb.fromY; } } return [p.cx, p.cy, 0, p.cx, p.cy, r]; } /** * Set radial gradation options (used only in the library) * @private * @param {Paper|CanvasRenderingContext2D} ctx Paper or canvas context * @param {Array<number>} opt Options */ _setGradOpt(ctx, opt) { ctx.translate(opt.center[0], opt.center[1]); ctx.scale(opt.scale[0], opt.scale[1]); ctx.translate(-opt.center[0], -opt.center[1]); } }
JavaScript
class Fill extends StyleBase { /** * Make a filling style * @param {Fill=} base Original filling style */ constructor(base) { super(base, 'White'); } /** * Reset * @param {string} color Color * @return {Fill} This filling style */ reset(color) { super.reset(color); return this; } // gradArea = {fromX, fromY, toX, toY, left, top, right, bottom} /** * Set the filling style on the paper * @param {Paper|CanvasRenderingContext2D} ctx Paper or canvas context * @param {Array<number>} gradArea Gradation area */ assign(ctx, gradArea) { ctx.fillStyle = this._makeStyle(ctx, gradArea); ctx.globalAlpha *= this._alpha; ctx.globalCompositeOperation = this._composition; this._shadow.assign(ctx); if (this._gradOpt.scale) this._setGradOpt(ctx, this._gradOpt); } /** * Draw shape using the filling style * @param {Paper|CanvasRenderingContext2D} ctx Paper or canvas context * @param {Array<number>} gradArea Gradation area */ draw(ctx, gradArea) { ctx.save(); this.assign(ctx, gradArea); ctx.fill(); ctx.restore(); } }
JavaScript
class Stroke extends StyleBase { /** * Make a stroke style * @param {Stroke=} base Original stroke style */ constructor(base) { super(base, 'Black'); this._width = base ? base._width : 1; this._cap = base ? base._cap : 'butt'; this._join = base ? base._join : 'bevel'; this._miterLimit = base ? base._miterLimit : 10; this._dash = base ? base._dash : null; this._dashOffset = base ? base._dashOffset : 0; } /** * Reset * @param {string} color Color * @return {Fill} This filling style */ reset(color) { super.reset(color); this._width = 1; this._cap = 'butt'; this._join = 'bevel'; this._miterLimit = 10; this._dash = null; this._dashOffset = 0; return this; } /** * Set the line width * @param {number=} width Line width * @return {number|Stroke} Line width or this stroke */ width(width) { if (width === undefined) return this._width; this._width = width; return this; } /** * Set the line cap * @param {string=} cap Line cap * @return {string|Stroke} Line cap or this stroke */ cap(cap) { if (cap === undefined) return this._cap; this._cap = cap; return this; } /** * Set the line join * @param {string=} join Line join * @return {string|Stroke} Line join or this stroke */ join(join) { if (join === undefined) return this._join; this._join = join; return this; } /** * Set the upper limit of miter * @param {number=} miterLimit Upper limit of miter * @return {number|Stroke} Upper limit of miter or this stroke */ miterLimit(miterLimit) { if (miterLimit === undefined) return this._miterLimit; this._miterLimit = miterLimit; return this; } /** * Set a dash pattern * @param {Array<number>=} dash Dash pattern * @return {Array<number>|Stroke} Dash pattern or this stroke */ dash(...dash) { if (dash === undefined) return this._dash.concat(); if (Array.isArray(dash[0])) { this._dash = [...dash[0]]; } else { this._dash = [...dash]; } return this; } /** * Set the offset of dash pattern * @param {number=} dashOffset The offset of dash pattern * @return {number|Stroke} The offset of dash pattern or this stroke */ dashOffset(dashOffset) { if (dashOffset === undefined) return this._dashOffset; this._dashOffset = dashOffset; return this; } // gradArea = {fromX, fromY, toX, toY, left, top, right, bottom} /** * Assign the stroke style in the paper * @param {Paper|CanvasRenderingContext2D} ctx Paper or canvas context * @param {Array<number>} gradArea Gradation area */ assign(ctx, gradArea) { ctx.strokeStyle = this._makeStyle(ctx, gradArea); ctx.globalAlpha *= this._alpha; ctx.globalCompositeOperation = this._composition; this._shadow.assign(ctx); if (this._gradOpt.scale) this._setGradOpt(ctx, this._gradOpt); ctx.lineWidth = this._width; ctx.lineCap = this._cap; ctx.lineJoin = this._join; ctx.miterLimit = this._miterLimit; ctx.setLineDash(this._dash ? this._dash : []); ctx.lineDashOffset = this._dashOffset; } /** * Draw lines using the stroke style * @param {Paper|CanvasRenderingContext2D} ctx Paper or canvas context * @param {Array<number>} gradArea Gradation area */ draw(ctx, gradArea) { ctx.save(); this.assign(ctx, gradArea); ctx.stroke(); ctx.restore(); } }
JavaScript
class DestinationAmerica extends DiscoverySite { static get DESTINATION_AMERICA_URL() { return DESTINATION_AMERICA_URL; }; /** * Constructor. * @param {string} page - The Puppeteer page object to use for this site. */ constructor(page) { super(page, DESTINATION_AMERICA_URL, "Destination America"); } }
JavaScript
class HTML { // Inserts the budget when the user submits it insertBudget(amount) { // Insert into HTML budgetTotal.innerHTML = `${amount}`; budgetLeft.innerHTML = `${amount}`; } // Displays a message (correct or invalid) printMessage(message, className) { const messageWrapper = document.createElement('div'); messageWrapper.classList.add('text-center', 'alert', className); messageWrapper.appendChild(document.createTextNode(message)); // Insert into HTML document.querySelector('.primary').insertBefore(messageWrapper, addExpenseForm); // Clear the error setTimeout(function () { document.querySelector('.primary .alert').remove(); addExpenseForm.reset(); }, 3000); } // Displays the expenses from the form into the list addExpenseToList(name, amount) { const expensesList = document.querySelector('#expenses ul'); // Create a li const li = document.createElement('li'); li.className = "list-group-item d-flex justify-content-between align-items-center"; // Create the template <span class="badge badge-primary badge-pill">$ ${amount}</span> // add new materialize class later for pill shape li.innerHTML = ` ${name} <span>$ ${amount}</span> `; // Insert into the HTML expensesList.appendChild(li); } // Subtract expense amount from budget trackBudget(amount) { const budgetLeftDollars = budget.substractFromBudget(amount); budgetLeft.innerHTML = `${budgetLeftDollars}`; // Check when 25% is left if ((budget.budget / 4) > budgetLeftDollars) { budgetLeft.parentElement.parentElement.classList.remove('alert-success', 'alert-warning'); budgetLeft.parentElement.parentElement.classList.add('alert-danger'); } else if ((budget.budget / 2) > budgetLeftDollars) { budgetLeft.parentElement.parentElement.classList.remove('alert-success'); budgetLeft.parentElement.parentElement.classList.add('alert-warning'); } } }
JavaScript
class ChatChannel { constructor() { Object.defineProperty(this, "getName", { configurable: false, writable: false, value: this.getName }); Object.defineProperty(this, "setConn", { configurable: false, writable: false, value: this.setConn }); Object.defineProperty(this, "route", { configurable: false, writable: false, value: this.route }); Object.defineProperty(this, "ChangeName", { configurable: false, writable: false, value: this.sendChangeName }); Object.defineProperty(this, "Message", { configurable: false, writable: false, value: this.sendMessage }); this._onChangeNameFn = null; this._onMessageFn = null; this._onUserEnterFn = null; this._onUserLeftFn = null; this._onUserListUpdateFn = null; this._connectedFn = null; this._disconnectedFn = null; } /** * @callback connectedCb */ /** * @function ChatChannel#connected * @param {connectedCb} callback */ connected(callback){ this._connectedFn = callback; } /** * @callback disconnectedCb */ /** * @function ChatChannel#disconnected * @param {disconnectedCb} callback */ disconnected(callback){ this._disconnectedFn = callback; } getName() { return "Chat" } setConn(conn) { this.conn = conn } route(name, body) { switch(name) { default: console.log("unexpected event ", name, "in channel Chat") break case "ChangeName": return this.onChangeNameFn(body) case "Message": return this.onMessageFn(body) case "UserEnter": return this.onUserEnterFn(body) case "UserLeft": return this.onUserLeftFn(body) case "UserListUpdate": return this.onUserListUpdateFn(body) } } /** * @function ChatChannel#onChangeNameFn * @param {ChangeName} event */ onChangeNameFn(event) { if(this._onChangeNameFn == null) { console.log("unhandled message 'ChangeName' received") return } this._onChangeNameFn(event) } /** * @callback onChangeNameCb * @param {ChangeName} event */ /** * @function ChatChannel#onChangeName * @param {onChangeNameCb} callback */ onChangeName(callback) { this._onChangeNameFn = callback } /** * @function ChatChannel#onMessageFn * @param {Message} event */ onMessageFn(event) { if(this._onMessageFn == null) { console.log("unhandled message 'ChangeName' received") return } this._onMessageFn(event) } /** * @callback onMessageCb * @param {Message} event */ /** * @function ChatChannel#onMessage * @param {onMessageCb} callback */ onMessage(callback) { this._onMessageFn = callback } /** * @function ChatChannel#onUserEnterFn * @param {UserEnter} event */ onUserEnterFn(event) { if(this._onUserEnterFn == null) { console.log("unhandled message 'ChangeName' received") return } this._onUserEnterFn(event) } /** * @callback onUserEnterCb * @param {UserEnter} event */ /** * @function ChatChannel#onUserEnter * @param {onUserEnterCb} callback */ onUserEnter(callback) { this._onUserEnterFn = callback } /** * @function ChatChannel#onUserLeftFn * @param {UserLeft} event */ onUserLeftFn(event) { if(this._onUserLeftFn == null) { console.log("unhandled message 'ChangeName' received") return } this._onUserLeftFn(event) } /** * @callback onUserLeftCb * @param {UserLeft} event */ /** * @function ChatChannel#onUserLeft * @param {onUserLeftCb} callback */ onUserLeft(callback) { this._onUserLeftFn = callback } /** * @function ChatChannel#onUserListUpdateFn * @param {UserListUpdate} event */ onUserListUpdateFn(event) { if(this._onUserListUpdateFn == null) { console.log("unhandled message 'ChangeName' received") return } this._onUserListUpdateFn(event) } /** * @callback onUserListUpdateCb * @param {UserListUpdate} event */ /** * @function ChatChannel#onUserListUpdate * @param {onUserListUpdateCb} callback */ onUserListUpdate(callback) { this._onUserListUpdateFn = callback } /** * @function ChatChannel#sendChangeName * @param {ChangeName} message */ sendChangeName = function(message) { this.conn.send( JSON.stringify({channel:this.getName(), name:"ChangeName", body: message}) ); } /** * @function ChatChannel#sendMessage * @param {Message} message */ sendMessage = function(message) { this.conn.send( JSON.stringify({channel:this.getName(), name:"Message", body: message}) ); } }
JavaScript
class TelegramEmbed extends Component { constructor(props) { super(props); this.state = { src: this.props.src, id: "", height: "80px", }; this.messageHandler = this.messageHandler.bind(this); this.urlObj = document.createElement("a"); } componentDidMount() { window.addEventListener("message", this.messageHandler); this.iFrame.addEventListener("load", () => { this.checkFrame(this.state.id); }); } componentWillUnmount() { window.removeEventListener("message", this.messageHandler); } messageHandler({ data, source }) { if ( !data || typeof data !== "string" || source !== this.iFrame.contentWindow ) { return; } const action = JSON.parse(data); if (action.event === "resize" && action.height) { this.setState({ height: action.height + "px", }); } } checkFrame(id) { this.iFrame.contentWindow.postMessage( JSON.stringify({ event: "visible", frame: id }), "*" ); } UNSAFE_componentWillReceiveProps({ src }) { if (this.state.src !== src) { this.urlObj.href = src; const id = `telegram-post${this.urlObj.pathname.replace( /[^a-z0-9_]/gi, "-" )}`; this.setState({ src, id }, () => this.checkFrame(id)); } } render() { const { src, height } = this.state; const { container } = this.props; return ( <div data-sharing-id={container} style={containerStyles}> <iframe title={src} ref={(node) => (this.iFrame = node)} src={src + "?embed=1"} height={height} id={ "telegram-post" + this.urlObj.pathname.replace(/[^a-z0-9_]/gi, "-") } style={styles} /> </div> ); } }
JavaScript
class Router extends EventEmitter { // # # # # # // # # # # // ### ### ### # ## ### ### ## ### ## ### // # # # # # # # # ## # # ## # # # ## # # // # ## # # # # # # ## # ## # # ## # // # # ### ### #### ### ### ## ## # # ## # /** * Adds a listener. * @param {Events} args The arguments. * @returns {this} The return. */ addListener(...args) { return super.addListener(...args); } // ## ### // # # # # // # # # # // ## # # /** * Adds a listener. * @param {Events} args The arguments. * @returns {this} The return. */ on(...args) { return super.on(...args); } // # # ## # // # # # # # // ## ### ## ## # # # ### ## ### ## // # # # # ## # ## # # # # # # # ## // # # # ## # # # # # # ## # # # ## // ## # # ## ## # # ## # # ## # # ## /** * Checks the cache and refreshes it if necessary. * @param {string} file The name of the class. * @returns {Promise} A promise that resolves once the cache is checked. */ async checkCache(file) { // Ensure we've already loaded the class, otherwise bail. const route = routes[file]; if (!route) { throw new Error("Invald class name."); } const stats = await fs.stat(require.resolve(route.file)); if (!route.lastModified || route.lastModified.getTime() !== stats.mtime.getTime()) { delete require.cache[require.resolve(route.file)]; route.class = require(route.file); route.lastModified = stats.mtime; } } // # ## ## // # # # # // ### ## ### # # ### ### ### ## ### // # # # ## # # # # # ## ## # ## ## // ## ## # # # # # ## ## ## ## ## // # ## ## ## ### # # ### ### ## ### // ### /** * Gets all of the available classes. * @param {string} dir The directory to get the classes for. * @returns {Promise} A promise that resolves when all the classes are retrieved. */ async getClasses(dir) { const list = await fs.readdir(dir); for (const file of list) { const filename = path.resolve(dir, file); const stat = await fs.stat(filename); if (stat && stat.isDirectory()) { await this.getClasses(filename); } else { const routeClass = require(filename); /** @type {RouterBase.Route} */ const route = routeClass.route; routes[filename] = route; if (route.webSocket) { routes[filename].events = Object.getOwnPropertyNames(routeClass).filter((p) => typeof routeClass[p] === "function"); } else if (!route.include) { routes[filename].methods = Object.getOwnPropertyNames(routeClass).filter((p) => typeof routeClass[p] === "function"); } if (route.notFound) { notFoundFilename = filename; } else if (route.methodNotAllowed) { methodNotAllowedFilename = filename; } else if (route.serverError) { serverErrorFilename = filename; } routes[filename].file = filename; this.checkCache(filename); } } } // # ### # // # # # # // ### ## ### # # ## # # ### ## ### // # # # ## # ### # # # # # # ## # # // ## ## # # # # # # # # ## # // # ## ## # # ## ### ## ## # // ### /** * Gets the router to use for the website. * @param {string} routesPath The directory with the route classes. * @param {object} [options] The options to use. * @param {boolean} [options.hot] Whether to use hot reloading for RouterBase classes. Defaults to true. * @returns {Promise<Express.Router>} A promise that resolves with the router to use for the website. */ async getRouter(routesPath, options) { options = {...{hot: true}, ...options || {}}; await this.getClasses(routesPath); const router = express.Router(), filenames = Object.keys(routes), includes = filenames.filter((c) => routes[c].include), webSockets = filenames.filter((c) => routes[c].webSocket), pages = filenames.filter((c) => !routes[c].include && !routes[c].webSocket && routes[c].path && routes[c].methods && routes[c].methods.length > 0); // Setup websocket routes. webSockets.forEach((filename) => { const route = /** @type {RouterBase.BaseRoute & RouterBase.WebsocketRoute} */(routes[filename]); // eslint-disable-line no-extra-parens router.ws(route.path, ...route.middleware, (ws, req) => { // @ts-ignore ws._url = req.url.replace("/.websocket", "").replace(".websocket", "") || "/"; route.events.forEach((event) => { ws.on(event, (...args) => { route.class[event](ws, ...args); }); }); }); }); // Setup page routes. pages.forEach((filename) => { const route = /** @type {RouterBase.BaseRoute & RouterBase.WebRoute} */(routes[filename]); // eslint-disable-line no-extra-parens route.methods.forEach((method) => { router[method](route.path, ...route.middleware, async (/** @type {Express.Request} */ req, /** @type {Express.Response} */ res, /** @type {function} */ next) => { if (res.headersSent) { return; } try { if (options.hot) { for (const include of includes) { await this.checkCache(include); } await this.checkCache(filename); } if (!route.class[req.method.toLowerCase()]) { if (methodNotAllowedFilename !== "") { await routes[methodNotAllowedFilename].class.get(req, res, next); return; } res.status(405).send("HTTP 405 Method Not Allowed"); return; } await route.class[req.method.toLowerCase()](req, res, next); return; } catch (err) { this.emit("error", { message: `An error occurred in ${req.method.toLowerCase()} ${route.path} from ${req.ip} for ${req.url}.`, err, req }); } if (serverErrorFilename !== "") { await routes[serverErrorFilename].class.get(req, res, next); return; } res.status(500).send("HTTP 500 Server Error"); }); }); }); // 404 remaining pages. router.use(async (req, res, next) => { if (res.headersSent) { return; } if (notFoundFilename !== "") { await routes[notFoundFilename].class.get(req, res, next); return; } res.status(404).send("HTTP 404 Not Found"); }); // 500 errors. router.use(async (err, req, res, next) => { if (err.status && err.status !== 500 && err.expose) { if (res.headersSent) { return; } res.status(err.status).send(err.message); } else { this.emit("error", { message: "An unhandled error has occurred.", err, req }); if (res.headersSent) { return; } if (serverErrorFilename !== "") { await routes[serverErrorFilename].class.get(req, res, next); return; } res.status(500).send("HTTP 500 Server Error"); } }); return router; } // ## ### ### ## ### // # ## # # # # # # # # // ## # # # # # // ## # # ## # /** * Handles a router error. * @param {HttpErrors.HttpError} err The error object. * @param {Express.Request} req The request. * @param {Express.Response} res The response. * @param {Express.NextFunction} next The function to be called if the error is not handled. * @returns {Promise} A promise that resolves when the error is handled. */ async error(err, req, res, next) { if (err.status && err.status !== 500 && err.expose) { if (res.headersSent) { return; } res.status(err.status).send(err.message); } else { this.emit("error", { message: "An unhandled error has occurred.", err, req }); if (res.headersSent) { return; } if (serverErrorFilename !== "") { await routes[serverErrorFilename].class.get(req, res, next); return; } res.status(500).send("HTTP 500 Server Error"); } } }
JavaScript
class EditPanel extends React.Component { render() { const { children, title, handleSave, handleCancel } = this.props; return ( <Card> <Card.Title>{title}</Card.Title> <Card.Body>{children}</Card.Body> <Card.Footer> <Button size="sm" onClick={handleCancel}> Cancel </Button> <Button size="sm" onClick={handleSave}> Save </Button> </Card.Footer> </Card> ); } }
JavaScript
class FeedBackController { /** * Initializing all necssary variables * @param $http * @param $timeout */ constructor($http, $timeout) { this.$http = $http; this.$timeout = $timeout; this.feedbacks = []; this.successAdded = false; this.errorMessage = false; /** * Getting all feedbacks if there anyone */ $http.get('/api/feedbacks').then(response => { this.feedbacks = response.data; }); } /** * Saving feedbacks * @param form */ addFeedback(form) { let self = this; if (form.$valid) { if (this.newFeedback) { this.$http.post('/api/feedbacks', this.newFeedback) .then(res => { if(res.status === 201) { this.$http.get('/api/feedbacks').then(response => { this.feedbacks = response.data; this.successMessage = 'Your feedback has been sent successfully!'; form.$setPristine(); this.newFeedback = {}; $('#name').focus(); this.$timeout(function() { self.successAdded = false; }, 5000); }); } else { this.errorMessage = res.errmsg; } }); } } } /** * Updating feedbacks * @param form */ updateFeedback(form) { let self = this; if (form.$valid) { if (this.newFeedback) { this.$http.put('/api/feedbacks/' + this.newFeedback._id, this.newFeedback) .then(res => { if(res.status === 200) { this.$http.get('/api/feedbacks').then(response => { this.feedbacks = response.data; this.successMessage = 'Feedback Updated successfully!'; form.$setPristine(); this.newFeedback = {}; $('#name').focus(); this.$timeout(function() { self.successMessage = false; }, 5000); }); } else { this.errorMessage = res.errmsg; } }); } } } /** * Preparing do edit * @param feedback */ setEdit(feedback) { this.newFeedback = feedback; } /** * Removing feedbacks by id * @param feedback */ removeFeedback(feedback) { this.$http.delete('/api/feedbacks/' + feedback._id) .then(res => { if(res.status === 204) { this.$http.get('/api/feedbacks').then(response => { this.feedbacks = response.data; }); } }) } }
JavaScript
class InterpolatedPose { constructor() { this.start = new Pose(); this.current = new Pose(); this.end = new Pose(); this.offset = vec3.create(); } /** * Set the target comfort offset for the time `t + dt`. */ setOffset(ox, oy, oz) { vec3.set(delta, ox, oy, oz); vec3.sub(delta, delta, this.offset); vec3.add(this.start.p, this.start.p, delta); vec3.add(this.current.p, this.current.p, delta); vec3.add(this.end.p, this.end.p, delta); vec3.scale(this.start.f, this.start.f, k); vec3.add(this.start.f, this.start.f, delta); vec3.normalize(this.start.f, this.start.f); vec3.scale(this.current.f, this.current.f, k); vec3.add(this.current.f, this.current.f, delta); vec3.normalize(this.current.f, this.current.f); vec3.scale(this.end.f, this.end.f, k); vec3.add(this.end.f, this.end.f, delta); vec3.normalize(this.end.f, this.end.f); vec3.set(this.offset, ox, oy, oz); } /** * Set the target position and orientation for the time `t + dt`. * @param px - the horizontal component of the position. * @param py - the vertical component of the position. * @param pz - the lateral component of the position. * @param fx - the horizontal component of the position. * @param fy - the vertical component of the position. * @param fz - the lateral component of the position. * @param ux - the horizontal component of the position. * @param uy - the vertical component of the position. * @param uz - the lateral component of the position. * @param t - the time at which to start the transition. * @param dt - the amount of time to take making the transition. */ setTarget(px, py, pz, fx, fy, fz, ux, uy, uz, t, dt) { const ox = this.offset[0]; const oy = this.offset[1]; const oz = this.offset[2]; this.end.set(px + ox, py + oy, pz + oz, fx, fy, fz, ux, uy, uz); this.end.t = t + dt; if (dt > 0) { this.start.copy(this.current); this.start.t = t; } else { this.start.copy(this.end); this.start.t = t; this.current.copy(this.end); this.current.t = t; } } /** * Set the target position for the time `t + dt`. * @param px - the horizontal component of the position. * @param py - the vertical component of the position. * @param pz - the lateral component of the position. * @param t - the time at which to start the transition. * @param dt - the amount of time to take making the transition. */ setTargetPosition(px, py, pz, t, dt) { this.setTarget(px, py, pz, this.end.f[0], this.end.f[1], this.end.f[2], this.end.u[0], this.end.u[1], this.end.u[2], t, dt); } /** * Set the target orientation for the time `t + dt`. * @param fx - the horizontal component of the position. * @param fy - the vertical component of the position. * @param fz - the lateral component of the position. * @param ux - the horizontal component of the position. * @param uy - the vertical component of the position. * @param uz - the lateral component of the position. * @param t - the time at which to start the transition. * @param dt - the amount of time to take making the transition. */ setTargetOrientation(fx, fy, fz, ux, uy, uz, t, dt) { this.setTarget(this.end.p[0], this.end.p[1], this.end.p[2], fx, fy, fz, ux, uy, uz, t, dt); } /** * Calculates the new position for the given time. */ update(t) { this.current.interpolate(this.start, this.end, t); } }
JavaScript
class Slider extends Component { constructor(props) { super(props); this.state = { slideTo: 0, sliderWidth: 0, slideWidth: 0 }; } slideRight = () => { let slideTo = this.state.slideTo - this.state.sliderWidth; if(slideTo < (this.state.slidesWidth - this.state.sliderWidth) * -1) { slideTo = (this.state.slidesWidth - this.state.sliderWidth) * -1; } this.setState({ ...this.state, slideTo: slideTo }) } slideLeft = () => { let slideTo = this.state.slideTo + this.state.sliderWidth; if(slideTo > 0) { slideTo = 0; } this.setState({ ...this.state, slideTo: slideTo }) } componentDidMount() { const { slides, viewable, breakpoint } = this.props; const sliderItems = document.querySelectorAll('.slider .slider-item'); const maxWidth = document.getElementById('slider'); const slidesInView = (breakpoint !== 'mobile') ? viewable : 1; const slideWidth = maxWidth.clientWidth / slidesInView; for(let i=0; i<sliderItems.length; i++) { sliderItems[i].style.width = `${slideWidth}px`; } document.getElementById('slider-inner').style.width = `${slideWidth * slides}px`; this.setState({ sliderWidth: parseInt(document.getElementById('slider').clientWidth, 10), slidesWidth: parseInt(slideWidth * slides, 10) }); } render() { const { children } = this.props; const { slideTo, sliderWidth, slidesWidth } = this.state; return ( <div id="slider" className="slider"> <div className="slider-viewport"> <div id="slider-inner" className="slider-inner" style={{ left: `${slideTo}px` }}> {children} </div> </div> <div className={classnames('slider-control next', { disabled: slideTo <= (slidesWidth - sliderWidth) * -1 })} onClick={this.slideRight} > <i className="fas fa-2x fa-chevron-circle-right" /> </div> <div className={classnames('slider-control prev', { disabled: slideTo === 0 })} onClick={this.slideLeft} > <i className="fas fa-2x fa-chevron-circle-left" /> </div> </div> ); } }
JavaScript
class TableMaterial extends Component { state = { fixedHeader: true, fixedFooter: true, stripedRows: true, showRowHover: true, selectable: true, multiSelectable: false, enableSelectAll: false, deselectOnClickaway: true, showCheckboxes: false, height: '100%', }; handleToggle = (event, toggled) => { this.setState({ [event.target.name]: toggled, }); }; handleChange = (event) => { this.setState({height: event.target.value}); }; render() { return ( <div> <Table height={this.state.height} fixedHeader={this.state.fixedHeader} fixedFooter={this.state.fixedFooter} selectable={this.state.selectable} multiSelectable={this.state.multiSelectable} > <TableHeader displaySelectAll={this.state.showCheckboxes} adjustForCheckbox={this.state.showCheckboxes} enableSelectAll={this.state.enableSelectAll} > </TableHeader> <TableBody displayRowCheckbox={this.state.showCheckboxes} deselectOnClickaway={this.state.deselectOnClickaway} showRowHover={this.state.showRowHover} stripedRows={this.state.stripedRows} > {tableData.map( (row, index) => ( <TableRow key={index}> <TableRowColumn>{index}</TableRowColumn> <TableRowColumn>{row.name}</TableRowColumn> <TableRowColumn>{row.status}</TableRowColumn> </TableRow> ))} </TableBody> </Table> </div> ); } }
JavaScript
class SvelteComponent { $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set($$props) { if (this.$$set && !is_empty($$props)) { this.$$.skip_bound = true; this.$$set($$props); this.$$.skip_bound = false; } } }
JavaScript
class SvelteComponentDev extends SvelteComponent { constructor(options) { if (!options || (!options.target && !options.$$inline)) { throw new Error("'target' is a required option"); } super(); } $destroy() { super.$destroy(); this.$destroy = () => { console.warn('Component was already destroyed'); // eslint-disable-line no-console }; } $capture_state() { } $inject_state() { } }
JavaScript
class JsDumper { /** * Constructor. * * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container */ __construct(container) { if (! container.frozen) { throw new RuntimeException('Cannot dump an uncompiled container. Please call compile() on your builder first'); } this._container = container; this._inlinedDefinitions = new Map(); this._serviceIdToMethodNameMap = undefined; this._usedMethodNames = undefined; this._definitionVariables = undefined; this._referenceVariables = undefined; this._variableCount = undefined; this._targetDirMaxMatches = undefined; this._targetDirRegex = undefined; this._addThrow = false; } /** * Dumps the service container. * * Available options: * * class_name: The class name [default: ProjectContainer] * * base_class: The base class name [default: Jymfony.Component.DependencyInjection.Container] * * build_time: The build unix time. * * @param {Object.<string, *>} [options = {}] * * @returns {Object<string, string>} */ dump(options = {}) { options = Object.assign({}, { base_class: 'Jymfony.Component.DependencyInjection.Container', class_name: 'ProjectContainer', build_time: ~~(Date.now() / 1000), }, options); (new AnalyzeServiceReferencesPass()).process(this._container); if (options.dir) { const dir = __jymfony.rtrim(options.dir, '/').split(path.sep); let i = dir.length; if (3 <= i) { let regex = ''; const lastOptionalDir = 8 < i ? i - 5 : 3; this._targetDirMaxMatches = i - lastOptionalDir; while (--i >= lastOptionalDir) { regex = __jymfony.sprintf('(%s%s)?', __jymfony.regex_quote(path.sep + dir[i]), regex); } do { regex = __jymfony.regex_quote(path.sep + dir[i]) + regex; } while (0 < --i); this._targetDirRegex = new RegExp(__jymfony.regex_quote(dir[0]) + regex); } } this._initMethodNamesMap(options.base_class); let main = this._startClass(options.class_name, options.base_class); main += this._getServices(); main += this._getDefaultParametersMethod(); main += this._endClass(options.class_name); const hash = ContainerBuilder.hash(main).replace(/[._]/g, 'x'); const code = { ['Container'+hash+'/'+options.class_name+'.js']: main, }; const time = options.build_time; const id = __jymfony.crc32(hash + time); code[options.class_name + '.js'] = ` // This file has been auto-generated by the Jymfony Dependency Injection Component for internal use. const Container${hash} = require('./Container${hash}/${options.class_name}.js'); module.exports = new Container${hash}({ 'container.build_hash': '${hash}', 'container.build_id': '${id}', 'container.build_time': ${time}, }); `; return code; } /** * @param {string} baseClass * * @private */ _initMethodNamesMap(baseClass) { this._serviceIdToMethodNameMap = new Map(); this._usedMethodNames = new Set(); try { const reflectionClass = new ReflectionClass(baseClass); for (const method of reflectionClass.methods) { this._usedMethodNames.add(method); } } catch (e) { // Do nothing } } /** * @param {string} className * @param {string} baseClass * * @returns {string} * * @private */ _startClass(className, baseClass) { const targetDirs = undefined === this._targetDirMaxMatches ? '' : ` let dir = path.dirname(__dirname); this._targetDirs = [ dir ]; for (let i = 1; i <= ${this._targetDirMaxMatches}; ++i) { this._targetDirs.push(dir = path.dirname(dir)); } `; return `const Container = Jymfony.Component.DependencyInjection.Container; const LogicException = Jymfony.Component.DependencyInjection.Exception.LogicException; const RuntimeException = Jymfony.Component.DependencyInjection.Exception.RuntimeException; const FrozenParameterBag = Jymfony.Component.DependencyInjection.ParameterBag.FrozenParameterBag; const RewindableGenerator = Jymfony.Component.DependencyInjection.Argument.RewindableGenerator; const path = require('path'); class ${className} extends ${baseClass} { __construct(buildParameters = {}) {${targetDirs} super.__construct(new FrozenParameterBag(Object.assign({}, this._getDefaultsParameters(), buildParameters))); ${this._getMethodMap()} ${this._getAliases()} this._privates = {}; } compile() { throw new LogicException('You cannot compile a dumped container'); } get frozen() { return true; } `; } /** * @param {string} className * * @returns {string} * * @private */ _endClass(className) { let code = ''; if (this._addThrow) { code += ` _throw(message) { throw new RuntimeException(message); } `; } return code + ` } module.exports = ${className}; `; } /** * @returns {string} * * @private */ _getMethodMap() { let code = `this._methodMap = { `; const definitions = this._container.getDefinitions(); const ids = Object.keys(definitions).sort(); for (const id of ids) { const definition = definitions[id]; if (! definition.isPublic() || definition.isSynthetic()) { continue; } code += ' ' + this._export(id) + ': ' + this._export(this._generateMethodName(id)) + ',\n'; } return code + ' };\n'; } /** * @returns {string} * * @private */ _getAliases() { let code = `this._aliases = { `; const aliases = this._container.getAliases(); const ids = Object.keys(aliases).sort(); for (const alias of ids) { let id = aliases[alias].toString(); while (undefined !== aliases[id]) { id = aliases[id].toString(); } if (aliases[alias].isDeprecated()) { const deprecatedMessage = this._export(aliases[alias].getDeprecationMessage(alias)); code += ' get ' + this._export(alias) + '() {\n' + ' __jymfony.trigger_deprecation(' + deprecatedMessage + ')\n' + ' return ' + this._export(id) + ';\n' + ' },\n'; } else { code += ' ' + this._export(alias) + ': ' + this._export(id) + ',\n'; } } return code + ' };\n'; } /** * @param {*} value * * @returns {string} * * @private */ _export(value) { if (undefined !== this._targetDirRegex && isString(value) && value.match(this._targetDirRegex)) { value = JSON.stringify(value); value = value.replace(this._targetDirRegex, (...args) => { for (let i = this._targetDirMaxMatches; 1 <= i; --i) { if (undefined === args[i]) { continue; } return '" + this._targetDirs[' + (this._targetDirMaxMatches - i) + '] + "'; } }); return value.replace(/"" \+ /g, '').replace(/ \+ ""/g, ''); } return this._doExport(value); } /** * @param {*} value * * @returns {string} * * @private */ _doExport(value) { if (isScalar(value) || isArray(value) || isObjectLiteral(value)) { return JSON.stringify(value); } if (undefined === value) { return 'undefined'; } if (null === value) { return 'null'; } throw new Error('Unimplemented exporting value "' + value + '"'); } /** * @param {string} id * * @returns {string} * * @private */ _generateMethodName(id) { if (this._serviceIdToMethodNameMap[id]) { return this._serviceIdToMethodNameMap[id]; } let name = Container.camelize(id); name = name.replace(/[^a-zA-Z0-9_\x7f-\xff]/g, ''); let methodName = `get${name}Service`; let suffix = 1; while (this._usedMethodNames.has(methodName)) { ++suffix; methodName = `get${name}${suffix}Service`; } this._serviceIdToMethodNameMap[id] = methodName; this._usedMethodNames.add(methodName); return methodName; } /** * @returns {string} * * @private */ _getServices() { let publicServices = '', privateServices = ''; const serviceIds = Object.keys(this._container.getDefinitions()).sort(); for (const id of serviceIds) { const definition = this._container.getDefinition(id); if (definition.isPublic()) { publicServices += this._getService(id, definition); } else { privateServices += this._getService(id, definition); } } return publicServices + privateServices; } /** * @returns {string} * * @private */ _getDefaultParametersMethod() { let code = '{\n'; const parameters = this._container.parameterBag.all(); for (const key of Object.keys(parameters)) { const dumped = this._dumpParameter(key, false); if (0 === dumped.indexOf('this.getParameter')) { continue; } code += ` "${key}": ${dumped},` + '\n'; } code += ' }'; return ` _getDefaultsParameters() { return ${code}; }`; } /** * Generate a service. * * @param {string} id * @param {Jymfony.Component.DependencyInjection.Definition} definition * * @private */ _getService(id, definition) { if (definition.isSynthetic()) { return ''; } this._definitionVariables = new Map(); this._referenceVariables = {}; this._variableCount = 0; let class_; const returns = []; if (definition.isSynthetic()) { returns.push('@throws {Jymfony.Component.DependencyInjection.RuntimeException} always since this service is expected to be injected dynamically'); } else if ((class_ = definition.getClass())) { returns.push('@returns {' + (-1 !== class_.indexOf('%') ? '*' : class_) + '}'); } else if (definition.getFactory() || definition.getModule()) { returns.push('@returns {Object}'); } if (definition.isDeprecated()) { returns.push('@deprecated ' + definition.getDeprecationMessage(id)); } let doc = ''; const visibility = definition.isPublic() ? 'public ' : ''; const shared = definition.isShared() ? 'shared ' : ''; let lazyInitialization = ''; if (definition.isLazy()) { doc = ' * @param {boolean} lazyLoad Whether to try to lazy-load this service' + doc; lazyInitialization = 'lazyLoad = true'; } if (doc.length) { doc += '\n'; } const methodName = this._generateMethodName(id); return ` /** * Gets the ${visibility}'${id}' ${shared}service. * ${doc} * ${returns.join('\n * ').replace(/\n * \n/g, '\n *\n')} */ ${methodName}(${lazyInitialization}) { ${this._addLocalTempVariables(id, definition)}\ ${this._addInlinedDefinitions(id, definition)}\ ${this._addServiceInstance(id, definition)}\ ${this._addInlinedDefinitionsSetup(id, definition)}\ ${this._addProperties(definition)}\ ${this._addMethodCalls(definition)}\ ${this._addShutdownCalls(definition)}\ ${this._addConfigurator(definition)}\ ${this._addReturn(id, definition)}\ } `; } /** * @param {string} cId * @param {Jymfony.Component.DependencyInjection.Definition} definition * * @returns {string} * * @private */ _addLocalTempVariables(cId, definition) { const template = ' let %s = %s;\n'; const localDefinitions = [ definition, ...this._getInlinedDefinitions(definition) ]; const calls = {}; const behavior = {}; for (const iDefinition of localDefinitions) { this._getServiceCallsFromArguments(iDefinition.getArguments(), calls, behavior); this._getServiceCallsFromArguments(iDefinition.getMethodCalls(), calls, behavior); this._getServiceCallsFromArguments(iDefinition.getShutdownCalls(), calls, behavior); this._getServiceCallsFromArguments(iDefinition.getProperties(), calls, behavior); this._getServiceCallsFromArguments([ iDefinition.getConfigurator() ], calls, behavior); this._getServiceCallsFromArguments([ iDefinition.getFactory() ], calls, behavior); } let code = ''; for (const [ id, callCount ] of __jymfony.getEntries(calls)) { if ('service_container' === id || id === cId) { continue; } if (1 < callCount) { const name = this._getNextVariableName(); this._referenceVariables[id] = new Variable(name); if (Container.EXCEPTION_ON_INVALID_REFERENCE === behavior[id]) { code += __jymfony.sprintf(template, name, this._getServiceCall(id)); } else { code += __jymfony.sprintf(template, name, this._getServiceCall(id, new Reference(id, Container.NULL_ON_INVALID_REFERENCE))); } } } if ('' !== code) { code += '\n'; } return code; } /** * @param {string} id * @param {Jymfony.Component.DependencyInjection.Definition} definition * * @returns {string} * * @private */ _addInlinedDefinitions(id, definition) { let code = ''; const nbOccurrences = new Map(); const processed = new Set(); const inlinedDefinitions = this._getInlinedDefinitions(definition); for (const iDefinition of inlinedDefinitions) { if (! nbOccurrences.has(iDefinition)) { nbOccurrences.set(iDefinition, 1); } else { const i = nbOccurrences.get(iDefinition); nbOccurrences.set(iDefinition, i + 1); } } for (const sDefinition of inlinedDefinitions) { if (processed.has(sDefinition)) { continue; } processed.add(sDefinition); if (1 < nbOccurrences.get(sDefinition) || sDefinition.getMethodCalls().length || sDefinition.getShutdownCalls().length || Object.keys(sDefinition.getProperties()).length || sDefinition.getConfigurator()) { const name = this._getNextVariableName(); this._definitionVariables.set(sDefinition, new Variable(name)); if (this._hasReference(id, sDefinition.getArguments())) { throw new ServiceCircularReferenceException(id, [ id ]); } code += this._addNewInstance(sDefinition, 'let ' + name, ' = '); if (! this._hasReference(id, sDefinition.getMethodCalls(), true) && ! this._hasReference(id, sDefinition.getProperties(), true)) { code += this._addProperties(sDefinition, name); code += this._addMethodCalls(sDefinition, name); code += this._addShutdownCalls(sDefinition, name); code += this._addConfigurator(sDefinition, name); } code += '\n'; } } return code; } /** * Generate service instance * * @param {string} id * @param {Jymfony.Component.DependencyInjection.Definition} definition * * @returns {string} * * @private */ _addServiceInstance(id, definition) { const simple = this._isSimpleInstance(id, definition); let instantiation = ''; if (definition.isShared()) { const variable = definition.isPublic() ? '_services' : '_privates'; instantiation = `this.${variable}["${id}"] = ` + (simple ? '' : 'instance'); } else { instantiation = 'instance = '; } let ret = ''; if (simple) { ret = 'return '; } else { instantiation += ' = '; } let code = this._addNewInstance(definition, ret, instantiation); if (! definition.isShared() || ! simple) { code = ' let instance;\n' + code; } if (! simple) { code += '\n'; } return code; } /** * @param {string} id * @param {Jymfony.Component.DependencyInjection.Definition} definition * * @returns {string} * * @private */ _addInlinedDefinitionsSetup(id, definition) { this._referenceVariables[id] = 'instance'; let code = ''; const processed = new Set(); for (const iDefinition of this._getInlinedDefinitions(definition)) { if (processed.has(iDefinition)) { continue; } processed.add(iDefinition); if (! this._hasReference(id, iDefinition.getMethodCalls(), true) && ! this._hasReference(id, iDefinition.getShutdownCalls(), true) && ! this._hasReference(id, iDefinition.getProperties(), true)) { continue; } // If the instance is simple, the return statement has already been generated // So, the only possible way to get there is because of a circular reference if (this._isSimpleInstance(id, definition)) { throw new ServiceCircularReferenceException(id, [ id ]); } const name = this._definitionVariables.get(iDefinition); code += this._addMethodCalls(iDefinition, name); code += this._addShutdownCalls(iDefinition, name); code += this._addProperties(iDefinition, name); code += this._addConfigurator(iDefinition, name); } if ('' !== code) { code += '\n'; } return code; } /** * @param {string} id * @param {Jymfony.Component.DependencyInjection.Definition} definition * @param {string|Jymfony.Component.DependencyInjection.Variable} [variableName = instance] * * @returns {string} * * @private */ _addProperties(definition, variableName = 'instance') { let code = ''; for (const [ name, value ] of __jymfony.getEntries(definition.getProperties())) { code += __jymfony.sprintf(' %s.%s = %s;\n', variableName, name, this._dumpValue(value)); } return code; } /** * @param {Jymfony.Component.DependencyInjection.Definition} definition * @param {string|Jymfony.Component.DependencyInjection.Variable} [variableName = instance] * * @returns {string} * * @private */ _addMethodCalls(definition, variableName = 'instance') { let code = ''; for (const call of definition.getMethodCalls()) { const args = []; for (const value of call[1]) { args.push(this._dumpValue(value)); } code += this._wrapServiceConditionals(call[1], __jymfony.sprintf(' %s.%s(%s);\n', variableName, call[0], args.join(', '))); } return code; } /** * @param {Jymfony.Component.DependencyInjection.Definition} definition * @param {string|Jymfony.Component.DependencyInjection.Variable} [variableName = instance] * * @returns {string} * * @private */ _addShutdownCalls(definition, variableName = 'instance') { let code = ''; for (const call of definition.getShutdownCalls()) { const args = []; for (const value of call[1]) { args.push(this._dumpValue(value)); } code += this._wrapServiceConditionals(call[1], __jymfony.sprintf(' this.registerShutdownCall(%s.%s.bind(%s, %s));\n', variableName, call[0], variableName, args.join(', '))); } return code; } /** * @param {Jymfony.Component.DependencyInjection.Definition} definition * @param {string|Jymfony.Component.DependencyInjection.Variable} [variableName = instance] * * @returns {string} * * @private */ _addConfigurator(definition, variableName = 'instance') { const callable = definition.getConfigurator(); if (! callable) { return ''; } if (isArray(callable)) { if (callable[0] instanceof Reference || (callable[0] instanceof Definition && this._definitionVariables.has(definition))) { return __jymfony.sprintf(' %s.%s(%s);\n', this._dumpValue(callable[0]), callable[1], variableName); } const class_ = this._dumpValue(callable[0]); throw new RuntimeException(class_); } return __jymfony.sprintf(' %s(%s);\n', callable, variableName); } /** * @param {string} id * @param {Jymfony.Component.DependencyInjection.Definition} definition * * @returns {string} * * @private */ _addReturn(id, definition) { if (this._isSimpleInstance(id, definition)) { return ''; } return ' return instance;\n'; } /** * @param {*} value * @param {boolean} [interpolate = true] * * @returns {string} * * @throws {Jymfony.Component.DependencyInjection.Exception.RuntimeException} * * @private */ _dumpValue(value, interpolate = true) { if (value instanceof ArgumentInterface) { const scope = [ this._definitionVariables, this._referenceVariables, this._variableCount ]; this._definitionVariables = this._referenceVariables = undefined; try { if (value instanceof ServiceClosureArgument) { value = value.values[0]; const code = this._dumpValue(value, interpolate); return __jymfony.sprintf('() => {\n return %s;\n }', code); } if (value instanceof IteratorArgument) { const operands = [ 0 ]; const code = [ 'new RewindableGenerator((function * () {' ]; const values = value.values; let countCode; if (! values || 0 === Object.keys(values).length) { code.push(' return new EmptyIterator();'); } else { countCode = [ 'function () {' ]; for (let v of Object.values(values)) { const c = this._getServiceConditionals(v); if (c) { operands.push('((' + c + ') ? 1 : 0)'); } else { ++operands[0]; } v = this._wrapServiceConditionals(v, __jymfony.sprintf(' yield %s;\n', this._dumpValue(v, interpolate))); for (const line of v.split('\n')) { if (line) { code.push(' ' + line); } } } countCode.push(__jymfony.sprintf(' return %s;', operands.join(' + '))); countCode.push(' }'); } code.push(__jymfony.sprintf(' }).bind(this), %s)', 1 < operands.length ? countCode.join('\n') : operands[0])); return code.join('\n'); } if (value instanceof ServiceLocatorArgument) { let serviceMap = ''; for (const [ k, v ] of __jymfony.getEntries(value.values)) { if (! v) { continue; } serviceMap += __jymfony.sprintf('\n %s: %s,', this._export(__jymfony.ltrim(k, '?')), this._dumpValue(new ServiceClosureArgument(v)).replace(/^/mg, ' ').trim(), ); } return __jymfony.sprintf('new \%s({%s\n })', ReflectionClass.getClassName(ServiceLocator), serviceMap); } } finally { [ this._definitionVariables, this._referenceVariables, this._variableCount ] = scope; } } else if (value instanceof Definition) { if (value.hasErrors()) { this._addThrow = true; return __jymfony.sprintf('this._throw(%s)', this._export(value.getErrors()[0])); } if (this._definitionVariables && this._definitionVariables.has(value)) { return this._dumpValue(this._definitionVariables.get(value), interpolate); } if (0 < value.getMethodCalls().length) { throw new RuntimeException('Cannot dump definitions which have method calls'); } if (0 < value.getShutdownCalls().length) { throw new RuntimeException('Cannot dump definitions which have shutdown calls'); } if (value.getConfigurator()) { throw new RuntimeException('Cannot dump definitions which have configurator'); } const args = []; for (const argument of value.getArguments()) { args.push(this._dumpValue(argument)); } const factory = value.getFactory(); if (factory) { if (isString(factory)) { return __jymfony.sprintf('%s(%s)', this._dumpLiteralClass(this._dumpValue(factory)), args.join(', ')); } if (isArray(factory)) { if (isString(factory[0])) { return __jymfony.sprintf('%s.%s(%s)', this._dumpLiteralClass(this._dumpValue(factory[0])), factory[1], args.join(', ')); } if (factory[0] instanceof Definition) { return __jymfony.sprintf('getCallableFromArray([%s, \'%s\'])(%s)', this._dumpValue(factory[0]), factory[1], args.join(', ')); } if (factory[0] instanceof Reference) { return __jymfony.sprintf('%s.%s(%s)', this._dumpValue(factory[0]), factory[1], args.join(', ')); } } throw new RuntimeException('Cannot dump definition because of invalid factory'); } const class_ = value.getClass(); if (! class_) { throw new RuntimeException('Cannot dump definition which have no class nor factory'); } return __jymfony.sprintf('new %s(%s)', this._dumpLiteralClass(this._dumpValue(class_)), args.join(', ')); } else if (value instanceof Variable) { return value.toString(); } else if (value instanceof Reference) { const id = value.toString(); if (this._referenceVariables && this._referenceVariables[id]) { return this._dumpValue(this._referenceVariables[id], interpolate); } return this._getServiceCall(id, value); } else if (value instanceof Parameter) { return this._dumpParameter(value.toString()); } else if (interpolate && isString(value)) { let match; if ((match = /^%([^%]+)%$/.exec(value))) { return this._dumpParameter(match[1]); } const replaceParameters = (match, p1, p2) => { return '"+' + this._dumpParameter(p2) + '+"'; }; return this._export(value).replace(RegExp('(?<!%)(%)([^%]+)\\1', 'g'), replaceParameters).replace(/%%/g, '%'); } else if (isArray(value) || isObjectLiteral(value)) { const code = []; for (const [ k, v ] of __jymfony.getEntries(value)) { code.push((isArray(value) ? '' : this._dumpValue(k, interpolate) + ': ') + this._dumpValue(v)); } return __jymfony.sprintf(isArray(value) ? '[%s]' : '{%s}', code.join(', ')); } else if (isObject(value)) { throw new RuntimeException('Unable to dump a service container if a parameter is an object'); } else if (isFunction(value)) { throw new RuntimeException('Unable to dump a service container if a parameter is a function'); } else if (null === value || undefined === value) { return this._export(value); } return value; } /** * @param {Jymfony.Component.DependencyInjection.Definition} definition * * @returns {Jymfony.Component.DependencyInjection.Definition[]} * * @private */ _getInlinedDefinitions(definition) { if (! this._inlinedDefinitions.has(definition)) { const definitions = [ ...this._getDefinitionsFromArguments(definition.getArguments()), ...this._getDefinitionsFromArguments(definition.getMethodCalls()), ...this._getDefinitionsFromArguments(definition.getShutdownCalls()), ...this._getDefinitionsFromArguments(definition.getProperties()), ...this._getDefinitionsFromArguments([ definition.getConfigurator() ]), ...this._getDefinitionsFromArguments([ definition.getFactory() ]), ]; this._inlinedDefinitions.set(definition, definitions); } return this._inlinedDefinitions.get(definition); } /** * @param {*} args * * @returns {IterableIterator<Jymfony.Component.DependencyInjection.Definition>} * * @private */ * _getDefinitionsFromArguments(args) { for (const argument of Object.values(args)) { if (argument instanceof Definition) { yield * this._getInlinedDefinitions(argument); yield argument; } else if (isArray(argument) || isObjectLiteral(argument)) { yield * this._getDefinitionsFromArguments(argument); } } } /** * Dumps a parameter. * * @param {string} name * @param {boolean} [resolveEnv = true] * * @returns {string} * * @private */ _dumpParameter(name, resolveEnv = true) { if (resolveEnv && 'env()' !== name && 'env(' === name.substr(0, 4) && ')' === name.substr(-1, 1)) { const matches = /env\((.+)\)/.exec(name); const envVarName = matches[1]; this._container.addResource(new EnvVariableResource(envVarName)); return 'this.getParameter(\"env('+envVarName+')\")'; } if (! this._container.hasParameter(name)) { return 'this.getParameter(\"'+name+'\")'; } const parameter = this._container.getParameter(name); if (parameter instanceof Reference) { throw new InvalidArgumentException(__jymfony.sprintf('You cannot dump a container with parameters that contain references to other services (reference to service "%s" found in "%s").', parameter.toString(), name)); } else if (parameter instanceof Definition) { throw new InvalidArgumentException(__jymfony.sprintf('You cannot dump a container with parameters that contain service definitions. Definition for "%s" found in "%s".', parameter.getClass(), name)); } else if (parameter instanceof Variable) { throw new InvalidArgumentException(__jymfony.sprintf('You cannot dump a container with parameters that contain variable references. Variable "%s" found in "%s".', parameter.toString(), name)); } const placeholders = {}; const resolved = this._resolveParameter(parameter, resolveEnv, placeholders); return __jymfony.strtr(this._export(resolved), placeholders); } /** * Recursively resolve parameters for dumping. * * @param {string|*} parameter * @param {boolean} resolveEnv * @param {Object.<string, string>} placeholders * * @returns {*} * * @private */ _resolveParameter(parameter, resolveEnv, placeholders) { if (isArray(parameter) || isObjectLiteral(parameter)) { for (const [ key, value ] of __jymfony.getEntries(parameter)) { parameter[this._resolveParameter(key, resolveEnv, placeholders)] = this._resolveParameter(value, resolveEnv, placeholders); } } if (! isString(parameter)) { return parameter; } return parameter.replace(/%%|%([^%\s]+)%/g, (match, p1) => { if (! p1) { return '%%'; } if (resolveEnv && 'env()' !== p1 && 'env(' === p1.substr(0, 4) && ')' === p1.substr(-1, 1)) { const matches = /env\((.+)\)/.exec(p1); const envVarName = matches[1]; const key = 'ENV__' + envVarName + '__' + ContainerBuilder.hash(envVarName); placeholders[this._doExport(key)] = 'this.getParameter(\"env('+envVarName+')\")'; return key; } if (! this._container.hasParameter(p1)) { const key = 'PARAMETER__' + p1 + '__' + ContainerBuilder.hash(p1); placeholders[this._doExport(key)] = 'this.getParameter(\"'+p1+'\")'; return key; } return this._container.getParameter(p1); }); } /** * @param {string} id * @param {Jymfony.Component.DependencyInjection.Reference} [reference] * * @returns {string} * * @private */ _getServiceCall(id, reference = undefined) { while (this._container.hasAlias(id)) { id = this._container.getAlias(id).toString(); } if ('service_container' === id) { return 'this'; } let code; if (this._container.hasDefinition(id)) { const definition = this._container.getDefinition(id); if (! definition.isSynthetic()) { if (undefined !== reference && Container.IGNORE_ON_UNINITIALIZED_REFERENCE === reference.invalidBehavior) { code = 'undefined'; if (! definition.isShared()) { return code; } } else { if (definition.hasErrors()) { this._addThrow = true; return __jymfony.sprintf('this._throw(%s)', this._export(definition.getErrors()[0])); } code = 'this.' + this._generateMethodName(id) + '()'; } if (definition.isShared()) { code = __jymfony.sprintf('(this._%s[%s] || %s)', definition.isPublic() ? 'services' : 'privates', this._dumpValue(id), code); } return code; } } if (undefined !== reference && Container.IGNORE_ON_UNINITIALIZED_REFERENCE === reference.invalidBehavior) { return 'undefined'; } if (undefined !== reference && Container.EXCEPTION_ON_INVALID_REFERENCE !== reference.invalidBehavior) { code = __jymfony.sprintf('this.get(%s, Container.NULL_ON_INVALID_REFERENCE)', this._export(id)); } else { code = __jymfony.sprintf('this.get(%s)', this._export(id)); } return __jymfony.sprintf('(this._services[%s] || %s)', this._export(id), code); } /** * @param {string} class_ * * @returns {string} * * @private */ _dumpLiteralClass(class_) { if ('"' !== class_.charAt(0)) { throw new RuntimeException('Invalid class name'); } return class_.substring(1, class_.length-1); } /** * @param {*} args * @param {Object} calls * @param {Object} behavior * * @private */ _getServiceCallsFromArguments(args, calls, behavior) { for (const argument of Object.values(args)) { if (argument instanceof Reference) { const id = argument.toString(); if (! calls[id]) { calls[id] = 0; } if (! behavior[id]) { behavior[id] = argument.invalidBehavior; } else if (Container.EXCEPTION_ON_INVALID_REFERENCE !== behavior[id]) { behavior[id] = argument.invalidBehavior; } ++calls[id]; } else if (isArray(argument) || isObjectLiteral(argument)) { this._getServiceCallsFromArguments(argument, calls, behavior); } } } /** * @param {string} id * @param {Jymfony.Component.DependencyInjection.Definition} definition * * @returns {boolean} * * @private */ _isSimpleInstance(id, definition) { for (const sDefinition of [ definition, ...this._getInlinedDefinitions(definition) ]) { if (definition !== sDefinition && ! this._hasReference(id, sDefinition.getMethodCalls()) && ! this._hasReference(id, sDefinition.getShutdownCalls())) { continue; } if (0 < sDefinition.getMethodCalls().length || 0 < Object.keys(sDefinition.getShutdownCalls()).length || 0 < Object.keys(sDefinition.getProperties()).length || sDefinition.getConfigurator()) { return false; } } return true; } /** * @param {Jymfony.Component.DependencyInjection.Definition} definition * @param {string} ret * @param {string} instantiation * * @returns {string} * * @private */ _addNewInstance(definition, ret, instantiation) { if ('Jymfony.Component.DependencyInjection.ServiceLocator' === definition.getClass() && definition.hasTag('container.service_locator')) { const args = {}; for (const [ k, argument ] of __jymfony.getEntries(definition.getArgument(0))) { args[k] = argument.values[0]; } return __jymfony.sprintf(` ${ret}%s;\n`, this._dumpValue(new ServiceLocatorArgument(args))); } let class_ = this._dumpValue(definition.getClass()); const args = Array.from(definition.getArguments().map(T => this._dumpValue(T))); if (definition.getModule()) { const [ module, property ] = definition.getModule(); if (property) { return __jymfony.sprintf(` ${ret}${instantiation}new (require(%s)[%s])(%s);\n`, this._dumpValue(module), this._dumpValue(property), args.join(', ')); } return __jymfony.sprintf(` ${ret}${instantiation}require(%s);\n`, this._dumpValue(module)); } else if (definition.getFactory()) { const callable = definition.getFactory(); if (isArray(callable)) { if (callable[0] instanceof Reference || (callable[0] instanceof Definition && this._definitionVariables.has(callable[0]))) { return __jymfony.sprintf(` ${ret}${instantiation}%s.%s(%s);\n`, this._dumpValue(callable[0]), callable[1], args.join(', ')); } class_ = this._dumpValue(callable[0]); if ('"' === class_.charAt(0)) { return __jymfony.sprintf(` ${ret}${instantiation}%s.%s(%s);\n`, this._dumpLiteralClass(class_), callable[1], args.join(', ')); } if (0 === class_.indexOf('new ')) { return __jymfony.sprintf(` ${ret}${instantiation}(%s).%s(%s);\n`, class_, callable[1], args.join(', ')); } return __jymfony.sprintf(` ${ret}${instantiation}getCallableFromArray(%s, %s)(%s);\n`, class_, this._export(callable[1]), args.join(', ')); } return __jymfony.sprintf(` ${ret}${instantiation}%s(%s);\n`, this._dumpLiteralClass(this._dumpValue(callable)), args.join(', ')); } return __jymfony.sprintf(` ${ret}${instantiation}new %s(%s);\n`, this._dumpLiteralClass(class_), args.join(', ')); } /** * @returns {string} * * @private */ _getNextVariableName() { let name = ''; let i = this._variableCount; if ('' === name) { name += firstChars[i % firstChars.length]; i = ~~(i / firstChars.length); } while (0 < i) { --i; name += nonFirstChars[i % nonFirstChars.length]; i = ~~(i / nonFirstChars.length); } ++this._variableCount; return '$' + name; } /** * @param {string} id * @param {*} args * @param {boolean} [deep = false] * @param {Set} [visited = new Set()] * * @returns {boolean} * * @private */ _hasReference(id, args, deep = false, visited = new Set()) { for (const argument of Object.values(args)) { if (argument instanceof Reference) { const argumentId = argument.toString(); if (id === argumentId) { return true; } if (deep && ! visited.has(argumentId) && 'service_container' !== argumentId) { visited.add(argumentId); const service = this._container.getDefinition(argumentId); // Todo // If (service.isLazy() && ! (this._getProxyDumper instanceof NullDumper)) args = [ ...service.getMethodCalls(), ...service.getShutdownCalls(), ...service.getArguments(), ...Object.values(service.getProperties()) ]; if (this._hasReference(id, args, deep, visited)) { return true; } } } else if (isArray(argument) || isObjectLiteral(argument)) { if (this._hasReference(id, argument, deep, visited)) { return true; } } } return false; } /** * @param {*} value * * @returns {string} * * @private */ _getServiceConditionals(value) { const conditions = []; for (const service of ContainerBuilder.getInitializedConditionals(value)) { if (! this._container.hasDefinition(service)) { return 'false'; } conditions.push(__jymfony.sprintf('undefined !== this->%s[\'%s\']', this._container.getDefinition(service).isPublic() ? 'services' : 'privates', service)); } for (const service of ContainerBuilder.getServiceConditionals(value)) { if (this._container.hasDefinition(service) && ! this._container.getDefinition(service).isPublic()) { continue; } conditions.push(__jymfony.sprintf('this.has(\'%s\')', service)); } if (0 === conditions.length) { return ''; } return conditions.join(' && '); } /** * @param {*} value * @param {string} code * * @returns {string} * * @private */ _wrapServiceConditionals(value, code) { const conditionals = this._getServiceConditionals(value); if (! conditionals.length) { return code; } code.split('\n').map(line => line ? ' ' + line : line).join('\n'); return __jymfony.sprintf(' if (%s) {\n%s }\n', conditionals, code); } }
JavaScript
class Message { constructor(id, {content, author}) { this.id = id; this.content = content; this.author = author; } }
JavaScript
class Path { /** * Returns the path to the user data directory. If the script is executed in the 'npm test' * environment (i.e., the --tmpdir argument is provided), the path to the tmp directory is * being returned. * * @return {string} The path to the user data directory. */ static home() { // Use tmp directory for testcases if (process.argv[4] === '--tmpdir') { return '/tmp/financelist'; } switch (process.platform) { case 'darwin': return join(process.env.HOME, 'Library', 'Application Support', 'FinanceList-Desktop'); case 'linux': return join(process.env.HOME, '.local', 'share', 'FinanceList-Desktop'); case 'win32': return join(process.env.APPDATA || require('os').homedir(), 'FinanceList-Desktop'); default: return join(require('os').homedir(), 'FinanceList-Desktop'); } } /** * Returns the path separator for the currently used operating system. * * @return {string} The path separator for the currently used operating system. */ static sep() { return sep; } /** * Returns the path to the storage directory. * * @return {string} The path to the storage directory. */ static getStoragePath() { return Path.home() + Path.sep() + 'storage'; } /** * Returns the path to the settings.json file. * * @return {string} The path to the settings.json file. */ static getSettingsFilePath() { return Path.getStoragePath() + Path.sep() + 'settings.json'; } /** * Creates the given path if it does not exist yet. * * @param {string} newPath The path which should be created. */ static createPath(newPath) { let {existsSync, mkdirSync} = require('fs'); let toBeCreated = (require('os').platform() === 'win32') ? '' : '/'; newPath.split(Path.sep()).forEach(folder => { if (folder.length) { toBeCreated += (folder + Path.sep()); if (!existsSync(toBeCreated)) { mkdirSync(toBeCreated); } } }); } /** * Moves all json files from a source directory to a target directory. * * @param {string} from The source directory. * @param {string} to The target directory. * @param {Storage} storage Storage object to access the storage. * @param {function} callback Callback function which takes one boolean parameter * that indicates whether the operation succeeded or not (true = success). */ static moveJsonFiles(from, to, storage, callback) { let {readdirSync, renameSync} = require('fs'); let users = storage.readPreference('users'); for (let file of readdirSync(from)) { if (file !== 'settings.json' && (file.endsWith('.json') || users.includes(file))) { try { renameSync(from + Path.sep() + file, to + Path.sep() + file); } catch (err) { // Cross-device linking will cause an error. callback(false); break; } } } callback(true); } /** * Returns all json files in a given directory. * * @param {string} dir The directory which contents we want to read. * @return {array} An array containing the names of all json files in the given directory. */ static listJsonFiles(dir) { let {readdirSync} = require('fs'); return readdirSync(dir).filter(file => file.endsWith('.json')); } }
JavaScript
class ErrorBoundary extends Component { // Constructor constructor(props) { super(props); this.state = { error: null }; } static getDerivedStateFromError = error => { return { error }; }; // Capture error componentDidCatch(error) { this.setState({error: error}) } // Render render() { const { error } = this.state; if (this.state.error) { return ( <Container className='Container'> <div className='Error'> <img src={imageError} alt="error" /> <h1>{this.props.t('An uncontrolled error has been detected in the application.')}</h1> <h2>{this.props.t('Please, reload page. Or contact the admin.')}</h2> <p>{error.message}</p> </div> </Container> ); } return this.props.children; } }
JavaScript
class Home extends Component { state = { language: "en", speedPatricles: 0.1, }; componentDidMount() { let itemLocal = localStorage.getItem("i18nextLng"); if (itemLocal) { this.setState({ language: itemLocal }); i18next.changeLanguage(itemLocal); } if (!itemLocal) { i18next.changeLanguage("en"); } this.partialInitial(); } partialInitial = () => { Particles.init({ selector: ".backgroundEffect", maxParticles: 70, color: "red", sizeVariations: 5, speed: 0.1, }); }; componentDidUpdate(prevProps, prevState) { let { language } = this.state; prevState.language !== this.state.language && localStorage.setItem("i18nextLng", language); } changeLanguageHandler(lang) { this.setState({ language: lang }); i18next.changeLanguage(lang); } render() { let { t } = this.props; let { language } = this.state; return ( <> <div className="wrapperEffectsHome"> <RadioToggleLanguage onChangeLanguageHandler={this.changeLanguageHandler.bind(this)} currentLanguage={language} /> <canvas className="backgroundEffect"></canvas> </div> <main> <ul className="menuHome"> <NavLink to={routes.about}> <li data-hover={t("Presentation.10")} className="title AboutPortfolio button" > <span className="hiddenText">{t("Presentation.1")}</span> </li> </NavLink> <NavLink to={routes.work}> <li data-hover={t("Presentation.21")} className="title worksPortfolio button works" > <span className="hiddenText worksHidden"> {t("Presentation.2")} </span> </li> </NavLink> <NavLink to={routes.contact}> <li data-hover={t("Presentation.32")} className="title contactPortfolio button" > <span className="hiddenText">{t("Presentation.3")}</span> </li> </NavLink> </ul> </main> </> ); } }
JavaScript
class GatewayVisitor extends CollectingVisitor { /** * Constructs the {@link GatewayVisitor} object with a web3 instance * connected to an Ethereum node and a Gateway smart contract instance not * connected to any address * @param {Web3} web3 a web3 instance connected to an Ethereum node * @param {Gateway} gateway a gateway instance not connected to any address */ constructor(web3, gateway) { super(); /** @private */ this.web3 = web3; /** @private */ this.gateway = gateway; } /** * Updates a single Gateway. Gateway must conform to Gateway interface defined * in {@link FincontractMarketplace} * @throws {Error} If address is `0x0` * @param {String} address - 32-byte address of a Gateway to be updated * @param {String} type - type of a Gateway: `If` or `ScaleObs` for * logging purposes * @return {Promise<null,Error>} - promise which resolve to nothing if * the Gateway was correctly update or rejects with an Error if the address * was `0x0` */ updateGateway(address, type) { if (!parseInt(address, 16)) { throw new Error(`Gateway's address was 0x0`); } const gw = this.gateway.at(address); return new Sender(gw, this.web3) .send('update', []) .watch({block: 'latest'}, () => { log.info(`Finished updating ${type} gateway at: ${short(address)}`); }); } /** * Called during preorder traversal when processing {@link FincIfNode}. * Updates the current node's Gateway and returns a Promise list * to the parent node. * @override * @param {FincNode} node - node currently being processed * @param {Array<Promise>} left - an Array of Promises containing * Gateway updates from processing left child (first subtree) * of the current node * @param {Array<Promise>} right - an Array of Promises containing * Gateway updates from processing right child (second subtree) * of the current node * @return {Array} an Array of Promises containing the Promise that updates * Gateway of the current node concatenated with the Promise lists of its * children */ processIfNode(node, left, right) { const self = this.updateGateway(node.gatewayAddress, 'If'); return [...left, ...right, self]; } /** * Called during preorder traversal when processing {@link FincScaleObsNode}. * Updates the current node's Gateway and returns a Promise list * to the parent node. * @override * @param {FincNode} node - node currently being processed * @param {Array<Promise>} child - an Array of Promises containing * Gateway updates from processing its only child (its subtree) * @return {Array} an Array of Promises containing the Promise that updates * Gateway of the current node concatenated with the Promise list of its * child */ processScaleObsNode(node, child) { const self = this.updateGateway(node.gatewayAddress, 'ScaleObs'); return [...child, self]; } }
JavaScript
class GatewayUpdater { /** * Constructs the {@link GatewayUpdater} object with a web3 instance * connected to an Ethereum node and a Gateway smart contract instance not * connected to any address * @param {Web3} web3 a web3 instance connected to an Ethereum node * @param {Gateway} gateway a gateway instance not connected to any address */ constructor(web3, gateway) { /** @private */ this.gv = new GatewayVisitor(web3, gateway); } /** * @param {FincNode} node - {@link FincNode} description tree * @return {Promise<null,Error>} promise that resolves to nothing if all * Gateways were correctly updated or rejects with an Error */ updateAllGateways(node) { return Promise.all(this.gv.visit(node)); } }
JavaScript
class Loader { /** * @param {import('../Kong')} client */ constructor (client) { this.client = client this.critical = false } /** * @returns {Loader} * @abstract */ load () {} }
JavaScript
class BridgeIO extends SignalingAPI { /** * @private */ constructor (options, n2n) { super(options) this.parent = n2n this._debug = debug('n2n:bridge:io') this.on(events.signaling.RECEIVE_OFFER, ({ jobId, initiator, destination, forward, offerType, offer }) => { if (!initiator || !destination || !offer || !offerType) throw new Error('PLEASE REPORT, Problem with the offline signaling service. provide at least initiator, destination, type a,d the offer as properties in the object received') // do we have the initiator in our list of connections? if (!this.parent.pendingInview.has(initiator) && offerType === 'new') { // we do have the socket for the moment, create it this.parent.createNewSocket(this.parent.options.socket, initiator, false) // ATTENTION: LISTENERS HAVE TO BE DECLARED ONCE! this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER, (socketOffer) => { this.sendOfferBack({ jobId, initiator, destination, forward, offer: socketOffer, offerType: 'back' }) }) this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER_RENEGOCIATE, (socketOffer) => { const off = { jobId, initiator, destination, offer: socketOffer, offerType: 'back' } this.parent.signaling.direct.sendOfferBackRenegociate(off) }) // WE RECEIVE THE OFFER ON THE ACCEPTOR this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else { // now if it is a new offer, give it to initiator socket, otherwise to destination socket if (offerType === 'new') { // check if it is in pending or living if (this.parent.pendingInview.has(initiator)) { this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingInview.has(initiator)) { this.parent.livingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } } else if (offerType === 'back') { // check if it is in pending or living if (this.parent.pendingOutview.has(destination)) { this.parent.pendingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingOutview.has(destination)) { this.parent.livingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } } } }) } /** * @description Connect.Just connect, oh wait? (-_-) * @param {Object} options options for the connection if needed * @return {Promise} Promise resolved when the connection succeeded * @private */ async connect (options) {} /** * Send an offer to the forwarding peer * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async sendOfferTo (offer) { offer.type = events.n2n.bridgeIO.BRIDGE_FORWARD this._debug('[%s] send to forwarding peer: %s', this.parent.id, offer.forward) // send the message on the outview link this.parent.send(this.parent.options.n2n.protocol, offer.forward, offer, true) } /** * Send back an accepted offer to the forwarding peer * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async sendOfferBack (offer) { offer.type = events.n2n.bridgeIO.BRIDGE_FORWARD_BACK this._debug('[%s] send back the offer to the forwarding peer: %s', this.parent.id, offer.forward, offer) // always send back on an inview link this.parent.send(this.parent.options.n2n.protocol, offer.forward, offer, false) } /** * Forward an offer to the peer that will accept the offer * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async forward (offer) { offer.type = events.n2n.bridgeIO.BRIDGE_FORWARD_RESPONSE this._debug('[%s] forwarding to %s', this.parent.id, offer.destination, offer, offer.outview) // always forward on an outview link this.parent.send(this.parent.options.n2n.protocol, offer.destination, offer, true) } /** * Forward back an accepted offer to the peer that initiate the connection * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async forwardBack (offer) { offer.type = events.n2n.bridgeIO.BRIDGE_FORWARD_RESPONSE this._debug('[%s] forwarding back to %s', this.parent.id, offer.initiator, offer, offer.outview) // forward back the message on an (inview/outview) link, it depends on the argument this.parent.send(this.parent.options.n2n.protocol, offer.initiator, offer, false) } /** * Perform a bridge without locking any connection, this is your responsability to lock connections correctly. * From (inview) to dest (outview) * @param {String} from peer id (initiator) * @param {String} dest peer id (destination) * @param {Number} [timeout=this.parent.options.n2n.timeout] time to wait before rejecting. * @return {Promise} * @private */ async bridge (from, dest, timeout = this.parent.options.n2n.timeout) { return new Promise((resolve, reject) => { if (this.parent.livingInview.has(from) && this.parent.livingOutview.has(dest)) { const jobId = translator.new() const tout = setTimeout(() => { reject(new Error('timeout')) }, timeout) this.parent.events.once(jobId, (msg) => { clearTimeout(tout) if (msg.response) { resolve() } else { reject(new Error('bridge rejected.')) } }) this.parent.send(this.parent.options.n2n.protocol, from, { type: events.n2n.bridgeIO.BRIDGE, from, dest, forward: this.parent.id, jobId }, false).catch(e => { reject(e) }) } else { reject(new Error(`[${this.parent.id}/bridgeOO] from need to be in our inview and dest in our outview`)) } }) } /** * On bridge request init the exchange of offer. by creating the new socket and starting the creation of offers. * @param {String} id peer id that send the request * @param {String} from initiator (us) * @param {String} dest destination (the new peer we will be connected) * @param {String} forward peer id who send the request * @param {String} jobId id of the job * @return {void} * @private */ _bridge (id, { from, dest, forward, jobId }) { const sendResponse = (response) => { this.parent.send(this.parent.options.n2n.protocol, forward, { type: events.n2n.RESPONSE, response: true, jobId }).catch(e => { console.error('cannot send response', e) }) } if (this.parent.livingOutview.has(dest)) { this.parent.increaseOccurences(dest, true).then(() => { sendResponse(true) }).catch(e => { console.error('cannot increase occurences', e) }) } else if (!this.parent.livingOutview.has(dest) && !this.parent.pendingOutview.has(dest)) { new Promise((resolve, reject) => { const tout = setTimeout(() => { reject(new Error('timeout')) }, this.parent.options.n2n.timeout) const socket = this.parent.createNewSocket(this.parent.options.socket, dest, true) socket.on('error', (error) => { this.parent._manageError(error, dest, true, reject, 'bridgeIO') }) socket.on(events.socket.EMIT_OFFER, (offer) => { const off = { jobId, initiator: this.parent.id, destination: dest, forward, offer, offerType: 'new' } this.parent.signaling.bridgeIO.sendOfferTo(off) }) socket.connect().then(() => { clearTimeout(tout) resolve() }).catch(e => { clearTimeout(tout) reject(e) }) }).then(() => { sendResponse(true) }).catch(e => { sendResponse(false) }) } else if (!this.parent.livingOutview.has(dest) && this.parent.pendingOutview.has(dest)) { const tout = setTimeout(() => { sendResponse(false, `pending connection has never been connected. (from: ${from}, dest:${dest} forward: ${forward})`) }, this.parent.options.n2n.timeout) this.parent.pendingOutview.get(dest).socket.once('connect', () => { clearTimeout(tout) this.parent.connectFromUs(dest).then(() => { sendResponse(true) }).catch(e => { sendResponse(false, e.message) }) }) } else { sendResponse(false) } } } // not implemented for the moment
JavaScript
class BridgeOI extends SignalingAPI { /** * @private */ constructor (options, n2n) { super(options) this.parent = n2n this._debug = debug('n2n:bridge:oi') this.on(events.signaling.RECEIVE_OFFER, ({ jobId, initiator, destination, forward, offerType, offer }) => { if (!initiator || !destination || !offer || !offerType) throw new Error('PLEASE REPORT, Problem with the offline signaling service. provide at least initiator, destination, type a,d the offer as properties in the object received') // do we have the initiator in our list of connections? if (!this.parent.pendingInview.has(initiator) && offerType === 'new') { // we do have the socket for the moment, create it this.parent.createNewSocket(this.parent.options.socket, initiator, false) // ATTENTION: LISTENERS HAVE TO BE DECLARED ONCE! this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER, (socketOffer) => { this.sendOfferBack({ jobId, initiator, destination, forward, offer: socketOffer, offerType: 'back' }) }) this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER_RENEGOCIATE, (socketOffer) => { const off = { jobId, initiator, destination, offer: socketOffer, offerType: 'back' } this.parent.signaling.direct.sendOfferBackRenegociate(off) }) // WE RECEIVE THE OFFER ON THE ACCEPTOR this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else { // now if it is a new offer, give it to initiator socket, otherwise to destination socket if (offerType === 'new') { // check if it is in pending or living if (this.parent.pendingInview.has(initiator)) { this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingInview.has(initiator)) { this.parent.livingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } } else if (offerType === 'back') { // check if it is in pending or living if (this.parent.pendingOutview.has(destination)) { this.parent.pendingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingOutview.has(destination)) { this.parent.livingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } } } }) } /** * @description Connect.Just connect, oh wait? (-_-) * @param {Object} options options for the connection if needed * @return {Promise} Promise resolved when the connection succeeded * @private */ async connect (options) {} /** * Send an offer to the forwarding peer * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async sendOfferTo (offer) { offer.type = events.n2n.bridgeOI.BRIDGE_FORWARD this._debug('[%s] send to forwarding peer: %s', this.parent.id, offer.forward) // send the message on an (inview/outview) link, it depends on the argument this.parent.send(this.parent.options.n2n.protocol, offer.forward, offer, false) } /** * Send back an accepted offer to the forwarding peer * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async sendOfferBack (offer) { offer.type = events.n2n.bridgeOI.BRIDGE_FORWARD_BACK this._debug('[%s] send back the offer to the forwarding peer: %s', this.parent.id, offer.forward, offer) // always send back on an inview link this.parent.send(this.parent.options.n2n.protocol, offer.forward, offer, true) } /** * Forward an offer to the peer that will accept the offer * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async forward (offer) { offer.type = events.n2n.bridgeOI.BRIDGE_FORWARD_RESPONSE this._debug('[%s] forwarding to %s', this.parent.id, offer.destination, offer) // always forward on an outview link this.parent.send(this.parent.options.n2n.protocol, offer.destination, offer, false) } /** * Forward back an accepted offer to the peer that initiate the connection * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async forwardBack (offer) { offer.type = events.n2n.bridgeOI.BRIDGE_FORWARD_RESPONSE this._debug('[%s] forwarding back to %s', this.parent.id, offer.initiator, offer) // forward back the message on an (inview/outview) link, it depends on the argument this.parent.send(this.parent.options.n2n.protocol, offer.initiator, offer, true) } /** * Perform a bridge without locking any connection, this is your responsability to lock connections correctly. * From (outview) to dest (inview) * @param {String} from peer id (initiator) * @param {String} dest peer id (destination) * @param {Number} [timeout=this.parent.options.n2n.timeout] time to wait before rejecting. * @return {Promise} * @private */ async bridge (from, dest, timeout = this.parent.options.n2n.timeout) { return new Promise((resolve, reject) => { if (this.parent.livingOutview.has(from) && this.parent.livingInview.has(dest)) { const jobId = translator.new() const tout = setTimeout(() => { reject(new Error('timeout')) }, timeout) this.parent.events.once(jobId, (msg) => { clearTimeout(tout) if (msg.response) { resolve() } else { reject(new Error('bridge rejected.')) } }) this.parent.send(this.parent.options.n2n.protocol, from, { type: events.n2n.bridgeOI.BRIDGE, from, dest, forward: this.parent.id, jobId }, true).catch(e => { reject(e) }) } else if (!this.parent.livingOutview.has(dest)) { reject(new Error(`[${this.parent.id}/bridgeOO] from need to be in our outview and dest in our inview`)) } }) } /** * @private */ _bridge (id, { from, dest, forward, jobId }) { const sendResponse = (response) => { this.parent.send(this.parent.options.n2n.protocol, forward, { type: events.n2n.RESPONSE, response, jobId }, false).catch(e => { console.error('cannot send response', e) }) } if (this.parent.livingOutview.has(dest)) { this.parent.increaseOccurences(dest, true).then(() => { sendResponse(true) }).catch(e => { console.error('cannot increase occurences', e) sendResponse(false) }) } else if (!this.parent.livingOutview.has(dest) && !this.parent.pendingOutview.has(dest)) { new Promise((resolve, reject) => { const tout = setTimeout(() => { reject(new Error('timeout')) }, this.parent.options.n2n.timeout) const socket = this.parent.createNewSocket(this.parent.options.socket, dest, true) socket.on('error', (error) => { this.parent._manageError(error, dest, true, reject, 'bridgeOI') }) socket.on(events.socket.EMIT_OFFER, (offer) => { const off = { initiator: this.parent.id, destination: dest, forward, offer, jobId, offerType: 'new' } this.sendOfferTo(off) }) socket.connect().then(() => { clearTimeout(tout) resolve() }).catch(e => { clearTimeout(tout) reject(e) }) }).then(() => { sendResponse(true) }).catch(e => { sendResponse(false) }) } else if (!this.parent.livingOutview.has(dest) && this.parent.pendingOutview.has(dest)) { const tout = setTimeout(() => { sendResponse(false, `pending connection has never been connected. (from: ${from}, dest:${dest} forward: ${forward})`) }, this.parent.options.n2n.timeout) this.parent.pendingOutview.get(dest).socket.once('connect', () => { clearTimeout(tout) this.parent.connectFromUs(dest).then(() => { sendResponse(true) }).catch(e => { sendResponse(false, e.message) }) }) } else { sendResponse(false) } } } // not implemented for the moment
JavaScript
class BridgeOO extends SignalingAPI { /** * @private */ constructor (options, n2n) { super(options) this.parent = n2n this._debug = debug('n2n:bridge:oo') this.on(events.signaling.RECEIVE_OFFER, ({ jobId, initiator, destination, forward, offerType, offer }) => { if (!initiator || !destination || !offer || !offerType || !jobId || !forward) throw new Error('PLEASE REPORT, Problem with the offline signaling service. provide at least jobId, initiator, destination, forward, offerType, offer') // do we have the initiator in our list of connections? if (!this.parent.pendingInview.has(initiator) && offerType === 'new') { // we do have the socket for the moment, create it this.parent.createNewSocket(this.parent.options.socket, initiator, false) // ATTENTION: LISTENERS HAVE TO BE DECLARED ONCE! this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER, (socketOffer) => { this.sendOfferBack({ jobId, initiator, destination, forward, offer: socketOffer, offerType: 'back' }) }) this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER_RENEGOCIATE, (socketOffer) => { const off = { jobId, initiator, destination, offer: socketOffer, offerType: 'back' } this.parent.signaling.direct.sendOfferBackRenegociate(off) }) // WE RECEIVE THE OFFER ON THE ACCEPTOR this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else { // now if it is a new offer, give it to initiator socket, otherwise to destination socket if (offerType === 'new') { // check if it is in pending or living if (this.parent.pendingInview.has(initiator)) { this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingInview.has(initiator)) { this.parent.livingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } } else if (offerType === 'back') { // check if it is in pending or living if (this.parent.pendingOutview.has(destination)) { this.parent.pendingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingOutview.has(destination)) { this.parent.livingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } } } }) } /** * @description Connect.Just connect, oh wait? (-_-) * @param {Object} options options for the connection if needed * @return {Promise} Promise resolved when the connection succeeded * @private */ async connect (options) {} /** * Send an offer to the forwarding peer * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async sendOfferTo (offer) { offer.type = events.n2n.bridgeOO.BRIDGE_FORWARD this._debug('[%s] send to forwarding peer: %s', this.parent.id, offer.forward) // send the message on an (inview/outview) link, it depends on the argument this.parent.send(this.parent.options.n2n.protocol, offer.forward, offer, false) } /** * Send back an accepted offer to the forwarding peer * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async sendOfferBack (offer) { offer.type = events.n2n.bridgeOO.BRIDGE_FORWARD_BACK this._debug('[%s] send back the offer to the forwarding peer: %s', this.parent.id, offer.forward, offer) // always send back on an inview link this.parent.send(this.parent.options.n2n.protocol, offer.forward, offer, false) } /** * Forward an offer to the peer that will accept the offer * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async forward (offer) { offer.type = events.n2n.bridgeOO.BRIDGE_FORWARD_RESPONSE this._debug('[%s] forwarding to %s', this.parent.id, offer.destination, offer) // always forward on an outview link this.parent.send(this.parent.options.n2n.protocol, offer.destination, offer, true) } /** * Forward back an accepted offer to the peer that initiate the connection * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async forwardBack (offer) { offer.type = events.n2n.bridgeOO.BRIDGE_FORWARD_RESPONSE this._debug('[%s] forwarding back to %s', this.parent.id, offer.initiator, offer) // forward back the message on an (inview/outview) link, it depends on the argument this.parent.send(this.parent.options.n2n.protocol, offer.initiator, offer, true) } /** * Perform a bridge without locking any connection, this is your responsability to lock connections correctly. * From (outview) to dest (outview) * @param {String} from peer id (initiator) * @param {String} dest peer id (destination) * @param {Number} [timeout=this.parent.options.n2n.timeout] time to wait before rejecting. * @return {Promise} * @private */ async bridge (from, dest, timeout = this.parent.options.n2n.timeout) { return new Promise((resolve, reject) => { if (!this.parent.livingOutview.has(from)) { reject(new Error(`[${this.parent.id}/bridgeOO] peerId is not in our outview: ${from}`)) } else if (!this.parent.livingOutview.has(dest)) { reject(new Error(`[${this.parent.id}/bridgeOO] peerId is not in our outview: ${dest}`)) } else { const jobId = translator.new() const tout = setTimeout(() => { reject(new Error(`[${this.parent.id}/bridge00] (jobId=${jobId}) connection timeout(${timeout} (ms)) from ${from} to ${dest}`)) }, timeout) this._debug(`[${this.parent.id}/bridge00] waiting response for jobId:${jobId} `) this.parent.events.once(jobId, (msg) => { clearTimeout(tout) this._debug(`[${this.parent.id}/bridge00] receive response for jobId:${jobId} `) if (msg.response) { resolve() } else { reject(new Error('bridge rejected. Reason: ' + msg.reason)) } }) this.parent.send(this.parent.options.n2n.protocol, from, { type: events.n2n.bridgeOO.BRIDGE, from, dest, forward: this.parent.id, jobId }, true).catch(e => { console.error('cannot send a bridge request to ' + from, e) clearTimeout(tout) reject(e) }) } }) } /** * @private */ _bridge (id, { from, dest, forward, jobId }) { const sendResponse = (response, reason = 'none') => { this.parent.send(this.parent.options.n2n.protocol, forward, { type: events.n2n.RESPONSE, response, reason, jobId }, false).then(() => { this._debug(`[${this.parent.id}] response sent for jobId=${jobId}`) }).catch(e => { console.error(`[${this.parent.id}] cannot send response for jobId=${jobId} to id=${forward}`, e) }) } if (this.parent.livingOutview.has(dest)) { this.parent.increaseOccurences(dest, true).then(() => { sendResponse(true) }).catch(e => { console.error('cannot increase occurences', e) sendResponse(false, e.message) }) } else if (!this.parent.livingOutview.has(dest) && !this.parent.pendingOutview.has(dest)) { const p = () => new Promise((resolve, reject) => { let connected = false const tout = setTimeout(() => { if (connected) console.error(new Error('[_bridgeOO] timeout' + connected)) reject(new Error('[_bridgeOO] timeout' + connected)) }, this.parent.options.n2n.timeout) const socket = this.parent.createNewSocket(this.parent.options.socket, dest, true) socket.on('error', (error) => { this.parent._manageError(error, dest, true, reject, 'bridgeOO') }) socket.on(events.socket.EMIT_OFFER, (offer) => { const off = { jobId, initiator: this.parent.id, destination: dest, forward, offer, offerType: 'new' } this.sendOfferTo(off) }) socket.connect().then(() => { clearTimeout(tout) resolve() }).catch(e => { clearTimeout(tout) reject(e) }) }) p().then(() => { sendResponse(true) }).catch(e => { sendResponse(false, e.message) }) } else { const tout = setTimeout(() => { sendResponse(false, `pending connection has never been connected. (from: ${from}, dest:${dest} forward: ${forward})`) }, this.parent.options.n2n.timeout) this.parent.pendingOutview.get(dest).socket.once('connect', () => { clearTimeout(tout) this.parent.connectFromUs(dest).then(() => { sendResponse(true) }).catch(e => { sendResponse(false, e.message) }) }) } } } // not implemented for the moment
JavaScript
class DirectSignaling extends SignalingAPI { /** * @private */ constructor (options, n2n) { super(options) this.parent = n2n this._debug = debug('n2n:direct') this.on(events.signaling.RECEIVE_OFFER, ({ jobId, initiator, destination, offerType, offer }) => { this._debug('[%s][%s] receive an offer from %s: ', this.parent.id, jobId, initiator, offer) if (!initiator || !destination || !offer || !offerType) throw new Error('PLEASE REPORT, Problem with the offline signaling service. provide at least initiator, destination, type a,d the offer as properties in the object received') // do we have the initiator in our list of connections? if (!this.parent.pendingInview.has(initiator) && offerType === 'new') { // we do have the socket for the moment, create it this.parent.createNewSocket(this.parent.options.socket, initiator, false) // ATTENTION: LISTENERS HAVE TO BE DECLARED ONCE! this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER, (socketOffer) => { const off = { jobId, initiator, destination, offer: socketOffer, offerType: 'back' } this.sendOfferBack(off) }) this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER_RENEGOCIATE, (socketOffer) => { const off = { jobId, initiator, destination, offer: socketOffer, offerType: 'back' } this.sendOfferBackRenegociate(off) }) // WE RECEIVE THE OFFER ON THE ACCEPTOR this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else { // now if it is a new offer, give it to initiator socket, otherwise to destination socket if (offerType === 'new') { // check if it is in pending or living if (this.parent.pendingInview.has(initiator)) { this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingInview.has(initiator)) { this.parent.livingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } } else if (offerType === 'back') { // check if it is in pending or living if (this.parent.pendingOutview.has(destination)) { this.parent.pendingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingOutview.has(destination)) { this.parent.livingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } } } }) } /** * @description Connect.Just connect, oh wait? (-_-) * @param {Object} options options for the connection if needed * @return {Promise} Promise resolved when the connection succeeded * @private */ async connect (options) {} /** * Send an offer to the forwarding peer * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async sendOfferTo (offer) { offer.type = events.n2n.DIRECT_TO this.parent.send(this.parent.options.n2n.protocol, offer.destination, offer, false).then(() => { this._debug('[%s] send to direct peer: %s', this.parent.id, offer.destination, offer) }).catch(e => { console.error('[%s] send to direct, error', this.parent.id, e) }) } /** * Send back an accepted offer to the forwarding peer * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async sendOfferBack (offer) { offer.type = events.n2n.DIRECT_BACK this._debug('[%s] send back the offer to the direct peer: %s', this.parent.id, offer.initiator, offer) this.parent.send(this.parent.options.n2n.protocol, offer.initiator, offer).catch(e => { console.error('[%s] send back to direct, error', this.parent.id, e) }) } /** * Send back an accepted offer to the forwarding peer (for renegociate ) * @param {Object} offer the offer to send * @return {Promise} Promise resolved when the offer has been sent * @private */ async sendOfferBackRenegociate (offer) { offer.type = events.n2n.DIRECT_BACK this._debug('[%s][RENEGOCIATE]send back the offer to the direct peer: %s', this.parent.id, offer.initiator, offer) this.parent.send(this.parent.options.n2n.protocol, offer.initiator, offer, false).catch(e => { console.error('[%s] send back to direct, error', this.parent.id, e) }) } /** * Ask to the peer identified by peerId to establish a connection with us. It add an arc from its outview to our inview. * To not lock the connection forever the function will timeout after the timeout specified in the function (also in options) * So if the connection timed out and the connection is well established. * Good to luck to find a way to solve your problem. (set a bigger timeout (-_-)) * @param {String} peerId id of the peer that will establish the connection * @param {Number} [timeout=this.parent.options.n2n.timeout] timeout before time out the connection * @param {Boolean} [outview=true] if true try in to ask in the outview, if false try to send the message on the inview * @return {Promise} Resolve when the connection is successfully established. Reject otherwise, error or timeout, or peer not found. * @private */ async connectToUs (peerId, timeout = this.parent.options.n2n.timeout, outview = true) { if ((!this.parent.livingOutview.has(peerId) && outview) || (!this.parent.livingInview.has(peerId) && !outview)) { throw errors.peerNotFound(peerId) } else { return new Promise((resolve, reject) => { // first send a message to peerId const jobId = translator.new() const tout = setTimeout(() => { const e = new Error(`timed out (${timeout} (ms)) jobId= ${jobId}. Cannot establish a connection between us and ${peerId}`) reject(e) }, timeout) // always put two second to handle a maximum of 2s of delay minimum... this.parent.events.once(jobId, (msg) => { if (msg.response) { clearTimeout(tout) resolve() } else { clearTimeout(tout) // means no reject(new Error('Connection could be established. Something wrong happened. Reason: ' + msg.reason)) } }) this.parent.send(this.parent.options.n2n.protocol, peerId, { type: events.n2n.CONNECT_TO_US, jobId, outview, id: this.parent.id }, outview).then(() => { this._debug('[%s][%s] connectToUs message sent to %s to connect to US..', this.parent.id, jobId, peerId) }).catch(e => { clearTimeout(tout) reject(e) }) }) } } /** * @private */ async _connectToUs ({ id, jobId, outview }) { this._debug('[%s][%s][_connectToUs] receive a connectToUs order from %s...', this.parent.id, jobId, id) const peerId = id const sendResponse = (response, reason) => { // send back the response on the inview, because the message comes from the inview... this.parent.send(this.parent.options.n2n.protocol, peerId, { type: events.n2n.RESPONSE, response, reason, jobId }, !outview).then(() => { this._debug('[%s][%s][_connectToUs] send response to %s :', this.parent.id, jobId, id, response, outview) }).catch(e => { this._debug('[%s][%s][_connectToUs] cannot send response to %s :', this.parent.id, jobId, id, response, outview) }) } const p = () => new Promise((resolve, reject) => { if (!this.parent.livingOutview.has(peerId) && this.parent.livingInview.has(peerId) && !this.parent.pendingOutview.has(peerId)) { // we need to create the connection by exchanging offer between the two peers const tout = setTimeout(() => { reject(new Error(`[${this.parent.id}][${jobId}][to=${id}] timeout`)) }, this.parent.options.n2n.timeout) const socket = this.parent.createNewSocket(this.parent.options.socket, peerId, true) socket.on('error', (error) => { this.parent._manageError(error, peerId, true, reject, 'direct') }) socket.on(events.socket.EMIT_OFFER, (offer) => { const off = { jobId, initiator: this.parent.id, destination: peerId, offer, offerType: 'new' } this.sendOfferTo(off) }) socket.connect().then(() => { clearTimeout(tout) resolve() }).catch(e => { clearTimeout(tout) reject(e) }) } else if (this.parent.livingOutview.has(peerId) && this.parent.livingInview.has(peerId)) { this._debug('[%s][%s][_connectToUs] the peer is in our outview so, just increase occurences %s...', this.parent.id, jobId, id) this.parent.connectFromUs(peerId).then(() => { this._debug('[%s][%s][_connectToUs] Increase occurences has been done ...', this.parent.id, jobId, id) resolve() }).catch(e => { this._debug('[%s][%s][_connectToUs] Increase occurences has crashed ...', this.parent.id, jobId, id) reject(e) }) } else if (!this.parent.livingOutview.has(peerId) && this.parent.livingInview.has(peerId) && this.parent.pendingOutview.has(peerId)) { const tout = setTimeout(() => { reject(new Error('pending connection has never been connected.')) }, this.parent.options.n2n.timeout) this.parent.pendingOutview.get(peerId).socket.once('connect', () => { clearTimeout(tout) this.parent.connectFromUs(peerId).then(() => { this._debug('[%s][%s][_connectToUs/afterpending] Increase occurences has been done ...', this.parent.id, jobId, id) resolve() }).catch(e => { this._debug('[%s][%s][_connectToUs/afterpending] Increase occurences has crashed ...', this.parent.id, jobId, id) reject(e) }) }) } else if (!outview && this.parent.livingOutview.has(peerId) && !this.parent.livingInview.has(peerId)) { this._debug('[%s][%s][_connectToUs] the peer is in our outview so, just increase occurences %s...', this.parent.id, jobId, id) this.parent.connectFromUs(peerId).then(() => { this._debug('[%s][%s][_connectToUs] Increase occurences has been done ...', this.parent.id, jobId, id) resolve() }).catch(e => { this._debug('[%s][%s][_connectToUs] Increase occurences has crashed ...', this.parent.id, jobId, id) reject(e) }) } else { reject(new Error('ConnectToUs errored, case not handled.')) } }) p().then(() => { sendResponse(true) }).catch(e => { this._debug('[%s][%s][_connectToUs] is errored %s...', this.parent.id, jobId, id, e) sendResponse(false, e.message) }) } } // not implemented for the moment
JavaScript
class OfflineSignaling extends SignalingAPI { /** * @private */ constructor (options, n2n) { super(options) this._debug = (__webpack_require__(/*! debug */ "./node_modules/debug/src/browser.js"))('n2n:offline') this.parent = n2n this.on(events.signaling.RECEIVE_OFFER, ({ jobId, initiator, destination, type, offer }) => { // do we have the initiator in our list of connections? this._debug('[%s] receive an offline offer ', this.parent.id, { jobId, initiator, destination, type, offer }) if (!this.parent.pendingInview.has(initiator) && type === 'new') { // we do have the socket for the moment, create it this.parent.createNewSocket(this.parent.options.socket, initiator, false) this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER, (socketOffer) => { const off = { jobId, initiator, destination, offer: socketOffer, type: 'back' } this.sendOffer(off) }) this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER_RENEGOCIATE, (socketOffer) => { const off = { jobId, initiator, destination, offer: socketOffer, offerType: 'back' } this.parent.signaling.direct.sendOfferBackRenegociate(off) }) // WE RECEIVE THE OFFER ON THE ACCEPTOR this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else { // now if it is a new offer, give it to initiator socket, otherwise to destination socket if (type === 'new') { // check if it is in pending or living if (this.parent.pendingInview.has(initiator)) { this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingInview.has(initiator)) { this.parent.livingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } } else if (type === 'back') { // check if it is in pending or living if (this.parent.pendingOutview.has(destination)) { this.parent.pendingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingOutview.has(destination)) { this.parent.livingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } } } }) } /** * Just connect. * @return {Promise} * @private */ async connect () { this.emit('connect') } /** * @param {Object} offer Object containing offers * @return {void} * @private */ sendOffer (offer) { this.emit(events.signaling.EMIT_OFFER, offer) } }
JavaScript
class OnlineSignaling extends SignalingAPI { /** * @private */ constructor (options, n2n) { super(options) this.parent = n2n this.on(events.signaling.RECEIVE_OFFER, ({ jobId, initiator, destination, type, offer }) => { if (!initiator || !destination || !offer || !type) throw new Error('PLEASE REPORT, Problem with the signaling service. provide at least initiator, destination, type and the offer as properties in the object received') if (!this.parent.livingInview.has(initiator) && !this.parent.pendingInview.has(initiator) && type === 'new') { // we do have the socket for the moment, create it this.parent.createNewSocket(this.parent.options.socket, initiator, false) // ATTENTION: LISTENERS HAVE TO BE DECLARED ONCE! this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER, (socketOffer) => { this.sendOffer({ initiator, destination, offer: socketOffer, type: 'back' }) }) this.parent.pendingInview.get(initiator).socket.on(events.socket.EMIT_OFFER_RENEGOCIATE, (socketOffer) => { // console.log('[bridge] receive a negociate offer') const off = { jobId, initiator, destination, offer: socketOffer, offerType: 'back' } this.parent.signaling.direct.sendOfferBackRenegociate(off) }) this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else { // now if it is a new offer, give it to initiator socket, otherwise to destination socket if (type === 'new') { // check if it is in pending or living if (this.parent.pendingInview.has(initiator)) { this.parent.pendingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingInview.has(initiator)) { this.parent.livingInview.get(initiator).socket.emit(events.socket.RECEIVE_OFFER, offer) } } else if (type === 'back') { // check if it is in pending or living if (this.parent.pendingOutview.has(destination)) { this.parent.pendingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } else if (this.parent.livingOutview.has(destination)) { this.parent.livingOutview.get(destination).socket.emit(events.socket.RECEIVE_OFFER, offer) } } } }) } /** * @description Connect the signaling service to a Socket.io signaling server (see the server in ./server) * @param {Object} options options for the connection if needed * @return {Promise} Promise resolved when the connection succeeded * @private */ connect (room = 'default', options = this.options) { if (this.socket) return Promise.resolve() return new Promise((resolve, reject) => { const address = `${options.host}:${options.port}` const socket = io(address, { autoConnect: false, query: { room, id: options.parent.id } }) socket.connect() socket.once('connect', () => { this._initializeSocket(socket) resolve() }) socket.once('connect_error', (error) => { socket.close() console.error('Signaling server connect_error: ', error) socket.off('connect') socket.off('connect_failed') socket.off('connect_timeout') reject(error) }) socket.once('connect_failed', (error) => { socket.close() console.error('Signaling server connect_failed: ', error) socket.off('connect') socket.off('connect_failed') socket.off('connect_timeout') reject(error) }) socket.once('connect_timeout', (timeout) => { socket.close() console.error('Signaling server connect_timeout: ', timeout) socket.off('connect') socket.off('connect_failed') socket.off('connect_error') reject(timeout) }) }) } /** * Disconnect the signaling service from the signaling server * @return {void} */ disconnect () { if (this.socket) { this.socket.close() this.socket.off('connect') this.socket.off('connect_failed') this.socket.off('connect_error') } } /** * Initialize the Socket.io socket. * @param {Socket.io} socket * @return {void} * @private */ _initializeSocket (socket) { this.socket = socket this.on(events.signaling.EMIT_OFFER, (offer) => { socket.emit('offer', offer) }) socket.on('offer', (offer) => { this.emit(events.signaling.RECEIVE_OFFER, offer) }) socket.on('error', (error) => { console.error('Signaling Service error: ', error) }) socket.on('disconnect', (error) => { console.log('Signaling Service disconnection: ', error) }) socket.on('reconnect_error', (error) => { socket.close() console.error('Signaling Service disconnection: ', error) }) socket.on('reconnect_failed', (error) => { socket.close() console.error('Signaling Service disconenction: ', error) }) socket.on('reconnect_attempt', () => { console.log('Signaling Service attempting a reconnection') }) socket.on('reconnect', (number) => { console.log('Signaling Service successfull reconnection when attempting a reconnection: ', number) }) } /** * Get a new peer from the signaling service, can be undefined or a string representing the peer id to connect with * @return {Promise} Promise resolved with the peerId or undefined as result or reject with an error * @private */ getNewPeer () { return new Promise((resolve, reject) => { const jobId = translator.new() this.socket.emit('getNewPeer', jobId) this.socket.once(jobId, (peerId) => { resolve(peerId) }) }) } /** * Send an offer to the signaling service * @param {Object} offer the offer to send to the signaling server * @return {Promise} Promise resolved when the offer has been sent * @private */ async sendOffer (offer) { this.socket.emit('offer', offer) } } // not implemented for the moment
JavaScript
class Signaling extends EventEmitter { /** * @private */ constructor (options = {}) { super() this.options = options } /** * Disconnect the signaling service * @return {Promise} Resolved when disconnect. */ async disconnect () { return Promise.resolve() } /** * @description (**Abstract**) Connect the signaling service * @param {Object} options options for the connection if needed * @return {Promise} Promise resolved when the connection succeeded * @private */ async connect (options) { return Promise.reject(errors.nyi()) } /** * (**Abstract**) Get a new peer from the signaling service, can be undefined or a string representing the peer id to connect with * @return {Promise} Promise resolved with the peerId or undefined as result or reject with an error * @private */ async getNewPeer () { return Promise.reject(errors.nyi()) } /** * (**Abstract**) Send an offer to the signaling service * @param {Object} offer the offer to send to the signaling server * @return {Promise} Promise resolved when the offer has been sent * @private */ async sendOffer (offer) { return Promise.reject(errors.nyi()) } /** * Method called when an offer has been received always with the format {initiator, destination, offer} * @param {Object} offer the offer received * @return {void} * @private */ receiveOffer (offer) { this.emit(events.signaling.RECEIVE_OFFER, offer) } }
JavaScript
class SimplePeerWrapper extends Socket { /** * @private */ constructor (options) { options = lmerge({ moc: false, MocClass: __webpack_require__(/*! ./webrtc-moc */ "./lib/sockets/webrtc-moc.js"), trickle: true, initiator: false, config: { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }, { urls: 'stun:global.stun.twilio.com:3478?transport=udp' }] // default simple peer iceServers... } }, options) super(options) } /** * Callback called when you receive an offer from a signaling service. * This callback has to be implemented by you. * @param {Object} offer Offer received. * @return {void} * @private */ _receiveOffer (offer) { this.statistics.offerReceived++ this._debug('[socket:%s] the socket just received an offer (status=%s)', this.socketId, this.status, this.statistics, this.options.initiator, offer) this._create() this.__socket.signal(offer) } /** * Create the socket if not created, * @param {Object} [options=this.options] Options object * @return {void} * @private */ _create (options = this.options) { options.initiator = false if (!this.__socket) { if (this.options.moc) { this.__socket = new this.options.MocClass(options) } else { this.__socket = new SimplePeer(options) } this.status = 'connecting' this.__socket.once('connect', () => { this.signalConnect() }) this.__socket.on('signal', (offer) => { this.emitOffer(offer) }) this.__socket.on('close', () => { if (this.status !== 'disconnected') { this.signalDisconnect() } }) this.__socket.on('error', (error) => { // this.signalDisconnect() this.__socket.destroy(error) this._manageErrors(error) }) this.__socket.on('data', (...args) => { this._receiveData(...args) }) } } /** * Create the socket, begin the signaling mechanism, and wait for connection. * Called by the abstract socket upon connection. * @param {Object} [options=this.options.socket] Options Object * @return {Promise} * @private */ _connect (options = this.options.socket) { options.initiator = true this._debug('Options for the new socket: ', options) return new Promise(async (resolve, reject) => { if (options.moc) { this.__socket = new this.options.MocClass(options) } else { this.__socket = new SimplePeer(options) } this.__socket.on('signal', (offer) => { this.emitOffer(offer) }) this.__socket.once('connect', () => { this.signalConnect() resolve() }) this.__socket.once('error', (error) => { this.__socket.destroy(error) this._manageErrors(error) }) this.__socket.on('data', (...args) => { this._receiveData(...args) }) this.__socket.once('close', () => { if (this.status !== 'disconnected') { this.signalDisconnect() } }) }) } /** * Send a message to the other socket. * Called by the abstract socket upon message to send. * @param {Object} data Data to send * @return {Promise} * @private */ async _send (data) { this._create() try { this.__socket.send(data) } catch (e) { throw e } } /** * Disconenct the socket and return a promise. * Called by the abstract socket upon disconnection * @return {Promise} Resolved when disconnected. * @private */ async _disconnect () { return new Promise((resolve, reject) => { this.__socket.once('close', () => { resolve() }) this.__socket.destroy() }) } }
JavaScript
class Socket extends EventEmitter { /** * @description Constructor of the Socket class, the connect method just initialize a socket and wait for an accepted offer * @param {Object} options any options needed * @private */ constructor (options = {}) { super() this.socketId = translator.new() this._debug = (__webpack_require__(/*! debug */ "./node_modules/debug/src/browser.js"))('n2n:socket') this._debugMessage = (__webpack_require__(/*! debug */ "./node_modules/debug/src/browser.js"))('n2n:message') this.options = lmerge({ chunks: 16000, timeout: 5000 }, options) this.status = 'disconnected' // connected or disconnected this.on(events.socket.RECEIVE_OFFER, this.receiveOffer) this.buffer = [] this.statistics = { offerSent: 0, offerReceived: 0 } this._errored = false this._errors = [] this._offers = { emitted: [], received: [] } } /** * Review the buffer of data sent * @return {void} * @private */ reviewBuffer () { let data while ((data = this.buffer.shift())) { this.send(data) } } /** * Signal to the supervisor of the socket that this socket is conencted and review the internal buffer * @return {void} * @private */ signalConnect () { this.status = 'connected' this.emit('connect') this.reviewBuffer() } /** * Signal to the supervisor of the socket that this socket is disconnected * @return {void} * @private */ signalDisconnect () { this.status = 'disconnected' this.emit('close', this.socketId) } /** * @description To Implement: you will receive all offers here, do what you want with them, Usefull for connection if you are using simple-peer or webrtc * @param {Object} offer offer received from someone who want to connect to us * @return {void} * @private */ _receiveOffer (offer) { throw errors.nyi() } /** * @description you will receive all offers here, do what you want with them, Usefull for connection if you are using simple-peer or webrtc * @param {Object} offer offer received from someone who want to connect to us * @return {void} * @private */ receiveOffer (offer) { this._offers.received.push(offer) this._receiveOffer(offer) } /** * Send an offer to the supervisor of the socket for sending the offer (perhaps used by a signaling service) * @param {Object} offer * @return {void} * @private */ emitOffer (offer) { offer.sid = this.socketId offer.stats = this.statistics.offerSent this.statistics.offerSent++ this._debug('[socket:%s] Send an accepted offer (status=%s): ', this.socketId, this.status, offer, this.statistics) if (this.status === 'connected') { this._debug('The socket is connected but you continue to emit offers...', offer, this.status, this.__socket._channel.readyState) this.emit(events.socket.EMIT_OFFER_RENEGOCIATE, offer) } else { this.emit(events.socket.EMIT_OFFER, offer) } this._offers.emitted.push(offer) } /** * @description [**To implement**] * Connect the socket to a peer you have to provide. * You have to implement this method and return a promise that resolve when the connection is completed. * @param {Object} options options passed to the function * @return {Promise} Promise resolved when the socket is connected * @private */ _connect (options) { return Promise.reject(errors.nyi()) } /** * @description [**To implement**] * Send a message on the socket to the peer which is connected to this socket. * You have to implement this method and return a promise that resolve when the message is sent * @param {Object} data data to send * @param {Object} options options * @return {Promise} Promise resolved when the message is sent * @private */ _send (data, options) { return Promise.reject(errors.nyi()) } /** * Callback called when data are received * Default bbehavior: emit data on the event bus when received with the event 'data' * @param {Object} data data received * @return {void} * @private */ _receiveData (data) { if (this.status === 'connecting') { this.signalConnect() } this._debug('[socket:%s] receiving data, size=%f', this.socketId, sizeof(data)) this.emit('data', data) } /** * Call this method upon errors * Emit on the supervizor an 'error' event with args as parameter * @param {...*} args atguments * @return {void} * @private */ _manageErrors (...args) { this._errored = true this._errors.push(...args) this._debug('Error on the socket: ', ...args) this.emit('error', ...args) } /** * @description [**To implement**] * Destroy/disconnect the socket * You have to implement this method and return a promise that resolve when the socket is destroyed * @return {Promise} Promise resolved when the socket is destroyed/disconnected * @private */ _disconnect () { return Promise.reject(errors.nyi()) } /** * @description Connect the socket to a peer using the signaling service provided by the supervisor of the socket. * @param {Object} options options passed to the function * @return {Promise} Promise resolved when the socket is connected * @private */ async connect (options = this.options) { this.status = 'connecting' return this._connect(options).then((res) => { this.signalConnect() return res }).catch(e => e) } /** * @description Send a message on the socket to the peer which is connected to this socket. * @param {Object} data data to send * @param {Object} options options * @return {Promise} Promise resolved when the message is sent * @private */ async send (data, options) { const size = sizeof(data) this._debug('[socket:%s] Data size sent (max allowed=%f Bytes): %f', this.socketId, this.options.chunks, size) if (size > this.options.chunks) { return Promise.reject(new Error('Your data is too big. Max allowed: ' + this.options.chunks)) } else { if (this.status === 'connected') { return this._send(data, options) } else if (this.status === 'connecting') { this.buffer.push(data) } else if (['disconnecting', 'disconnected'].includes(this.status)) { throw new Error('socket disconnected or disconnecting: status=' + this.status) } } } /** * @description Destroy/disconnect the socket * @return {Promise} Promise resolved when the socket is destroyed/disconnected * @private */ async disconnect (options = this.options) { this.status = 'disconnected' return new Promise((resolve, reject) => { const tout = setTimeout(() => { if (this.status === 'disconnected') { resolve() } else { reject(new Error('')) } }, options.timeout) setTimeout(() => { if (this.status === 'disconnected') { clearTimeout(tout) resolve() } }, 0) this._disconnect(options).then((res) => { clearTimeout(tout) this.signalDisconnect() resolve(res) }).catch(e => { clearTimeout(tout) reject(e) }) }) } }
JavaScript
class Manager { /** * @private */ constructor () { this._statistics = { message: 0 } this.manager = new Map() this._options = { latency: 0, connections: 100, disconnections: 200 } debugManager('manager initialized') } // @private get stats () { return this._statistics } // @private set (peerId, peer) { if (this.manager.has(peerId)) { throw new Error('this peer already exsists: ' + peerId) } this.manager.set(peerId, peer) } // @private connect (from, to) { debugManager('peer connected from/to: ', from, to) this.manager.get(to)._connectWith(from) setTimeout(() => { this.manager.get(from)._connectWith(to) }, this._options.connections) } // @private destroy (from, to) { debugManager('peer disconnected from/to: ', from, to) if (this.manager.has(from)) { this.manager.get(from)._close() } // notify the overside of the socket after 5 seconds setTimeout(() => { if (this.manager.has(to)) { this.manager.get(to)._close() } }, this._options.disconnections) } // @private send (from, to, msg, retry = 0) { this._send(from, to, msg, retry) } // @private _send (from, to, msg, retry = 0) { try { if (!this.manager.has(from) || !this.manager.has(to)) { throw new Error('need a (from) and (to) peer.') } else { this._statistics.message++ this.manager.get(to)._receive(msg) } } catch (e) { throw new Error('cannot send the message. perhaps your destination is not reachable.', e) } } }
JavaScript
class OctalPrng { constructor (seed) { this.seed = seed this.randBit = function () { this.seed = (5 * this.seed + 7) % 8 return this.seed % 2 } this.randOctalDigit = function () { this.seed = (5 * this.seed + 7) % 8 return this.seed } this.clonePrng = function () { return new OctalPrng(this.seed) } } }
JavaScript
class ShortPrng { constructor (seed) { this.seed = seed this.randBit = function () { this.seed = (0x660D * this.seed + 0xF35F) % 65536 return this.seed % 2 } this.randOctalDigit = function () { this.seed = (0x660D * this.seed + 0xF35F) % 65536 return this.seed % 8 } this.randShort = function () { this.seed = (0x660D * this.seed + 0xF35F) % 65536 return this.seed } this.clonePrng = function () { return new ShortPrng(this.seed) } } }
JavaScript
class Parser{ /** Public methods **/ /** * Parses the given dice notation * and returns a list of dice and modifiers found * * @link https://en.m.wikipedia.org/wiki/Dice_notation * @param {string} notation * @returns {Array} */ static parse(notation){ if (!notation) { throw Error('Notation is required'); } else if (typeof notation !== 'string') { throw Error('Notation must be a string'); } // parse the notation const parsed = parser.parse(notation); // (Hopefully) temporary solution to parse the generic objects into class instances return parseExpression(parsed); } }
JavaScript
class Library { // Maps (stringified) library spec to Library static _libraryTable = new Map(); // Holds spec (not Library) static currentLibrary = null; static featureList = []; constructor(environment) { this.environment = environment; this.exports = new Map(); } static create(spec) { const prefix = spec.map(x => to_write(x)).join("."); const env = Environment.makeToplevelEnvironment(prefix, sym => { return Sym(`${prefix}:${sym.name}`) }); return new Library(env); } // Called when loading a library from file (or something) static expandLibrary(form) { const spec = form.cdr.car; this.makeLibrary(spec); return this.withLibrary(spec, () => { const decls = form.cdr.cdr; const forms = decls.map(x => this._interpretLibraryDeclaration(x).to_array()).flat(); return this._expandToplevel(forms); }); } static _interpretLibraryDeclaration(decl) { switch (decl.car) { case Sym("begin"): return decl.cdr; case Sym("import"): decl.cdr.forEach(x => this.libraryImport(x)); return nil case Sym("export"): decl.cdr.forEach(x => this.libraryExport(x)); return nil case Sym("cond-expand"): return this._interpretCondExpand(decl.cdr); case Sym("include"): TODO case Sym("include-library-declarations"): TODO default: throw new BiwaError("_interpretLibraryDeclaration: unknown decl.car", decl); } } import(lib) { this.environment.importLibrary(lib); } nameMap() { const ret = []; this.exports.forEach((nickname, id) => { ret.push([nickname, this.environment.assq(id)]) }); return ret; } // Register an export item of the current library // `spec` is either a symbol or `(id nickname)` export(spec) { let id, nickname; if (isSymbol(spec)) { id = spec; nickname = spec; } else { id = spec.cdr.car; nickname = spec.cdr.cdr.car; } this.addExport(nickname, id); } static _interpretCondExpand(clauses) { TODO } // Register `id` as exported item of this library addExport(nickname, id) { this.exports.set(nickname, id); } to_write() { return "#<Library>" } }
JavaScript
class RefString { /** * Object wrapper around a string. * * @param {string} s */ constructor(s) { this.value = s; } /** * @param {RegExp} regexp * @returns {RegExpMatchArray?} */ match(regexp) { return this.value.match(regexp); } /** * @param {number} from * @param {number} [length] * @returns {string} */ substr(from, length) { return this.value.substr(from, length); } }
JavaScript
class Argument { /** * Creates a new argument * @param {object} options The argument options * @param {string} options.type The argument type * @param {string} options.key The key for the argument. This is the name you access the argument with in your command function * @param {string} options.label The argument label, used in the help command * @param {boolean} [options.optional=false] Wether the argument is optional * @param {boolean} [options.infinite=false] Wether the argument is infinite */ constructor({ type, key, label, optional = false, infinite = false } = {}) { if(typeof type !== 'string') throw new TypeError(`Argument types must be passed as a string, not ${typeof type}`); if(typeof key !== 'string') throw new TypeError(`Argument keys must be passed as a string, not ${typeof type}`); if(typeof label !== 'string') throw new TypeError(`Argument labels must be passed as a string, not ${typeof type}`); if(typeof optional !== 'boolean') throw new TypeError(`Argument option "optional" must be passed as a boolean, not ${typeof optional}`); if(typeof infinite !== 'boolean') throw new TypeError(`Argument option "infinite" must be passed as a boolean, not ${typeof infinite}`); if(!validators[type]) throw new TypeError(`Argument type ${type} doesn't exist`); this.type = type; this.key = key; this.label = label; this.optional = optional; this.infinite = infinite; } /** * Validates if the value is of the correct type * @private * @param {*} value The value to validate * @param {Client} client The client to use (for discord type parsing) * @returns {boolean} Wether the value is of the correct type */ validate(value, client) { return validators[this.type].validate(value, client); } /** * Parses the value to the argument type * @private * @param {*} value The value to parse * @param {Client} client The client to use (for discord type parsing) * @returns {*} The parsed value */ parse(value, client) { return validators[this.type].parse(value, client); } }
JavaScript
class MarkdownRenderer extends Renderer { constructor(theme) { super(); this.theme = theme; this.withTokens = false; } blockquote(text) { if (this.withTokens) { text = text.replace(/<p>/ig, '<p>&gt; '); } return super.blockquote(text); } code(text, lang) { if (this.withTokens) text = "```<br/>" + text + "<br/>```"; const theme = this.theme; const bgColor = ColorManipulator.fade(theme.palette.accent1Color, 0.2); const fgColor = theme.palette.disabledColor; const font = theme.monoFontFamily; return `<div style="background-color: ${bgColor}; font-family: ${font}; color: ${fgColor}; white-space: pre-wrap; margin-left: 2em;">${text}</div>`; } codespan(text) { const fgColor = this.theme.palette.disabledColor; const font = this.theme.monoFontFamily; if (this.withTokens) text = "`" + text + "`"; return `<span style="color: ${fgColor}; font-family: ${font};">${text}</span>`; } del(text) { if (this.withTokens) text = `~~${text}~~`; return super.del(text); } em(text) { if (this.withTokens) text = `*${text}*`; return super.em(text); } heading(text, level) { const theme = this.theme; let textColor; if (level <= 1) { textColor = theme.palette.accent1Color; } else if (level <= 2) { textColor = theme.palette.accent2Color; } else if (level <= 4) { textColor = theme.palette.accent3Color; } else if (level <= 5) { textColor = theme.palette.textColor; } else { textColor = theme.palette.disabledColor; } const prefix = this.withTokens ? '#'.repeat(level) + ' ' : ''; return `<h${level} style="color: ${textColor}">${prefix}${text}</h1>`; } hr() { return super.hr(); } html(text) { return super.html(text); } image(href, title, text) { return super.image(href, title, text); } link(href, title, text) { let el = super.link(href, title, text); const fgColor = this.theme.palette.primary1Color; if (this.withTokens) el = `[${el}](${href})`; return `<span style="color: ${fgColor}">${el}</span>`; } list(body, ordered) { return super.list(body, ordered); } listitem(text) { const checkbox = /^(\[(\s|x|\*)?\])/; const matches = text.match(checkbox); if (matches && matches.length > 1) { const checked = matches[1].match(/(x|\*)/) ? " task-item-checked" : ""; return '<li class="task-item' + checked + '">' + text.replace(checkbox, '') + '</li>'; } return super.listitem(text); } paragraph(text) { return super.paragraph(text); } strong(text) { if (this.withTokens) text = `**${text}**`; return super.strong(text); } table(header, body) { return super.table(header, body); } tablerow(text) { return super.tablerow(text); } tablecell(text, flags) { return super.tablecell(text, flags); } }
JavaScript
class ActionButton extends React.Component { render() { const { text, clicked, onClick, title, } = this.props; // [EditByRan] device-specific rendering if (isMobile){ return <div className={classNames('action_button', 'button', onClick ? 'primary' : 'disabled', { 'clicked': clicked })} style={ { width: '94px', height: '40px', right: '20px', bottom: '252px', 'border-radius': '20px', } } onClick={onClick} title={title} > {text} </div>; } else { return <div className={classNames('action_button', 'button', onClick ? 'primary' : 'disabled', { 'clicked': clicked })} style={ { width: '120px', left: '50%', top: '745px', 'margin-left': '-73px', } } onClick={onClick} title={title} > {text} </div>; } } }
JavaScript
class Fullscreen { constructor () { this.event = 'fullscreenchange' this.prefixes = ['', 'webkit'] } get isAllowed () { return Boolean(document.fullscreenEnabled || document.webkitFullscreenEnabled) } get isActive () { return Boolean(this.element) } get element () { return (document.fullscreenElement || document.webkitFullscreenElement) } on (callback) { this.prefixes.forEach(prefix => { document.addEventListener(prefix + this.event, callback, false) }) } off (callback) { this.prefixes.forEach(prefix => { document.removeEventListener(prefix + this.event, callback, false) }) } }
JavaScript
class Quizquestions{ constructor(question,option1,option2,option3,option4,rightAnswer){ this.question = question; this.option1 = option1; this.option2 = option2; this.option3 = option3; this.option4 = option4; this.rightAnswer = rightAnswer; } displayQuestions(){ textFont("Verdana"); fill("#e2d1b4"); rect(10,20,windowWidth - 20, 280, 20); fill("black"); textSize(40); text(this.question , 800, 150); } displayOptions(){ //option 1 button displayoption1 = createButton(this.option1); displayoption1.position(300, 400); displayoption1.size(400, 75 ); displayoption1.style("background-color", "#8799c1"); displayoption1.style("font-size", "25px"); displayoption1.style("border-radius", "20px"); displayoption1.style("color", "white"); displayoption1.mousePressed(this.ans1); displayoption1.rightAnswer = this.rightAnswer; noStroke(); //option 2 button displayoption2 = createButton(this.option2); displayoption2.position(950, 400); displayoption2.size(400, 75 ); displayoption2.style("background-color", "#8799c1"); displayoption2.style("font-size", "25px"); displayoption2.style("border-radius", "20px"); displayoption2.style("color", "white"); displayoption2.mousePressed(this.ans2); displayoption2.rightAnswer = this.rightAnswer; noStroke(); //option 3 button displayoption3 = createButton(this.option3 ); displayoption3.position(300, 550); displayoption3.size(400, 75 ); displayoption3.style("background-color", "#8799c1"); displayoption3.style("font-size", "25px"); displayoption3.style("border-radius", "20px"); displayoption3.style("color", "white"); displayoption3.mousePressed(this.ans3); displayoption3.rightAnswer = this.rightAnswer; noStroke(); //option 4 button displayoption4 = createButton(this.option4); displayoption4.position(950, 550); displayoption4.size(400, 75 ); displayoption4.style("background-color", "#8799c1"); displayoption4.style("font-size", "25px"); displayoption4.style("border-radius", "20px"); displayoption4.style("color", "white"); displayoption4.mousePressed(this.ans4); displayoption4.rightAnswer = this.rightAnswer; noStroke(); } // checking if option 1 is correct or wrong ans1(){ if(Click === true){ console.log(this); if( "a" === this.rightAnswer){ displayoption1.style("background-color", "green"); displayoption2.style("background-color", "red"); displayoption3.style("background-color", "red"); displayoption4.style("background-color", "red"); answersCorrect++; } else{ displayoption1.style("background-color", "red"); answersWrong++; if("b" === this.rightAnswer){ displayoption2.style("background-color", "green"); } else if("c" === this.rightAnswer){ displayoption3.style("background-color", "green"); } else if("d" === this.rightAnswer){ displayoption4.style("background-color", "green"); } } } Click = false; } // checking if option 2 is correct or wrong ans2(){ if(Click === true){ if("b" === this.rightAnswer){ displayoption2.style("background-color", "green"); displayoption1.style("background-color", "red"); displayoption3.style("background-color", "red"); displayoption4.style("background-color", "red"); answersCorrect++; } else { displayoption2.style("background-color", "red"); answersWrong++; if("a" === this.rightAnswer){ displayoption1.style("background-color", "green"); } else if("c" === this.rightAnswer){ displayoption3.style("background-color", "green"); } else if("d" === this.rightAnswer){ displayoption4.style("background-color", "green"); } } Click = false; } } // checking if option 3 is correct or wrong ans3(){ if(Click === true){ console.log(this); if( "c" === this.rightAnswer){ displayoption3.style("background-color", "green"); displayoption1.style("background-color", "red"); displayoption2.style("background-color", "red"); displayoption4.style("background-color", "red"); answersCorrect++; } else{ displayoption3.style("background-color", "red"); answersWrong++; if("b" === this.rightAnswer){ displayoption2.style("background-color", "green"); } else if("a" === this.rightAnswer){ displayoption1.style("background-color", "green"); } else if("d" === this.rightAnswer){ displayoption4.style("background-color", "green"); } } Click = false; } } // checking if option 4 is correct or wrong ans4(){ if(Click === true){ if( "d" === this.rightAnswer){ displayoption4.style("background-color", "green"); displayoption1.style("background-color", "red"); displayoption2.style("background-color", "red"); displayoption3.style("background-color", "red"); answersCorrect++; } else{ displayoption4.style("background-color", "red"); answersWrong++; if("b" === this.rightAnswer){ displayoption2.style("background-color", "green"); } else if("c" === this.rightAnswer){ displayoption3.style("background-color", "green"); } else if("a" === this.rightAnswer){ displayoption1.style("background-color", "green"); } } Click = false; } } displaynumberOfQuestionsDisplayed(){ fill("purple"); text("Question "+ numberOfQuestionDisplayed + "/10" , 800, 350); textSize(30); } }
JavaScript
class Slider extends Carousel { /** *Creates an instance of Slider. * @param {*} element * @memberof Slider */ constructor(element) { super(element); this.carouselScrollbar = this.carouselElem.querySelector(CONSTANTS.SEL_CAROUSEL_SCROLLBAR); if(this.carouselScrollbar) { this.setScrollbar(0); } } /** * * * @param {*} index * @memberof Slider */ advanceCarousel(index) { this.setLayout(); const INDEX_OF_TARGET_SLIDE = index; if (this.inTransition === false) { this.inTransition = true; this.slideContainer.style.transform = "translateX(" + (-100 * (this.slideWidth / this.slidesContainerWidth)) * INDEX_OF_TARGET_SLIDE + "%)"; if (this.flexHeight) { this.updateHeight($slides.eq(INDEX_OF_TARGET_SLIDE).outerHeight()); } this.currentSlide = this.slides.item(INDEX_OF_TARGET_SLIDE); this.setIndexToValue(INDEX_OF_TARGET_SLIDE); //console.log(this.carouselScrollbar); // Set scrollbar layout if(this.carouselScrollbar) { this.setScrollbar(INDEX_OF_TARGET_SLIDE); } window.setTimeout(() => { this.inTransition = false; }, this.transition); } } /** * * * @memberof Slider */ setScrollbar(index) { const SCROLL_SEGMENTS = Math.ceil(this.numberOfSlides / (this.slidesContainerWidth / this.slideWidth)); const BASE_BAR_UNIT = Math.round((100 / this.numberOfSlides) * 1000) / 1000; // set left padding const LEFT_PADDING = index * BASE_BAR_UNIT; this.carouselScrollbar.style.paddingLeft = LEFT_PADDING + '%'; // set right padding var RIGHT_PADDING = (this.numberOfSlides - (Math.round(this.slidesContainerWidth / this.slideWidth) + index)) * BASE_BAR_UNIT; this.carouselScrollbar.style.paddingRight = RIGHT_PADDING + '%'; } }
JavaScript
class SimpleMap extends React.Component { state = { center: { lat: -33.8, lng: 150.8202351 }, zoom: 9 }; onChange = ({ center, zoom, bounds, ...other }) => { console.log("this.props.onChange", center, zoom, bounds, other); this.setState({ center, zoom }); }; onChildClick = (key, childProps) => { console.log("this.props.onChildClick", key, childProps); }; onChildMouseEnter = (key /*, childProps */) => { console.log("this.props.onChildMouseEnter", key); }; onChildMouseLeave = (/* key, childProps */) => { console.log("this.props.onChildMouseLeave"); }; calcWidthForPopulation = (pop, zoom) => { // zoom is documented https://developers.google.com/maps/documentation/javascript/tutorial#zoom-levels // 1: World // 5: Landmass/continent // 10: City // 15: Streets // 20: Buildings const zoomFactors = [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, // 0-5 1.0, 2.0, 3.0, 4.0, 7.5, // 6-10 10, 12, 13, 14, 15, // 11-15 16, 17, 18, 19, 20 // 16-20 ]; const minWidth = 10; if (!pop) { return minWidth; } if (zoom < 6) { return minWidth; } const factor = zoomFactors[zoom] || 1; return Math.max(minWidth, Math.log(pop) * factor); }; render() { // const { classes } = this.props; const { center, zoom } = this.state; return ( <GoogleMapReact bootstrapURLKeys={{ key: GoogleMapsApiKey }} style={styles.map} center={center} zoom={zoom} onChange={this.onChange} onChildMouseEnter={this.onChildMouseEnter} onChildMouseLeave={this.onChildMouseLeave} > {Locations.map( (x, i) => x.found && ( <Circle key={i} lat={x.lat} lng={x.lng} zoom={zoom} width={this.calcWidthForPopulation(x.students, zoom)}> <MarkerPopup model={x} /> </Circle> ) )} </GoogleMapReact> ); } }
JavaScript
class ThreadMember extends Base { /** * @param {ThreadChannel} thread The thread that this member is associated with * @param {APIThreadMember} data The data for the thread member */ constructor(thread, data) { super(thread.client); /** * The thread that this member is a part of * @type {ThreadChannel} */ this.thread = thread; /** * The timestamp the member last joined the thread at * @type {?number} */ this.joinedTimestamp = null; /** * The id of the thread member * @type {Snowflake} */ this.id = data.user_id; this._patch(data); } _patch(data) { this.joinedTimestamp = new Date(data.join_timestamp).getTime(); /** * The flags for this thread member * @type {ThreadMemberFlags} */ this.flags = new ThreadMemberFlags(data.flags).freeze(); } /** * The guild member associated with this thread member * @type {?GuildMember} * @readonly */ get guildMember() { return this.thread.guild.members.resolve(this.id); } /** * The last time this member joined the thread * @type {?Date} * @readonly */ get joinedAt() { return this.joinedTimestamp ? new Date(this.joinedTimestamp) : null; } /** * The user associated with this thread member * @type {?User} * @readonly */ get user() { return this.client.users.resolve(this.id); } /** * Whether the client user can manage this thread member * @type {boolean} * @readonly */ get manageable() { return !this.thread.archived && this.thread.editable; } /** * Removes this member from the thread. * @param {string} [reason] Reason for removing the member * @returns {ThreadMember} */ remove(reason) { return __awaiter(this, void 0, void 0, function* () { yield this.thread.members.remove(this.id, reason); return this; }); } }
JavaScript
class dynamodbHelper { /** * @class dynamodbHelper * @constructor */ constructor() { this.creds = new AWS.EnvironmentCredentials('AWS'); // Lambda provided credentials } dynamodbPutObjectsFromS3Folder(sourceS3Bucket, sourceS3Prefix, table) { console.log(`source bucket: ${sourceS3Bucket}`); console.log(`source prefix: ${sourceS3Prefix}`); console.log(`ddb table: ${table}`); const s3 = new AWS.S3(); const documentClient = new AWS.DynamoDB.DocumentClient(); let _self = this; function _listAllFiles(allFiles, token) { let opts = { Bucket: sourceS3Bucket, Prefix: sourceS3Prefix }; if (token) { opts.ContinuationToken = token; } return s3.listObjectsV2(opts).promise().then(data => { allFiles = allFiles.concat(data.Contents.map((e) => { return e.Key.split(sourceS3Prefix + '/').pop(); })); if (data.IsTruncated) { return _listAllFiles(allFiles, data.NextContinuationToken); } else return allFiles; }); } return _listAllFiles([], null).then(files => { console.log('Found:', JSON.stringify(files)); files = files.filter(file => { return file.indexOf('.json') > 0; }); return files.reduce((previousValue, currentValue, index, array) => { return previousValue.then(chainResults => { console.log('Getting:', currentValue); return s3.getObject({ Bucket: sourceS3Bucket, Key: sourceS3Prefix + '/' + currentValue }).promise().then(data => { const params = { TableName: table, Item: JSON.parse(data.Body.toString('ascii')) }; params.Item.createdAt = moment() .utc() .format(); params.Item.updatedAt = moment() .utc() .format(); console.log('Putting:', currentValue, params); return documentClient.put(params).promise(); }).then(result => { console.log('Put file', currentValue, 'in db'); return [...chainResults, { file: currentValue }]; }).catch(err => { console.error('ERROR: failed to write', currentValue, 'to DB', JSON.stringify(err)); throw err; }); }); }, Promise.resolve([]).then(arrayOfResults => arrayOfResults)); // return Promise.all(files.map(file => { // console.log('Getting:', file); // return s3.getObject({ // Bucket: sourceS3Bucket, // Key: sourceS3Prefix + '/' + file // }).promise().then(data => { // const params = { // TableName: table, // Item: JSON.parse(data.Body.toString('ascii')), // ReturnValues: 'ALL_OLD' // }; // params.Item.createdAt = moment() // .utc() // .format(); // params.Item.updatedAt = moment() // .utc() // .format(); // console.log(file, params); // return documentClient.put(params).promise(); // }).then(result => { // console.log('Put file', file, 'in db', result); // return { // file: file // }; // }).catch(err => { // console.error('ERROR: failed to write', file, 'to DB', JSON.stringify(err)); // throw err; // }); // })); }).then(results => { return { result: results }; }); } dynamodbSaveItem(item, ddbTable) { item.created_at = moment.utc().format(); item.updated_at = moment.utc().format(); const docClient = new AWS.DynamoDB.DocumentClient(); return docClient.put({ TableName: ddbTable, Item: item }).promise().then(result => { return item; }); } }
JavaScript
class ModelArchitect extends ModelBDI { constructor(beliefs) { const roomInfo = beliefs['roomInfo']; const isConstructionFinished = roomInfo ? !(roomInfo['constructionSites'].length) : null; const _beliefs = { isConstructionFinished, 'target': null, 'intent': null, 'roomInfo': null, 'threatSafeRange': null, 'frequentlyWalkedPos': [], 'structureMinDistance': null, 'structureMaxDistance': null, 'lowValuePerimeterInternalRadius': null, 'highValuePerimeterInternalRadius': null, 'containersPerSource': null }; Object.assign(_beliefs, beliefs); super(_beliefs); } desires() { return [ { title: 'cancelConstructionSites', actions: () => { for (const site of this.beliefs['target']) { site.remove(); } }, conditions: () => { const roomInfo = this.beliefs['roomInfo']; const room = roomInfo['room']; const threats = roomInfo['threats']; const structures = roomInfo['structures']; const constructionSites = roomInfo['constructionSites']; const threatSafeRange = this.beliefs['threatSafeRange']; // early exit if ( !constructionSites.length) { return false; } // cancel construction in locations that are occupied by threats const cancelledSites = []; for (const constructionSite of constructionSites) { if (constructionSite.pos.findInRange(threats, threatSafeRange).length) { cancelledSites.push(constructionSite); } } if (cancelledSites.length) { this.beliefs['target'] = cancelledSites; this.beliefs['intent'] = 'cancelConstructionSites'; return true; } } }, { title: 'placeTowerStructures', actions: () => { const roomInfo = this.beliefs['roomInfo']; for (const site of this.beliefs['target']) { roomInfo['room'].createConstructionSite(site, STRUCTURE_TOWER); } }, conditions: () => { const roomInfo = this.beliefs['roomInfo']; const room = roomInfo['room']; const structures = roomInfo['structures']; const constructionSites = roomInfo['constructionSites']; const maxTowerStructures = roomInfo['maxTowerStructures']; const spawnStructures = structures.filter( (x) => (x.structureType == STRUCTURE_SPAWN) ); const towerStructures = structures.filter( (x) => (x.structureType == STRUCTURE_TOWER) ); const towerConstructionSites = constructionSites.filter( (x) => (x.structureType == STRUCTURE_TOWER) ); const structureMinDistance = this.beliefs['structureMinDistance']; const structureMaxDistance = this.beliefs['structureMaxDistance']; let totalTowerStructures = towerStructures.length + towerConstructionSites.length; // early exit if ( (totalTowerStructures >= maxTowerStructures) || !spawnStructures.length) { return false; } // find best locations const towerSites = []; for (const spawnStructure of spawnStructures) { const location = utils.findPrimeLocation(spawnStructure.pos, roomInfo, structureMinDistance, structureMaxDistance); if (location) { towerSites.push(location); totalTowerStructures++; } if (totalTowerStructures >= maxTowerStructures) { break; } } if (towerSites.length) { this.beliefs['target'] = towerSites; this.beliefs['intent'] = 'placeTowerStructures'; return true; } } }, // TODO: the strategy for these needs revising // { // title: 'placeContainerStructures', // actions: () => { // const roomInfo = this.beliefs['roomInfo']; // for (const site of this.beliefs['target']) { // roomInfo['room'].createConstructionSite(site, STRUCTURE_CONTAINER); // } // }, // conditions: () => { // const roomInfo = this.beliefs['roomInfo']; // const room = roomInfo['room']; // const structures = roomInfo['structures']; // const energySources = roomInfo['energySources']; // const constructionSites = roomInfo['constructionSites']; // const containerStructures = roomInfo['energyContainers']; // const containerConstructionSites = constructionSites.filter( (x) => (x.structureType == STRUCTURE_CONTAINER) ); // const maxContainerStructures = Math.min( roomInfo['maxContainerStructures'], // (this.beliefs['containersPerSource'] * energySources.length) ); // const structureMinDistance = this.beliefs['structureMinDistance']; // const structureMaxDistance = this.beliefs['structureMaxDistance']; // // let totalContainerStructures = containerStructures.length + containerConstructionSites.length; // // // early exit // if ( (totalContainerStructures >= maxContainerStructures) || !energySources.length) { return false; } // // // find best locations // const containerSites = []; // for (const energySource of energySources) { // const location = utils.findPrimeLocation(energySource.pos, roomInfo, structureMinDistance, structureMaxDistance); // if (location) { // containerSites.push(location); // totalContainerStructures++; // } // if (totalContainerStructures >= maxContainerStructures) { // break; // } // } // // if (containerSites.length) { // this.beliefs['target'] = containerSites; // this.beliefs['intent'] = 'placeContainerStructures'; // return true; // } // } // }, { title: 'placeExtensionStructures', actions: () => { const roomInfo = this.beliefs['roomInfo']; for (const site of this.beliefs['target']) { roomInfo['room'].createConstructionSite(site, STRUCTURE_EXTENSION); } }, conditions: () => { const roomInfo = this.beliefs['roomInfo']; const room = roomInfo['room']; const structures = roomInfo['structures']; const energySources = roomInfo['energySources']; const constructionSites = roomInfo['constructionSites']; const maxExtensionStructures = roomInfo['maxExtensionStructures']; const extensionStructures = structures.filter( (x) => (x.structureType == STRUCTURE_EXTENSION) ); const extensionConstructionSites = constructionSites.filter( (x) => (x.structureType == STRUCTURE_EXTENSION) ); const structureMinDistance = this.beliefs['structureMinDistance']; const structureMaxDistance = this.beliefs['structureMaxDistance']; const isConstructionFinished = this.beliefs['isConstructionFinished']; let totalExtensionStructures = extensionStructures.length + extensionConstructionSites.length; // early exit if ( !isConstructionFinished || (totalExtensionStructures >= maxExtensionStructures) || !energySources.length) { return false; } // find best locations const extensionSites = []; for (const energySource of energySources) { const location = utils.findPrimeLocation(energySource.pos, roomInfo, structureMinDistance, structureMaxDistance); if (location) { extensionSites.push(location); totalExtensionStructures++; } if (totalExtensionStructures >= maxExtensionStructures) { break; } } if (extensionSites.length) { this.beliefs['target'] = extensionSites; this.beliefs['intent'] = 'placeExtensionStructures'; return true; } } }, { title: 'placeRampartStructures', actions: () => { const roomInfo = this.beliefs['roomInfo']; for (const site of this.beliefs['target']) { roomInfo['room'].createConstructionSite(site, STRUCTURE_RAMPART); } }, conditions: () => { const roomInfo = this.beliefs['roomInfo']; const room = roomInfo['room']; const structures = roomInfo['structures']; const lowValueStructures = roomInfo['lowValueStructures']; const highValueStructures = roomInfo['highValueStructures']; const energySources = roomInfo['energySources']; const constructionSites = roomInfo['constructionSites']; const maxRampartStructures = roomInfo['maxRampartStructures']; const isConstructionFinished = this.beliefs['isConstructionFinished']; const lowValuePerimeterInternalRadius = this.beliefs['lowValuePerimeterInternalRadius']; const highValuePerimeterInternalRadius = this.beliefs['highValuePerimeterInternalRadius']; const lowValueRampartThickness = Math.max( (lowValuePerimeterInternalRadius - 1), 0 ); const highValueRampartThickness = Math.max( (highValuePerimeterInternalRadius - 1), 0 ); const rampartStructures = structures.filter( (x) => (x.structureType == STRUCTURE_RAMPART) ); const rampartConstructionSites = constructionSites.filter( (x) => (x.structureType == STRUCTURE_RAMPART) ); let totalRampartStructures = rampartStructures.length + rampartConstructionSites.length; // early exit if ( !isConstructionFinished || (totalRampartStructures >= maxRampartStructures) ) { return false; } // find best locations let rampartSites = []; // around high-value structures for (const structure of highValueStructures) { // ignore ramparts if (structure.structureType == STRUCTURE_RAMPART) { continue; } const perimeter = utils.getPosPerimeter(structure.pos, roomInfo, highValueRampartThickness, true); if (perimeter) { rampartSites = rampartSites.concat(perimeter, [structure.pos]); } } // around low-value structures for (const structure of lowValueStructures) { // ignore ramparts if (structure.structureType == STRUCTURE_RAMPART) { continue; } const perimeter = utils.getPosPerimeter(structure.pos, roomInfo, lowValueRampartThickness, true); if (perimeter) { rampartSites = rampartSites.concat(perimeter, [structure.pos]); } } // around energy sources for (const energySource of energySources) { const perimeter = utils.getPosPerimeter(energySource.pos, roomInfo, lowValueRampartThickness, true); if (perimeter) { rampartSites = rampartSites.concat(perimeter); } } // remove duplicates and existing construction sites rampartSites = utils.uniqPos(rampartSites); rampartSites = rampartSites.filter( (x) => (utils.isPosBuildable(x, roomInfo) && !utils.isPosRampart(x, roomInfo)) ); // ensure we don't exceed limits const rampartSitesLimit = Math.max(Math.min((maxRampartStructures - totalRampartStructures), MAX_CONSTRUCTION_SITES), 0); rampartSites = rampartSites.slice(0, rampartSitesLimit); // normalize room positions rampartSites = rampartSites.map( (x) => (room.getPositionAt(x.x, x.y)) ); if (rampartSites.length) { this.beliefs['target'] = rampartSites; this.beliefs['intent'] = 'placeRampartStructures'; return true; } } }, { title: 'placeRoadStructures', actions: () => { const roomInfo = this.beliefs['roomInfo']; for (const site of this.beliefs['target']) { roomInfo['room'].createConstructionSite(site, STRUCTURE_ROAD); } }, conditions: () => { const roomInfo = this.beliefs['roomInfo']; const room = roomInfo['room']; const energySources = roomInfo['energySources']; const frequentlyWalkedPos = this.beliefs['frequentlyWalkedPos']; const isConstructionFinished = this.beliefs['isConstructionFinished']; // early exit if (!isConstructionFinished || !frequentlyWalkedPos.length) { return false; } // TODO: reconsideration, this has seriously high cost ... // place roads to enable access around energy sources // let energySourceSites = energySources.map( (x) => (this.getPosPerimeter(x.pos, 1, true)) ); // energySourceSites = energySourceSites.reduce( (x, y) => (x.concat(y)), [] ); // energySourceSites = energySourceSites.map( (x) => (room.getPositionAt(x.x, x.y)) ); // energySourceSites = energySourceSites.filter( (x) => (this.isPosWall(x, x.look())) ); // place roads on frequently walked swamps const frequentlyWalkedPosSites = frequentlyWalkedPos.filter( (x) => (utils.isPosSwamp(x, roomInfo) && utils.isPosBuildable(x, roomInfo)) ); // const roadSites = energySourceSites.concat(frequentlyWalkedPosSites); let roadSites = frequentlyWalkedPosSites; const roadSitesLimit = Math.min(roadSites.length, MAX_CONSTRUCTION_SITES); roadSites = roadSites.slice(0, roadSitesLimit); if (roadSites.length) { this.beliefs['target'] = roadSites; this.beliefs['intent'] = 'placeRoadStructures'; return true; } } } ]; } }
JavaScript
class Browser { /** * Scroll once to a given location (xPos, yPos) * @param {number} xPos * @param {number} yPos */ static scrollTo(xPos, yPos) { window.scrollTo(xPos, yPos); } /** * Scroll multiple times by given pixel amount (xPx, yPx) * @param {number} xPx * @param {number} yPx */ static scrollBy(xPx, yPx) { window.scrollBy(xPx, yPx); } /** * Opens a new browser window. * * Name pamareter can have following values: name or target value (name|_blank|_parent|_self|_top) * * Specs parameter is defined as comma,separated,list,without,whitespace and it can have following values: * channelmode=yes|no|1|0, * direcotries=yes|no|1|0, * fullscreen=yes|no|1|0, * height=pixels, * left=pixels, * location=yes|no|1|0, * menubar=yes|no|1|0, * resizable=yes|no|1|0, * scrollbars=yes|no|1|0, * status=yes|no|1|0, * titlebar=yes|no|1|0, * toolbar|yes|no|1|0, * top=pixels, * width=pixels min 100 * * Replace parameter defines is a new history entry created or is current replaced with the new one. * If true the current entry is replaced with the new one. If false a new history entry is created. * @param {string} url * @param {string} name * @param {string} specs * @param {boolean} replace * @returns Reference to the opened window or null if opening the window failes. */ static open(url, name, specs, replace) { return window.open(url, name, specs, replace); } /** * Closes a given opened window. Same as calling openedWindow.close(); * @param {*} openedWindow */ static close(openedWindow) { openedWindow.close(); } /** * Opens a print webpage dialog. */ static print() { window.print(); } /** * Displays an alert dialog with a given message and an OK button. * @param {string} message */ static alert(message) { window.alert(message); } /** * Displays a confirm dialog with a given message, OK and Cancel button. * @param {string} message * @returns True if OK was pressed otherwise false. */ static confirm(message) { return window.confirm(message); } /** * Displays a prompt dialog with a given message, a prefilled default text, OK and Cancel button. * @param {string} message * @param {string} defaultText * @returns If OK was pressed and an input field has text then the text is returned. * If the input does not have text and OK was pressed then empty string is returned. * If Cancel was pressed then null is returned. */ static prompt(message, defaultText) { return window.prompt(message, defaultText); } /** * Method is used to make a media query to the viewport/screen object. The media query is done according to a given mediaString. * Syntax of the media string would be (min-width: 300px) but using this method enables user to omit parentheses(). * Which then leads to syntax min-width: 300px. * * Method returns a MediaQueryList object which has few neat properties. Matches and media in addition it has * two functions addListener and removeListener which can be used to query media in realtime. Usage could be something following: * * var matcher = Browser.mediaMatcher("max-height: 300px"); * * matcher.addlistener(function(matcher) { * if(matcher.matches) * Tree.getBody().setStyles({backgroundColor: "red"}); * else * Tree.getBody().setStyles({backgroundColor: "green"}); * }); * * matcher.media returns the media query string. * * matcher.matches returns the boolean indicating does it does the query string match or not. True if it matches, otherwise false. * * mathcer.addListener(function(matcher)) is used to track changes on the viewport/screen. * * matcher.removeListener(listenerFunction) is used to remove a created listener. * @param {string} mediaString * @returns MediaQueryList object. */ static mediaMatcher(mediaString) { if(mediaString.indexOf("(") !== 0) mediaString = "("+mediaString; if(mediaString.indexOf(")") !== mediaString.length -1) mediaString = mediaString+")"; return window.matchMedia(mediaString); } /** * Loads one page back in the browsers history list. */ static pageBack() { history.back(); } /** * Loads one page forward in the browsers history list. */ static pageForward() { history.forward(); } /** * Loads to specified page in the browsers history list. A parameter can either be a number or string. * If the parameter is number then positive and negative values are allowed as positive values will go forward * and negative values will go backward. * If the parameter is string then it must be partial or full url of the page in the history list. * @param {string|number} numberOfPagesOrUrl */ static pageGo(numberOfPagesOrUrl) { history.go(numberOfPagesOrUrl) } /** * Create a new history entry with given parameters without reloading the page. State object will be the state * next history entry will be using. Title is ignored value by the history object at the time but it could be * the same title what the HTML Document page has at the moment of create the new history entry. New url must * be of the same origin (e.g. www.example.com) but the rest of url could be anything. * @param {object} stateObject * @param {string} title * @param {string} newURL */ static pushState(stateObject, title, newURL) { history.pushState(stateObject, title, newURL); } /** * Replace a history entry with given parameters without reloading the page. State object will be the state * next history entry will be using. Title is ignored value by the history object at the time but it could be * the same title what the HTML Document page has at the moment of create the new history entry. New url must * be of the same origin (e.g. www.example.com) but the rest of url could be anything. * @param {object} stateObject * @param {string} title * @param {string} newURL */ static replaceState(stateObject, title, newURL) { history.replaceState(stateObject, title, newURL); } /** * Loads a new page. * @param {string} newURL */ static newPage(newURL) { location.assign(newURL); } /** * Reloads a current page. If a parameter force is true then the page will be loaded from the server * otherwise from the browsers cache. * @param {boolean} force */ static reloadPage(force) { location.reload(force); } /** * Replaces a current page with a new one. If the page is replaced then it wont be possible to go back * to the previous page from the history list. * @param {string} newURL */ static replacePage(newURL) { location.replace(newURL); } /** * @returns Anchor part of the url e.g. #heading2. */ static getAnchorHash() { return location.hash; } /** * Sets a new anhorpart of the url e.g. #heading3. * @param {string} hash */ static setAnchorHash(hash) { location.hash = hash; } /** * @returns Hostname and port in host:port format. */ static getHostnamePort() { return location.host; } /** * Set a hostname and port in format host:port. * @param {string} hostPort */ static setHostnamePort(hostPort) { location.host = hostPort; } /** * @returns Hostname e.g. www.google.com. */ static getHostname() { return location.hostname; } /** * Set a hostname * @param {string} hostname */ static setHostname(hostname) { location.hostname = hostname; } /** * @returns Entire URL of the webpage. */ static getURL() { return location.href; } /** * Set location of a current page to point to a new location e.g. http://some.url.test or #someAcnhor on the page. * @param {string} newURL */ static setURL(newURL) { location.href = newURL; } /** * @returns protocol, hostname and port e.g. https://www.example.com:443 */ static getOrigin() { return location.origin; } /** * @returns Part of the URL after the slash(/) e.g. /photos/ */ static getPathname() { return location.pathname; } /** * Sets a new pathname for this location. * @param {string} pathname */ static setPathname(pathname) { location.pathname = pathname; } /** * @returns Port number of the connection between server and client. */ static getPort() { return location.port; } /** * Sets a new port number for the connection between server and client. * @param {number} portNumber */ static setPort(portNumber) { location.port = portNumber; } /** * @returns Protocol part of the URL e.g. http: or https:. */ static getProtocol() { return location.protocol; } /** * Set a new protocol for this location to use. * @param {string} protocol */ static setProtocol(protocol) { location.protocol = protocol; } /** * @returns Part of the URL after the question(?) mark. e.g. ?attr=value&abc=efg. */ static getSearchString() { return location.search; } /** * Sets a new searchString into the URL * @param {string} searchString */ static setSearchString(searchString) { location.search = searchString; } /** * @returns Codename of the browser. */ static getCodename() { return navigator.appCodeName; } /** * @returns Name of the browser. */ static getName() { return navigator.appName; } /** * @returns Version of the browser. */ static getVersion() { return navigator.appVersion; } /** * @returns True if cookies are enabled otherwise false. */ static isCookiesEnabled() { return navigator.cookieEnabled; } /** * @returns GeoLocation object. */ static getGeoLocation() { return navigator.geolocation; } /** * @returns Language of the browser. */ static getLanguage() { return navigator.language; } /** * @returns A platform name of which the browser is compiled on. */ static getPlatform() { return navigator.platform; } /** * @returns A name of an engine of the browser. */ static getProduct() { return navigator.product; } /** * @returns A header string sent to a server by the browser. */ static getUserAgentHeader() { return navigator.userAgent; } /** * @returns Color depth of the current screen. */ static getColorDepth() { return screen.colorDepth; } /** * @returns Total height of the current screen. */ static getFullScreenHeight() { return screen.height; } /** * @returns Total width of the current screen. */ static getFullScreenWidth() { return screen.width; } /** * @returns Height of the current screen excluding OS. taskbar. */ static getAvailableScreenHeight() { return screen.availHeight; } /** * @returns Width of the current screen exluding OS. taskbar. */ static getAvailableScreenWidth() { return screen.availWidth; } }
JavaScript
class Mailer { /** * Creates an instance of Mailer. * @param {any} [options={}] * * @memberof Mailer */ constructor(options = {}) { this.config = Object.assign({ transportConfig: { type: 'stub', transportoptions: { debug: true, args: ['-t', '-i'] } }, }, options.config); this.transport = options.transport; this.getEmailTemplateHTMLString = getEmailTemplateHTMLString.bind(this); this.getTransport = getTransport.bind(this); this.sendEmail = sendEmail.bind(this); return this; } /** * reads a filepath and returns the email template string (will use EJS to render later by default) * * @static * * @memberof Mailer */ static getEmailTemplateHTMLString(options) { return getEmailTemplateHTMLString(options); } /** * returns a node mailer transport based off of a json configuration * * @static * * @memberof Mailer */ static getTransport(options) { return getTransport(options); } /** * sends email with nodemailer * * @static * @param {any} [options={}] all of the options to a node mailer transport sendMail function * @param {object|string} options.to * @param {object|string} options.cc * @param {object|string} options.bcc * @param {object|string} options.replyto * @param {object|string} options.subject * @param {object|string} options.html * @param {object|string} options.text * @param {object|string} options.generateTextFromHTML * @param {object|string} options.emailtemplatestring * @param {object|string} options.emailtemplatedata * @returns {promise} resolves the status of an email * * @memberof Mailer */ static sendEmail(options){ return sendEmail(options); } }
JavaScript
class Ast { constructor(value) { this.value = value; } getContents() { return this.value; } /** * Format the AST into JSON format * @return {String} JSON format of AST */ asJson() { return JSON.stringify(this.value, null, '\t'); } /** * Apply the given ESQuery to the AST and return all matches * * @param {string} query * @return {Ast[]} */ queryAst(query) { console.log('[QueryAST] ', query); let selectorAst = esquery.parse(query); let matches = esquery.match(this.value, selectorAst); return matches.map(a => new Ast(a)); } /** * Apply the geiven ESQuery and return a single result. The first result is used if more than one result is found * * @param {String} query * @return {Ast} */ querySingleAst(query) { console.log('[QuerySingleAst] ', query); let selectorAst = esquery.parse(query); let matches = esquery.match(this.value, selectorAst); if (matches.length > 0) { return new Ast(matches[0]); } return null; } }
JavaScript
class ReactAst extends Ast { /** * Returns a list of all components found in the AST * * @return {ReactAst[]} Subtree of every React component in the AST */ getComponents() { // Option 1 to define components let components = this.queryAst( '[body] > [type="VariableDeclaration"] > [init.type="CallExpression"][init.callee.property.name="createClass"]' ); // Option 2 to define components let components2 = this.queryAst( '[body] [right.type="CallExpression"][right.callee.property.name="createClass"]' ); // merge and retrieve let allComponents = components.concat(components2); return allComponents.map(a => new ReactAst(a.getContents())); } /** * Returns the name of the current component * This method only works if it is invoked on a subtree returned by getComponents() * * @return {String} Name of the current component */ getName() { if (this.getContents().left && this.getContents().left.type === 'MemberExpression') { return this.getContents().left.property.name; } return this.getContents().id.name; } }
JavaScript
class PolymerAst extends Ast { /** * Returns a list of all components found in the AST * * @return {ReactAst[]} Subtree of every React component in the AST */ getComponents() { // Option 1 to define components let components = this.queryAst( '[body] [type=CallExpression][callee.type="SequenceExpression"]' ).filter(a => a.getContents().callee.expressions[1].property.name="default"); // Option 2 to define components let components2 = this.queryAst( '[body] [type=CallExpression][callee.name=Polymer]' ); // merge and retrieve let allComponents = components.concat(components2); return allComponents .map(a => new PolymerAst(a.getContents())); } /** * Returns the name of the current component * This method only works if it is invoked on a subtree returned by getComponents() * * @return {String} Name of the current component */ getName() { let name = this.queryAst( '[type=Property][key.type=Identifier][key.name=is]' ); return name[0].getContents().value.value; } }
JavaScript
class AngularAst extends Ast { /** * Returns a list of all components found in the AST * * @return {ReactAst[]} Subtree of every React component in the AST */ getComponents() { let components = this.queryAst( '[type="ExpressionStatement"] [callee.property.name=component]' ); return components.map(a => new AngularAst(a.getContents())); } /** * Returns the name of the current component * This method only works if it is invoked on a subtree returned by getComponents() * * @return {String} Name of the current component */ getName() { return this.getContents().arguments[0].value; } }
JavaScript
class AstHelper { /** * Extracts the expression found in a subtree * An expression would be the full variable usage (e.g. this.props.ob.foo.title...) or a method call * this.ob.asd.we.df.foo(). * Method can also handle static values and arrays/objects which will just recursively traverse the nodes * * Execution can be seen as some kind of flattening the tree * (while losing a significant amount of additional information) * * @param {Object} expr Subtree nodes to extract the information * @return {String|Object|Array} Flattened information contained in the subtree */ static extractExpression(expr) { let type = expr.type; if (type === 'ThisExpression') { return 'this'; } if (type === 'Identifier') { return expr.name; } if (type === 'Literal') { return expr.value; } if (type === 'MemberExpression') { return this.extractExpression(expr.object) + '.'+expr.property.name; } if (type === 'CallExpression') { return this.extractExpression(expr.callee) + '()'; } if (type === 'ArrayExpression') { return expr.elements.map(a => this.extractExpression(a)); } if (type === 'ObjectExpression') { let foo = {}; expr.properties.forEach(a => { return foo[this.extractExpression(a.key)] = this.extractExpression(a.value) }); return foo; } return null; } /** * Checks whether the provided parameter is a node structure that resembles the React.createElement function call * * @param {Object} entry Tree structure to test * @return {Boolean} True if it is a React.createElement function call */ static isReactCreateElement(entry) { return entry.type === 'CallExpression' && (AstHelper.extractExpression(entry).endsWith('.default.createElement()') || AstHelper.extractExpression(entry) === ('React.createElement()')); } /** * Helper method to extract only relevant information from the tree structure of the function parameters * * @param {Object} expr Tree structure with function parameters * @return {Array} List of all parameters reduced to name and values */ static extractFunctionParameters(expr) { if (expr.arguments === undefined || expr.arguments.length === 0) { return undefined; } return expr.arguments.map(a => { return { type: a.type, value: AstHelper.extractExpression(a) }; }); } /** * Checks whether the AST provided contains a React component definition * * @param {Ast} code Ast which is checked for React compliant component definitions * @return {Boolean} True if a React component is present, false otherwise */ static isReactCode(code) { let checker = code.querySingleAst('[callee.property.name="createClass"]'); if (!checker) return false; let check1 = checker.querySingleAst('[callee.object.name="React"]'); if (check1 !== null) return true; let check2 = checker.querySingleAst('[callee.object.property.name="default"]'); if (check2 !== null) return true; return false; } /** * Checks whether the AST provided contains a Angular component definition * * @param {Ast} code Ast which is checked for Angular compliant component definitions * @return {Boolean} True if a Angular component is present, false otherwise */ static isAngularCode(code) { let checker = code.querySingleAst('[type="ExpressionStatement"] [callee.property.name=component]'); return checker !== null; } /** * Checks whether the AST provided contains a Polymer component definition * * @param {Ast} code Ast which is checked for Polymer compliant component definitions * @return {Boolean} True if a Polymer component is present, false otherwise */ static isPolymerCode(code) { let checker = code.querySingleAst('[body] [type=CallExpression][callee.type="SequenceExpression"] [property.name="default"]'); if (checker === null) { checker = code.querySingleAst('[body] [type=CallExpression][callee.name=Polymer]'); } return checker !== null; } }
JavaScript
class ProduceQpData extends FBP(LitElement) { constructor() { super(); this.addEventListener('click', this.produce); } _FBPReady() { super._FBPReady(); if (this.auto) { this.produce(); } } /** * @private * @return {Object} */ static get properties() { return { /** * Description */ auto: { type: Boolean }, qp: { type: Object }, qpescaped: { type: String }, }; } produce() { if (this.qpescaped) { this.qp = JSON.parse(unescape(this.qpescaped)); } const customEvent = new Event('data', { composed: true, bubbles: true }); customEvent.detail = this.qp; this.dispatchEvent(customEvent); } /** * Themable Styles * @private * @return {CSSResult} */ static get styles() { // language=CSS return ( Theme.getThemeForComponent('ProduceQpData') || css` :host { display: inline-block; } :host([hidden]) { display: none; } ` ); } /** * @private * @returns {TemplateResult} */ render() { // language=HTML return html` <furo-button label="load test data" outline></furo-button> `; } }
JavaScript
class Tile { constructor(number) { this.tileNumber = number; this.left = null; this.top = null; this.right = null; this.bottom = null; this.value = null; this.neighbours = []; } /** * helper fucntions to initilise the tiles * @param {Tile} */ insertInArr(t) { if (t !== null) this.neighbours.push(t); } /** * helper fucntions to initilise the tiles * @param {Tile} */ assignLeft(t) { this.insertInArr(t) this.left = t; } /** * helper fucntions to initilise the tiles * @param {Tile} */ assignTop(t) { this.insertInArr(t) this.top = t; } /** * helper fucntions to initilise the tiles * @param {Tile} */ assignRight(t) { this.insertInArr(t); this.right = t; } /** * helper fucntions to initilise the tiles * @param {Tile} */ assignBottom(t) { this.insertInArr(t); this.bottom = t; } /** * it saves the value property of tile, eg: 'a' * @param {String} char */ setValue(char) { this.value = char; } /** * unsetting by nullifying the value property */ unsetValue() { this.value = null; } /** * check if the value property of a tile has not been set, so it's empty * @returns {Boolean} */ isEmpty() { return !this.value; } /** * check if the value property of a tile has been set, so it's taken * @returns {Boolean} */ isTaken() { if (this.value) { return true } return false; } randDirection() { //return this.neighbours[Math.floor(Math.random() * this.neighbours.length)] } component() { //TileComponent returns a functional component return TileComponent({ app: window.app, char: this.value, tileNumber: this.tileNumber }); } }
JavaScript
class SubNavToggleArrowDown extends EventAbstract { /** * Execute the action to the event. */ exec() { this.event.preventDefault(); // If on the toggle item and the menu is expanded go down in to the first // menu item link as the focus. if (this.parentNav.isExpanded()) { event.stopPropagation(); event.preventDefault(); this.getElement('firstSubnavLink').focus(); } // If current focus is on the toggle and the menu is not open, go to the // next sibling menu item. else { var node = this.getElement('next') || this.getElement('parentNavNext') || this.getElement('last'); if (node) { node.focus(); } } } }
JavaScript
class ECS extends ComponentRegistry { constructor(components) { super(); this.entities = new Map(); if (Array.isArray(components) && components.length) { this.registerComponents(...components); } } /** * @param {Array} [components] components to attach to the entity * @param {string} [id] entity id * @returns {Entity} */ createEntity(components, id) { const entity = new Entity(this, id); if (this.entities.has(entity.id)) { warn(`[ECS.createEntity] entity with id:${entity.id} already exists! entity id's must be unique!`); return; } this.entities.set(entity.id, entity); if (Array.isArray(components)) { components.forEach((componentClass) => { if (Array.isArray(componentClass)) { this.createComponent(entity, ...componentClass); // c => [componentClass, data] } else { this.createComponent(entity, componentClass); } }); } return entity; } /** * @param {Array<EntityDescriptor>} entities * @returns {Array<Entity>} */ buildFromJSON(entities) { return entities.map((entity) => { if (Array.isArray(entity)) { const [id, data] = entity; const components = Object.keys(data).map(name => [name, data[name]]); return this.createEntity(components, id); } return this.createEntity(null, entity); }); } getEntity(id) { return this.entities.get(id); } destroyEntity(id) { const e = this.entities.get(id); if (e) { this.entities.delete(id); if (!e[$entityIsDestroyed]) { e.destroy(); } } } destroyAllEntities() { this.entities.forEach(e => e.destroy()); } }
JavaScript
class TestHelper { /************************************************** * Before and After methods *************************************************/ static before(){ Facade.ioc = IoC; IoC.instances.set('ioc', IoC); this.timerProvider = new TimerServiceProvider(IoC); this.timerProvider.register(); this.provider = new EventServiceProvider(IoC); this.provider.register(); } static after(){ IoC.flush(); Facade.ioc = null; Facade.clearResolvedInstances(); } /************************************************** * Helpers *************************************************/ /** * Returns a new Event Dispatcher * * @param {Container|object|null} [ioc] * @param {TimeMaster|null} [timeMaster] * * @return {Dispatcher} */ static makeDispatcher(ioc = null, timeMaster = null){ return new Dispatcher(ioc, timeMaster); } /** * Returns a new Subscriber * * @param {Map.<string, Array.<string|function|Listener>>|null} listeners A map of events and their listeners * * @return {Subscriber} */ static makeSubscriber(listeners = null){ let subscriber = new Subscriber(); if(listeners !== null){ subscriber.listeners = listeners; } return subscriber; } /** * Returns a new empty Listener * @return {EmptyListener} */ static makeEmptyListener(){ return new EmptyListener(); } /** * Returns a dummy listener class (not initiated) * * @return {DummyListener} */ static get dummyListenerClass(){ return DummyListener; } /** * Returns a dummy background class (not initiated) * * @return {DummyBackgroundListener} */ static get dummyBackgroundListener(){ return DummyBackgroundListener; } /** * Returns a new (empty) dummy background listener * * @return {DummyBackgroundListener} */ static makeDummyBackgroundListener(){ return new DummyBackgroundListener(); } /** * Returns a listener class (not initiated) * * @return {EmptyListener} */ static get listenerClass(){ return EmptyListener; } /** * Returns a counting listener class (not initiated) * * @return {CountingListener} */ static get countingListenerClass(){ return CountingListener; } }
JavaScript
class Winners extends Scene { /** * @param {Object[]} winners Winners array */ constructor({winners}) { super(); this._winners = winners; this._config = config.scenes.Winners; } async onCreated() { this._init(); } /** * @private */ _init() { this._addBackground(); this._initTeams(); } /** * Adds the background to the scene * @private */ _addBackground() { const background = new Background(); background.scale.set(1.1); background.changeColors({ circleColor1: '#0085D1', circleColor2: '#0085D1', bgColor1: '#102AEB', bgColor2: '#102AEB', }); this.addChild(background); } /** * Sorts the winner array by team place and starts the teams animation * @private */ async _initTeams() { this._winners.sort((a, b) => parseInt(b.place, 10) - parseInt(a.place, 10)); await delay(this._config.startDelay * 1000); this._startTeamVisualization(); } /** * Starts the team countdown visualization * @private * @returns promise */ async _startTeamVisualization() { for (const teamInfo of this._winners) { const team = new Team(teamInfo); this.addChild(team); setTimeout(() => { this._emitShockwave(); }, 1000); team.enterAnimation(); // Don't continue if it's the team in first place if (parseInt(teamInfo.place, 10) === 1) return; await delay(this._config.betweenTeamsDelay * 1000); await team.leaveAnimation(); this.removeChild(team); } } /** * Shockwave effect emitted whenever a team is displayed * @private */ async _emitShockwave() { const displacementSprite = new Sprite.from('displacement'); const displacementFilter = new filters.DisplacementFilter(displacementSprite); const filterIntensity = 60; this.addChild(displacementSprite); this.filters = [displacementFilter]; displacementFilter.autoFit = false; displacementFilter.scale.set(filterIntensity); displacementSprite.anchor.set(0.5); displacementSprite.scale.set(0); // TODO: FIX DISPLACEMENT FILTER "DISPLACEMENT" ISSUE AND REMOVE THIS HACK this.position.x = -filterIntensity / 2; this.position.y = -filterIntensity / 2; await gsap.to(displacementSprite, { pixi: { scale: 10, }, duration: this._config.shockwaveDuration, }); this.removeChild(displacementSprite); this.filters = []; // TODO: REMOVE THIS AFTER THE ISSUE MENTIONED IN THE COMMENT ABOVE IS RESOLVED this.position.x = 0; this.position.y = 0; } /** * Hook called by the application when the browser window is resized. * Use this to re-arrange the game elements according to the window size * * @param {Number} width Window width * @param {Number} height Window height */ onResize(width, height) { // eslint-disable-line no-unused-vars } }
JavaScript
class ETMLocal { constructor() { this.initSocketIO(); } initSocketIO() { console.log("Registering socket io bindings for ETMLocal plugin") } show_info(id, data) { sidebar.setContent(etmlocal_plugin.create_sidebar_content(id, data).get(0)); sidebar.show(); } create_sidebar_content(id, data) { let $div = $('<div>').attr('id', 'etmlocal-main-div'); let $title = $('<h1>').text('ETMLocal - '+id); $div.append($title); $div.append(etmlocal_plugin.generate_table(data)); return $div; } generate_table(data) { if (Object.keys(data[0]).length !== 0) { let $table = $('<table>').addClass('pure-table pure-table-striped').attr('id', 'etmlocal_table'); let $thead = $('<thead>').append($('<tr>').append($('<th>').text('Key')).append($('<th>') .text('Value'))); let $tbody = $('<tbody>'); $table.append($thead); $table.append($tbody); for (let key in data[0]) { let value = data[0][key]; $tbody.append($('<tr>') .append($('<td>').css('width', '220px').css('font-size', '9px').css('word-break', 'break-all').text(key)) .append($('<td>').css('font-size', '9px').text(value))); } return $table; } else { return $('<p>').text('No information'); } } area_info(event, id) { socket.emit('etmlocal_get_info', id, function(res) { etmlocal_plugin.show_info(id, res); }); } static create(event) { if (event.type === 'client_connected') { etmlocal_plugin = new ETMLocal(); return etmlocal_plugin; } if (event.type === 'add_contextmenu') { let layer = event.layer; let layer_type = event.layer_type; let id = layer.id; if (layer_type === 'area') { layer.options.contextmenuItems.push({ text: 'get ETMLocal info', icon: resource_uri + 'icons/Vesta.png', callback: function(e) { etmlocal_plugin.area_info(e, id); } }); } } if (event.type === 'settings_menu_items') { let menu_items = { 'value': 'etmlocal_plugin_settings', 'text': 'ETMLocal plugin', 'settings_func': function() { return $('<p>').text('ETMLocal plugin')}, 'sub_menu_items': [] }; return menu_items; } } }
JavaScript
class ToyotaGroen2020 { constructor(item, aantal){ let VoorRaad = this; VoorRaad.artikel = item; VoorRaad.voorraad = parseFloat(aantal); } verhoogVoorraadMet1(){ console.log(this.voorraad +=1); } verlaagVoorraadMet(somAftrekken){ let verlagenMulti = this; verlagenMulti.somAftrekken = parseFloat(somAftrekken); if((this.voorraad === parseFloat(0) || this.voorraad < parseFloat(0) || this.voorraad <= parseFloat(0) || this.voorraad - verlagenMulti.somAftrekken <= parseFloat(-1))){ console.log("Geen voorraad beschikbaar voor dit artikel, verlaging kan niet plaatsvinden. Er zijn", this.voorraad, " op deze locatie beschikbaar. Wilt u nieuwe modellen bestellen ? : "); console.log("sec0"); } else if((this.voorraad <=parseFloat-1)){ console.log("Geen voorraad beschikbaar voor dit artikel, verlaging kan niet plaatsvinden. Er zijn", this.voorraad, " op deze locatie beschikbaar. Wilt u nieuwe modellen bestellen ? : "); console.log("sec1"); } else if(this.voorraad >=1 ){ console.log((this.voorraad -= verlagenMulti.somAftrekken)); console.log("sec2"); } } verhoogVoorraadMet(optellenMulti){ let verhogerMulti = this; verhogerMulti.optellenMulti = parseFloat(optellenMulti); console.log((this.voorraad += verhogerMulti.optellenMulti)); } }
JavaScript
class RandomWalk { constructor(test, assert) { this.test = test; this.assert = assert; this.steps = []; this.consistencyChecks = []; } addStep(name, options, params) { options.name = name; if (!options.weight) { options.weight = 1.0; } if (typeof options.isApplicable != 'function') { options.isApplicable = () => true; } this.steps.forEach((step) => { if (step.name == options.name) { throw `There is already a step called {options.name}.`; } }); this.steps.push({ step: options, params }); } async doSteps(count) { if (this.history === undefined) { this.history = []; } for (let i = 0; i < count; i++) { await this.doRandomStep(); } } async doRandomStep() { const possibleSteps = this.steps.filter(item => item.step.isApplicable()); if (!possibleSteps.length) { throw 'No possible steps found!'; } const { step, params } = sample(possibleSteps); await this.doStep(step, params); } async doStep(step, params) { if (!params) { params = {}; } this.history.push({ step, params }); await step.execute(this.assert, params); } async execute(name, newParams) { const steps = this.steps.filter(item => item.step.name === name); if (steps.length === 0) { throw `No step with name '${name}' found!`; } const { step, params } = steps[0]; await this.doStep(step, newParams || params); } async repeatFromHistory(history) { this.setup(); history.forEach(async (entry) => { const { step, params } = entry; await this.doStep(step, params); }); } setup() { this.history = []; } }
JavaScript
class TokenOnline extends React.Component { constructor() { super(); this.handleSwitchToOfflineMode = this.handleSwitchToOfflineMode.bind(this); this.handleSwitchToSmsAuthorization = this.handleSwitchToSmsAuthorization.bind(this); } handleSwitchToSmsAuthorization(event) { event.preventDefault(); if (this.props.context.formData) { const smsFallbackCallback = this.props.smsFallbackCallback; // set the SMS fallback userInput this.props.context.formData.userInput["smsFallback.enabled"] = true; // save updated form data in the backend this.props.dispatch(updateFormData(this.props.context.formData, function () { // update Token component state - switch to SMS fallback immediately smsFallbackCallback(true); })); } } handleSwitchToOfflineMode(event) { event.preventDefault(); if (this.props.context.formData) { const offlineModeCallback = this.props.offlineModeCallback; // set the offline mode userInput this.props.context.formData.userInput["offlineMode.enabled"] = true; // save updated form data in the backend this.props.dispatch(updateFormData(this.props.context.formData, function () { // update Token component state - switch to offline mode immediately offlineModeCallback(true); })); } } render() { return ( <div className="auth-actions"> {(this.props.username) ? ( <div> <FormGroup> <div className="attribute row"> <div className="message-information"> <FormattedMessage id="login.loginNumber"/> </div> </div> </FormGroup> <FormGroup> <div className="attribute row"> <div className="col-xs-12"> <FormControl autoComplete="off" type="text" value={this.props.username} disabled={true}/> </div> </div> </FormGroup> </div> ) : ( undefined )} <div className="font-small message-information"> <FormattedMessage id="message.token.confirm"/><br/> <div className="image mtoken"/> </div> {(this.props.offlineModeAvailable) ? ( <div className="font-small message-information"> <FormattedMessage id="message.token.offline"/><br/> <a href="#" onClick={this.handleSwitchToOfflineMode}> <FormattedMessage id="message.token.offline.link"/> </a> </div> ) : ( undefined )} {(this.props.smsFallbackAvailable) ? ( <div className="font-small message-information"> <a href="#" onClick={this.handleSwitchToSmsAuthorization}> <FormattedMessage id="smsAuthorization.fallback.link"/> </a> </div> ) : ( undefined )} <div className="attribute row"> <a href="#" onClick={this.props.cancelCallback} className="btn btn-lg btn-default"> <FormattedMessage id="operation.cancel"/> </a> </div> </div> ) } }
JavaScript
class BotMasterRow extends BotRow { /** * Gets all defined columns of the DB row. * @return {Array<string>} the array of column names */ static getColumns() { return Object.values(MasterSettingColumns); } /** * Gets key defined columns of the DB row. * @return {Array<string>} the array of key column names */ static getKeyColumns() { return [MasterSettingColumns.settingName]; } }
JavaScript
class Client { /** * Constructs by setting connection options and initiates a connection * * @param {object} options Cassandra driver connection options * * @returns {void} */ constructor(options) { this.connect(options); } /** * Gets the Cassandra driver connection options. * * If not defined, it'll default to environment variable * CASSANDRA_CONTACT_POINTS if defined, otherwise 127.0.0.1 * * @returns {object} Cassandra driver connection options */ get options() { if (this._options) { return this._options; } return { contactPoints: ( process.env.CASSANDRA_CONTACT_POINTS || '127.0.0.1' ).split(',') }; } /** * Gets a connection promise * * If there's no promise already in memory, it'll create one, * store it and return it. * * @returns {object} Cassandra client within a promise */ get connection() { if (this._connection) { return this._connection; } return this._connection = q(this.options) .then(options => ( new cassandra.Client(options) )); } /** * Initiates a cassandra driver instance by setting connection options * and return connection promise. * * @param {object} options Cassandra driver connection options * * @returns {object} Cassandra connection within a promise */ connect(options) { this._options = options; return this.connection; } /** * Creates a keyspace if it doesn't already exists and switches to it * * @param {string} name Keyspace name * @param {object} replication Replication options * @param {boolean} writes Durable writes option * * @returns {object} Promise */ create_keyspace( name, replication={class: 'SimpleStrategy', replication_factor: 1}, writes=false ) { return proxy( this.connection, 'execute', format( 'create keyspace if not exists %s\ with replication = %s\ and durable_writes = %s', name, JSON.stringify(replication).replace(/"/g, '\''), writes.toString() ) ) .then(() => proxy( this.connection, 'execute', format('use %s', name) )); } /** * Creates a table if it doesn't already exists * * @param {string} name Table name * @param {object} columns A set with {column_name: 'type'} * * @returns {object} Promise */ create_table(name, columns) { return proxy( this.connection, 'execute', format( 'create table if not exists %s (%s)', name, _.map(columns, (type, key) => { return format(key, type); }).join(', ') ) ); } }
JavaScript
class DigitalMarketingAnalysisContainer extends Component { /*====================================================================== // Scroll to top of page upon container being mounted. ======================================================================*/ componentDidMount() { window.scrollTo(0, 0); } /*====================================================================== // This is the first step of Digital Marketing. The user will enter // a keyword, a location, an area, drivers, and a B2 option. This will // then be passed to the parent container, which will perform the // GET request with the provided parameters before proceeding to step 2 // where the user can view results. ======================================================================*/ render () { return ( <div className="main-body-analysis"> <h3>What keyword would you like to analyze?</h3> <input className="standard-input" type="text" name="digital-marketing-keyword" placeholder="Hotel" onChange={ this.props.keywordChange } /> <h3>How large of an area would you like to target?</h3> <select className="analysis-select" onChange={ this.props.areaChange }> <option value="Local">Local</option> <option value="State">State</option> <option value="Country">Country</option> <option value="Worldwide">Worldwide</option> </select> <h3>Which primary location?</h3> <input className="standard-input" type="text" name="digital-marketing-location" placeholder="Seattle" onChange={ this.props.locationChange } /> <div className="analysis-form-drivers"> <h3>What are the main drivers of your analysis?</h3> <input className="standard-input" type="text" name="digital-marketing-driver1" placeholder="Driver #1" onChange={ this.props.driver1Change } /> <input className="standard-input" type="text" name="digital-marketing-driver2" placeholder="Driver #2" onChange={ this.props.driver2Change } /> <input className="standard-input" type="text" name="digital-marketing-driver3" placeholder="Driver #3" onChange={ this.props.driver3Change } /> <input className="standard-input" type="text" name="digital-marketing-driver4" placeholder="Driver #4" onChange={ this.props.driver4Change } /> <input className="standard-input" type="text" name="digital-marketing-driver5" placeholder="Driver #5" onChange={ this.props.driver5Change } /> </div> <h3>Is this for Business to Consumer, Business to Business, or both?</h3> <select className="analysis-select" onChange={ this.props.b2Change }> <option value="B2B">B2C</option> <option value="B2C">B2B</option> <option value="Both">Both</option> </select> <button className="standard-button" onClick={ this.props.analyze }>Begin Analysis</button> </div> ) } }
JavaScript
class PureComponent extends React.Component { shouldComponentUpdate( nextProps, nextState) { return !shallowEqual( this.props, nextProps) || !shallowEqual( this.state, nextState) } }
JavaScript
class Video { constructor ( elem, data ) { this.elem = elem; this.elemData = data; this.wrap = this.elem.find( ".js-video-wrap" ); this.node = this.elem.find( ".js-video-node" ); this.uiEl = this.elem.find( ".js-video-ui" ); this.ui = { pp: this.uiEl.find( ".js-video-pp" ), fs: this.uiEl.find( ".js-video-fs" ), sound: this.uiEl.find( ".js-video-sound" ), ellapsed: this.uiEl.find( ".js-video-ellapsed" ) }; this.isFallback = false; this.isPlaying = false; this.isReadyState = false; this.isToggledPlayback = false; this.videoFS = null; // Store instance with element... this.elem.data( "Video", this ); // Vimeo without CMS mobile alternative if ( this.elemData.json.vimeo ) { this.vimeoId = this.elemData.json.vimeo.split( "/" ).pop().replace( /\//g, "" ); this.fetch().then(( json ) => { this.vimeoData = json; this.vimeo = this.getVimeoSource( json.files ); this.source = this.vimeo.link; this.width = this.vimeo.width; this.height = this.vimeo.height; this.wrapit(); this.load(); }); } } fetch () { return $.ajax({ url: `/api/vimeo/${this.vimeoId}`, method: "GET", dataType: "json" }); } wrapit () { // Aspect Ratio if ( this.wrap.length ) { this.wrap[ 0 ].style.paddingBottom = `${this.height / this.width * 100}%`; } } load () { this.node.on( "loadedmetadata", () => { this.isReadyState = true; if ( !this.width || !this.height ) { this.width = this.node[ 0 ].videoWidth; this.height = this.node[ 0 ].videoHeight; this.wrapit(); } // Basic events this.events(); // UI only events if ( this.uiEl.length ) { this.uiEvents(); } if ( this.elemData.auto ) { this.automate(); } }); // Video source this.node[ 0 ].src = this.source; // Preload video this.node[ 0 ].load(); } automate () { this.controller = new Controller(); this.controller.go(() => { if ( this.isToggledPlayback ) { this.controller.stop(); return; } if ( core.util.isElementVisible( this.elem[ 0 ] ) && !this.isPlaying ) { this.play( "Autoplay" ); } else if ( !core.util.isElementVisible( this.elem[ 0 ] ) && this.isPlaying ) { this.pause( "Autopause" ); } }); } events () { this.node.on( "play", () => { this.isPlaying = true; this.elem.addClass( "is-playing" ).removeClass( "is-paused" ); }); this.node.on( "pause", () => { this.isPlaying = false; this.elem.addClass( "is-paused" ).removeClass( "is-playing" ); }); this.node.on( "ended", () => { this.isPlaying = false; this.elem.removeClass( "is-playing is-paused" ); }); } uiEvents () { this.wrap.on( "click", () => { this.togglePlay(); }); this.ui.pp.on( "click", () => { this.togglePlay(); }); this.ui.sound.on( "click", () => { this.toggleSound(); }); this.ui.fs.on( "click", () => { if ( this.isFsMode() ) { this.exitFsMode(); } else { this.enterFsMode(); } }); this.node.on( "timeupdate", () => { this.ui.ellapsed[ 0 ].style.width = `${this.node[ 0 ].currentTime / this.node[ 0 ].duration * 100}%`; }); } fallbackHandler () { this.destroy(); this.isFallback = true; const picture = this.getVimeoPicture( this.vimeoData.pictures ); this.elem[ 0 ].innerHTML = this.elemData.fs ? `<div class="video__pic js-video-pic -cover" data-img-src="${picture.link}"></div>` : `<img class="video__img js-video-pic" data-img-src="${picture.link}" />`; core.util.loadImages( this.elem.find( ".js-video-pic" ), core.util.noop ); core.dom.body.find( ".js-home-reel-cta" ).remove(); } getVimeoPicture ( pictures ) { const min = 640; const pics = pictures.sizes.filter(( size ) => { return (size.width >= min); }).sort( ( a, b ) => { return ( b.width < a.width ) ? 1 : -1; }); return pics[ 0 ]; } getVimeoSource ( files ) { let hds = files.filter( ( file ) => file.quality === "hd" ); let sds = files.filter( ( file ) => file.quality === "sd" ); let hd = null; let sd = null; // HD sort highest quality to the top hds = hds.sort( ( a, b ) => { return ( b.width > a.width ) ? 1 : -1; }); // SD sort lower quality to the top ( come on man, mobile devices and shit ) sds = sds.sort( ( a, b ) => { return ( b.width < a.width ) ? 1 : -1; }); // HD use 1280 if window isn't even large enough for proper 1920 if ( hds.length > 1 && window.innerWidth <= 1680 ) { hd = hds[ 1 ]; } else { hd = hds[ 0 ]; } // SD use lowest quality as a default sd = sds[ 0 ]; // core.log( "Video HD", hd.width, hd ); // core.log( "Video SD", sd.width, sd ); return (core.detect.isDevice() ? sd : hd); } toggleSound () { if ( !this.isMuted ) { this.isMuted = true; this.node[ 0 ].muted = true; this.elem.addClass( "is-muted" ); } else { this.isMuted = false; this.node[ 0 ].muted = false; this.elem.removeClass( "is-muted" ); } } togglePlay () { this.isToggledPlayback = true; if ( !this.isPlaying ) { this.play( "CLICK PLAY VIDEO" ); } else { this.pause( "CLICK PAUSE VIDEO" ); } } enterFsMode () { if ( this.node[ 0 ].requestFullscreen ) { this.node[ 0 ].requestFullscreen(); } else if ( this.node[ 0 ].webkitRequestFullscreen ) { this.node[ 0 ].webkitRequestFullscreen(); } else if ( this.node[ 0 ].mozRequestFullScreen ) { this.node[ 0 ].mozRequestFullScreen(); } else if ( this.node[ 0 ].msRequestFullscreen ) { this.node[ 0 ].msRequestFullscreen(); } } exitFsMode () { if ( document.exitFullscreen ) { document.exitFullscreen(); } else if ( document.webkitExitFullscreen ) { document.webkitExitFullscreen(); } else if ( document.mozCancelFullScreen ) { document.mozCancelFullScreen(); } else if ( document.msExitFullscreen ) { document.msExitFullscreen(); } } isFsMode () { return ( document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement ); } play ( msg ) { if ( this.isFallback ) { return this; } if ( this.isPlaying ) { return this; } this.node[ 0 ].play() .then(() => { // FS ? if ( this.elemData.fs && !this.videoFS ) { this.videoFS = new VideoFS( this ); } }).catch(() => { this.fallbackHandler(); }); core.log( msg || "PLAY VIDEO" ); } pause ( msg ) { if ( this.isFallback ) { return this; } if ( !this.isPlaying ) { return this; } this.node[ 0 ].pause(); core.log( msg || "PAUSE VIDEO" ); } destroy () { if ( this.isFallback ) { return this; } if ( this.controller ) { this.controller.stop(); this.controller = null; } if ( this.videoFS ) { this.videoFS.destroy(); this.videoFS = null; } this.wrap.off(); this.node.off(); this.ui.pp.off(); this.ui.fs.off(); this.ui.sound.off(); if ( this.node && this.node.length ) { this.node[ 0 ].src = ""; this.node.off().remove(); delete this.node; } } }
JavaScript
class Options { static process (validatorContext, input, rules, returnRawOutput) { const output = [] if (!Array.isArray(rules)) { rules = [rules] } rules.forEach(rule => { Object.keys(rule).forEach(key => { if (key === 'do') return const setting = {} setting[key] = rule[key] try { if (validatorContext.supportedOptions && validatorContext.supportedOptions.indexOf(key) === -1) { output.push(constructError(validatorContext, input, setting, `The '${key}' option is not supported for '${validatorContext.name}' validator, please see README for all available options`)) } else { const result = require(`./options/${key}`).process(validatorContext, input, rule) output.push(constructOutput(validatorContext, input, setting, result)) } } catch (err) { output.push(constructError(validatorContext, input, setting, err.message)) } }) }) return returnRawOutput ? output : consolidateResult(output, validatorContext) } }
JavaScript
class Form extends Component { state = { eventType: null, eventDateTime: null, // toMakeConnection: false, }; componentDidMount() { const { isCreate } = this.props; const filledValues = isCreate ? null : this.getCurrentItem(); this.setState({ eventType: get(filledValues, 'type', null), }); } changeDate = value => { this.setState({ eventDateTime: value, }); }; changeEventType = e => { this.setState({ eventType: e.target.value, }); }; // toggleMakeConnection = () => { // this.setState({ // toMakeConnection: !this.state.toMakeConnection, // }); // }; getConvertDateTime = () => { const { isCreate } = this.props; const filledValues = isCreate ? null : this.getCurrentItem(); const dateTime = get(filledValues, 'dateTime', null) const dateObj = new Date(dateTime); return dateObj.toISOString(); }; submitForm = data => { const { isCreate, createNewItem, updateItem } = this.props; const { eventDateTime } = this.state; const filledValues = isCreate ? null : this.getCurrentItem(); const newType = get(data, 'type', null); const additionalData = { dateTime: eventDateTime ? eventDateTime.toISOString() : this.getConvertDateTime(), type: newType ? newType : get(filledValues, 'type', null), dateCreated: isCreate ? 1000 * moment().unix() : get(filledValues, 'dateCreated', null), }; const formData = Object.assign({}, data, additionalData); if (isCreate) { createNewItem(formData); } else { const filledValues = this.getCurrentItem(); const id = get(filledValues, 'sourceId', null); const source = get(filledValues, 'source', null); formData.id = id; formData.source = source; updateItem(id, formData, filledValues); } }; getCurrentItem = () => { const { eventsList, location } = this.props; const pathname = get(location, 'pathname', null); const pathnameArray = pathname.split('/'); const sourceId = get(pathnameArray, [2], null); const eventsListArray = Object.values(eventsList); let result = null; for (let i = 0, n = eventsListArray.length; i < n; i++) { let item = eventsListArray[i]; if (item.sourceId === sourceId) { result = item; break; } } return result; }; render() { const { classes, isCreate } = this.props; const { eventDateTime, eventType, toMakeConnection } = this.state; const filledValues = isCreate ? null : this.getCurrentItem(); const dateTime= get(filledValues, 'dateTime', null); const dateCreated = get(filledValues, 'dateCreated', null); return ( <React.Fragment> <LocalForm model="event" onSubmit={values => this.submitForm(values)}> <FormGroup className={classes.formGroup}> <FormLabel className={classes.formLabel}>Event Name</FormLabel> <Control.text className={classes.formInput} model='event.name' defaultValue={get(filledValues, 'name', null)} /> </FormGroup> <FormGroup className={classes.formGroup}> <FormLabel className={classes.formLabel}>Event Type</FormLabel> <Control.select className={classes.formSelect} model='event.type' onChange={(e) => this.changeEventType(e)} required> <option value=''>-- Select from --</option> { eventTypes.map((item, key) => { return ( <option key={key} value={item.id} selected={item.id === get(filledValues, 'type', null)}>{item.label}</option> ) })} </Control.select> </FormGroup> <FormGroup className={classes.formGroup}> <FormLabel className={classes.formLabel}>Notes</FormLabel> <Control.textarea className={classes.formTextarea} model='event.description' defaultValue={get(filledValues, 'description', null)} /> </FormGroup> <FormGroup className={classes.formGroup}> <FormLabel className={classes.formLabel}>Event date</FormLabel> <DatePicker className={classes.formInput} selected={eventDateTime ? eventDateTime : dateTime} onChange={value => this.changeDate(value)} showTimeSelect dateFormat="dd-MM-yyyy HH:mm" timeFormat="HH:mm" timeIntervals={15} /> </FormGroup> {/*{*/} {/* (eventType === "Discharge") &&*/} {/* <React.Fragment>*/} {/* <div className={classes.checkboxBlock}>*/} {/* <FormControl className={classes.formControl}>*/} {/* <FormLabel className={classes.formLabel}>To make connection</FormLabel>*/} {/* <FormControlLabel*/} {/* className={classes.formControlLabel}*/} {/* control={*/} {/* <CustomSwitch*/} {/* checked={toMakeConnection}*/} {/* value={toMakeConnection}*/} {/* onChange={() => this.toggleMakeConnection()}*/} {/* />*/} {/* }*/} {/* label={<Typography className={classes.switcherLabel}>{toMakeConnection ? "Yes" : "No"}</Typography>}*/} {/* />*/} {/* </FormControl>*/} {/* </div>*/} {/* {*/} {/* toMakeConnection &&*/} {/* <FormGroup className={classes.formGroup}>*/} {/* <FormLabel className={classes.formLabel}>To make connection with</FormLabel>*/} {/* <Control.select className={classes.formSelect} model='event.connection' required>*/} {/* <option value=''>-- Select from --</option>*/} {/* { connectionTypes.map((item, key) => {*/} {/* return (*/} {/* <option key={key} value={item.id} selected={item.id === get(filledValues, 'connection', null)}>{item.label}</option>*/} {/* )*/} {/* })}*/} {/* </Control.select>*/} {/* </FormGroup>*/} {/* }*/} {/* <FormGroup className={classes.formGroup}>*/} {/* <FormLabel className={classes.formLabel}>Details</FormLabel>*/} {/* <Control.select className={classes.formSelect} model='event.details' required>*/} {/* <option value=''>-- Select from --</option>*/} {/* { detailsTypes.map((item, key) => {*/} {/* return (*/} {/* <option key={key} value={item.id} selected={item.id === get(filledValues, 'details', null)}>{item.label}</option>*/} {/* )*/} {/* })}*/} {/* </Control.select>*/} {/* </FormGroup>*/} {/* </React.Fragment>*/} {/*}*/} <FormGroup className={classes.formGroup}> <FormLabel className={classes.formLabel}>Author</FormLabel> <Control.text className={classes.formInput} model='event.author' defaultValue={get(filledValues, 'author', localStorage.getItem('username'))} disabled={true} /> </FormGroup> <FormGroup className={classes.formGroup}> <FormLabel className={classes.formLabel}>Date</FormLabel> <Control.text className={classes.formInput} model="event.dateCreated" defaultValue={dateCreated ? moment(dateCreated).format('DD-MM-YYYY') : moment().format('DD-MM-YYYY')} disabled={true} /> </FormGroup> <SectionToolbar {...this.props} /> </LocalForm> </React.Fragment> ); } }
JavaScript
class ArrayDictionary { constructor( words = [] ) { this.words = words this.addWords(words) } contains(word) { return this.words[word] } count() { return this.words.length } addWords (words) { words.forEach( (word) => { this.add(word) }) } add (word) { if ( !word.length ) return this.words[word] = word } remove (word) { this.words[word] = undefined } addWordsFromTextFile(filePath, $delimeter = "\n") { // this one only works inside nodejs const fs = require('fs') this.addWords(fs.readFile(filePath, (function(err, data) { if (err) throw err; return data.split(delimeter) }))) } }
JavaScript
class Uuid extends key_1.default { /** * Generates a key for the schema. * * @throws {KeyError} */ generate() { this.setId(uuid_1.v4()); } }
JavaScript
class IntervalModule extends Module { /** * @memberof Vevet.IntervalModule * @typedef {object} EventData * @augments Vevet.Event.EventData * @property {Vevet.IntervalModule.EventObj} data Callback data. */ /** * @memberof Vevet.IntervalModule * @typedef {object} EventObj * @augments Vevet.IntervalModule.EventObjSettings * @property {Function} do */ /** * @memberof Vevet.IntervalModule * @typedef {object} EventObjSettings * @augments Vevet.Event.EventObjSettings * @property {number} interval Interval of callbacks (ms). * @property {boolean} [disableOnBlur] Disable interval on window blur. */ /** * @description Add a callback. * * @param {Vevet.IntervalModule.EventObj} data - Callback data. * @param {boolean} [bool=true] - Defines if the event is enabled. * * @returns {string} Returns a string with an id of the callback. * * @example * let id = interval.add({ * interval: 1000, * do: () => { * alert("callback launched"); * } * }, true); */ add(data, bool = true) { return super.add(data, bool); } /** * @function Vevet.IntervalModule#on * @memberof Vevet.IntervalModule * * @param {''} target * @param {Function} callback * @param {Vevet.IntervalModule.EventObjSettings} prop * * @returns {string} */ /** * @member Vevet.IntervalModule#_events * @memberof Vevet.IntervalModule * @protected * @type {Array<Vevet.IntervalModule.EventData>} */ /** * @member Vevet.IntervalModule#events * @memberof Vevet.IntervalModule * @readonly * @type {Array<Vevet.IntervalModule.EventData>} */ _addCallback(id) { let obj = this.get(id); if (!obj) { return false; } // create interval vars obj._intervalFunc = false; obj._focus = false; obj._blur = false; obj._on = obj.on; // disable on blur if (typeof obj.data.disableOnBlur != 'boolean') { obj.data.disableOnBlur = true; } // enable interval if possible if (obj.on) { if (obj.data.disableOnBlur) { if (document.hasFocus()) { this._on(id); } } else { this._on(id); } } // add events if (obj.data.disableOnBlur) { obj._focus = this.listener(window, 'focus', this._on.bind(this, id)); obj._blur = this.listener(window, 'blur', this._off.bind(this, id)); } } _turnCallback(id) { let obj = this.get(id); obj._on = obj.on; if (obj.on) { if (obj.data.disableOnBlur) { if (document.hasFocus()) { this._on(id); } } else { this._on(id); } } else { this._off(id); } } _removeCallback(id) { let obj = this.get(id); // remove interval if (obj._intervalFunc !== false) { clearInterval(obj._intervalFunc); } // remove events if (obj.data.disableOnBlur) { this.removeEventListener({ id: obj._focus.id, el: obj._focus.el }); this.removeEventListener({ id: obj._blur.id, el: obj._blur.el }); } } /** * @description Enable event. * * @param {string} id - Id of the event. * * @protected */ _on(id){ let obj = this.get(id); // disable interval at first this._off(id); if (!obj._on) { return; } // set interval if (obj.data.disableOnBlur) { if (document.hasFocus()) { this._enable(obj); } } else { this._enable(obj); } } /** * @description Enable interval * @param {Vevet.IntervalModule.EventData} obj * @protected */ _enable(obj) { obj._intervalFunc = setInterval(() => { this._launch(obj); }, obj.data.interval); } /** * @description Disable event. * * @param {string} id - Id of the event. * * @protected */ _off(id) { let obj = this.get(id); // clear interval if (obj._intervalFunc !== false) { clearInterval(obj._intervalFunc); obj._intervalFunc = false; } } }
JavaScript
class DataStream { constructor(arrayBuffer) { this.buffer = arrayBuffer; this.data = new DataView(arrayBuffer); this.pointer = 0; } get bytes() { return new Uint8Array(this.buffer); } get byteLength() { return this.data.byteLength; } seek(offset, whence) { switch (whence) { case 2 /* End */: this.pointer = this.data.byteLength + offset; break; case 1 /* Current */: this.pointer += offset; break; case 0 /* Begin */: default: this.pointer = offset; break; } } readUint8() { const val = this.data.getUint8(this.pointer); this.pointer += 1; return val; } writeUint8(value) { this.data.setUint8(this.pointer, value); this.pointer += 1; } readInt8() { const val = this.data.getInt8(this.pointer); this.pointer += 1; return val; } writeInt8(value) { this.data.setInt8(this.pointer, value); this.pointer += 1; } readUint16(littleEndian = true) { const val = this.data.getUint16(this.pointer, littleEndian); this.pointer += 2; return val; } writeUint16(value, littleEndian = true) { this.data.setUint16(this.pointer, value, littleEndian); this.pointer += 2; } readInt16(littleEndian = true) { const val = this.data.getInt16(this.pointer, littleEndian); this.pointer += 2; return val; } writeInt16(value, littleEndian = true) { this.data.setInt16(this.pointer, value, littleEndian); this.pointer += 2; } readUint32(littleEndian = true) { const val = this.data.getUint32(this.pointer, littleEndian); this.pointer += 4; return val; } writeUint32(value, littleEndian = true) { this.data.setUint32(this.pointer, value, littleEndian); this.pointer += 4; } readInt32(littleEndian = true) { const val = this.data.getInt32(this.pointer, littleEndian); this.pointer += 4; return val; } writeInt32(value, littleEndian = true) { this.data.setInt32(this.pointer, value, littleEndian); this.pointer += 4; } readBytes(count) { const bytes = new Uint8Array(this.data.buffer, this.pointer, count); this.pointer += bytes.byteLength; return bytes; } writeBytes(bytes) { bytes.forEach((byte) => this.writeUint8(byte)); } readHex(count, reverse = false) { const bytes = this.readBytes(count); let hex = []; for (let i = 0; i < bytes.length; i++) { hex.push(bytes[i].toString(16).padStart(2, '0')); } if (reverse) hex.reverse(); return hex.join('').toUpperCase(); } readChars(count) { const chars = this.readBytes(count); let str = ''; for (let i = 0; i < chars.length; i++) { const char = chars[i]; if (char === 0) break; str += String.fromCharCode(char); } return str; } writeChars(string) { for (let i = 0; i < string.length; i++) { const char = string.charCodeAt(i); this.writeUint8(char); } } readWideChars(count) { const chars = new Uint16Array(this.data.buffer, this.pointer, count); let str = ''; for (let i = 0; i < chars.length; i++) { const char = chars[i]; if (char == 0) break; str += String.fromCharCode(char); } this.pointer += chars.byteLength; return str; } }
JavaScript
class FlipnoteParserBase extends DataStream { constructor() { /** Static file format info */ super(...arguments); /** Instance file format info */ /** Custom object tag */ this[Symbol.toStringTag] = 'Flipnote'; /** Default formats used for {@link getTitle()} */ this.titleFormats = { COMMENT: 'Comment by $USERNAME', FLIPNOTE: 'Flipnote by $USERNAME', ICON: 'Folder icon' }; /** File audio track info, see {@link FlipnoteAudioTrackInfo} */ this.soundMeta = new Map(); /** Animation frame global layer visibility */ this.layerVisibility = { 1: true, 2: true, 3: true }; /** (KWZ only) Indicates whether or not this file is a Flipnote Studio 3D folder icon */ this.isFolderIcon = false; /** (KWZ only) Indicates whether or not this file is a handwritten comment from Flipnote Gallery World */ this.isComment = false; /** (KWZ only) Indicates whether or not this Flipnote is a PPM to KWZ conversion from Flipnote Studio 3D's DSi Library service */ this.isDsiLibraryNote = false; } /** * Get file default title - e.g. "Flipnote by Y", "Comment by X", etc. * A format object can be passed for localisation, where `$USERNAME` gets replaced by author name: * ```js * { * COMMENT: 'Comment by $USERNAME', * FLIPNOTE: 'Flipnote by $USERNAME', * ICON: 'Folder icon' * } * ``` * @category Utility */ getTitle(formats = this.titleFormats) { if (this.isFolderIcon) return formats.ICON; const title = this.isComment ? formats.COMMENT : formats.FLIPNOTE; return title.replace('$USERNAME', this.meta.current.username); } /** * Returns the Flipnote title when casting a parser instance to a string * * ```js * const str = 'Title: ' + note; * // str === 'Title: Flipnote by username' * ``` * @category Utility */ toString() { return this.getTitle(); } /** * Allows for frame index iteration when using the parser instance as a for..of iterator * * ```js * for (const frameIndex of note) { * // do something with frameIndex... * } * ``` * @category Utility */ *[Symbol.iterator]() { for (let i = 0; i < this.frameCount; i++) yield i; } /** * Get the pixels for a given frame layer, as palette indices * NOTE: layerIndex are not guaranteed to be sorted by 3D depth in KWZs, use {@link getFrameLayerOrder} to get the correct sort order first * NOTE: if the visibility flag for this layer is turned off, the result will be empty * @category Image */ getLayerPixels(frameIndex, layerIndex, imageBuffer = new Uint8Array(this.imageWidth * this.imageHeight)) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); assertRange(layerIndex, 0, this.numLayers - 1, 'Layer index'); // palette const palette = this.getFramePaletteIndices(frameIndex); const palettePtr = layerIndex * this.numLayerColors; // raw pixels const layers = this.decodeFrame(frameIndex); const layerBuffer = layers[layerIndex]; // image dimensions and crop const srcStride = this.srcWidth; const width = this.imageWidth; const height = this.imageHeight; const xOffs = this.imageOffsetX; const yOffs = this.imageOffsetY; // clear image buffer before writing imageBuffer.fill(0); // handle layer visibility by returning a blank image if the layer is invisible if (!this.layerVisibility[layerIndex + 1]) return imageBuffer; // convert to palette indices and crop for (let srcY = yOffs, dstY = 0; dstY < height; srcY++, dstY++) { for (let srcX = xOffs, dstX = 0; dstX < width; srcX++, dstX++) { const srcPtr = srcY * srcStride + srcX; const dstPtr = dstY * width + dstX; let pixel = layerBuffer[srcPtr]; if (pixel !== 0) imageBuffer[dstPtr] = palette[palettePtr + pixel]; } } return imageBuffer; } /** * Get the pixels for a given frame layer, as RGBA pixels * NOTE: layerIndex are not guaranteed to be sorted by 3D depth in KWZs, use {@link getFrameLayerOrder} to get the correct sort order first * NOTE: if the visibility flag for this layer is turned off, the result will be empty * @category Image */ getLayerPixelsRgba(frameIndex, layerIndex, imageBuffer = new Uint32Array(this.imageWidth * this.imageHeight), paletteBuffer = new Uint32Array(16)) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); assertRange(layerIndex, 0, this.numLayers - 1, 'Layer index'); // palette this.getFramePaletteUint32(frameIndex, paletteBuffer); const palettePtr = layerIndex * this.numLayerColors; // raw pixels const layers = this.decodeFrame(frameIndex); const layerBuffer = layers[layerIndex]; // image dimensions and crop const srcStride = this.srcWidth; const width = this.imageWidth; const height = this.imageHeight; const xOffs = this.imageOffsetX; const yOffs = this.imageOffsetY; // clear image buffer before writing imageBuffer.fill(paletteBuffer[0]); // handle layer visibility by returning a blank image if the layer is invisible if (!this.layerVisibility[layerIndex + 1]) return imageBuffer; // convert to palette indices and crop for (let srcY = yOffs, dstY = 0; dstY < height; srcY++, dstY++) { for (let srcX = xOffs, dstX = 0; dstX < width; srcX++, dstX++) { const srcPtr = srcY * srcStride + srcX; const dstPtr = dstY * width + dstX; let pixel = layerBuffer[srcPtr]; if (pixel !== 0) imageBuffer[dstPtr] = paletteBuffer[palettePtr + pixel]; } } return imageBuffer; } /** * Get the image for a given frame, as palette indices * @category Image */ getFramePixels(frameIndex, imageBuffer = new Uint8Array(this.imageWidth * this.imageHeight)) { // image dimensions and crop const srcStride = this.srcWidth; const width = this.imageWidth; const height = this.imageHeight; const xOffs = this.imageOffsetX; const yOffs = this.imageOffsetY; // palette const palette = this.getFramePaletteIndices(frameIndex); // clear framebuffer with paper color imageBuffer.fill(palette[0]); // get layer info + decode into buffers const layerOrder = this.getFrameLayerOrder(frameIndex); const layers = this.decodeFrame(frameIndex); // merge layers into framebuffer for (let i = 0; i < this.numLayers; i++) { const layerIndex = layerOrder[i]; const layerBuffer = layers[layerIndex]; const palettePtr = layerIndex * this.numLayerColors; // skip if layer is not visible if (!this.layerVisibility[layerIndex + 1]) continue; // merge layer into rgb buffer for (let srcY = yOffs, dstY = 0; dstY < height; srcY++, dstY++) { for (let srcX = xOffs, dstX = 0; dstX < width; srcX++, dstX++) { const srcPtr = srcY * srcStride + srcX; const dstPtr = dstY * width + dstX; let pixel = layerBuffer[srcPtr]; if (pixel !== 0) imageBuffer[dstPtr] = palette[palettePtr + pixel]; } } } return imageBuffer; } /** * Get the image for a given frame as an uint32 array of RGBA pixels * @category Image */ getFramePixelsRgba(frameIndex, imageBuffer = new Uint32Array(this.imageWidth * this.imageHeight), paletteBuffer = new Uint32Array(16)) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); // image dimensions and crop const srcStride = this.srcWidth; const width = this.imageWidth; const height = this.imageHeight; const xOffs = this.imageOffsetX; const yOffs = this.imageOffsetY; // palette this.getFramePaletteUint32(frameIndex, paletteBuffer); // clear framebuffer with paper color imageBuffer.fill(paletteBuffer[0]); // get layer info + decode into buffers const layerOrder = this.getFrameLayerOrder(frameIndex); const layers = this.decodeFrame(frameIndex); // merge layers into framebuffer for (let i = 0; i < this.numLayers; i++) { const layerIndex = layerOrder[i]; const layerBuffer = layers[layerIndex]; const palettePtr = layerIndex * this.numLayerColors; // skip if layer is not visible if (!this.layerVisibility[layerIndex + 1]) continue; // merge layer into rgb buffer for (let srcY = yOffs, dstY = 0; dstY < height; srcY++, dstY++) { for (let srcX = xOffs, dstX = 0; dstX < width; srcX++, dstX++) { const srcPtr = srcY * srcStride + srcX; const dstPtr = dstY * width + dstX; let pixel = layerBuffer[srcPtr]; if (pixel !== 0) imageBuffer[dstPtr] = paletteBuffer[palettePtr + pixel]; } } } return imageBuffer; } /** * Get the color palette for a given frame, as an uint32 array * @category Image */ getFramePaletteUint32(frameIndex, paletteBuffer = new Uint32Array(16)) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); const colors = this.getFramePalette(frameIndex); paletteBuffer.fill(0); colors.forEach(([r, g, b, a], i) => paletteBuffer[i] = (a << 24) | (b << 16) | (g << 8) | r); return paletteBuffer; } /** * Get the usage flags for a given track accross every frame * @returns an array of booleans for every frame, indicating whether the track is used on that frame * @category Audio */ getSoundEffectFlagsForTrack(trackId) { return this.getSoundEffectFlags().map(frammeFlags => frammeFlags[trackId]); } ; /** * Is a given track used on a given frame * @category Audio */ isSoundEffectUsedOnFrame(trackId, frameIndex) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); if (!this.soundEffectTracks.includes(trackId)) return false; return this.getFrameSoundEffectFlags(frameIndex)[trackId]; } /** * Does an audio track exist in the Flipnote? * @returns boolean * @category Audio */ hasAudioTrack(trackId) { return this.soundMeta.has(trackId) && this.soundMeta.get(trackId).length > 0; } }
JavaScript
class KwzParser extends FlipnoteParserBase { /** * Create a new KWZ file parser instance * @param arrayBuffer an ArrayBuffer containing file data * @param settings parser settings */ constructor(arrayBuffer, settings = {}) { super(arrayBuffer); /** File format type, reflects {@link KwzParser.format} */ this.format = FlipnoteFormat.KWZ; /** Custom object tag */ this[Symbol.toStringTag] = 'Flipnote Studio 3D KWZ animation file'; /** Animation frame width, reflects {@link KwzParser.width} */ this.imageWidth = KwzParser.width; /** Animation frame height, reflects {@link KwzParser.height} */ this.imageHeight = KwzParser.height; /** X offset for the top-left corner of the animation frame */ this.imageOffsetX = 0; /** Y offset for the top-left corner of the animation frame */ this.imageOffsetY = 0; /** Number of animation frame layers, reflects {@link KwzParser.numLayers} */ this.numLayers = KwzParser.numLayers; /** Number of colors per layer (aside from transparent), reflects {@link KwzParser.numLayerColors} */ this.numLayerColors = KwzParser.numLayerColors; /** key used for Flipnote verification, in PEM format */ this.publicKey = KwzParser.publicKey; /** @internal */ this.srcWidth = KwzParser.width; /** Which audio tracks are available in this format, reflects {@link KwzParser.audioTracks} */ this.audioTracks = KwzParser.audioTracks; /** Which sound effect tracks are available in this format, reflects {@link KwzParser.soundEffectTracks} */ this.soundEffectTracks = KwzParser.soundEffectTracks; /** Audio track base sample rate, reflects {@link KwzParser.rawSampleRate} */ this.rawSampleRate = KwzParser.rawSampleRate; /** Audio output sample rate, reflects {@link KwzParser.sampleRate} */ this.sampleRate = KwzParser.sampleRate; /** Global animation frame color palette, reflects {@link KwzParser.globalPalette} */ this.globalPalette = KwzParser.globalPalette; this.prevDecodedFrame = null; this.bitIndex = 0; this.bitValue = 0; this.settings = { ...KwzParser.defaultSettings, ...settings }; this.layerBuffers = [ new Uint8Array(KwzParser.width * KwzParser.height), new Uint8Array(KwzParser.width * KwzParser.height), new Uint8Array(KwzParser.width * KwzParser.height), ]; // skip through the file and read all of the section headers so we can locate them this.buildSectionMap(); // if the KIC section is present, we're dealing with a folder icon // these are single-frame KWZs without a KFH section for metadata, or a KSN section for sound // while the data for a full frame (320*240) is present, only the top-left 24*24 pixels are used if (this.sectionMap.has('KIC')) { this.isFolderIcon = true; // icons still use the full 320 * 240 frame size, so we just set up our image crop to deal with that this.imageWidth = 24; this.imageHeight = 24; this.frameCount = 1; this.frameSpeed = 0; this.framerate = KWZ_FRAMERATES[0]; this.thumbFrameIndex = 0; this.getFrameOffsets(); } // if the KSN section is not present, then this is a handwritten comment from the Flipnote Gallery World online service // these are single-frame KWZs, just with no sound else if (!this.sectionMap.has('KSN')) { this.isComment = true; this.decodeMeta(); this.getFrameOffsets(); } // else let's assume this is a regular note else { this.decodeMeta(); this.getFrameOffsets(); this.decodeSoundHeader(); } // apply special optimisations for converted DSi library notes if (this.settings.dsiLibraryNote) { this.isDsiLibraryNote = true; } // automatically crop out the border around every frame if (this.settings.borderCrop) { // dsi library notes can be cropped to their original resolution if (this.isDsiLibraryNote) { this.imageOffsetX = 32; this.imageOffsetY = 24; this.imageWidth = 256; this.imageHeight = 192; } // even standard notes have a bit of a border... else if (!this.isFolderIcon) { this.imageOffsetX = 5; this.imageOffsetY = 5; this.imageWidth = 310; this.imageHeight = 230; } } } buildSectionMap() { const fileSize = this.byteLength - 256; const sectionMap = new Map(); let sectionCount = 0; let ptr = 0; // counting sections should mitigate against one of mrnbayoh's notehax exploits while (ptr < fileSize && sectionCount < 6) { this.seek(ptr); const magic = this.readChars(4).substring(0, 3); const length = this.readUint32(); sectionMap.set(magic, { ptr, length }); ptr += length + 8; sectionCount += 1; } this.bodyEndOffset = ptr; this.sectionMap = sectionMap; assert(sectionMap.has('KMC') && sectionMap.has('KMI')); } readBits(num) { // assert(num < 16); if (this.bitIndex + num > 16) { const nextBits = this.readUint16(); this.bitValue |= nextBits << (16 - this.bitIndex); this.bitIndex -= 16; } const result = this.bitValue & BITMASKS[num]; this.bitValue >>= num; this.bitIndex += num; return result; } readFsid() { if (this.settings.dsiLibraryNote) { // format as DSi PPM FSID const hex = this.readHex(10, true); return hex.slice(2, 18); } const hex = this.readHex(10); return `${hex.slice(0, 4)}-${hex.slice(4, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 18)}`.toLowerCase(); } readFilename() { const ptr = this.pointer; const chars = this.readChars(28); if (chars.length === 28) return chars; // Otherwise, this is likely a DSi Library note, // where sometimes Nintendo's buggy PPM converter includes the original packed PPM filename this.seek(ptr); const mac = this.readHex(3); const random = this.readChars(13); const edits = this.readUint16().toString().padStart(3, '0'); this.seek(ptr + 28); return `${mac}_${random}_${edits}`; } decodeMeta() { if (this.settings.quickMeta) return this.decodeMetaQuick(); assert(this.sectionMap.has('KFH')); this.seek(this.sectionMap.get('KFH').ptr + 12); const creationTime = dateFromNintendoTimestamp(this.readUint32()); const modifiedTime = dateFromNintendoTimestamp(this.readUint32()); // const simonTime = this.readUint32(); const rootAuthorId = this.readFsid(); const parentAuthorId = this.readFsid(); const currentAuthorId = this.readFsid(); const rootAuthorName = this.readWideChars(11); const parentAuthorName = this.readWideChars(11); const currentAuthorName = this.readWideChars(11); const rootFilename = this.readFilename(); const parentFilename = this.readFilename(); const currentFilename = this.readFilename(); const frameCount = this.readUint16(); const thumbIndex = this.readUint16(); const flags = this.readUint16(); const frameSpeed = this.readUint8(); const layerFlags = this.readUint8(); this.isSpinoff = (currentAuthorId !== parentAuthorId) || (currentAuthorId !== rootAuthorId); this.frameCount = frameCount; this.frameSpeed = frameSpeed; this.framerate = KWZ_FRAMERATES[frameSpeed]; this.duration = timeGetNoteDuration(this.frameCount, this.framerate); this.thumbFrameIndex = thumbIndex; this.layerVisibility = { 1: (layerFlags & 0x1) === 0, 2: (layerFlags & 0x2) === 0, 3: (layerFlags & 0x3) === 0, }; // Try to auto-detect whether the current author ID matches a converted PPM ID // if (isKwzDsiLibraryFsid(currentAuthorId)) { // this.isDsiLibraryNote = true; // } this.meta = { lock: (flags & 0x1) !== 0, loop: (flags & 0x2) !== 0, isSpinoff: this.isSpinoff, frameCount: frameCount, frameSpeed: frameSpeed, duration: this.duration, thumbIndex: thumbIndex, timestamp: modifiedTime, creationTimestamp: creationTime, root: { username: rootAuthorName, fsid: rootAuthorId, region: getKwzFsidRegion(rootAuthorId), filename: rootFilename, isDsiFilename: rootFilename.length !== 28 }, parent: { username: parentAuthorName, fsid: parentAuthorId, region: getKwzFsidRegion(parentAuthorId), filename: parentFilename, isDsiFilename: parentFilename.length !== 28 }, current: { username: currentAuthorName, fsid: currentAuthorId, region: getKwzFsidRegion(currentAuthorId), filename: currentFilename, isDsiFilename: currentFilename.length !== 28 }, }; } decodeMetaQuick() { assert(this.sectionMap.has('KFH')); this.seek(this.sectionMap.get('KFH').ptr + 0x8 + 0xC4); const frameCount = this.readUint16(); const thumbFrameIndex = this.readUint16(); this.readUint16(); const frameSpeed = this.readUint8(); const layerFlags = this.readUint8(); this.frameCount = frameCount; this.thumbFrameIndex = thumbFrameIndex; this.frameSpeed = frameSpeed; this.framerate = KWZ_FRAMERATES[frameSpeed]; this.duration = timeGetNoteDuration(this.frameCount, this.framerate); this.layerVisibility = { 1: (layerFlags & 0x1) === 0, 2: (layerFlags & 0x2) === 0, 3: (layerFlags & 0x3) === 0, }; } getFrameOffsets() { assert(this.sectionMap.has('KMI') && this.sectionMap.has('KMC')); const numFrames = this.frameCount; const kmiSection = this.sectionMap.get('KMI'); const kmcSection = this.sectionMap.get('KMC'); assert(kmiSection.length / 28 >= numFrames); const frameMetaOffsets = new Uint32Array(numFrames); const frameDataOffsets = new Uint32Array(numFrames); const frameLayerSizes = []; let frameMetaPtr = kmiSection.ptr + 8; let frameDataPtr = kmcSection.ptr + 12; for (let frameIndex = 0; frameIndex < numFrames; frameIndex++) { this.seek(frameMetaPtr + 4); const layerASize = this.readUint16(); const layerBSize = this.readUint16(); const layerCSize = this.readUint16(); frameMetaOffsets[frameIndex] = frameMetaPtr; frameDataOffsets[frameIndex] = frameDataPtr; frameMetaPtr += 28; frameDataPtr += layerASize + layerBSize + layerCSize; assert(frameMetaPtr < this.byteLength, `frame${frameIndex} meta pointer out of bounds`); assert(frameDataPtr < this.byteLength, `frame${frameIndex} data pointer out of bounds`); frameLayerSizes.push([layerASize, layerBSize, layerCSize]); } this.frameMetaOffsets = frameMetaOffsets; this.frameDataOffsets = frameDataOffsets; this.frameLayerSizes = frameLayerSizes; } decodeSoundHeader() { assert(this.sectionMap.has('KSN')); let ptr = this.sectionMap.get('KSN').ptr + 8; this.seek(ptr); this.bgmSpeed = this.readUint32(); assert(this.bgmSpeed <= 10); this.bgmrate = KWZ_FRAMERATES[this.bgmSpeed]; const trackSizes = new Uint32Array(this.buffer, ptr + 4, 20); const soundMeta = new Map(); soundMeta.set(FlipnoteAudioTrack.BGM, { ptr: ptr += 28, length: trackSizes[0] }); soundMeta.set(FlipnoteAudioTrack.SE1, { ptr: ptr += trackSizes[0], length: trackSizes[1] }); soundMeta.set(FlipnoteAudioTrack.SE2, { ptr: ptr += trackSizes[1], length: trackSizes[2] }); soundMeta.set(FlipnoteAudioTrack.SE3, { ptr: ptr += trackSizes[2], length: trackSizes[3] }); soundMeta.set(FlipnoteAudioTrack.SE4, { ptr: ptr += trackSizes[3], length: trackSizes[4] }); this.soundMeta = soundMeta; } /** * Get the color palette indices for a given frame. RGBA colors for these values can be indexed from {@link KwzParser.globalPalette} * * Returns an array where: * - index 0 is the paper color index * - index 1 is the layer A color 1 index * - index 2 is the layer A color 2 index * - index 3 is the layer B color 1 index * - index 4 is the layer B color 2 index * - index 5 is the layer C color 1 index * - index 6 is the layer C color 2 index * @category Image */ getFramePaletteIndices(frameIndex) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); this.seek(this.frameMetaOffsets[frameIndex]); const flags = this.readUint32(); return [ flags & 0xF, (flags >> 8) & 0xF, (flags >> 12) & 0xF, (flags >> 16) & 0xF, (flags >> 20) & 0xF, (flags >> 24) & 0xF, (flags >> 28) & 0xF, ]; } /** * Get the RGBA colors for a given frame * * Returns an array where: * - index 0 is the paper color * - index 1 is the layer A color 1 * - index 2 is the layer A color 2 * - index 3 is the layer B color 1 * - index 4 is the layer B color 2 * - index 5 is the layer C color 1 * - index 6 is the layer C color 2 * @category Image */ getFramePalette(frameIndex) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); const indices = this.getFramePaletteIndices(frameIndex); return indices.map(colorIndex => this.globalPalette[colorIndex]); } getFrameDiffingFlag(frameIndex) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); this.seek(this.frameMetaOffsets[frameIndex]); const flags = this.readUint32(); return (flags >> 4) & 0x07; } getFrameLayerSizes(frameIndex) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); this.seek(this.frameMetaOffsets[frameIndex] + 0x4); return [ this.readUint16(), this.readUint16(), this.readUint16() ]; } getFrameLayerDepths(frameIndex) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); this.seek(this.frameMetaOffsets[frameIndex] + 0x14); const a = [ this.readUint8(), this.readUint8(), this.readUint8() ]; return a; } getFrameAuthor(frameIndex) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); this.seek(this.frameMetaOffsets[frameIndex] + 0xA); return this.readFsid(); } decodeFrameSoundFlags(frameIndex) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); this.seek(this.frameMetaOffsets[frameIndex] + 0x17); const soundFlags = this.readUint8(); return [ (soundFlags & 0x1) !== 0, (soundFlags & 0x2) !== 0, (soundFlags & 0x4) !== 0, (soundFlags & 0x8) !== 0, ]; } getFrameCameraFlags(frameIndex) { this.seek(this.frameMetaOffsets[frameIndex] + 0x1A); const cameraFlags = this.readUint8(); return [ (cameraFlags & 0x1) !== 0, (cameraFlags & 0x2) !== 0, (cameraFlags & 0x4) !== 0, ]; } /** * Get the layer draw order for a given frame * @category Image * @returns Array of layer indexes, in the order they should be drawn */ getFrameLayerOrder(frameIndex) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); const depths = this.getFrameLayerDepths(frameIndex); return [2, 1, 0].sort((a, b) => depths[b] - depths[a]); } /** * Decode a frame, returning the raw pixel buffers for each layer * @category Image */ decodeFrame(frameIndex, diffingFlag = 0x7, isPrevFrame = false) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); // return existing layer buffers if no new frame has been decoded since the last call if (this.prevDecodedFrame === frameIndex) return this.layerBuffers; // the prevDecodedFrame check is an optimisation for decoding frames in full sequence if (this.prevDecodedFrame !== frameIndex - 1 && frameIndex !== 0) { // if this frame is being decoded as a prev frame, then we only want to decode the layers necessary // diffingFlag is negated with ~ so if no layers are diff-based, diffingFlag is 0 if (isPrevFrame) diffingFlag = diffingFlag & ~this.getFrameDiffingFlag(frameIndex + 1); // if diffing flag isn't 0, decode the previous frame before this one if (diffingFlag !== 0) this.decodeFrame(frameIndex - 1, diffingFlag, true); } let framePtr = this.frameDataOffsets[frameIndex]; const layerSizes = this.frameLayerSizes[frameIndex]; for (let layerIndex = 0; layerIndex < 3; layerIndex++) { // dsi gallery conversions don't use the third layer, so it can be skipped if this is set if (this.settings.dsiLibraryNote && layerIndex === 3) break; this.seek(framePtr); let layerSize = layerSizes[layerIndex]; framePtr += layerSize; const pixelBuffer = this.layerBuffers[layerIndex]; // if the layer is 38 bytes then it hasn't changed at all since the previous frame, so we can skip it if (layerSize === 38) continue; // if this layer doesn't need to be decoded for diffing if (((diffingFlag >> layerIndex) & 0x1) === 0) continue; // reset readbits state this.bitIndex = 16; this.bitValue = 0; // tile skip counter let skipTileCounter = 0; for (let tileOffsetY = 0; tileOffsetY < 240; tileOffsetY += 128) { for (let tileOffsetX = 0; tileOffsetX < 320; tileOffsetX += 128) { // loop small tiles for (let subTileOffsetY = 0; subTileOffsetY < 128; subTileOffsetY += 8) { const y = tileOffsetY + subTileOffsetY; if (y >= 240) break; for (let subTileOffsetX = 0; subTileOffsetX < 128; subTileOffsetX += 8) { const x = tileOffsetX + subTileOffsetX; if (x >= 320) break; // continue to next tile loop if skipTileCounter is > 0 if (skipTileCounter > 0) { skipTileCounter -= 1; continue; } let pixelBufferPtr = y * KwzParser.width + x; const tileType = this.readBits(3); if (tileType === 0) { const linePtr = this.readBits(5) * 8; const pixels = KWZ_LINE_TABLE_COMMON.subarray(linePtr, linePtr + 8); pixelBuffer.set(pixels, pixelBufferPtr); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); } else if (tileType === 1) { const linePtr = this.readBits(13) * 8; const pixels = KWZ_LINE_TABLE.subarray(linePtr, linePtr + 8); pixelBuffer.set(pixels, pixelBufferPtr); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); pixelBuffer.set(pixels, pixelBufferPtr += 320); } else if (tileType === 2) { const linePtr = this.readBits(5) * 8; const a = KWZ_LINE_TABLE_COMMON.subarray(linePtr, linePtr + 8); const b = KWZ_LINE_TABLE_COMMON_SHIFT.subarray(linePtr, linePtr + 8); pixelBuffer.set(a, pixelBufferPtr); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); } else if (tileType === 3) { const linePtr = this.readBits(13) * 8; const a = KWZ_LINE_TABLE.subarray(linePtr, linePtr + 8); const b = KWZ_LINE_TABLE_SHIFT.subarray(linePtr, linePtr + 8); pixelBuffer.set(a, pixelBufferPtr); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); } // most common tile type else if (tileType === 4) { const flags = this.readBits(8); for (let mask = 1; mask < 0xFF; mask <<= 1) { if (flags & mask) { const linePtr = this.readBits(5) * 8; const pixels = KWZ_LINE_TABLE_COMMON.subarray(linePtr, linePtr + 8); pixelBuffer.set(pixels, pixelBufferPtr); } else { const linePtr = this.readBits(13) * 8; const pixels = KWZ_LINE_TABLE.subarray(linePtr, linePtr + 8); pixelBuffer.set(pixels, pixelBufferPtr); } pixelBufferPtr += 320; } } else if (tileType === 5) { skipTileCounter = this.readBits(5); continue; } // type 6 doesnt exist else if (tileType === 7) { let pattern = this.readBits(2); let useCommonLines = this.readBits(1); let a, b; if (useCommonLines !== 0) { const linePtrA = this.readBits(5) * 8; const linePtrB = this.readBits(5) * 8; a = KWZ_LINE_TABLE_COMMON.subarray(linePtrA, linePtrA + 8); b = KWZ_LINE_TABLE_COMMON.subarray(linePtrB, linePtrB + 8); pattern += 1; } else { const linePtrA = this.readBits(13) * 8; const linePtrB = this.readBits(13) * 8; a = KWZ_LINE_TABLE.subarray(linePtrA, linePtrA + 8); b = KWZ_LINE_TABLE.subarray(linePtrB, linePtrB + 8); } switch (pattern % 4) { case 0: pixelBuffer.set(a, pixelBufferPtr); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); break; case 1: pixelBuffer.set(a, pixelBufferPtr); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); break; case 2: pixelBuffer.set(a, pixelBufferPtr); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); break; case 3: pixelBuffer.set(a, pixelBufferPtr); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); pixelBuffer.set(a, pixelBufferPtr += 320); pixelBuffer.set(b, pixelBufferPtr += 320); break; } } } } } } } this.prevDecodedFrame = frameIndex; return this.layerBuffers; } /** * Get the sound effect flags for every frame in the Flipnote * @category Audio */ decodeSoundFlags() { if (this.soundFlags !== undefined) return this.soundFlags; this.soundFlags = new Array(this.frameCount) .fill(false) .map((_, i) => this.decodeFrameSoundFlags(i)); return this.soundFlags; } /** * Get the sound effect usage flags for every frame * @category Audio */ getSoundEffectFlags() { return this.decodeSoundFlags().map((frameFlags) => ({ [FlipnoteSoundEffectTrack.SE1]: frameFlags[0], [FlipnoteSoundEffectTrack.SE2]: frameFlags[1], [FlipnoteSoundEffectTrack.SE3]: frameFlags[2], [FlipnoteSoundEffectTrack.SE4]: frameFlags[3], })); } /** * Get the sound effect usage for a given frame * @param frameIndex * @category Audio */ getFrameSoundEffectFlags(frameIndex) { const frameFlags = this.decodeFrameSoundFlags(frameIndex); return { [FlipnoteSoundEffectTrack.SE1]: frameFlags[0], [FlipnoteSoundEffectTrack.SE2]: frameFlags[1], [FlipnoteSoundEffectTrack.SE3]: frameFlags[2], [FlipnoteSoundEffectTrack.SE4]: frameFlags[3], }; } /** * Get the raw compressed audio data for a given track * @returns Byte array * @category Audio */ getAudioTrackRaw(trackId) { const trackMeta = this.soundMeta.get(trackId); assert(trackMeta.ptr + trackMeta.length < this.byteLength); return new Uint8Array(this.buffer, trackMeta.ptr, trackMeta.length); } decodeAdpcm(src, dst, predictor = 0, stepIndex = 0) { const srcSize = src.length; let dstPtr = 0; let sample = 0; let step = 0; let diff = 0; // loop through each byte in the raw adpcm data for (let srcPtr = 0; srcPtr < srcSize; srcPtr++) { let currByte = src[srcPtr]; let currBit = 0; while (currBit < 8) { // 2 bit sample if (stepIndex < 18 || currBit > 4) { sample = currByte & 0x3; step = ADPCM_STEP_TABLE[stepIndex]; diff = step >> 3; if (sample & 1) diff += step; if (sample & 2) diff = -diff; predictor += diff; stepIndex += ADPCM_INDEX_TABLE_2BIT[sample]; currByte >>= 2; currBit += 2; } // 4 bit sample else { sample = currByte & 0xf; step = ADPCM_STEP_TABLE[stepIndex]; diff = step >> 3; if (sample & 1) diff += step >> 2; if (sample & 2) diff += step >> 1; if (sample & 4) diff += step; if (sample & 8) diff = -diff; predictor += diff; stepIndex += ADPCM_INDEX_TABLE_4BIT[sample]; currByte >>= 4; currBit += 4; } stepIndex = clamp(stepIndex, 0, 79); // clamp as 12 bit then scale to 16 predictor = clamp(predictor, -2048, 2047); dst[dstPtr] = predictor * 16; dstPtr += 1; } } return dstPtr; } /** * Get the decoded audio data for a given track, using the track's native samplerate * @returns Signed 16-bit PCM audio * @category Audio */ decodeAudioTrack(trackId) { const settings = this.settings; const src = this.getAudioTrackRaw(trackId); const dstSize = this.rawSampleRate * 60; // enough for 60 seconds, the max bgm size const dst = new Int16Array(dstSize); // initial decoder state let predictor = 0; let stepIndex = 40; // Nintendo messed up the initial adpcm state for a bunch of the PPM conversions on DSi Library // they are effectively random, so you can optionally provide your own state values, or let the lib make a best guess if (this.isDsiLibraryNote) { if (trackId === FlipnoteAudioTrack.BGM) { // allow manual overrides for default predictor if (settings.initialBgmPredictor !== null) predictor = settings.initialBgmPredictor; // allow manual overrides for default step index if (settings.initialBgmStepIndex !== null) stepIndex = settings.initialBgmStepIndex; // bruteforce step index by finding the lowest track root mean square if (settings.guessInitialBgmState) { let bestRms = 0xFFFFFFFF; // arbritrarily large let bestStepIndex = 0; for (stepIndex = 0; stepIndex <= 40; stepIndex++) { const dstPtr = this.decodeAdpcm(src, dst, predictor, stepIndex); const rms = pcmGetRms(dst.subarray(0, dstPtr)); // uses same underlying memory as dst if (rms < bestRms) { bestRms = rms; bestStepIndex = stepIndex; } } stepIndex = bestStepIndex; } } else { const trackIndex = this.soundEffectTracks.indexOf(trackId); // allow manual overrides for default predictor if (Array.isArray(settings.initialSePredictors) && settings.initialSePredictors[trackIndex] !== undefined) predictor = settings.initialSePredictors[trackIndex]; // allow manual overrides for default step index if (Array.isArray(settings.initialSeStepIndices) && settings.initialSeStepIndices[trackIndex] !== undefined) stepIndex = settings.initialSeStepIndices[trackIndex]; } } // decode track const dstPtr = this.decodeAdpcm(src, dst, predictor, stepIndex); // copy part of dst with slice() so dst buffer can be garbage collected return dst.slice(0, dstPtr); } /** * Get the decoded audio data for a given track, using the specified samplerate * @returns Signed 16-bit PCM audio * @category Audio */ getAudioTrackPcm(trackId, dstFreq = this.sampleRate) { const srcPcm = this.decodeAudioTrack(trackId); let srcFreq = this.rawSampleRate; if (trackId === FlipnoteAudioTrack.BGM) { const bgmAdjust = (1 / this.bgmrate) / (1 / this.framerate); srcFreq = this.rawSampleRate * bgmAdjust; } if (srcFreq !== dstFreq) return pcmResampleLinear(srcPcm, srcFreq, dstFreq); return srcPcm; } pcmAudioMix(src, dst, dstOffset = 0) { const srcSize = src.length; const dstSize = dst.length; for (let n = 0; n < srcSize; n++) { if (dstOffset + n > dstSize) break; // half src volume const samp = dst[dstOffset + n] + src[n]; dst[dstOffset + n] = clamp(samp, -32768, 32767); } } /** * Get the full mixed audio for the Flipnote, using the specified samplerate * @returns Signed 16-bit PCM audio * @category Audio */ getAudioMasterPcm(dstFreq = this.sampleRate) { const dstSize = Math.ceil(this.duration * dstFreq); const master = new Int16Array(dstSize); const hasBgm = this.hasAudioTrack(FlipnoteAudioTrack.BGM); const hasSe1 = this.hasAudioTrack(FlipnoteAudioTrack.SE1); const hasSe2 = this.hasAudioTrack(FlipnoteAudioTrack.SE2); const hasSe3 = this.hasAudioTrack(FlipnoteAudioTrack.SE3); const hasSe4 = this.hasAudioTrack(FlipnoteAudioTrack.SE4); // Mix background music if (hasBgm) { const bgmPcm = this.getAudioTrackPcm(FlipnoteAudioTrack.BGM, dstFreq); this.pcmAudioMix(bgmPcm, master, 0); } // Mix sound effects if (hasSe1 || hasSe2 || hasSe3 || hasSe4) { const samplesPerFrame = dstFreq / this.framerate; const se1Pcm = hasSe1 ? this.getAudioTrackPcm(FlipnoteAudioTrack.SE1, dstFreq) : null; const se2Pcm = hasSe2 ? this.getAudioTrackPcm(FlipnoteAudioTrack.SE2, dstFreq) : null; const se3Pcm = hasSe3 ? this.getAudioTrackPcm(FlipnoteAudioTrack.SE3, dstFreq) : null; const se4Pcm = hasSe4 ? this.getAudioTrackPcm(FlipnoteAudioTrack.SE4, dstFreq) : null; const soundEffectFlags = this.decodeSoundFlags(); for (let i = 0; i < this.frameCount; i++) { const seFlags = soundEffectFlags[i]; const seOffset = Math.ceil(i * samplesPerFrame); if (hasSe1 && seFlags[0]) this.pcmAudioMix(se1Pcm, master, seOffset); if (hasSe2 && seFlags[1]) this.pcmAudioMix(se2Pcm, master, seOffset); if (hasSe3 && seFlags[2]) this.pcmAudioMix(se3Pcm, master, seOffset); if (hasSe4 && seFlags[3]) this.pcmAudioMix(se4Pcm, master, seOffset); } } this.audioClipRatio = pcmGetClippingRatio(master); return master; } /** * Get the body of the Flipnote - the data that is digested for the signature * @category Verification */ getBody() { const bodyEnd = this.bodyEndOffset; return this.bytes.subarray(0, bodyEnd); } /** * Get the Flipnote's signature data * @category Verification */ getSignature() { const bodyEnd = this.bodyEndOffset; return this.bytes.subarray(bodyEnd, bodyEnd + 256); } /** * Verify whether this Flipnote's signature is valid * @category Verification */ async verify() { const key = await rsaLoadPublicKey(KWZ_PUBLIC_KEY, 'SHA-256'); return await rsaVerify(key, this.getSignature(), this.getBody()); } }
JavaScript
class HasPosition extends Component { constructor (parent, x, y) { super(parent, "position"); this.x = x; this.y = y; } }
JavaScript
class Ai extends Component { constructor (parent, positionComponent, mover) { super(parent, "ai"); this.positionComponent = positionComponent; this.mover = mover; } doNotOutOfBoundsCheck (x, y, dir) { switch (dir) { case 'up' : if (y - 1 < 0) {return true} break; // >= because of 0 index (0 - 49 is 50 tiles) case 'down' : if (y + 1 >= mapOptions.height) {return true} break; case 'left' : if (x - 1 < 0) {return true} break; case 'right': if (x + 1 >= mapOptions.width) {return true} break; } return false; } }
JavaScript
class App extends Component { constructor(props) { super(); this.classes = props.classes; } render() { return( <div className="App"> <IntlProvider locale={navigator.language}> <Router> <div className={this.classes.root}> <ErrorNotifier /> <ActionNotifier /> <header> <HeaderAppBar history={this.props.history} /> </header> <main className={this.classes.content}> <div className={this.classes.toolbar} /> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/users" component={Users} /> <Route exact path="/users/:userId" component={User} /> <Route exact path="/events" component={Events} /> <Route exact path="/events/:eventId" component={Event} /> <Route exact path="/events/:eventId/teams" component={EventTeams} /> <Route exact path="/event-teams/:eventTeamId" component={EventTeam} /> </Switch> </main> </div> </Router> </IntlProvider> </div> ); } }
JavaScript
class App extends Component { constructor(props) { super(props); this.state = { modal: false, viewCompleted: false, activeItem: { title: "", description: "", completed: false }, taskList: [] }; } refreshList = () => { /* Axios connects between the backend and the frontend, to send and receive HTTP requests; i.e send client requests to server, get server response to client */ axios .get("http://localhost:8000/api/tasks/") // this returns a promise .then(res => this.setState({ taskList: res.data })) .catch(err => console.log(err)); // incase of err, catch them }; // This is invoked immediately after a component is mounted (inserted into the tree) componentDidMount() { this.refreshList(); } // to handle modal open & close toggle = () => { this.setState({ modal: !this.state.modal }); }; // Create item obj, setState to item obj, open modal createItem = () => { const item = { title: "", description: "", completed: false }; this.setState({ activeItem: item, modal: !this.state.modal }); }; // setState to given item obj, open modal, Edit item obj editItem = item => { this.setState({ activeItem: item, modal: !this.state.modal }); }; // Submit an item handleSubmit = item => { this.toggle(); // for updating tasks, if (item.id) { // get specific item and modify it axios .put(`http://localhost:8000/api/tasks/${item.id}/`, item) .then(res => this.refreshList()); return; } // post item after modifying, to complete update axios .post("http://localhost:8000/api/tasks/", item) .then(res => this.refreshList()); }; /* - for testing handleSubmit = item => { //added this after modal creation this.toggle(); alert("save" + JSON.stringify(item));}; */ handleDelete = item => { // delete item axios .delete(`http://localhost:8000/api/tasks/${item.id}/`) .then(res => this.refreshList()); }; /* - for testing Delete item - function added after modal creation. handleDelete = item => { alert("delete" + JSON.stringify(item)) }; */ displayCompleted = status => { if (status) { return this.setState({ viewCompleted: true }); } return this.setState({ viewCompleted: false }); }; // renders two spans which control which set of items are displayed renderTabList = () => { return ( <div className="my-5 tab-list"> <span onClick={() => this.displayCompleted(true)} className={this.state.viewCompleted ? "active" : ""} > completed </span> <span onClick={() => this.displayCompleted(false)} className={this.state.viewCompleted ? "" : "active"} > Incompleted </span> </div> ); }; // Main variable to render items on the screen, completed/uncompleted renderItems = () => { const { viewCompleted } = this.state; const newItems = this.state.taskList.filter( // recall view completed set to false by default item => item.completed === viewCompleted ); // return new items while mapping each item return newItems.map(item => ( <li key={item.id} className="list-group-item d-flex justify-content-between align-items-center"> <span // if viewCompleted = true; then css class = strike through title title={item.description} className={`todo-title mr-2 ${this.state.viewCompleted ? "completed-todo" : ""}`} > {item.title} </span> <span> <button onClick={() => this.editItem(item)} className="btn btn-info m-2"> Edit </button> <button onClick={() => this.handleDelete(item)} className="btn btn-danger"> Delete </button> </span> </li> )); }; // rendering jsx render() { return ( <main className="content"> <h1 className="text-info text-uppercase text-center m-4">Task Manager</h1> <div className="row "> <div className="col-md-6 col-sm-10 mx-auto p-0"> <div className="card p-3"> <div className=""> <button onClick={this.createItem} className="btn btn-primary"> Add task </button> </div> {this.renderTabList()} <ul className="list-group list-group-flush"> {this.renderItems()} </ul> </div> </div> </div> <footer className='m-2 bg-info text-white text-center'> Codexgrey Copyright 2022 &copy; All Rights Reserved </footer> {/* if true, i want activeItem, toggle and onSave as props, else do none active item represents the task item i want to edit */} {this.state.modal ? ( <Modal activeItem={this.state.activeItem} toggle={this.toggle} onSave={this.handleSubmit} /> ) : null} </main> ); } }
JavaScript
class Heart { /** * Creates an instance of Heart * @param {number} adDuration Duration in pixels of the atria depolarization * @param {number} vdDuration Duration in pixels of the ventricle depolarization * @param {number} vrDuration Duration in pixels of the ventricle repolarization * * @property {number} this.beatDuration Duration in pixels of the whole beat * @property {number} this.nextBeat Time between last beat, and next beat * @property {number} this.nextBeatIn Time remaining for next beat * @property {number[]} this.bpm Time between two particular beats * @property {number} this.voltage Current voltage value. No units used. */ constructor(adDuration, vdDuration, vrDuration) { this.adDuration = adDuration; this.vdDuration = vdDuration; this.vrDuration = vrDuration; this.beatDuration = adDuration + vdDuration + vrDuration; this.nextBeat = 60; this.nextBeatIn = 60; this.bpm = []; this.voltage = 0; } /** * Assign the heart a new voltage value, and report that value to the ECG * the heart is connected to. * @param {number} voltage */ setVoltage(voltage) { this.voltage = voltage; ecg.addValue({y: this.voltage}); } /** * Generates the voltage values corresponding to the atria depolarization process. * This is the process that generates the first part of the curve of every beat. * * @param {number} time Time in pixels since the atria depolarization process started */ atriaDepolarization(time) { // This process is not close to what reality does, but here it is generated using a // sin function where only the positive values remain, making a bump followed by a // flat section let y = randomGaussian(5, 1) * sin(time * (360 / this.adDuration)); // To compensate for the y-axis inverted direction, return -y when y is over 0 y = y > 0 ? -y : 0.2 * (1 - y); // Update the voltage to whatever value was calculated this.setVoltage(y + noise(time)); } /** * Generates the voltage values corresponding to the ventricle depolarization process. * This is the process that generates the spiky part of the curve of every beat. * * @param {number} time Time in pixels since the ventricle depolarization process started */ ventricleDepolarization(time) { let y; // In the first third, the curve has a spike going down if (time <= this.vdDuration / 3) y = (randomGaussian(8, 2) * (this.vdDuration - time)) / 6; // In the second third, the curve has a big spike going up else if (time < (2 * this.vdDuration) / 3) { y = (randomGaussian(70, 2) * abs(1.5 - (this.vdDuration - time))) / 3; y = -y; } // In the last third, the curve has another spike (bigger than the first one) going down else { y = (randomGaussian(20, 2) * (this.vdDuration - time)) / 3; } // Update the voltage to whatever value was calculated this.setVoltage(y); } /** * Generates the voltage values corresponding to the ventricle repolarization process. * This is the process that generates the last part of the curve of every beat. * * @param {number} time Time in pixels since the ventricle repolarization process started */ ventricleRepolarization(time) { // This process is not close to what reality does, but here it is generated using a // sin function where only the positive values remain, but displaced half a turn to // make a flat section followed by a bump let y = randomGaussian(8, 2) * sin(180 + time * (360 / this.vrDuration)); // To compensate for the y-axis inverted direction, return -y when y is over 0 y = y < 0 ? 0.2 * (1 - y) : -y; // Update the voltage to whatever value was calculated this.setVoltage(y + noise(time)); } updateBPM() { // bpm = 3600 / pixel-distance this.bpm.push(3600 / this.nextBeat); // To make rapid frequency changes meaningful, get the average bpm using only the // last 5 values of time, not all of them. So dispose the oldest one when the list // length is over 5. if (this.bpm.length > 5) this.bpm.splice(0, 1); ecg.drawBPM(round(this.bpm.reduce((p, c) => p + c, 0) / this.bpm.length)); } getHeartBeat(){ /** Takes value from Rpi, recv_bpm and maps it to the closest graphable value. * There is probably a more graceful way of doing this, but didn't feel like * crunching numbers at the time. */ let new_bpm = (document.getElementById('heartVal').innerText).split(" ")[0]; var beatMap = { 200: 18, 180: 20, 144: 25, 120: 30, 116: 31, 113: 32, 109: 33, 106: 34, 103: 35, 100: 36, 97: 37, 95: 38, 92: 39, 90: 40, 88: 41, 86: 42, 84: 43, 82: 44, 80: 45, 78: 46, 77: 47, 75: 48, 73: 49, 72: 50, 71: 51, 69: 52, 68: 53, 67: 54, 65: 55, 64: 56, 63: 57, 62: 58, 61: 59, 60: 60, }; const numbers = [ 200, 180, 144, 120, 116, 113, 109, 106, 103, 100, 97, 95, 92, 90, 88, 86, 84, 82, 80, 78, 77, 75, 73, 72, 71, 69, 68, 67, 65, 64, 63, 62, 61, 60, ]; numbers.sort((a, b) => { return Math.abs(new_bpm - a) - Math.abs(new_bpm - b); }) return beatMap[numbers[0]]; } /** * Decrease this.nextBeatIn to simulate the pass of time. * If necessary, create a new this.nextBeat value */ updateTimeToNextBeat() { // This indicates that the next beat will begin in the next iteration if (this.nextBeatIn-- === 0) { // Then calculate a new "remaining time" for the next beat. // Use returned value from Rpi to modify the heart frequency this.nextBeat = abs(this.getHeartBeat()); // If the pixel time between beat and beat is less than 18, force it to be // 18. This value makes to a bpm of 200. if (this.nextBeat < 18) this.nextBeat = 18; // Get new bpm values using the last this.nextBeat this.updateBPM(); // Reset the remaining time to the new calculated time this.nextBeatIn = this.nextBeat; } } /** * Get voltage values for every second of the beat, even at rest (no-beating time * after the ventricle repolarization finished, and before the next atria depolarization) * @param {*} time Time in pixels after the atria depolarization started */ beat(time) { // Update the time left for the start of the next beat this.updateTimeToNextBeat(); // If according to time, beat is in the atria depolarization process, call that function if (time <= this.adDuration) { this.atriaDepolarization(time); return; } // If according to time, beat is in the ventricle depolarization process, call that function // Update the time so the value sent is relative to the start of the ventricle // depolarization process time -= this.adDuration; if (time <= this.vdDuration) { this.ventricleDepolarization(time); return; } // If according to time, beat is in the ventricle repolarization process, call that function // Update the time so the value sent is relative to the start of the ventricle // repolarization process time -= this.vdDuration; if (time <= this.vrDuration) { this.ventricleRepolarization(time); return; } // If function reached this point, it's not in any of the beat processes, and it's resting. // Add a noisy voltage value this.setVoltage(0 + noise(draw_i * 0.5) * 5); } }
JavaScript
class ECG { /** * @param {Object} graphZero Coordinates of the {0, 0} value of the graph * @param {Object[]} values Array of {x, y} objects. x plots time, y plots voltage * @param {number} maxValuesHistory Maximum number of values before wiping oldest one */ constructor(graphZero, values, maxValuesHistory) { this.graphZero = graphZero; this.values = values; this.maxValuesHistory = maxValuesHistory; this.maximumX = maxValuesHistory; } /** * Add a new voltage value to the values array. If it exceeds the maximum number of * values allowed to store, remove the oldest one before. * @param {Object} value {x, y} object. x represents time, y represents voltage */ addValue(value) { // If no x (time) value is received, assume it is the successor of the last value // in the values array. If the new x exceeds the maximum allowed, make x = 0 if (this.values.length >= this.maxValuesHistory) this.values.splice(0, 1); if (value.x === undefined) { value.x = (this.values[this.values.length - 1].x + 1) % this.maximumX; } this.values.push(value); } /** * Draw lines joining every voltage value throughout time in the screen */ plotValues() { push(); for (let i = 1; i < this.values.length; i++) { // If the previous value has a X coordinate higher than the current one, // don't draw it, to avoid lines crossing from end to start of the ECG plot area. if (this.values[i - 1].x > this.values[i].x) continue; // Older values are drawn with a lower alpha let alpha = i / this.values.length; // Set the color of the drawing stroke(121, 239, 150, alpha); fill(121, 239, 150, alpha); // Line from previous value to current value line( this.graphZero.x + this.values[i - 1].x, this.graphZero.y + this.values[i - 1].y, this.graphZero.x + this.values[i].x, this.graphZero.y + this.values[i].y ); // For the last 5 values, draw a circle with a radius going in function to // its index. This to make the leading line thicker if (i + 5 > this.values.length) { circle( this.graphZero.x + this.values[i].x, this.graphZero.y + this.values[i].y, this.values.length / i ); } } pop(); } /** * Update the html content of the span containing the bpm info * @param {number} bpm */ drawBPM(bpm) { document.getElementById("disp-bpm").innerHTML = bpm; } }
JavaScript
class RestaurantOffersList extends Component { /** * Used to render the offers list item component. * * @returns {ReactElement} OfferItem component */ renderFlatListItem(item) { return ( <RestaurantOfferItem item={item} onPress={() => Actions.offershDetailsScreen({ item })} /> ); } rendersScreen(offers) { return ( <FlatList data={offers} keyExtractor={(item) => item.id} renderItem={({ item }) => this.renderFlatListItem(item)} /> ); } /** * Used to render favorite offers screen component * * @returns {ReactElement} OffersListScreen component */ render() { if (this.props.restaurant) { if (this.props.restaurant.offers) { return ( <View style={Styles.offersContainer}> <Text style={Styles.restaurantName}>عدد الاعلانات المنشورة</Text> <Text style={Styles.restaurantName}>{this.props.restaurant.offers.length}</Text> <View style={Styles.sublineDivider} /> {this.rendersScreen(this.props.restaurant.offers)} </View> ); } } return <View />; } }