language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class RGL extends event.EventEmitter { constructor(autoconfig = true, secureSwitch = true, /* Unbind CTRL-C */ mappings_c = _mappings_c, mappings_b = _mappings_b, _Map = RGLMap, _Tile = RGLTile, ground = new RGLGround()) { super(); this.secureSwitch = secureSwitch; this.mappings_c = mappings_c; this.mappings_b = mappings_b; this._Map = _Map; this._Tile = _Tile; this.ground = ground; this.binds = null; if (!RGL.supportsColors) console.warn("Terminal colors are not supported!"); this.mappings_c = new Map(mappings_c); this.mappings_b = new Map(mappings_b); if (autoconfig) { Promise.all([ this.loadMappings_c(), this.loadMappings_b() ]).catch(() => debug_e("RGL.autoconf: EMAPPING")).then(() => { this._Tile.mappings_c = this.mappings_c; this._Tile.mappings_b = this.mappings_b; debug("RGL.ctor deffered mappings."); }); this.bind(); } this._Tile.mappings_c = this.mappings_c; this._Tile.mappings_b = this.mappings_b; this._Tile.mappings_s = RGL.mappings_s; } //ctor /** * Whether the TTY supports basic colors. */ static get supportsColors() { return !!chalk_1.default.level; } //supportsColors loadMappings_c(map = "RGLMappings_c.js") { this.emit("_loadColors", map); return RGL.loadMappings(map, this.mappings_c); } //loadMappings_c loadMappings_b(map = "RGLMappings_b.js") { this.emit("_loadBackground", map); return RGL.loadMappings(map, this.mappings_b); } //loadMappings_c /** * Include custom mappings. * * @param map - Load new mappings * @param orig - Mappings to override */ static async loadMappings(map, orig) { debug("RGL.loadMappings:", util_1.inspect(orig, { breakLength: Infinity })); if (typeof map === "string") { let data; delete require.cache[require.resolve(map)]; try { data = require(map); } catch (e) { data = new Map([]); } for (let sig of data) orig.set(sig[0], sig[1]); } else if (map instanceof Map) { for (let sig of map) orig.set(sig[0], sig[1]); } else throw Errors.EBADTPYE; return orig; } //loadMappings /** * Bind the RGL engine to I/O. * * @param inp - The target user-input stream to bind, must be a TTY * @param out - The target user-input stream to bind, must be a TTY */ bind(inp = (this.binds ? this.binds.input : process.stdin) ?? process.stdin, out = (this.binds ? this.binds.output : process.stdout) ?? process.stdout, err = (this.binds ? this.binds.error : process.stderr) ?? process.stderr) { debug(`RGL.bind: ${this.binds}`); assert.ok(inp.isTTY && out.isTTY, Errors.ENOTTY); if (!!this.binds && !!this.binds.input) { debug(`RGL.bind: unbound`); this.binds.input.setRawMode(false); if (!!this.binds._inpCb) this.binds.input.removeListener("data", this.binds._inpCb); } this.binds = { input: inp, output: out, error: err }; this.binds.input.setRawMode(true); this.binds.input.on("data", this.binds._inpCb = data => { this.emit("rawkey", data); this.emit("key", data.toString()); if (this.secureSwitch && data.toString() === '\u0003') { this.emit("_exit"); process.exit(); } }); return this; } //bind unbind() { debug(`RGL.unbind: ${this.binds}`); assert.ok(this.binds && this.binds.input.isTTY && this.binds.output.isTTY, Errors.EBADBIND); this.binds.input.setRawMode(false); if (!!this.binds._inpCb) this.binds.input.removeListener("data", this.binds._inpCb); return this; } //unbind emit(event, ...args) { return super.emit(event, ...args); } //emit on(event, listener) { return super.on(event, listener); } //on /** * Start an instance of RGL. * * @param {any[]} params - Options passed to constructor */ static create(...params) { debug(`RGL.create`); return new RGL(...params); } //create } //RGL
JavaScript
class NetworkError extends Error { /** * Constructor * * @public */ constructor(...args) { super(...args); if(Error.captureStackTrace) { Error.captureStackTrace(this, NetworkError); } } }
JavaScript
class StockExchange extends react__WEBPACK_IMPORTED_MODULE_0__["Component"] { constructor(...args) { super(...args); this.state = { ratesData: null, loading: false }; } componentDidMount() { this.setState({ loading: true }); this.getCurrencyRates(); } // get currency rates getCurrencyRates() { axios__WEBPACK_IMPORTED_MODULE_1___default.a.get('https://data.fixer.io/api/latest?access_key=4e83fa57182d17c76a14535831d547c6').then(response => { this.setState({ loading: false, ratesData: response.data }); }).catch(error => { console.log(error); this.setState({ loading: false }); }); } render() { const { ratesData, loading } = this.state; if (loading) { return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctSectionLoader_RctSectionLoader__WEBPACK_IMPORTED_MODULE_4__["default"], null); } return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { className: "stock-exchange" }, ratesData !== null && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_List__WEBPACK_IMPORTED_MODULE_2__["default"], { className: "list-unstyled p-0" }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_ListItem__WEBPACK_IMPORTED_MODULE_3__["default"], null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", { src: __webpack_require__(/*! Assets/flag-icons/icons8-canada.png */ "./resources/js/assets/flag-icons/icons8-canada.png"), className: "img-fluid mr-10", alt: "cad" }), " CAD (Canadian Dollar)"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "ti-arrow-up text-success" }), " ", ratesData.rates ? ratesData.rates.CAD.toFixed(2) : 0)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_ListItem__WEBPACK_IMPORTED_MODULE_3__["default"], null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", { src: __webpack_require__(/*! Assets/flag-icons/icons8-germany.png */ "./resources/js/assets/flag-icons/icons8-germany.png"), className: "img-fluid mr-10", alt: "eur" }), " EUR (Euro)"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "ti-arrow-down text-danger" }), " ", ratesData.rates ? ratesData.rates.EUR.toFixed(2) : 0)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_ListItem__WEBPACK_IMPORTED_MODULE_3__["default"], null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", { src: __webpack_require__(/*! Assets/flag-icons/icons8-south_korea.png */ "./resources/js/assets/flag-icons/icons8-south_korea.png"), className: "img-fluid mr-10", alt: "krw" }), " KRW (Korea)"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "ti-arrow-down text-danger" }), " ", ratesData.rates ? ratesData.rates.NZD.toFixed(2) : 0)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_ListItem__WEBPACK_IMPORTED_MODULE_3__["default"], null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", { src: __webpack_require__(/*! Assets/flag-icons/icons8-india.png */ "./resources/js/assets/flag-icons/icons8-india.png"), className: "img-fluid mr-10", alt: "inr" }), " INR (Indian Rupees)"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "ti-arrow-up text-success" }), " ", ratesData.rates ? ratesData.rates.INR.toFixed(2) : 0)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_material_ui_core_ListItem__WEBPACK_IMPORTED_MODULE_3__["default"], null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", { src: __webpack_require__(/*! Assets/flag-icons/icons8-singapore.png */ "./resources/js/assets/flag-icons/icons8-singapore.png"), className: "img-fluid mr-10", alt: "sgd" }), " SGD (Singapore Dollar)"), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "ti-arrow-down text-danger" }), " ", ratesData.rates ? ratesData.rates.SGD.toFixed(2) : 0))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Components_RctCard__WEBPACK_IMPORTED_MODULE_5__["RctCardFooter"], { customClasses: "border-0 fs-12 text-base" }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("i", { className: "mr-5 zmdi zmdi-refresh" }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Util_IntlMessages__WEBPACK_IMPORTED_MODULE_6__["default"], { id: "widgets.updated10Minago" }))); } // @ts-ignore __reactstandin__regenerateByEval(key, code) { // @ts-ignore this[key] = eval(code); } }
JavaScript
class Routes { /** * Get all users. * Must be logged in with appropriate priviledges. * @returns {Promise} */ static getUsers(){ return fetch("/users") .catch((err) => { console.error(err); }); } /** * Get a user. * Must be logged in with appropriate priviledges. * @param {string} userId * @returns {Promise} */ static getUser(userId){ return fetch(`/user/${userId}`) .catch((err) => { console.error(err); }); } /** * Add a user. * @param {object} params * @param {string} params.username * @param {string} params.email * @param {string} params.password * @returns {Promise} */ static addUser({username, email, password}){ let body = JSON.stringify({username, email, password}); return fetch("/user", { method: "post", body: body }).catch((err) => { console.error(err); }); } /** * Delete a user. * Must be logged in with appropriate priviledges. * @param {string} userId * @returns {Promise} */ static deleteUser(userId){ return fetch(`/user/${userId}`, { method: "delete" }).catch((err) => { console.error(err); }); } /** * Update a user. * Note: password params is "older" and "newer" * because "new" cannot be used. * @param {object} params * @param {string} params.username * @param {string} params.email * @param {object} params.password * @param {string} params.password.older * @param {string} params.password.newer * @returns {Promise} */ static updateUser({username, email, password: {older, newer}}){ let body = JSON.stringify({username, email, password: {older, newer}}); return fetch("/user", { method: "put", body: body }).catch((err) => { console.error(err); }); } /** * Login a user * @param {object} params * @param {string} params.username * @param {string} params.password * @returns {Promise} */ static login({username, password}){ let body = JSON.stringify({username, password}); return fetch("/user/login", { method: "post", body: body }).catch((err) => { console.error(err); }); } /** * Login a user with no parameters. * Relies on a browser cookie being read. * @returns {Promise} */ static loginWithCookie(){ return fetch("/user/login", { method: "post", }).catch((err) => { console.error(err); }); } /** * Logout a user. * Only works if the user is logged in. * @returns {Promise} */ static logout(){ return fetch("/user/logout", { method: "post" }).catch((err) => { console.error(err); }); } /** * Register a user * @param {object} params * @param {string} params.username * @param {string} params.email * @param {string} params.password * @returns {Promise} */ static register({username, email, password}){ let body = JSON.stringify({username, email, password}); return fetch("/user/register", { method: "post", body: body }).catch((err) => { console.error(err); }); } /** * Reset a user's password * @param {object} params * @param {string} params.email * @returns {Promise} */ static resetPassword({email}){ let body = JSON.stringify({email}); return fetch("/user/reset", { method: "post", body: body }).catch((err) => { console.error(err); }); } }
JavaScript
class SideBar extends Component { constructor(props) { super(props); this.state = {}; // any method using this keyword must bind // example: this.method = this.method.bind(this) } componentDidMount() { // Things to do when the component is first rendered into the dom } componentWillUnmount() { // Things to do when the component is removed } render() { return ( <nav className="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#"> Idea-Connect </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#"> Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Idea </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> DashBoard </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Contact Us </a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" /> <button class="btn btn-outline-success my-2 my-sm-0" type="submit"> Search Idea </button> </form> </div> </nav> ); } }
JavaScript
class Text extends Entity { /** * @param {string} name * @param {number} x * @param {number} y * @param {string} content * @param {EntityOptions & TextOptions} options */ constructor(name, x, y, content, options = {}) { const { colour = Colour.BLACK, fontFamily = Font.MINECRAFT, fontSize = 24, isStatic = true } = options super(name, x, y, 'text', { ...options, isStatic }) if (fontFamily && !isValidFont(fontFamily)) { const validFonts = Object.values(Font).join(', ') throw Error(`No font family ${fontFamily} found. Options are: ${validFonts}`) } this.content = content this.fontFamily = fontFamily this.fontSize = fontSize this.colour = colour } }
JavaScript
class TextArea extends React.PureComponent { static displayName = 'TextArea' state = { hasFocus: false } constructor(props) { super(props) const { forwardedRef } = this.props this.inputRef = forwardedRef || React.createRef() } render() { const { css, onChange, onBlur, onFocus, forwardedRef, theme, fieldApi, fieldState, justifyContent, ...rest } = this.props const { readOnly } = this.props const { hasFocus } = this.state const { setValue, setTouched } = fieldApi const { value } = fieldState const isValid = value && !fieldState.error // Calculate the border color based on the current field state. let borderColor if (readOnly) { borderColor = theme.colors.gray } else if (fieldState.error) { borderColor = theme.colors.superRed } else if (value && !fieldState.error) { borderColor = theme.colors.superGreen } return ( <Flex flexDirection="column" justifyContent={justifyContent}> <SystemTextArea borderColor={borderColor || theme.colors.gray} opacity={readOnly ? 0.6 : null} css={Object.assign( { outline: 'none', '&:not([readOnly]):not([disabled]):focus': { border: `1px solid ${ isValid ? theme.colors.superGreen : theme.colors.lightningOrange } }` } }, css )} {...rest} ref={this.inputRef} value={!value && value !== 0 ? '' : value} onChange={e => { setValue(e.target.value) if (onChange) { onChange(e) } }} onBlur={e => { setTouched() // Make the state aware that the element is now focused. const newHasFocus = document.activeElement === this.inputRef.current if (hasFocus !== newHasFocus) { this.setState({ hasFocus: newHasFocus }) } if (onBlur) { onBlur(e) } }} onFocus={e => { // Make the state aware that the element is no longer focused. const newHasFocus = document.activeElement === this.inputRef.current if (hasFocus !== newHasFocus) { this.setState({ hasFocus: newHasFocus }) } if (onFocus) { onFocus(e) } }} error={fieldState.error} /> {fieldState.error && ( <Message variant={hasFocus ? 'warning' : 'error'} justifyContent={justifyContent} mt={2}> {fieldState.error} </Message> )} </Flex> ) } }
JavaScript
class RuleArrowFunctionParentheses extends CoreRule { /** * @var string */ get default() { return 'always'; } /** * @var string */ get property() { return 'arrowParens'; } /** * Mandatory entry function to create a decision * * @return boolean */ identify() { let output = this.default; const parentheses = [...this.input.matchAll(/[)]\s*=>/gms)].length; const noParentheses = [...this.input.matchAll(/[a-zA-Z0-9]\s*=>/gms)].length; // We have more non-spaced brackets than spaced brackets if (noParentheses > parentheses) { output = 'avoid'; } return output; } }
JavaScript
class PubsubPeerDiscovery extends Emittery { /** * @class * @param {object} options - Configuration options * @param {*} options.libp2p - Our libp2p node * @param {number} [options.interval = 10000] - How often (ms) we should broadcast our infos * @param {Array<string>} [options.topics = PubsubPeerDiscovery.TOPIC] - What topics to subscribe to. If set, the default will NOT be used. * @param {boolean} [options.listenOnly = false] - If true, we will not broadcast our peer data */ constructor ({ libp2p, interval = 10000, topics, listenOnly = false }) { super() this.libp2p = libp2p this.interval = interval this._intervalId = null this._listenOnly = listenOnly // Ensure we have topics if (Array.isArray(topics) && topics.length) { this.topics = topics } else { this.topics = [TOPIC] } this.removeListener = this.off.bind(this) this.removeAllListeners = this.clearListeners.bind(this) } /** * Subscribes to the discovery topic on `libp2p.pubsub` and performs a broadcast * immediately, and every `this.interval` */ start () { if (this._intervalId) return // Subscribe to pubsub for (const topic of this.topics) { this.libp2p.pubsub.subscribe(topic, (msg) => this._onMessage(msg)) } // Don't broadcast if we are only listening if (this._listenOnly) return // Broadcast immediately, and then run on interval this._broadcast() // Periodically publish our own information this._intervalId = setInterval(() => { this._broadcast() }, this.interval) } /** * Unsubscribes from the discovery topic */ stop () { clearInterval(this._intervalId) this._intervalId = null for (const topic of this.topics) { this.libp2p.pubsub.unsubscribe(topic) } } /** * Performs a broadcast via Pubsub publish * * @private */ _broadcast () { const peer = { publicKey: this.libp2p.peerId.pubKey.bytes, addrs: this.libp2p.multiaddrs.map(ma => ma.bytes) } const encodedPeer = PB.Peer.encode(peer).finish() for (const topic of this.topics) { log('broadcasting our peer data on topic %s', topic) this.libp2p.pubsub.publish(topic, encodedPeer) } } /** * Handles incoming pubsub messages for our discovery topic * * @private * @async * @param {Message} message - A pubsub message */ async _onMessage (message) { try { const peer = PB.Peer.decode(message.data) const peerId = await PeerId.createFromPubKey(peer.publicKey) // Ignore if we received our own response if (peerId.equals(this.libp2p.peerId)) return log('discovered peer %j on %j', peerId, message.topicIDs) this._onNewPeer(peerId, peer.addrs) } catch (err) { log.error(err) } } /** * Emit discovered peers. * * @private * @param {PeerId} peerId * @param {Array<Buffer>} addrs */ _onNewPeer (peerId, addrs) { if (!this._intervalId) return this.emit('peer', { id: peerId, multiaddrs: addrs.map(b => new Multiaddr(b)) }) } }
JavaScript
class GoogleHomeSpeaker { /** * @constructor */ constructor() { this.detector = undefined; this.tts = undefined; } /** * detect language * * @param {string} text * @return {string} code */ async detect(text) { return await new Promise((resolve) => { if ( typeof this.detector === 'undefined') { this.detector = LanguageDetect; } let result = this.detector.detectOne(text); if (typeof result === 'string' && result.length === 2 ) { return resolve(result); } return resolve('ja'); }); } /** * convert text to mp3 * @param {string} text * @return {string} url */ async textToMp3(text) { if ( typeof this.tts === 'undefined') { this.tts = getAudioUrl; } return this.tts(text,{ lang : await this.detect(text), slow: false , host: 'https://translate.google.com' }); } /** * run commands * @param {string} host * @param {string} text * @return {void} */ async run(host, text) { let gha = new GoogleHomeAudioPlay(host, await this.textToMp3(text)); return gha.run(); } }
JavaScript
class LineTypeSeriesBase { /** * Make positions for default data type. * @param {number} [seriesWidth] - width of series area * @returns {Array.<Array.<object>>} * @private */ _makePositionsForDefaultType(seriesWidth) { const {dimension: {height, width: dimensionWidth}} = this.layout; const seriesDataModel = this._getSeriesDataModel(); const width = seriesWidth || dimensionWidth || 0; const len = seriesDataModel.getGroupCount(); const baseTop = this.layout.position.top; let baseLeft = this.layout.position.left; let step; if (this.aligned) { step = width / (len > 1 ? (len - 1) : len); } else { step = width / len; baseLeft += (step / 2); } return seriesDataModel.map(seriesGroup => ( seriesGroup.map((seriesItem, index) => { let position; if (!snippet.isNull(seriesItem.end)) { position = { left: baseLeft + (step * index), top: baseTop + height - (seriesItem.ratio * height) }; if (snippet.isExisty(seriesItem.startRatio)) { position.startTop = baseTop + height - (seriesItem.startRatio * height); } } return position; }) ), true); } /** * Make positions for coordinate data type. * @param {number} [seriesWidth] - width of series area * @returns {Array.<Array.<object>>} * @private */ _makePositionForCoordinateType(seriesWidth) { const {dimension} = this.layout; const seriesDataModel = this._getSeriesDataModel(); const {height} = dimension; const {xAxis} = this.axisDataMap; const baseTop = this.layout.position.top; const baseLeft = this.layout.position.left; let width = seriesWidth || dimension.width || 0; let additionalLeft = 0; if (xAxis.sizeRatio) { additionalLeft = calculator.multiply(width, xAxis.positionRatio); width = calculator.multiply(width, xAxis.sizeRatio); } return seriesDataModel.map(seriesGroup => ( seriesGroup.map(seriesItem => { let position; if (!snippet.isNull(seriesItem.end)) { position = { left: baseLeft + (seriesItem.ratioMap.x * width) + additionalLeft, top: baseTop + height - (seriesItem.ratioMap.y * height) }; if (snippet.isExisty(seriesItem.ratioMap.start)) { position.startTop = height - (seriesItem.ratioMap.start * height) + chartConst.SERIES_EXPAND_SIZE; } } return position; }) ), true); } /** * Make basic positions for rendering line graph. * @param {number} [seriesWidth] - width of series area * @returns {Array.<Array.<object>>} * @private */ _makeBasicPositions(seriesWidth) { if (this.dataProcessor.isCoordinateType()) { return this._makePositionForCoordinateType(seriesWidth); } return this._makePositionsForDefaultType(seriesWidth); } /** * Calculate label position top. * @param {{top: number, startTop: number}} basePosition - base position * @param {number} value - value of seriesItem * @param {number} labelHeight - label height * @param {boolean} [isStart] - whether start value of seriesItem or not * @returns {number} position top * @private */ _calculateLabelPositionTop(basePosition, value, labelHeight, isStart) { const baseTop = basePosition.top; let top; if (predicate.isValidStackOption(this.options.stackType)) { top = ((basePosition.startTop + baseTop - labelHeight) / 2) + 1; } else if ((value >= 0 && !isStart) || (value < 0 && isStart)) { top = baseTop - labelHeight - SERIES_LABEL_PADDING; } else { top = baseTop + SERIES_LABEL_PADDING; } return top; } /** * Make label position for rendering label of series area. * @param {{left: number, top: number, startTop: ?number}} basePosition - base position for calculating * @param {number} labelHeight - label height * @param {(string | number)} label - label of seriesItem * @param {number} value - value of seriesItem * @param {boolean} [isStart] - whether start label position or not * @returns {{left: number, top: number}} * @private */ _makeLabelPosition(basePosition, labelHeight, label, value, isStart) { return { left: basePosition.left, top: this._calculateLabelPositionTop(basePosition, value, labelHeight / 2, isStart) }; } /** * Get label positions for line type chart * @param {object} seriesDataModel series data model * @param {object} theme label theme * @returns {object} * @private */ _getLabelPositions(seriesDataModel, theme) { const basePositions = arrayUtil.pivot(this.seriesData.groupPositions); const labelHeight = renderUtil.getRenderedLabelHeight(MAX_HEIGHT_WORD, theme); return seriesDataModel.map((seriesGroup, groupIndex) => ( seriesGroup.map((seriesItem, index) => { const basePosition = basePositions[groupIndex][index]; const end = this._makeLabelPosition(basePosition, labelHeight, seriesItem.endLabel, seriesItem.end); const position = {end}; if (seriesItem.isRange) { basePosition.top = basePosition.startTop; position.start = this._makeLabelPosition( basePosition, labelHeight, seriesItem.startLabel, seriesItem.start ); } return position; }) )); } /** * Get label texts * @param {object} seriesDataModel sereis data model * @returns {Array.<string>} * @private */ _getLabelTexts(seriesDataModel) { return seriesDataModel.map(seriesGroup => ( seriesGroup.map(({endLabel, isRange, startLabel}) => { const label = { end: this.decorateLabel(endLabel) }; if (isRange) { label.start = this.decorateLabel(startLabel); } return label; }) )); } /** * Render series label. * @param {object} paper paper * @returns {Array.<object>} * @private */ _renderSeriesLabel(paper) { const theme = this.theme.label; const seriesDataModel = this._getSeriesDataModel(); const groupLabels = this._getLabelTexts(seriesDataModel); const positionsSet = this._getLabelPositions(seriesDataModel, theme); return this.graphRenderer.renderSeriesLabel(paper, positionsSet, groupLabels, theme); } /** * To call showGroupTooltipLine function of graphRenderer. * @param {{ * dimension: {width: number, height: number}, * position: {left: number, top: number} * }} bound bound */ onShowGroupTooltipLine(bound) { if (!this.graphRenderer.showGroupTooltipLine) { return; } this.graphRenderer.showGroupTooltipLine(bound, this.layout); } /** * To call hideGroupTooltipLine function of graphRenderer. */ onHideGroupTooltipLine() { if (!this.isAvailableSeriesData() || !this.graphRenderer.hideGroupTooltipLine) { return; } this.graphRenderer.hideGroupTooltipLine(); } /** * Zoom by mouse drag. * @param {object} data - data */ zoom(data) { this._cancelMovingAnimation(); this._clearSeriesContainer(data.paper); this._setDataForRendering(data); this._renderSeriesArea(data.paper, snippet.bind(this._renderGraph, this)); if (!snippet.isNull(this.selectedLegendIndex)) { this.graphRenderer.selectLegend(this.selectedLegendIndex); } } /** * Whether changed or not. * @param {{min: number, max: number}} before - before limit * @param {{min: number, max: number}} after - after limit * @returns {boolean} * @private */ _isChangedLimit(before, after) { return before.min !== after.min || before.max !== after.max; } /** * Whether changed axis limit(min, max) or not. * @returns {boolean} * @private */ _isChangedAxisLimit() { const {beforeAxisDataMap, axisDataMap} = this; let changed = true; if (beforeAxisDataMap) { changed = this._isChangedLimit(beforeAxisDataMap.yAxis.limit, axisDataMap.yAxis.limit); if (axisDataMap.xAxis.limit) { changed = changed || this._isChangedLimit(beforeAxisDataMap.xAxis.limit, axisDataMap.xAxis.limit); } } this.beforeAxisDataMap = axisDataMap; return changed; } /** * Animate for motion of series area. * @param {function} callback - callback function * @private */ _animate(callback) { const duration = ADDING_DATA_ANIMATION_DURATION; const changedLimit = this._isChangedAxisLimit(); if (changedLimit && this.seriesLabelContainer) { this.seriesLabelContainer.innerHTML = ''; } if (!callback) { return; } this.movingAnimation = renderUtil.startAnimation(duration, callback, () => { this.movingAnimation = null; }); } /** * Make top of zero point for adding data. * @returns {number} * @private * @override */ _makeZeroTopForAddingData() { const seriesHeight = this.layout.dimension.height; const {limit} = this.axisDataMap.yAxis; return this._getLimitDistanceFromZeroPoint(seriesHeight, limit).toMax + SERIES_EXPAND_SIZE; } /** * Animate for adding data. * @param {{tickSize: number}} data - parameters for adding data. */ animateForAddingData({tickSize, limitMap, axisDataMap}) { const dimension = this.dimensionMap.extendedSeries; const shiftingOption = this.options.shifting; let seriesWidth = this.layout.dimension.width; this.limit = limitMap[this.chartType]; this.axisDataMap = axisDataMap; const seriesData = this._makeSeriesData(); const paramsForRendering = this._makeParamsForGraphRendering(dimension, seriesData); if (shiftingOption) { seriesWidth += tickSize; } const groupPositions = this._makePositions(seriesWidth); const zeroTop = this._makeZeroTopForAddingData(); this.graphRenderer.animateForAddingData(paramsForRendering, tickSize, groupPositions, shiftingOption, zeroTop); } /** * Cancel moving animation. * @private */ _cancelMovingAnimation() { if (this.movingAnimation) { cancelAnimationFrame(this.movingAnimation.id); this.movingAnimation = null; } } }
JavaScript
class BacksideError { constructor(message) { const native = (new Error(message)); [this.message, this.stack] = [native.message, native.stack]; } }
JavaScript
class Triangle extends Polygon { /** * The Triangle constructor. * @constructor * @param {Object} values - the values. */ constructor(values){ values.vertices = 3; super(values); this.heights = this._mapDecimals(values.heights); } /** * For the given values, returns a solved Triangle * @param {Object} values the values of the triangle. * @return {Triangle} - the solved triangle */ static of(values) { const t = new Triangle(values); return t.solve(); } /** * "AAA" is when we know all three angles of a triangle, but no sides. * AAA triangles are impossible to solve further since there is nothing to show us size * @return {Boolean} if this triangle is AAA */ isAAA() { return Object.keys(this.angles).length >= 2 && Object.keys(this.sides).length === 0; } /** * "SSS" is when we know three sides of the triangle, and want to find the missing angles. * @return {Boolean} if this triangle is SSS */ isSSS() { return Object.keys(this.angles).length === 0 && Object.keys(this.sides).length >= 2; } /** * "AAS" is when we know two angles and one side which is not between the angles. * @return {Boolean} if this triangle is AAS */ isAAS() { if(!(Object.keys(this.angles).length === 2 && Object.keys(this.sides).length === 1)){ return false; } if(this.angles.a && this.angles.c && (this.sides.c || this.sides.a)){ return true; } if(this.angles.a && this.angles.b && (this.sides.a || this.sides.b)){ return true; } if(this.angles.c && this.angles.b && (this.sides.c || this.sides.b)){ return true; } return false; } /** * "ASA" is when we know two angles and a side between the angles. * @return {Boolean} if this triangle is ASA */ isASA() { if(!(Object.keys(this.angles).length === 2 && Object.keys(this.sides).length === 1)){ return false; } if(this.angles.a && this.angles.c && this.sides.b){ return true; } if(this.angles.a && this.angles.b && this.sides.c){ return true; } if(this.angles.c && this.angles.b && this.sides.a){ return true; } return false; } /** * "SAS" is when we know two sides and the angle between them. * @return {Boolean} if this triangle is SAS */ isSAS() { if(!(Object.keys(this.sides).length === 2 && Object.keys(this.angles).length === 1)){ return false; } if(this.sides.a && this.sides.c && this.angles.b){ return true; } if(this.sides.a && this.sides.b && this.angles.c){ return true; } if(this.sides.c && this.sides.b && this.angles.a){ return true; } } /** * "SSA" is when we know two sides and an angle that is not the angle between the sides. * @return {Boolean} if this triangle is SSA */ isSSA() { if(!(Object.keys(this.sides).length === 2 && Object.keys(this.angles).length === 1)){ return false; } if(this.sides.b && this.sides.c && (this.angles.b || this.angles.c)){ return true; } if(this.sides.a && this.sides.b && (this.angles.b || this.angles.a)){ return true; } if(this.sides.a && this.sides.c && (this.angles.c || this.angles.a)){ return true; } return false; } /** * "HB" is when we know a side and its height. We can only calculate the area. * @return {Boolean} if this triangle is HB */ isHB() { return ['a', 'b', 'c'].map((k) => this.sides[k] && this.heights[k] ? true : false).reduce((p, c) => p || c); } solveAAA() { const _180 = new Decimal(180); if(this.angles.a && this.angles.b){ this.angles.c = _180.minus(this.angles.a.plus(this.angles.b)); }else if(this.angles.a && this.angles.c){ this.angles.b = _180.minus(this.angles.a.plus(this.angles.c)); }else if(this.angles.c && this.angles.b){ this.angles.a = _180.minus(this.angles.c.plus(this.angles.b)); } return this; } solveSSS() { const {a,b,c} = this.sides; const deg = Angle.getUnit('Degree'); // cos(aa) = (b2 + c2 − a2) / 2bc const cosA = b.pow(2).plus(c.pow(2)).minus(a.pow(2)).div(Decimal.mul(2, b.mul(c))); this.angles.a = Angle.of(cosA.acos(), 'rad').to(deg); // cos(ab) = (c2 + a2 − b2)/2ca const cosB = c.pow(2).plus(a.pow(2)).minus(b.pow(2)).div(Decimal.mul(2, c.mul(a))); this.angles.b = Angle.of(cosB.acos(), 'rad').to(deg); this.solveAAA(); return this; } solveAAS() { this.solveAAA(); if(!this.sides.a && this.sides.c){ this.sides.a = this.sideOf(this.angles.c, this.sides.c, this.angles.a); return this.solveAAS(); }else if(!this.sides.a && this.sides.b){ this.sides.a = this.sideOf(this.angles.b, this.sides.b, this.angles.a); return this.solveAAS(); }else if(!this.sides.b && this.sides.a){ this.sides.b = this.sideOf(this.angles.a, this.sides.a, this.angles.b); return this.solveAAS(); }else if(!this.sides.b && this.sides.c){ this.sides.b = this.sideOf(this.angles.c, this.sides.c, this.angles.b); return this.solveAAS(); }else if(!this.sides.c && this.sides.b){ this.sides.c = this.sideOf(this.angles.b, this.sides.b, this.angles.c); return this.solveAAS(); }else if(!this.sides.c && this.sides.a){ this.sides.c = this.sideOf(this.angles.a, this.sides.a, this.angles.c); return this.solveAAS(); } return this; } solveSAS() { const rad = Angle.getUnit('Radian'); const {a, b, c} = this.sides; // Use law of cosines for sides a2 = b2 + c2 − 2bc cos(aA) if(this.sides.b && this.sides.c){ const aA = Angle.of(this.angles.a, 'deg').to(rad).cos(); const cosA = Decimal.mul(2, b.mul(c)).mul(aA); this.sides.a = b.pow(2).plus(c.pow(2)).minus(cosA).sqrt(); }else if(this.sides.b && this.sides.a){ const aC = Angle.of(this.angles.c, 'deg').to(rad).cos(); const cosC = Decimal.mul(2, b.mul(a)).mul(aC); this.sides.c = b.pow(2).plus(a.pow(2)).minus(cosC).sqrt(); }else if(this.sides.a && this.sides.c){ const aB = Angle.of(this.angles.b, 'deg').to(rad).cos(); const cosB = Decimal.mul(2, c.mul(a)).mul(aB); this.sides.b = c.pow(2).plus(a.pow(2)).minus(cosB).sqrt(); } // Now we have to find the smallest angle which is the one of the smallest side's key. let smallestSide = null; for (const k in this.sides) { if (!this.sides.hasOwnProperty(k)) { continue; } if(!smallestSide){ smallestSide = k; continue; } const side = this.sides[k]; if(this.sides[smallestSide].gt(side) && this.angles[smallestSide]){ smallestSide = k; } } const side = this.sides[smallestSide]; let angle = null; // Now we use Law of sines to obtain the angle of the smallest side with the angle we know. if(this.angles.a){ const aA = Angle.of(this.angles.a, 'deg').to(rad).sin(); angle = side.mul(aA).div(this.sides.a); }else if(this.angles.b){ const aB = Angle.of(this.angles.b, 'deg').to(rad).sin(); angle = side.mul(aB).div(this.sides.b); }else if(this.angles.c){ const aC = Angle.of(this.angles.c, 'deg').to(rad).sin(); angle = side.mul(aC).div(this.sides.c); } // We need to convert to Degree from Radians const deg = Angle.getUnit('Degree'); this.angles[smallestSide] = Angle.of(angle.asin(), 'rad').to(deg); // Finally, calculate the missing angle. this.solveAAA(); return this; } solveSSA() { let side, angle; // First we need to know which angle/side pair we know. if(this.sides.a && this.angles.a){ side = this.sides.a; angle = this.angles.a; }else if(this.sides.b && this.angles.b){ side = this.sides.b; angle = this.angles.b; }else if(this.sides.c && this.angles.c){ side = this.sides.c; angle = this.angles.c; } // Using this side/angle pair and one of the sides, we can calculate this side's angle if(this.sides.a && !this.angles.a){ this.angles.a = this.angleOf(angle, side, this.sides.a); }else if(this.sides.b && !this.angles.b){ this.angles.b = this.angleOf(angle, side, this.sides.b); }else if(this.sides.c && !this.angles.c){ this.angles.c = this.angleOf(angle, side, this.sides.c); } // We are only missing one angle, so calculate it. this.solveAAA(); // Now we have all angles and two sides, so we use Law of sines to find the last side we're missing. if(!this.sides.a){ this.sides.a = this.sideOf(this.angles.b, this.sides.b, this.angles.a); }else if(!this.sides.b){ this.sides.b = this.sideOf(this.angles.c, this.sides.c, this.angles.b); }else if(!this.sides.c){ this.sides.c = this.sideOf(this.angles.b, this.sides.b, this.angles.c); } return this; } solveHB() { if(this.sides.a && this.heights.a){ this.area = this.sides.a.mul(this.heights.a).div(2); }else if(this.sides.b && this.heights.b){ this.area = this.sides.b.mul(this.heights.b).div(2); }if(this.sides.c && this.heights.c){ this.area = this.sides.c.mul(this.heights.c).div(2); } return this; } /** * Obtains the type of triangle. * @return {String} the triangle type. */ getType() { if(this.type){ return this.type; } const angles = this.getAngles(); if(angles.find((a) => a.gt(90))){ this.type = 'obtuse-'; }else if(angles.find((a) => a.eq(90))){ this.type = 'right-'; }else{ this.type = 'acute-'; } const eqS = this.numberOfEqualSides(); const eqA = this.numberOfEqualAngles(); this.type += eqA === 3 ? 'equilateral' // Separate as to make this work with AAA triangles. : eqS === 3 ? 'equilateral' : eqS === 2 ? 'isosceles' : 'scalene'; return this.type; } /** * Calculates the height the triangle for the given side. * @param {String} id - id of the side we want to obtain its height. * @return {BigDecimal} - height of the side. */ heightOf(id){ const rad = Angle.getUnit('Radian'); switch (id) { case 'a': return Angle.of(this.angles.c, 'deg').to(rad).sin().mul(this.sides.b); case 'b': return Angle.of(this.angles.a, 'deg').to(rad).sin().mul(this.sides.b); case 'c': return Angle.of(this.angles.b, 'deg').to(rad).sin().mul(this.sides.a); } } /** * Solves the triangle with the sides & angles we have. * @return {Triangle} the solved Triangle. */ solve() { if(this.solved){ return this; } if(this.isAAA()){ this.getType(); // Since we cannot know anything else of this triangles, we return. return this.solveAAA(); }else if(this.isHB()){ // Since we cannot know anything else of this triangles, we return. return this.solveHB(); }else if(this.isSSS()){ this.solveSSS(); }else if(this.isAAS() || this.isASA()){ this.solveAAS(); }else if(this.isSAS()){ this.solveSAS(); }else if(this.isSSA()){ this.solveSSA(); }else{ throw new Error(`Invalid triangle with values: ${JSON.stringify(this)}`); } // Now that the triangle is solved and we know all its angles and sides, we can calculate other stuff. this.perimeter = _.values(this.sides).reduce((a,b) => a.plus(b)); // Calculate the heights, which in the case of a Triangle, there are many. ['a', 'b', 'c'].forEach((k) => this.heights[k] = this.heightOf(k)); // Now we use Heron's Formula to calculate the area. this.area = this.heights.a.mul(this.sides.a).div(2); this.getType(); this.solved = true; return this; } }
JavaScript
class Bundle extends React.Component { static propTypes = propTypes; static defaultProps = defaultProps; constructor(props) { super(props); this.state = { BundledComponent: null, failed: false, }; } componentDidMount() { this.mounted = true; const { load } = this.props; load() .then(this.handleLoad) .catch(this.handleLoadError); } componentWillUnmount() { this.mounted = false; } handleLoad = (BundledComponent) => { if (!this.mounted) { console.warn('Bundle unmounted while loading Component.'); return; } let Component = BundledComponent.default || BundledComponent; const { decorator } = this.props; if (decorator) { Component = decorator(Component); } this.setState({ BundledComponent: Component, }); } handleLoadError = (err) => { if (!this.mounted) { console.warn('Bundle unmounted while loading Component.'); return; } this.setState({ failed: true }); console.warn('Bundle load failed.', err); } render() { const { load, // eslint-disable-line no-unused-vars, @typescript-eslint/no-unused-vars decorator, // eslint-disable-line no-unused-vars, @typescript-eslint/no-unused-vars errorText, loadingText, renderer: Loading, ...otherProps } = this.props; const { BundledComponent, failed, } = this.state; if (!BundledComponent) { const message = failed ? errorText : loadingText; return <Loading text={message} />; } return <BundledComponent {...otherProps} />; } }
JavaScript
class Dependencies { constructor() { // This class provides a lightweight facade for the `bottlejs` package. this._bottle = new Bottle(); this._container = this._bottle.container; } get(name) { const dep = this._container[name]; if (dep === undefined) { throw new Error(`No dependency registered for the name "${name}"`); } return dep; } registerClass(name, constructor, ...deps) { this._bottle.service(name, constructor, ...deps); } registerValue(name, value) { this._bottle.constant(name, value); } }
JavaScript
class GdxFor { /** * Construct a GDX-FOR communication object. * @param {Runtime} runtime - the Scratch 3.0 runtime * @param {string} extensionId - the id of the extension */ constructor (runtime, extensionId) { /** * The Scratch 3.0 runtime used to trigger the green flag button. * @type {Runtime} * @private */ this._runtime = runtime; /** * The BluetoothLowEnergy connection socket for reading/writing peripheral data. * @type {BLE} * @private */ this._scratchLinkSocket = null; /** * An @vernier/godirect Device * @type {Device} * @private */ this._device = null; this._runtime.registerPeripheralExtension(extensionId, this); /** * The id of the extension this peripheral belongs to. */ this._extensionId = extensionId; this.disconnect = this.disconnect.bind(this); this._onConnect = this._onConnect.bind(this); this._sensorsEnabled = null; } /** * Called by the runtime when user wants to scan for a peripheral. */ scan () { if (this._scratchLinkSocket) { this._scratchLinkSocket.disconnect(); } this._scratchLinkSocket = new BLE(this._runtime, this._extensionId, { filters: [ {namePrefix: 'GDX-FOR'} ], optionalServices: [ BLEUUID.service ] }, this._onConnect); } /** * Called by the runtime when user wants to connect to a certain peripheral. * @param {number} id - the id of the peripheral to connect to. */ connect (id) { if (this._scratchLinkSocket) { this._scratchLinkSocket.connectPeripheral(id); } } /** * Called by the runtime when a user exits the connection popup. * Disconnect from the GDX FOR. */ disconnect () { this._sensorsEnabled = false; if (this._scratchLinkSocket) { this._scratchLinkSocket.disconnect(); } } /** * Return true if connected to the goforce device. * @return {boolean} - whether the goforce is connected. */ isConnected () { let connected = false; if (this._scratchLinkSocket) { connected = this._scratchLinkSocket.isConnected(); } return connected; } /** * Starts reading data from peripheral after BLE has connected to it. * @private */ _onConnect () { const adapter = new ScratchLinkDeviceAdapter(this._scratchLinkSocket, BLEUUID); godirect.createDevice(adapter, {open: true, startMeasurements: false}).then(device => { this._device = device; this._device.keepValues = false; // todo: possibly remove after updating Vernier godirect module this._startMeasurements(); }); } /** * Enable and begin reading measurements * @private */ _startMeasurements () { this._device.sensors.forEach(sensor => { sensor.setEnabled(true); }); this._device.on('measurements-started', () => { this._sensorsEnabled = true; }); this._device.start(10); // Set the period to 10 milliseconds } /** * Device is connected and measurements enabled * @return {boolean} - whether the goforce is connected and measurements started. */ _canReadSensors () { return this.isConnected() && this._sensorsEnabled; } getForce () { if (this._canReadSensors()) { let force = this._device.getSensor(1).value; // Normalize the force, which can be measured between -50 and 50 N, // to be a value between -100 and 100. force = MathUtil.clamp(force * 2, -100, 100); return force; } return 0; } getTiltX () { if (this._canReadSensors()) { let x = this.getAccelerationX(); let y = this.getAccelerationY(); let z = this.getAccelerationZ(); let xSign = 1; let ySign = 1; let zSign = 1; if (x < 0.0) { x *= -1.0; xSign = -1; } if (y < 0.0) { y *= -1.0; ySign = -1; } if (z < 0.0) { z *= -1.0; zSign = -1; } // Compute the yz unit vector const z2 = z * z; const x2 = x * x; let value = z2 + x2; value = Math.sqrt(value); // For sufficiently small zy vector values we are essentially at 90 degrees. // The following snaps to 90 and avoids divide-by-zero errors. // The snap factor was derived through observation -- just enough to // still allow single degree steps up to 90 (..., 87, 88, 89, 90). if (value < 0.35) { value = 90; } else { // Compute the x-axis angle value = y / value; value = Math.atan(value); value *= 57.2957795; // convert from rad to deg } // Manage the sign of the result let xzSign = xSign; if (z > x) xzSign = zSign; if (xzSign === -1) value = 180.0 - value; value *= ySign; // Round the result to the nearest degree value += 0.5; return value; } return 0; } getTiltY () { if (this._canReadSensors()) { let x = this.getAccelerationX(); let y = this.getAccelerationY(); let z = this.getAccelerationZ(); let xSign = 1; let ySign = 1; let zSign = 1; if (x < 0.0) { x *= -1.0; xSign = -1; } if (y < 0.0) { y *= -1.0; ySign = -1; } if (z < 0.0) { z *= -1.0; zSign = -1; } // Compute the yz unit vector const z2 = z * z; const y2 = y * y; let value = z2 + y2; value = Math.sqrt(value); // For sufficiently small zy vector values we are essentially at 90 degrees. // The following snaps to 90 and avoids divide-by-zero errors. // The snap factor was derived through observation -- just enough to // still allow single degree steps up to 90 (..., 87, 88, 89, 90). if (value < 0.35) { value = 90; } else { // Compute the x-axis angle value = x / value; value = Math.atan(value); value *= 57.2957795; // convert from rad to deg } // Manage the sign of the result let yzSign = ySign; if (z > y) yzSign = zSign; if (yzSign === -1) value = 180.0 - value; value *= xSign; // Round the result to the nearest degree value += 0.5; return value; } return 0; } getAccelerationX () { return this._getAcceleration(2); } getAccelerationY () { return this._getAcceleration(3); } getAccelerationZ () { return this._getAcceleration(4); } _getAcceleration (sensorNum) { if (!this._canReadSensors()) return 0; const val = this._device.getSensor(sensorNum).value; return val; } getSpinSpeedX () { return this._getSpinSpeed(5); } getSpinSpeedY () { return this._getSpinSpeed(6); } getSpinSpeedZ () { return this._getSpinSpeed(7); } _getSpinSpeed (sensorNum) { if (!this._canReadSensors()) return 0; let val = this._device.getSensor(sensorNum).value; val = MathUtil.radToDeg(val); const framesPerSec = 1000 / this._runtime.currentStepTime; val = val / framesPerSec; // convert to from degrees per sec to degrees per frame val = val * -1; return val; } }
JavaScript
class Scratch3GdxForBlocks { /** * @return {string} - the name of this extension. */ static get EXTENSION_NAME () { return 'Force and Acceleration'; } /** * @return {string} - the ID of this extension. */ static get EXTENSION_ID () { return 'gdxfor'; } get AXIS_MENU () { return [ { text: 'x', value: AxisValues.X }, { text: 'y', value: AxisValues.Y }, { text: 'z', value: AxisValues.Z } ]; } get TILT_MENU () { return [ { text: 'x', value: TiltAxisValues.X }, { text: 'y', value: TiltAxisValues.Y } ]; } get FACE_MENU () { return [ { text: formatMessage({ id: 'gdxfor.up', default: 'up', description: 'the sensor is facing up' }), value: FaceValues.UP }, { text: formatMessage({ id: 'gdxfor.down', default: 'down', description: 'the sensor is facing down' }), value: FaceValues.DOWN } ]; } get PUSH_PULL_MENU () { return [ { text: formatMessage({ id: 'gdxfor.pushed', default: 'pushed', description: 'the force sensor was pushed inward' }), value: PushPullValues.PUSHED }, { text: formatMessage({ id: 'gdxfor.pulled', default: 'pulled', description: 'the force sensor was pulled outward' }), value: PushPullValues.PULLED } ]; } get GESTURE_MENU () { return [ { text: formatMessage({ id: 'gdxfor.moved', default: 'moved', description: 'the sensor was moved' }), value: GestureValues.MOVED }, { text: formatMessage({ id: 'gdxfor.shaken', default: 'shaken', description: 'the sensor was shaken' }), value: GestureValues.SHAKEN }, { text: formatMessage({ id: 'gdxfor.startedFalling', default: 'started falling', description: 'the sensor started free falling' }), value: GestureValues.STARTED_FALLING } ]; } /** * Construct a set of GDX-FOR blocks. * @param {Runtime} runtime - the Scratch 3.0 runtime. */ constructor (runtime) { /** * The Scratch 3.0 runtime. * @type {Runtime} */ this.runtime = runtime; // Create a new GdxFor peripheral instance this._peripheral = new GdxFor(this.runtime, Scratch3GdxForBlocks.EXTENSION_ID); } /** * @returns {object} metadata for this extension and its blocks. */ getInfo () { return { id: Scratch3GdxForBlocks.EXTENSION_ID, name: Scratch3GdxForBlocks.EXTENSION_NAME, blockIconURI: blockIconURI, showStatusButton: true, blocks: [ { opcode: 'whenForcePushedOrPulled', text: formatMessage({ id: 'gdxfor.whenForcePushedOrPulled', default: 'when force sensor [PUSH_PULL]', description: 'when the force sensor is pushed or pulled' }), blockType: BlockType.HAT, arguments: { PUSH_PULL: { type: ArgumentType.STRING, menu: 'pushPullOptions', defaultValue: PushPullValues.PUSHED } } }, { opcode: 'getForce', text: formatMessage({ id: 'gdxfor.getForce', default: 'force', description: 'gets force' }), blockType: BlockType.REPORTER }, { opcode: 'whenGesture', text: formatMessage({ id: 'gdxfor.whenGesture', default: 'when [GESTURE]', description: 'when the sensor detects a gesture' }), blockType: BlockType.HAT, arguments: { GESTURE: { type: ArgumentType.STRING, menu: 'gestureOptions', defaultValue: GestureValues.MOVED } } }, { opcode: 'getTilt', text: formatMessage({ id: 'gdxfor.getTilt', default: 'tilt [TILT]', description: 'gets tilt' }), blockType: BlockType.REPORTER, arguments: { TILT: { type: ArgumentType.STRING, menu: 'tiltOptions', defaultValue: TiltAxisValues.X } } }, { opcode: 'getSpinSpeed', text: formatMessage({ id: 'gdxfor.getSpinSpeed', default: 'spin speed [DIRECTION]', description: 'gets spin speed' }), blockType: BlockType.REPORTER, arguments: { DIRECTION: { type: ArgumentType.STRING, menu: 'axisOptions', defaultValue: AxisValues.Z } } }, { opcode: 'getAcceleration', text: formatMessage({ id: 'gdxfor.getAcceleration', default: 'acceleration [DIRECTION]', description: 'gets acceleration' }), blockType: BlockType.REPORTER, arguments: { DIRECTION: { type: ArgumentType.STRING, menu: 'axisOptions', defaultValue: AxisValues.X } } }, { opcode: 'isFacing', text: formatMessage({ id: 'gdxfor.isFacing', default: 'facing [FACING]?', description: 'is the device facing up or down?' }), blockType: BlockType.BOOLEAN, arguments: { FACING: { type: ArgumentType.STRING, menu: 'faceOptions', defaultValue: FaceValues.UP } } }, { opcode: 'isFreeFalling', text: formatMessage({ id: 'gdxfor.isFreeFalling', default: 'falling?', description: 'is the device in free fall?' }), blockType: BlockType.BOOLEAN } ], menus: { pushPullOptions: this.PUSH_PULL_MENU, gestureOptions: this.GESTURE_MENU, axisOptions: this.AXIS_MENU, tiltOptions: this.TILT_MENU, faceOptions: this.FACE_MENU } }; } whenForcePushedOrPulled (args) { switch (args.PUSH_PULL) { case PushPullValues.PUSHED: return this._peripheral.getForce() < FORCE_THRESHOLD * -1; case PushPullValues.PULLED: return this._peripheral.getForce() > FORCE_THRESHOLD; default: log.warn(`unknown push/pull value in whenForcePushedOrPulled: ${args.PUSH_PULL}`); return false; } } getForce () { return Math.round(this._peripheral.getForce()); } whenGesture (args) { switch (args.GESTURE) { case GestureValues.MOVED: return this.gestureMagnitude() > MOVED_THRESHOLD; case GestureValues.SHAKEN: return this.gestureMagnitude() > SHAKEN_THRESHOLD; case GestureValues.STARTED_FALLING: return this.isFreeFalling(); default: log.warn(`unknown gesture value in whenGesture: ${args.GESTURE}`); return false; } } getTilt (args) { switch (args.TILT) { case TiltAxisValues.X: return Math.round(this._peripheral.getTiltX()); case TiltAxisValues.Y: return Math.round(this._peripheral.getTiltY()); default: log.warn(`Unknown direction in getTilt: ${args.TILT}`); } } getSpinSpeed (args) { switch (args.DIRECTION) { case AxisValues.X: return Math.round(this._peripheral.getSpinSpeedX()); case AxisValues.Y: return Math.round(this._peripheral.getSpinSpeedY()); case AxisValues.Z: return Math.round(this._peripheral.getSpinSpeedZ()); default: log.warn(`Unknown direction in getSpinSpeed: ${args.DIRECTION}`); } } getAcceleration (args) { switch (args.DIRECTION) { case AxisValues.X: return Math.round(this._peripheral.getAccelerationX()); case AxisValues.Y: return Math.round(this._peripheral.getAccelerationY()); case AxisValues.Z: return Math.round(this._peripheral.getAccelerationZ()); default: log.warn(`Unknown direction in getAcceleration: ${args.DIRECTION}`); } } /** * @param {number} x - x axis vector * @param {number} y - y axis vector * @param {number} z - z axis vector * @return {number} - the magnitude of a three dimension vector. */ magnitude (x, y, z) { return Math.sqrt((x * x) + (y * y) + (z * z)); } accelMagnitude () { return this.magnitude( this._peripheral.getAccelerationX(), this._peripheral.getAccelerationY(), this._peripheral.getAccelerationZ() ); } gestureMagnitude () { return this.accelMagnitude() - GRAVITY; } isFacing (args) { switch (args.FACING) { case FaceValues.UP: return this._peripheral.getAccelerationZ() > FACING_THRESHOLD; case FaceValues.DOWN: return this._peripheral.getAccelerationZ() < FACING_THRESHOLD * -1; default: log.warn(`Unknown direction in isFacing: ${args.FACING}`); } } isFreeFalling () { return this.accelMagnitude() < FREEFALL_THRESHOLD; } }
JavaScript
class LogSubscriptionLambda extends Lambda { constructor(options) { if (!options) throw new Error('Options required'); super(options); const { FilterPattern = '', LogGroupName } = options; const required = [LogGroupName]; if (required.some((variable) => !variable)) throw new Error('You must provide a LogGroupName'); this.Resources[`${this.LogicalName}SubscriptionFilter`] = { Type: 'AWS::Logs::SubscriptionFilter', Condition: this.Condition, Properties: { DestinationArn: { 'Fn::GetAtt': [this.LogicalName, 'Arn'] }, FilterPattern: FilterPattern, LogGroupName: LogGroupName } }; this.Resources[`${this.LogicalName}Permission`] = { Type: 'AWS::Lambda::Permission', Condition: this.Condition, Properties: { Action: 'lambda:InvokeFunction', FunctionName: { 'Fn::GetAtt': [this.LogicalName, 'Arn'] }, Principal: { 'Fn::Sub': 'logs.${AWS::URLSuffix}' }, SourceArn: { 'Fn::Sub': ['arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:${Name}:*', { Name: LogGroupName }] } } }; } }
JavaScript
class DiffSpectElement2 extends DualViewerApplicationElement { constructor() { super(); this.dataPanel=null; this.resultsPanel=null; this.spectModule=new diffSpectModule(); this.spectModule.alertCallback=webutil.createAlert; this.patientInfoModal = null; } getApplicationStateFilenameExtension(saveimages=true) { if (saveimages) return 'diffspect'; return "state"; } getApplicationStateFilename(storeimages=true,ext=null) { ext = ext || this.getApplicationStateFilenameExtension(storeimages); let s=`${this.spectModule.app_state.patient_name}_${this.spectModule.app_state.patient_number}.${ext}`; s=s.trim().replace(/ /g,'_'); console.log(s); return s; } /** * Creates a small modal dialog to allow the user to enter the session password used to authenticate access to the local fileserver. * Also displays whether authentication succeeded or failed. */ showPatientInfoModal() { if (!this.patientInfoModal) { let nid=webutil.getuniqueid(); let uid=webutil.getuniqueid(); let dataEntryBox=$(` <div class='form-group'> <label for='name'>Patient Name:</label> <input type='text' class = 'form-control' id='${nid}' value=""> </div> <div class='form-group'> <label for='number'>Patient ID:</label> <input type='text' class = 'form-control' id='${uid}'> </div> `); this.patientInfoModal = webutil.createmodal('Enter Patient Information', 'modal-sm'); this.patientInfoModal.dialog.find('.modal-footer').find('.btn').remove(); this.patientInfoModal.body.append(dataEntryBox); let confirmButton = webutil.createbutton({ 'name': 'Save', 'type': 'btn-success' }); let cancelButton = webutil.createbutton({ 'name': 'Cancel', 'type': 'btn-danger' }); this.patientInfoModal.footer.append(confirmButton); this.patientInfoModal.footer.append(cancelButton); cancelButton.on('click', (e) => { e.preventDefault(); this.patientInfoModal.dialog.modal('hide'); }); confirmButton.on('click', (e) => { e.preventDefault(); this.patientInfoModal.dialog.modal('hide'); console.log(this); this.spectModule.app_state.patient_name=$('#'+nid).val(); this.spectModule.app_state.patient_number= $('#'+uid).val(); }); this.patientNameId=nid; this.patientNumberId=uid; } $('#'+this.patientNameId).val(this.spectModule.app_state.patient_name); $('#'+this.patientNumberId).val(this.spectModule.app_state.patient_number); this.patientInfoModal.dialog.modal('show'); } // ------------------------------------ // Element State // ------------------------------------ /** Get State as Object @returns {object} -- the state of the element as a dictionary*/ getElementState(storeImages=false) { let obj=super.getElementState(false);//storeImages); if (storeImages) { obj.spect = { name: this.spectModule.app_state.patient_name, number: this.spectModule.app_state.patient_number, }; for (let i=0;i<this.spectModule.saveList.length;i++) { let elem=this.spectModule.saveList[i]; if (!this.spectModule.app_state[elem]) { obj.spect[elem]=''; } else { if (this.spectModule.typeList[i]==='dictionary') { obj.spect[elem]=this.spectModule.app_state[elem]; } else { obj.spect[elem]=this.spectModule.app_state[elem].serializeToJSON(); } } } } else { obj.spect={}; for (let i=0;i<this.spectModule.saveList.length;i++) { obj.spect[this.spectModule.saveList[i]]=''; } } return obj; } /** Set the element state from a dictionary object @param {object} state -- the state of the element */ setElementState(dt=null,name="") { if (dt===null) return; console.log('Here loading',Object.keys(dt)); super.setElementState(dt,name); let input=dt.spect || {}; this.spectModule.app_state.patient_name= input.name || ''; this.spectModule.app_state.patient_number= input.number || 0; for (let i=0;i<this.spectModule.saveList.length;i++) { let elem=this.spectModule.saveList[i]; input[elem]=input[elem] || ''; if (input[elem].length<1) { this.spectModule.app_state[elem]=null; } else { if (this.spectModule.typeList[i]==='dictionary') { this.spectModule.app_state[elem]=input[elem]; console.log(elem+' loaded elements='+this.spectModule.app_state[elem].length); } else { this.spectModule.app_state[elem]=BisWebDataObjectCollection.parseObject(input[elem], this.spectModule.typeList[i]); console.log(elem+' loaded=',this.spectModule.app_state[elem].getDescription()); } } } if (null !== this.spectModule.app_state['tmap']) { console.log('Showing tmap'); this.showTmapImage(); } else { this.VIEWERS[0].setimage(this.spectModule.app_state['ictal']); this.dataPanel.show(); } if (null !== this.spectModule.app_state['hyper']) { console.log('Gen charts'); this.generateCharts(); this.resultsPanel.show(); } } // -------------------------------------------------------------------------------- // GUI Callbacks // ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- // Load Image Callback loadPatientImage(name='ictal') { let handleGenericFileSelect = (imgfile)=> { let newimage = new BisWebImage(); newimage.load(imgfile, false).then( () => { this.spectModule.app_state[name] = newimage; webutil.createAlert('Loaded '+name +': '+this.spectModule.app_state[name].getDescription()); this.VIEWERS[0].setimage(this.spectModule.app_state[name]); for (let i=0;i<this.spectModule.clearList.length;i++) { let elem=this.spectModule.clearList[i]; this.spectModule.app_state[elem]=null; } }); }; webfileutil.genericFileCallback( { "title" : `Load ${name} image`, "suffix" : "NII" }, ( (fname) => { handleGenericFileSelect(fname); }), ); } savePatientImage(name='ictal') { let img=this.spectModule.app_state[name]; img.save(); } // -------------------------------------------------------------------------------- // Create the SPECT Tool GUI // -------------------------------------------------------------------------------- initializeTree() { let treeOptionsCallback=this.treeCallback.bind(this); let p=new Promise( (resolve,reject) => { this.spectModule.loadAtlasData().then( () => { this.VIEWERS[0].setimage(this.spectModule.app_state.ATLAS_mri); resolve(); }).catch( (e) => { reject(e); }); }); this.applicationInitializedPromiseList.push(p); let tree=this.tree_div.find('#treeDiv'); let json_data = { 'core': { 'data': [ { 'text': 'Images', 'state': { 'opened': true, 'selected': false }, 'children': [ {'text': 'Interictal' }, {'text': 'Ictal' }, {'text': 'MRI' } ] }, { 'text': 'Registrations', 'state': { 'opened': false, 'selected': false }, 'children': [ { 'text': 'Interictal to Ictal' }, { 'text': 'ATLAS to Interictal' }, { 'text': 'ATLAS to Ictal' }, { 'text': 'MRI to Interictal' }, { 'text': 'MRI to Ictal' }, { 'text': 'ATLAS to MRI' }, ] }, { 'text': 'Diff SPECT', 'state': { 'opened': false, 'selected': false }, 'children': [ { 'text': 'Tmap Image' }, { 'text': 'Tmap Image (Native Space)' }, ] } ] }, 'plugins': ['contextmenu'], 'contextmenu' : { 'items': treeOptionsCallback } }; tree.jstree(json_data); } treeCallback(node) { const self=this; let items = { showimage: { 'label': 'Show Image', 'action': () => { if (node.text === "Interictal") { if (self.spectModule.app_state.interictal !== null) { webutil.createAlert('Displaying original interictal image'); self.VIEWERS[0].setimage(self.spectModule.app_state.interictal); } else { bootbox.alert('No interictal image loaded'); } } if (node.text === "Ictal") { if (self.spectModule.app_state.ictal !== null) { webutil.createAlert('Displaying original ictal image'); self.VIEWERS[0].setimage(self.spectModule.app_state.ictal); } else { bootbox.alert('No ictal image loaded'); } } if (node.text === "MRI") { if (self.spectModule.app_state.mri !== null) { webutil.createAlert('Displaying original mri image'); self.VIEWERS[0].setimage(self.spectModule.app_state.mri); } else { bootbox.alert('No MRI image loaded'); } } if (node.text === 'Tmap Image') { if (self.spectModule.app_state.tmap !== null) { self.showTmapImage(); } else { bootbox.alert('No diff-SPECT tmap image. You need to compute this first.'); } } if (node.text === 'Tmap Image (Native Space)') { if (self.spectModule.app_state.nativetmap !== null) { self.showNativeTmapImage(); } else { bootbox.alert('No diff-SPECT tmap image in native space in memory. You need to compute this first.'); } } }, }, loadinter: { 'label': 'Load Interictal', 'action': () => { self.loadPatientImage('interictal'); }, }, loadictal: { 'label': 'Load Ictal', 'action': () => { self.loadPatientImage('ictal'); } }, loadmri: { 'label': 'Load MRI', 'action': () => { self.loadPatientImage('mri'); } }, saveinter: { 'label': 'Save Interictal', 'action': () => { self.savePatientImage('interictal'); }, }, saveictal: { 'label': 'Save Ictal', 'action': () => { self.savePatientImage('ictal'); } }, savemri: { 'label': 'Save MRI', 'action': () => { self.savePatientImage('mri'); } }, showregistration: { 'label': 'Show Registration', 'action': () => { console.log('Action=',node.text); this.spectModule.setAutoUseMRI(); if (node.text === "ATLAS to Interictal") { self.showAtlasToInterictalRegistration(); } else if (node.text === "ATLAS to Ictal") { self.showAtlasToIctalRegistration(); } else if (node.text === "Interictal to Ictal") { self.showInterictalToIctalRegistration(); } else if (node.text ==="ATLAS to MRI") { self.showAtlasToMRIRegistration(); } else if (node.text ==="MRI to Interictal") { self.showMRIToInterictalRegistration(); } else if (node.text ==="MRI to Ictal") { self.showMRIToIctalRegistration(); } } }, saveregistration: { 'label': 'Save Registration', 'action': () => { console.log('Action=',node.text); this.spectModule.setAutoUseMRI(); if (node.text === "ATLAS to Interictal") { self.showAtlasToInterictalRegistration(true); } else if (node.text === "ATLAS to Ictal") { self.showAtlasToIctalRegistration(true); } else if (node.text === "Interictal to Ictal") { self.showInterictalToIctalRegistration(true); } else if (node.text ==="ATLAS to MRI") { self.showAtlasToMRIRegistration(true); } else if (node.text ==="MRI to Interictal") { self.showMRIToInterictalRegistration(true); } else if (node.text ==="MRI to Ictal") { self.showMRIToIctalRegistration(true); } } }, }; if (node.text === "Images") { items = null; } if (node.text !== 'Interictal') { delete items.loadinter; delete items.saveinter; } if (node.text !== 'Ictal') { delete items.loadictal; delete items.saveictal; } if (node.text !== 'MRI') { delete items.loadmri; delete items.savemri; } if (node.text !== 'Interictal' && node.text !== 'Ictal' && node.text !== 'Tmap Image' && node.text !== 'Tmap Image (Native Space)' && node.text !== 'MRI') { delete items.showimage; } if (node.text !== 'ATLAS to Interictal' && node.text !== 'ATLAS to Ictal' && node.text !== 'Interictal to Ictal' && node.text !== 'MRI to Interictal' && node.text !== 'MRI to Ictal' && node.text !== 'ATLAS to MRI') { delete items.showregistration; delete items.saveregistration; } return items; } // --------------------------------------------------------------------------------------- // Charts /** generate a single output table */ generateChart(parent,data,name) { let templates=webutil.getTemplates(); let newid=webutil.createWithTemplate(templates.bisscrolltable,$('body')); let stable=$('#'+newid); const self=this; let buttoncoords = {}; let callback = (e) => { let id=e.target.id; if (!id) { id=e.target.parentElement.id; if (!id) id=e.target.parentElement.parentElement.id; } let coordinate=buttoncoords[id]; self.VIEWERS[0].setcoordinates([coordinate[0], coordinate[1], coordinate[2]]); }; let thead = stable.find(".bisthead"); let tbody = stable.find(".bistbody",stable); thead.empty(); tbody.empty(); tbody.css({'font-size':'11px', 'user-select': 'none'}); thead.css({'font-size':'12px', 'user-select': 'none'}); let hd=$(`<tr> <td width="5%">#</td> <td width="25%">${name}-Coords</td> <td width="15%">Size</td> <td width="20%">ClusterP</td> <td width="20%">CorrectP</td> <td width="15%">MaxT</td> </tr>`); thead.append(hd); for (let i=0;i<data.length;i++) { let index=data[i].index; let size=data[i].size; let coords=data[i].coords.join(','); let clusterP=Number.parseFloat(data[i].clusterPvalue).toFixed(4); let correctP=Number.parseFloat(data[i].correctPvalue).toFixed(4); let maxt=Number.parseFloat(data[i].maxt).toFixed(3); let nid=webutil.getuniqueid(); let w=$(`<tr> <td width="5%">${index}</td> <td width="25%"><span id="${nid}" class="btn-link">${coords}</span></td> <td width="15%">${size}</td> <td width="20%">${clusterP}</td> <td width="20%">${correctP}</td> <td width="15%">${maxt}</td> </tr>`); tbody.append(w); $('#'+nid).click(callback); buttoncoords[nid]=data[i].coords; } parent.append(stable); } generateCharts() { if (this.spectModule.app_state.hyper === null) return; let pdiv=this.resultsToolsDiv; pdiv.empty(); pdiv.append($(`<H4> Results for ${this.spectModule.app_state.patient_name} : ${this.spectModule.app_state.patient_number}</H4>`)); let lst = [ 'Hyper', 'Hypo' ]; let data = [ this.spectModule.app_state.hyper, this.spectModule.app_state.hypo ]; let maxpass=1; for (let pass=0;pass<=maxpass;pass++) { this.generateChart(pdiv,data[pass],lst[pass]); } } saveResults(fobj) { let lst = [ 'Hyper', 'Hypo' ]; let datalist = [ this.spectModule.app_state.hyper, this.spectModule.app_state.hypo ]; let str=`Name, ${this.spectModule.app_state.patient_name}, Number, ${this.spectModule.app_state.patient_number}\n`; str+='Mode,Index,I,J,K,Size,clusterP,correctedP,maxT-score\n'; for (let pass=0;pass<datalist.length;pass++) { let data=datalist[pass]; let name=lst[pass]; for (let i=0;i<data.length;i++) { let index=data[i].index; let size=data[i].size; let coords=data[i].coords; let clusterP=Number.parseFloat(data[i].clusterPvalue).toFixed(8); let correctP=Number.parseFloat(data[i].correctPvalue).toFixed(8); let maxt=Number.parseFloat(data[i].maxt).toFixed(3); str+=`${name},${index},${coords[0]},${coords[1]},${coords[2]}`; str+=`${size},${clusterP},${correctP},${maxt}\n`; } } let fn=this.getApplicationStateFilename(false,'csv'); fobj=genericio.getFixedSaveFileName(fobj,fn); return new Promise(function (resolve, reject) { genericio.write(fobj, str).then((f) => { webutil.createAlert('Results saved in '+f); }).catch((e) => { webutil.createAlert('Failed to save results '+e,true); reject(e); }); }); } // --------------------------------------------------------------------------------------- // Show Transformations and Images setViewerOpacity(opa=0.5) { let cmapcontrol=this.VIEWERS[0].getColormapController(); let elem=cmapcontrol.getElementState(); elem.opacity=opa; cmapcontrol.setElementState(elem); cmapcontrol.updateTransferFunctions(true); } saveTransformation(operation) { let xform=this.spectModule.getComboTransformation(operation); xform.save(`${operation}.bisxform`); } showAtlasToInterictalRegistration(save=false) { this.spectModule.resliceImages('inter2Atlas',false).then( () => { webutil.createAlert('Displaying resliced interictal image over atlas SPECT image'); this.VIEWERS[0].setimage(this.spectModule.app_state.ATLAS_spect); this.VIEWERS[0].setobjectmap(this.spectModule.app_state.inter_in_atlas_reslice,false,'Overlay2'); this.setViewerOpacity(0.5); if (save) this.saveTransformation('inter2Atlas'); }).catch( (e) => { errormessage(e); }); } showMRIToInterictalRegistration(save=false) { this.spectModule.resliceImages('inter2mri',false).then( () => { webutil.createAlert('Displaying resliced interictal image over MRI image'); this.VIEWERS[0].setimage(this.spectModule.app_state.mri); this.VIEWERS[0].setobjectmap(this.spectModule.app_state.inter_in_mri_reslice,false,'Overlay2'); this.setViewerOpacity(0.5); if (save) this.saveTransformation('inter2mri'); }).catch( (e) => { errormessage(e); }); } showAtlasToIctalRegistration(save=false) { this.spectModule.resliceImages('ictal2Atlas',false).then( () => { webutil.createAlert('Displaying resliced ictal image over atlas SPECT image'); this.VIEWERS[0].setimage(this.spectModule.app_state.ATLAS_spect); this.VIEWERS[0].setobjectmap(this.spectModule.app_state.ictal_in_atlas_reslice,false,'Overlay2'); this.setViewerOpacity(0.5); if (save) this.saveTransformation('ictal2Atlas'); }).catch( (e) => { errormessage(e); }); } showMRIToIctalRegistration(save=false) { this.spectModule.resliceImages('ictal2mri',false).then( () => { webutil.createAlert('Displaying resliced ictal image over MRI image'); this.VIEWERS[0].setimage(this.spectModule.app_state.mri); this.VIEWERS[0].setobjectmap(this.spectModule.app_state.ictal_in_mri_reslice,false,'Overlay2'); this.setViewerOpacity(0.5); if (save) this.saveTransformation('ictal2mri'); }).catch( (e) => { errormessage(e); }); } showInterictalToIctalRegistration(save=false) { this.spectModule.resliceImages('inter2ictal',false).then( () => { webutil.createAlert('Displaying resliced ictal image over interictal image'); this.VIEWERS[0].setimage(this.spectModule.app_state.interictal); this.VIEWERS[0].setobjectmap(this.spectModule.app_state.ictal_in_inter_reslice,false,'Overlay2'); this.setViewerOpacity(0.5); if (save) this.saveTransformation('inter2ictal'); }).catch( (e) => { errormessage(e); }); } // New showAtlasToMRIRegistration(save=false) { this.spectModule.resliceImages('mri2Atlas',false).then( () => { webutil.createAlert('Displaying resliced mri image over atlas MRI image'); this.VIEWERS[0].setimage(this.spectModule.app_state.ATLAS_mri); this.VIEWERS[0].setobjectmap(this.spectModule.app_state.mri_in_atlas_reslice,false,'Orange'); this.setViewerOpacity(0.5); if (save) this.saveTransformation('mri2Atlas'); }).catch( (e) => { errormessage(e); }); } showTmapImage() { if (this.spectModule.app_state.tmap) { webutil.createAlert('Displaying diff-spect TMAP over atlas MRI image'); this.VIEWERS[0].setimage(this.spectModule.app_state.ATLAS_mri); this.VIEWERS[0].setobjectmap(this.spectModule.app_state.tmap, false, "Overlay"); let cmapcontrol=this.VIEWERS[0].getColormapController(); let elem=cmapcontrol.getElementState(); elem.minth=1.0; cmapcontrol.setElementState(elem); cmapcontrol.updateTransferFunctions(true); } else { errormessage('No tmap in memory'); } } showNativeTmapImage() { if (this.spectModule.app_state.nativetmap) { if (this.spectModule.app_state.does_have_mri) { webutil.createAlert('Displaying diff-spect TMAP over Native MRI image'); this.VIEWERS[0].setimage(this.spectModule.app_state.mri); } else { webutil.createAlert('Displaying diff-spect TMAP over Interictal image'); this.VIEWERS[0].setimage(this.spectModule.app_state.interictal); } this.VIEWERS[0].setobjectmap(this.spectModule.app_state.nativetmap, false, "Overlay"); let cmapcontrol=this.VIEWERS[0].getColormapController(); let elem=cmapcontrol.getElementState(); elem.minth=1.0; cmapcontrol.setElementState(elem); cmapcontrol.updateTransferFunctions(true); } else { errormessage('No native space tmap in memory'); } } computeAllRegistrations(nonlinear=false) { this.spectModule.app_state.nonlinear = nonlinear; this.spectModule.setAutoUseMRI(); this.spectModule.computeAllRegistrations().then( (m) => { this.spectModule.resliceImages('ictal2Atlas').then( () => { this.showAtlasToIctalRegistration(); this.dataPanel.show(); webutil.createAlert(m); }).catch( (e) => { console.log(e,e.stack); webutil.createAlert(e,true); }); }).catch( (e) => { console.log(e,e.stack); webutil.createAlert(e,true); }); } // --------------------------------------------------------------------------------------- // Extra Menu with createExtraMenu(menubar) { const self=this; let layoutid = this.getAttribute('bis-layoutwidgetid'); let layoutcontroller = document.querySelector(layoutid); this.dataPanel=new BisWebPanel(layoutcontroller, { name : 'Diff-Spect DataTree', permanent : false, width : '300', dual : false, }); this.spectToolsDiv = this.dataPanel.getWidget(); this.resultsPanel=new BisWebPanel(layoutcontroller, { name : 'Diff-Spect Results', permanent : false, width : '300', dual : true, mode : 'sidebar' }); this.resultsToolsDiv = this.resultsPanel.getWidget(); this.resultsToolsDiv.append($('<div> No results yet.</div>')); // stamp template this.tree_div=$(tree_template_string); this.spectToolsDiv.append(this.tree_div); // this.dataPanel.show(); // this.resultsPanel.hide(); this.initializeTree(); let sMenu = webutil.createTopMenuBarMenu("diff-SPECT", menubar); webutil.createMenuItem(sMenu, 'Enter Patient Info', () => { self.showPatientInfoModal(); }); webutil.createMenuItem(sMenu, 'Load Patient Ictal Image', () => { self.loadPatientImage('ictal'); }); webutil.createMenuItem(sMenu, 'Load Patient Inter-Ictal Image', () => { self.loadPatientImage('interictal'); }); webutil.createMenuItem(sMenu, 'Load Patient MRI Image', () => { self.loadPatientImage('mri'); }); webutil.createMenuItem(sMenu, 'Debug', () => { let s=self.spectModule.getDataDescription(); s=s.trim().replace(/\n/g,'<BR>'); bootbox.alert(s); }); webutil.createMenuItem(sMenu,''); webutil.createMenuItem(sMenu, 'Register Images using Linear Registration (fast,incaccurate)', () => { webutil.createAlert('Computing all registrations (linear)','progress',30,0, { 'makeLoadSpinner' : true }); setTimeout( () => { self.computeAllRegistrations(false); },100); }); webutil.createMenuItem(sMenu, 'Register Images With Nonlinear Registration (slow,accurate)', () => { webutil.createAlert('Computing all registrations (nonlinear)','progress',30,0, { 'makeLoadSpinner' : true }); setTimeout( () => { self.computeAllRegistrations(true); },100); }); webutil.createMenuItem(sMenu,''); webutil.createMenuItem(sMenu, 'Compute Diff Spect MAPS', () => { webutil.createAlert('Computing diff SPECT Maps','progress',30,0, { 'makeLoadSpinner' : true }); setTimeout( () => { self.spectModule.computeSpect().then( (m) => { webutil.createAlert(m); self.showTmapImage(); self.generateCharts(); self.resultsPanel.show(); }).catch( (e) => { webutil.createAlert(e,true); }); },100); }); webutil.createMenuItem(sMenu, 'Map TMAP to Native Space', () => { webutil.createAlert('Mapping TMAP to Native Space','progress',30,0, { 'makeLoadSpinner' : true }); setTimeout( () => { self.spectModule.mapTmapToNativeSpace().then( (m) => { webutil.createAlert(m); self.showNativeTmapImage(); self.resultsPanel.hide(); }).catch( (e) => { webutil.createAlert(e,true); }); },100); }); webutil.createMenuItem(sMenu,''); webutil.createMenuItem(sMenu,'Show diff SPECT Data Tree(Images)',() => { self.dataPanel.show(); }); webutil.createMenuItem(sMenu,'Show diff SPECT Text Results (Regions)',() => { self.resultsPanel.show(); }); webutil.createMenuItem(sMenu,''); webfileutil.createFileMenuItem(sMenu, 'Save diff SPECT Text Results', function (f) { self.saveResults(f); }, { title: 'Save diff SPECT Text Results', save: true, filters : [ { name: 'CSV File', extensions: ['csv']}], suffix : "csv", initialCallback : () => { return self.getApplicationStateFilename(false,"csv"); } }); } // --------------------------------------------------------------------------------------- // Main Function // connectedCallback() { this.simpleFileMenus=true; super.connectedCallback(); this.VIEWERS[0].collapseCore(); } }
JavaScript
class ChipsStackedExample { constructor() { this.availableColors = [ { name: 'none', color: undefined }, { name: 'Primary', color: 'primary' }, { name: 'Accent', color: 'accent' }, { name: 'Warn', color: 'warn' } ]; } }
JavaScript
class AudioActivityEvent extends Event { /** Creates a new "audioActivity" event */ constructor() { super("audioActivity"); /** @type {string} */ this.id = null; this.isActive = false; Object.seal(this); } /** * Sets the current state of the event * @param {string} id - the user for which the activity changed * @param {boolean} isActive - the new state of the activity */ set(id, isActive) { this.id = id; this.isActive = isActive; } }
JavaScript
class MockAudioContext { /** * Starts the timer at "now". **/ constructor() { this._t = performance.now() / 1000; Object.seal(this); } /** * Gets the current playback time. * @type {number} */ get currentTime() { return performance.now() / 1000 - this._t; } /** * Returns nothing. * @type {AudioDestinationNode} */ get destination() { return null; } }
JavaScript
class Vector { /** * Creates a new 3D point. **/ constructor() { this.x = 0; this.y = 0; this.z = 0; Object.seal(this); } /** * Sets the components of this vector. * @param {number} x * @param {number} y * @param {number} z */ set(x, y, z) { this.x = x; this.y = y; this.z = z; } /** * Copies another vector into this vector. * @param {Vector} other */ copy(other) { this.x = other.x; this.y = other.y; this.z = other.z; } /** * Performs a linear interpolation between two vectors, * storing the result in this vector. * @param {Vector} a * @param {Vector} b * @param {number} p */ lerp(a, b, p) { this.x = lerp(a.x, b.x, p); this.y = lerp(a.y, b.y, p); this.z = lerp(a.z, b.z, p); } /** * Computes the dot product of this vector with another vector * @param {Vector} other */ dot(other) { return this.x * other.x + this.y * other.y + this.z * other.z; } /** * Subtracts two vectors and stores the result in this vector. * @param {Vector} a * @param {Vector} b */ sub(a, b) { this.x = a.x - b.x; this.y = a.y - b.y; this.z = a.z - b.z; } /** * Performs a spherical linear interpolation between two vectors, * storing the result in this vector. * @param {Vector} a * @param {Vector} b * @param {number} p */ slerp(a, b, p) { const dot = a.dot(b); const angle = Math.acos(dot); if (angle !== 0) { const c = Math.sin(angle); const pA = Math.sin((1 - p) * angle) / c; const pB = Math.sin(p * angle) / c; this.x = pA * a.x + pB * b.x; this.y = pA * a.y + pB * b.y; this.x = pA * a.z + pB * b.z; } } /** * Gets the squared length of the vector **/ get lenSq() { return this.dot(this); } /** * Gets the length of the vector **/ get len() { return Math.sqrt(this.lenSq); } /** * Makes this vector a unit vector **/ normalize() { const len = this.len; if (len !== 0) { this.x /= len; this.y /= len; this.z /= len; } } }
JavaScript
class Pose { /** * Creates a new position and orientation, at a given time. **/ constructor() { this.t = 0; this.p = new Vector(); this.f = new Vector(); this.f.set(0, 0, -1); this.u = new Vector(); this.u.set(0, 1, 0); Object.seal(this); } /** * Sets the components of the pose. * @param {number} px * @param {number} py * @param {number} pz * @param {number} fx * @param {number} fy * @param {number} fz * @param {number} ux * @param {number} uy * @param {number} uz */ set(px, py, pz, fx, fy, fz, ux, uy, uz) { this.p.set(px, py, pz); this.f.set(fx, fy, fz); this.u.set(ux, uy, uz); } /** * Copies the components of another pose into this pose. * @param {Pose} other */ copy(other) { this.p.copy(other.p); this.f.copy(other.f); this.u.copy(other.u); } /** * Performs a lerp between two positions and a slerp between to orientations * and stores the result in this pose. * @param {Pose} a * @param {Pose} b * @param {number} p */ interpolate(start, end, t) { if (t <= start.t) { this.copy(start); } else if (end.t <= t) { this.copy(end); } else if (start.t < t) { const p = project(t, start.t, end.t); this.p.lerp(start.p, end.p, p); this.f.slerp(start.f, end.f, p); this.u.slerp(start.u, end.u, p); this.t = t; } } }
JavaScript
class BaseSpatializer extends EventBase { /** * Creates a spatializer that keeps track of position */ constructor() { super(); this.minDistance = 1; this.minDistanceSq = 1; this.maxDistance = 10; this.maxDistanceSq = 100; this.rolloff = 1; this.transitionTime = 0.5; } /** * Sets parameters that alter spatialization. * @param {number} minDistance * @param {number} maxDistance * @param {number} rolloff * @param {number} transitionTime **/ setAudioProperties(minDistance, maxDistance, rolloff, transitionTime) { this.minDistance = minDistance; this.maxDistance = maxDistance; this.transitionTime = transitionTime; this.rolloff = rolloff; } /** * Discard values and make this instance useless. */ dispose() { } /** * Performs the spatialization operation for the audio source's latest location. * @param {Pose} loc */ update(loc) { } }
JavaScript
class InterpolatedPose { /** * Creates a new position value that is blended from the current position to * a target position over time. **/ constructor() { this.start = new Pose(); this.current = new Pose(); this.end = new Pose(); /** @type {BaseSpatializer} */ this._spatializer = null; Object.seal(this); } get spatializer() { return this._spatializer; } set spatializer(v) { if (this.spatializer !== v) { if (this._spatializer) { this._spatializer.dispose(); } this._spatializer = v; } } dispose() { this.spatializer = null; } /** * Set the target position and orientation for the time `t + dt`. * @param {number} px - the horizontal component of the position. * @param {number} py - the vertical component of the position. * @param {number} pz - the lateral component of the position. * @param {number} fx - the horizontal component of the position. * @param {number} fy - the vertical component of the position. * @param {number} fz - the lateral component of the position. * @param {number} ux - the horizontal component of the position. * @param {number} uy - the vertical component of the position. * @param {number} uz - the lateral component of the position. * @param {number} t - the time at which to start the transition. * @param {number} dt - the amount of time to take making the transition. */ setTarget(px, py, pz, fx, fy, fz, ux, uy, uz, t, dt) { this.start.copy(this.current); this.start.t = t; this.end.set(px, py, pz, fx, fy, fz, ux, uy, uz); this.end.t = t + dt; } /** * Set the target position for the time `t + dt`. * @param {number} px - the horizontal component of the position. * @param {number} py - the vertical component of the position. * @param {number} pz - the lateral component of the position. * @param {number} t - the time at which to start the transition. * @param {number} dt - the amount of time to take making the transition. */ setTargetPosition(px, py, pz, t, dt) { this.setTarget( px, py, pz, this.end.f.x, this.end.f.y, this.end.f.z, this.end.u.x, this.end.u.y, this.end.u.z, t, dt); } /** * Set the target orientation for the time `t + dt`. * @param {number} fx - the horizontal component of the position. * @param {number} fy - the vertical component of the position. * @param {number} fz - the lateral component of the position. * @param {number} ux - the horizontal component of the position. * @param {number} uy - the vertical component of the position. * @param {number} uz - the lateral component of the position. * @param {number} t - the time at which to start the transition. * @param {number} dt - the amount of time to take making the transition. */ setTargetOrientation(fx, fy, fz, ux, uy, uz, t, dt) { this.setTarget( this.end.p.x, this.end.p.y, this.end.p.z, fx, fy, fz, ux, uy, uz, t, dt); } /** * Calculates the new position for the given time. * @protected * @param {number} t */ update(t) { this.current.interpolate(this.start, this.end, t); if (this.spatializer) { this.spatializer.update(this.current); } } }
JavaScript
class BaseSource extends BaseSpatializer { /** * Creates a spatializer that keeps track of the relative position * of an audio element to the listener destination. * @param {string} id * @param {MediaStream|HTMLAudioElement} stream */ constructor(id, stream) { super(); this.id = id; /** @type {HTMLAudioElement} */ this.audio = null; /** @type {MediaStream} */ this.stream = null; this.volume = 1; if (stream instanceof HTMLAudioElement) { this.audio = stream; } else if (stream instanceof MediaStream) { this.stream = stream; this.audio = document.createElement("audio"); this.audio.srcObject = this.stream; } else if (stream !== null) { throw new Error("Can't create a node from the given stream. Expected type HTMLAudioElement or MediaStream."); } this.audio.playsInline = true; } play() { if (this.audio) { this.audio.play(); } } /** * Discard values and make this instance useless. */ dispose() { if (this.audio) { this.audio.pause(); this.audio = null; } this.stream = null; super.dispose(); } /** * Changes the device to which audio will be output * @param {string} deviceID */ setAudioOutputDevice(deviceID) { if (this.audio && canChangeAudioOutput) { this.audio.setSinkId(deviceID); } } }
JavaScript
class ManualVolume extends BaseSource { /** * Creates a new spatializer that only modifies volume. * @param {string} id * @param {MediaStream|HTMLAudioElement} stream * @param {Pose} dest */ constructor(id, stream, dest) { super(id, stream); this.audio.muted = false; this.audio.play(); this.manual = new ManualBase(dest); /** @type {number} */ this._lastVolume = null; Object.seal(this); } /** * Performs the spatialization operation for the audio source's latest location. * @param {Pose} loc */ update(loc) { super.update(loc); this.manual.update(loc); if (this._lastVolume !== this.manual.volume) { this._lastVolume = this.audio.volume = this.manual.volume; } } }
JavaScript
class BaseWebAudio extends BaseAnalyzed { /** * Creates a new spatializer that uses the WebAudio API * @param {string} id * @param {MediaStream|HTMLAudioElement} stream * @param {number} bufferSize * @param {AudioContext} audioContext * @param {PannerNode|StereoPannerNode} inNode * @param {GainNode=} outNode */ constructor(id, stream, bufferSize, audioContext, inNode, outNode = null) { super(id, stream, bufferSize, audioContext, inNode); this.outNode = outNode || inNode; this.outNode.connect(audioContext.destination); if (this.inNode !== this.outNode) { this.inNode.connect(this.outNode); } } /** * Discard values and make this instance useless. */ dispose() { if (this.inNode !== this.outNode) { this.inNode.disconnect(this.outNode); } this.outNode.disconnect(this.outNode.context.destination); this.outNode = null; super.dispose(); } }
JavaScript
class ManualStereo extends BaseWebAudio { /** * Creates a new spatializer that performs stereo panning and volume scaling. * @param {string} id * @param {MediaStream|HTMLAudioElement} stream * @param {number} bufferSize * @param {AudioContext} audioContext * @param {Pose} dest */ constructor(id, stream, bufferSize, audioContext, dest) { super(id, stream, bufferSize, audioContext, audioContext.createStereoPanner(), audioContext.createGain()); this.manual = new ManualBase(dest); Object.seal(this); } /** * Performs the spatialization operation for the audio source's latest location. * @param {Pose} loc */ update(loc) { super.update(loc); this.manual.update(loc); this.inNode.pan.value = this.manual.pan; this.outNode.gain.value = this.manual.volume; } }
JavaScript
class PannerNew extends PannerBase { /** * Creates a new positioner that uses WebAudio's playback dependent time progression. * @param {string} id * @param {MediaStream|HTMLAudioElement} stream * @param {number} bufferSize * @param {AudioContext} audioContext */ constructor(id, stream, bufferSize, audioContext) { super(id, stream, bufferSize, audioContext); Object.seal(this); } /** * Performs the spatialization operation for the audio source's latest location. * @param {Pose} loc */ update(loc) { super.update(loc); const { p, f } = loc; this.inNode.positionX.setValueAtTime(p.x, 0); this.inNode.positionY.setValueAtTime(p.y, 0); this.inNode.positionZ.setValueAtTime(p.z, 0); this.inNode.orientationX.setValueAtTime(f.x, 0); this.inNode.orientationY.setValueAtTime(f.y, 0); this.inNode.orientationZ.setValueAtTime(f.z, 0); } }
JavaScript
class AudioListenerNew extends AudioListenerBase { /** * Creates a new positioner that uses WebAudio's playback dependent time progression. * @param {AudioListener} listener */ constructor(listener) { super(listener); Object.seal(this); } /** * Performs the spatialization operation for the audio source's latest location. * @param {Pose} loc */ update(loc) { super.update(loc); const { p, f, u } = loc; this.node.positionX.setValueAtTime(p.x, 0); this.node.positionY.setValueAtTime(p.y, 0); this.node.positionZ.setValueAtTime(p.z, 0); this.node.forwardX.setValueAtTime(f.x, 0); this.node.forwardY.setValueAtTime(f.y, 0); this.node.forwardZ.setValueAtTime(f.z, 0); this.node.upX.setValueAtTime(u.x, 0); this.node.upY.setValueAtTime(u.y, 0); this.node.upZ.setValueAtTime(u.z, 0); } /** * Creates a spatialzer for an audio source. * @private * @param {string} id * @param {MediaStream|HTMLAudioElement} stream - the audio element that is being spatialized. * @param {number} bufferSize - the size of the analysis buffer to use for audio activity detection * @param {AudioContext} audioContext * @param {Pose} dest * @return {BaseSource} */ createSource(id, stream, bufferSize, audioContext, dest) { return new PannerNew(id, stream, bufferSize, audioContext); } }
JavaScript
class PannerOld extends PannerBase { /** * Creates a new positioner that uses the WebAudio API's old setPosition method. * @param {string} id * @param {MediaStream|HTMLAudioElement} stream * @param {number} bufferSize * @param {AudioContext} audioContext */ constructor(id, stream, bufferSize, audioContext) { super(id, stream, bufferSize, audioContext); Object.seal(this); } /** * Performs the spatialization operation for the audio source's latest location. * @param {Pose} loc */ update(loc) { super.update(loc); const { p, f } = loc; this.inNode.setPosition(p.x, p.y, p.z); this.inNode.setOrientation(f.x, f.y, f.z); } }
JavaScript
class AudioListenerOld extends AudioListenerBase { /** * Creates a new positioner that uses WebAudio's playback dependent time progression. * @param {AudioListener} listener */ constructor(listener) { super(listener); Object.seal(this); } /** * Performs the spatialization operation for the audio source's latest location. * @param {Pose} loc */ update(loc) { super.update(loc); const { p, f, u } = loc; this.node.setPosition(p.x, p.y, p.z); this.node.setOrientation(f.x, f.y, f.z, u.x, u.y, u.z); } /** * Creates a spatialzer for an audio source. * @private * @param {string} id * @param {MediaStream|HTMLAudioElement} stream - the audio element that is being spatialized. * @param {number} bufferSize - the size of the analysis buffer to use for audio activity detection * @param {AudioContext} audioContext * @param {Pose} dest * @return {BaseSource} */ createSource(id, stream, bufferSize, audioContext, dest) { return new PannerOld(id, stream, bufferSize, audioContext); } }
JavaScript
class BufferList { /** * BufferList object mananges the async loading/decoding of multiple * AudioBuffers from multiple URLs. * @param {BaseAudioContext} context - Associated BaseAudioContext. * @param {string[]} bufferData - An ordered list of URLs. * @param {BufferListOptions} options - Options. */ constructor(context, bufferData, options) { if (!isAudioContext(context)) { throwError('BufferList: Invalid BaseAudioContext.'); } this._context = context; this._options = { dataType: BufferDataType.BASE64, verbose: false, }; if (options) { if (options.dataType && isDefinedENUMEntry(BufferDataType, options.dataType)) { this._options.dataType = options.dataType; } if (options.verbose) { this._options.verbose = Boolean(options.verbose); } } this._bufferData = this._options.dataType === BufferDataType.BASE64 ? bufferData : bufferData.slice(0); } /** * Starts AudioBuffer loading tasks. * @return {Promise<AudioBuffer[]>} The promise resolves with an array of * AudioBuffer. */ async load() { try { const tasks = this._bufferData.map((bData, taskId) => this._launchAsyncLoadTask(bData, taskId)); const buffers = await Promise.all(tasks); const messageString = this._options.dataType === BufferDataType.BASE64 ? this._bufferData.length + ' AudioBuffers from Base64-encoded HRIRs' : this._bufferData.length + ' files via XHR'; log('BufferList: ' + messageString + ' loaded successfully.'); return buffers; } catch (exp) { const message = 'BufferList: error while loading "' + bData + '". (' + exp.message + ')'; throwError(message); } } /** * Run async loading task for Base64-encoded string. * @private * @param {string} bData - Base64-encoded data. * @param {Number} taskId Task ID number from the ordered list |bufferData|. * @returns {Promise<AudioBuffer>} */ async _launchAsyncLoadTask(bData, taskId) { const arrayBuffer = await this._fetch(bData); const audioBuffer = await this._context.decodeAudioData(arrayBuffer); const messageString = this._options.dataType === BufferDataType.BASE64 ? 'ArrayBuffer(' + taskId + ') from Base64-encoded HRIR' : '"' + bData + '"'; log('BufferList: ' + messageString + ' successfully loaded.'); return audioBuffer; } /** * Get an array buffer out of the given data. * @private * @param {string} bData - Base64-encoded data. * @returns {Promise<ArrayBuffer>} */ async _fetch(bData) { if (this._options.dataType === BufferDataType.BASE64) { return getArrayBufferFromBase64String(bData); } else { const response = await fetch(bData); return await response.arrayBuffer(); } } }
JavaScript
class FOARotator { /** * First-order-ambisonic decoder based on gain node network. * @param {AudioContext} context - Associated AudioContext. */ constructor(context) { this._context = context; this._splitter = this._context.createChannelSplitter(4); this._inY = this._context.createGain(); this._inZ = this._context.createGain(); this._inX = this._context.createGain(); this._m0 = this._context.createGain(); this._m1 = this._context.createGain(); this._m2 = this._context.createGain(); this._m3 = this._context.createGain(); this._m4 = this._context.createGain(); this._m5 = this._context.createGain(); this._m6 = this._context.createGain(); this._m7 = this._context.createGain(); this._m8 = this._context.createGain(); this._outY = this._context.createGain(); this._outZ = this._context.createGain(); this._outX = this._context.createGain(); this._merger = this._context.createChannelMerger(4); // ACN channel ordering: [1, 2, 3] => [-Y, Z, -X] // Y (from channel 1) this._splitter.connect(this._inY, 1); // Z (from channel 2) this._splitter.connect(this._inZ, 2); // X (from channel 3) this._splitter.connect(this._inX, 3); this._inY.gain.value = -1; this._inX.gain.value = -1; // Apply the rotation in the world space. // |Y| | m0 m3 m6 | | Y * m0 + Z * m3 + X * m6 | | Yr | // |Z| * | m1 m4 m7 | = | Y * m1 + Z * m4 + X * m7 | = | Zr | // |X| | m2 m5 m8 | | Y * m2 + Z * m5 + X * m8 | | Xr | this._inY.connect(this._m0); this._inY.connect(this._m1); this._inY.connect(this._m2); this._inZ.connect(this._m3); this._inZ.connect(this._m4); this._inZ.connect(this._m5); this._inX.connect(this._m6); this._inX.connect(this._m7); this._inX.connect(this._m8); this._m0.connect(this._outY); this._m1.connect(this._outZ); this._m2.connect(this._outX); this._m3.connect(this._outY); this._m4.connect(this._outZ); this._m5.connect(this._outX); this._m6.connect(this._outY); this._m7.connect(this._outZ); this._m8.connect(this._outX); // Transform 3: world space to audio space. // W -> W (to channel 0) this._splitter.connect(this._merger, 0, 0); // Y (to channel 1) this._outY.connect(this._merger, 0, 1); // Z (to channel 2) this._outZ.connect(this._merger, 0, 2); // X (to channel 3) this._outX.connect(this._merger, 0, 3); this._outY.gain.value = -1; this._outX.gain.value = -1; this.setRotationMatrix3(new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, -1])); // input/output proxy. this.input = this._splitter; this.output = this._merger; } dispose() { // ACN channel ordering: [1, 2, 3] => [-Y, Z, -X] // Y (from channel 1) this._splitter.disconnect(this._inY, 1); // Z (from channel 2) this._splitter.disconnect(this._inZ, 2); // X (from channel 3) this._splitter.disconnect(this._inX, 3); // Apply the rotation in the world space. // |Y| | m0 m3 m6 | | Y * m0 + Z * m3 + X * m6 | | Yr | // |Z| * | m1 m4 m7 | = | Y * m1 + Z * m4 + X * m7 | = | Zr | // |X| | m2 m5 m8 | | Y * m2 + Z * m5 + X * m8 | | Xr | this._inY.disconnect(this._m0); this._inY.disconnect(this._m1); this._inY.disconnect(this._m2); this._inZ.disconnect(this._m3); this._inZ.disconnect(this._m4); this._inZ.disconnect(this._m5); this._inX.disconnect(this._m6); this._inX.disconnect(this._m7); this._inX.disconnect(this._m8); this._m0.disconnect(this._outY); this._m1.disconnect(this._outZ); this._m2.disconnect(this._outX); this._m3.disconnect(this._outY); this._m4.disconnect(this._outZ); this._m5.disconnect(this._outX); this._m6.disconnect(this._outY); this._m7.disconnect(this._outZ); this._m8.disconnect(this._outX); // Transform 3: world space to audio space. // W -> W (to channel 0) this._splitter.disconnect(this._merger, 0, 0); // Y (to channel 1) this._outY.disconnect(this._merger, 0, 1); // Z (to channel 2) this._outZ.disconnect(this._merger, 0, 2); // X (to channel 3) this._outX.disconnect(this._merger, 0, 3); } /** * Updates the rotation matrix with 3x3 matrix. * @param {Number[]} rotationMatrix3 - A 3x3 rotation matrix. (column-major) */ setRotationMatrix3(rotationMatrix3) { this._m0.gain.value = rotationMatrix3[0]; this._m1.gain.value = rotationMatrix3[1]; this._m2.gain.value = rotationMatrix3[2]; this._m3.gain.value = rotationMatrix3[3]; this._m4.gain.value = rotationMatrix3[4]; this._m5.gain.value = rotationMatrix3[5]; this._m6.gain.value = rotationMatrix3[6]; this._m7.gain.value = rotationMatrix3[7]; this._m8.gain.value = rotationMatrix3[8]; } /** * Updates the rotation matrix with 4x4 matrix. * @param {Number[]} rotationMatrix4 - A 4x4 rotation matrix. (column-major) */ setRotationMatrix4(rotationMatrix4) { this._m0.gain.value = rotationMatrix4[0]; this._m1.gain.value = rotationMatrix4[1]; this._m2.gain.value = rotationMatrix4[2]; this._m3.gain.value = rotationMatrix4[4]; this._m4.gain.value = rotationMatrix4[5]; this._m5.gain.value = rotationMatrix4[6]; this._m6.gain.value = rotationMatrix4[8]; this._m7.gain.value = rotationMatrix4[9]; this._m8.gain.value = rotationMatrix4[10]; } /** * Returns the current 3x3 rotation matrix. * @return {Number[]} - A 3x3 rotation matrix. (column-major) */ getRotationMatrix3() { const rotationMatrix3 = new Float32Array(9); rotationMatrix3[0] = this._m0.gain.value; rotationMatrix3[1] = this._m1.gain.value; rotationMatrix3[2] = this._m2.gain.value; rotationMatrix3[3] = this._m3.gain.value; rotationMatrix3[4] = this._m4.gain.value; rotationMatrix3[5] = this._m5.gain.value; rotationMatrix3[6] = this._m6.gain.value; rotationMatrix3[7] = this._m7.gain.value; rotationMatrix3[8] = this._m8.gain.value; return rotationMatrix3; } /** * Returns the current 4x4 rotation matrix. * @return {Number[]} - A 4x4 rotation matrix. (column-major) */ getRotationMatrix4() { const rotationMatrix4 = new Float32Array(16); rotationMatrix4[0] = this._m0.gain.value; rotationMatrix4[1] = this._m1.gain.value; rotationMatrix4[2] = this._m2.gain.value; rotationMatrix4[4] = this._m3.gain.value; rotationMatrix4[5] = this._m4.gain.value; rotationMatrix4[6] = this._m5.gain.value; rotationMatrix4[8] = this._m6.gain.value; rotationMatrix4[9] = this._m7.gain.value; rotationMatrix4[10] = this._m8.gain.value; return rotationMatrix4; } }
JavaScript
class FOARouter { /** * Channel router for FOA stream. * @param {AudioContext} context - Associated AudioContext. * @param {Number[]} channelMap - Routing destination array. */ constructor(context, channelMap) { this._context = context; this._splitter = this._context.createChannelSplitter(4); this._merger = this._context.createChannelMerger(4); // input/output proxy. this.input = this._splitter; this.output = this._merger; this.setChannelMap(channelMap || ChannelMap.DEFAULT); } /** * Sets channel map. * @param {Number[]} channelMap - A new channel map for FOA stream. */ setChannelMap(channelMap) { if (!Array.isArray(channelMap)) { return; } this._channelMap = channelMap; this._splitter.disconnect(); this._splitter.connect(this._merger, 0, this._channelMap[0]); this._splitter.connect(this._merger, 1, this._channelMap[1]); this._splitter.connect(this._merger, 2, this._channelMap[2]); this._splitter.connect(this._merger, 3, this._channelMap[3]); } dipose() { this._splitter.disconnect(this._merger, 0, this._channelMap[0]); this._splitter.disconnect(this._merger, 1, this._channelMap[1]); this._splitter.disconnect(this._merger, 2, this._channelMap[2]); this._splitter.disconnect(this._merger, 3, this._channelMap[3]); } }
JavaScript
class FOARenderer { /** * Omnitone FOA renderer class. Uses the optimized convolution technique. * @param {AudioContext} context - Associated AudioContext. * @param {FOARendererConfig} config */ constructor(context, config) { if (!isAudioContext(context)) { throwError('FOARenderer: Invalid BaseAudioContext.'); } this._context = context; this._config = { channelMap: FOARouter.ChannelMap.DEFAULT, renderingMode: RenderingMode.AMBISONIC, }; if (config) { if (config.channelMap) { if (Array.isArray(config.channelMap) && config.channelMap.length === 4) { this._config.channelMap = config.channelMap; } else { throwError( 'FOARenderer: Invalid channel map. (got ' + config.channelMap + ')'); } } if (config.hrirPathList) { if (Array.isArray(config.hrirPathList) && config.hrirPathList.length === 2) { this._config.pathList = config.hrirPathList; } else { throwError( 'FOARenderer: Invalid HRIR URLs. It must be an array with ' + '2 URLs to HRIR files. (got ' + config.hrirPathList + ')'); } } if (config.renderingMode) { if (Object.values(RenderingMode).includes(config.renderingMode)) { this._config.renderingMode = config.renderingMode; } else { log( 'FOARenderer: Invalid rendering mode order. (got' + config.renderingMode + ') Fallbacks to the mode "ambisonic".'); } } } this._buildAudioGraph(); this._tempMatrix4 = new Float32Array(16); } /** * Builds the internal audio graph. * @private */ _buildAudioGraph() { this.input = this._context.createGain(); this.output = this._context.createGain(); this._bypass = this._context.createGain(); this._foaRouter = new FOARouter(this._context, this._config.channelMap); this._foaRotator = new FOARotator(this._context); this._foaConvolver = new FOAConvolver(this._context); this.input.connect(this._foaRouter.input); this.input.connect(this._bypass); this._foaRouter.output.connect(this._foaRotator.input); this._foaRotator.output.connect(this._foaConvolver.input); this._foaConvolver.output.connect(this.output); this.input.channelCount = 4; this.input.channelCountMode = 'explicit'; this.input.channelInterpretation = 'discrete'; } dipose() { if (mode === RenderingMode.BYPASS) { this._bypass.connect(this.output); } this.input.disconnect(this._foaRouter.input); this.input.disconnect(this._bypass); this._foaRouter.output.disconnect(this._foaRotator.input); this._foaRotator.output.disconnect(this._foaConvolver.input); this._foaConvolver.output.disconnect(this.output); this._foaConvolver.dispose(); this._foaRotator.dispose(); this._foaRouter.dipose(); } /** * Initializes and loads the resource for the renderer. * @return {Promise} */ async initialize() { log( 'FOARenderer: Initializing... (mode: ' + this._config.renderingMode + ')'); const bufferList = this._config.pathList ? new BufferList(this._context, this._config.pathList, { dataType: 'url' }) : new BufferList(this._context, OmnitoneFOAHrirBase64); try { const hrirBufferList = await bufferList.load(); this._foaConvolver.setHRIRBufferList(hrirBufferList); this.setRenderingMode(this._config.renderingMode); log('FOARenderer: HRIRs loaded successfully. Ready.'); } catch (exp) { const errorMessage = 'FOARenderer: HRIR loading/decoding failed. Reason: ' + exp.message; throwError(errorMessage); } } /** * Set the channel map. * @param {Number[]} channelMap - Custom channel routing for FOA stream. */ setChannelMap(channelMap) { if (channelMap.toString() !== this._config.channelMap.toString()) { log( 'Remapping channels ([' + this._config.channelMap.toString() + '] -> [' + channelMap.toString() + ']).'); this._config.channelMap = channelMap.slice(); this._foaRouter.setChannelMap(this._config.channelMap); } } /** * Updates the rotation matrix with 3x3 matrix. * @param {Number[]} rotationMatrix3 - A 3x3 rotation matrix. (column-major) */ setRotationMatrix3(rotationMatrix3) { this._foaRotator.setRotationMatrix3(rotationMatrix3); } /** * Updates the rotation matrix with 4x4 matrix. * @param {Number[]} rotationMatrix4 - A 4x4 rotation matrix. (column-major) */ setRotationMatrix4(rotationMatrix4) { this._foaRotator.setRotationMatrix4(rotationMatrix4); } /** * Set the rotation matrix from a Three.js camera object. Depreated in V1, and * this exists only for the backward compatiblity. Instead, use * |setRotatationMatrix4()| with Three.js |camera.worldMatrix.elements|. * @deprecated * @param {Object} cameraMatrix - Matrix4 from Three.js |camera.matrix|. */ setRotationMatrixFromCamera(cameraMatrix) { // Extract the inner array elements and inverse. (The actual view rotation is // the opposite of the camera movement.) invertMatrix4(this._tempMatrix4, cameraMatrix.elements); this._foaRotator.setRotationMatrix4(this._tempMatrix4); } /** * Set the rendering mode. * @param {RenderingMode} mode - Rendering mode. * - 'ambisonic': activates the ambisonic decoding/binaurl rendering. * - 'bypass': bypasses the input stream directly to the output. No ambisonic * decoding or encoding. * - 'off': all the processing off saving the CPU power. */ setRenderingMode(mode) { if (mode === this._config.renderingMode) { return; } switch (mode) { case RenderingMode.AMBISONIC: this._foaConvolver.enable(); this._bypass.disconnect(); break; case RenderingMode.BYPASS: this._foaConvolver.disable(); this._bypass.connect(this.output); break; case RenderingMode.OFF: this._foaConvolver.disable(); this._bypass.disconnect(); break; default: log( 'FOARenderer: Rendering mode "' + mode + '" is not ' + 'supported.'); return; } this._config.renderingMode = mode; log('FOARenderer: Rendering mode changed. (' + mode + ')'); } }
JavaScript
class HOAConvolver { /** * A convolver network for N-channel HOA stream. * @param {AudioContext} context - Associated AudioContext. * @param {Number} ambisonicOrder - Ambisonic order. (2 or 3) * @param {AudioBuffer[]} [hrirBufferList] - An ordered-list of stereo * AudioBuffers for convolution. (SOA: 5 AudioBuffers, TOA: 8 AudioBuffers) */ constructor(context, ambisonicOrder, hrirBufferList) { this._context = context; this._active = false; this._isBufferLoaded = false; // The number of channels K based on the ambisonic order N where K = (N+1)^2. this._ambisonicOrder = ambisonicOrder; this._numberOfChannels = (this._ambisonicOrder + 1) * (this._ambisonicOrder + 1); this._buildAudioGraph(); if (hrirBufferList) { this.setHRIRBufferList(hrirBufferList); } this.enable(); } /** * Build the internal audio graph. * For TOA convolution: * input -> splitter(16) -[0,1]-> merger(2) -> convolver(2) -> splitter(2) * -[2,3]-> merger(2) -> convolver(2) -> splitter(2) * -[4,5]-> ... (6 more, 8 branches total) * @private */ _buildAudioGraph() { const numberOfStereoChannels = Math.ceil(this._numberOfChannels / 2); this._inputSplitter = this._context.createChannelSplitter(this._numberOfChannels); this._stereoMergers = []; this._convolvers = []; this._stereoSplitters = []; this._positiveIndexSphericalHarmonics = this._context.createGain(); this._negativeIndexSphericalHarmonics = this._context.createGain(); this._inverter = this._context.createGain(); this._binauralMerger = this._context.createChannelMerger(2); this._outputGain = this._context.createGain(); for (let i = 0; i < numberOfStereoChannels; ++i) { this._stereoMergers[i] = this._context.createChannelMerger(2); this._convolvers[i] = this._context.createConvolver(); this._stereoSplitters[i] = this._context.createChannelSplitter(2); this._convolvers[i].normalize = false; } for (let l = 0; l <= this._ambisonicOrder; ++l) { for (let m = -l; m <= l; m++) { // We compute the ACN index (k) of ambisonics channel using the degree (l) // and index (m): k = l^2 + l + m const acnIndex = l * l + l + m; const stereoIndex = Math.floor(acnIndex / 2); // Split channels from input into array of stereo convolvers. // Then create a network of mergers that produces the stereo output. this._inputSplitter.connect( this._stereoMergers[stereoIndex], acnIndex, acnIndex % 2); this._stereoMergers[stereoIndex].connect(this._convolvers[stereoIndex]); this._convolvers[stereoIndex].connect(this._stereoSplitters[stereoIndex]); // Positive index (m >= 0) spherical harmonics are symmetrical around the // front axis, while negative index (m < 0) spherical harmonics are // anti-symmetrical around the front axis. We will exploit this symmetry // to reduce the number of convolutions required when rendering to a // symmetrical binaural renderer. if (m >= 0) { this._stereoSplitters[stereoIndex].connect( this._positiveIndexSphericalHarmonics, acnIndex % 2); } else { this._stereoSplitters[stereoIndex].connect( this._negativeIndexSphericalHarmonics, acnIndex % 2); } } } this._positiveIndexSphericalHarmonics.connect(this._binauralMerger, 0, 0); this._positiveIndexSphericalHarmonics.connect(this._binauralMerger, 0, 1); this._negativeIndexSphericalHarmonics.connect(this._binauralMerger, 0, 0); this._negativeIndexSphericalHarmonics.connect(this._inverter); this._inverter.connect(this._binauralMerger, 0, 1); // For asymmetric index. this._inverter.gain.value = -1; // Input/Output proxy. this.input = this._inputSplitter; this.output = this._outputGain; } dispose() { if (this._active) { this.disable(); } for (let l = 0; l <= this._ambisonicOrder; ++l) { for (let m = -l; m <= l; m++) { // We compute the ACN index (k) of ambisonics channel using the degree (l) // and index (m): k = l^2 + l + m const acnIndex = l * l + l + m; const stereoIndex = Math.floor(acnIndex / 2); // Split channels from input into array of stereo convolvers. // Then create a network of mergers that produces the stereo output. this._inputSplitter.disconnect( this._stereoMergers[stereoIndex], acnIndex, acnIndex % 2); this._stereoMergers[stereoIndex].disconnect(this._convolvers[stereoIndex]); this._convolvers[stereoIndex].disconnect(this._stereoSplitters[stereoIndex]); // Positive index (m >= 0) spherical harmonics are symmetrical around the // front axis, while negative index (m < 0) spherical harmonics are // anti-symmetrical around the front axis. We will exploit this symmetry // to reduce the number of convolutions required when rendering to a // symmetrical binaural renderer. if (m >= 0) { this._stereoSplitters[stereoIndex].disconnect( this._positiveIndexSphericalHarmonics, acnIndex % 2); } else { this._stereoSplitters[stereoIndex].disconnect( this._negativeIndexSphericalHarmonics, acnIndex % 2); } } } this._positiveIndexSphericalHarmonics.disconnect(this._binauralMerger, 0, 0); this._positiveIndexSphericalHarmonics.disconnect(this._binauralMerger, 0, 1); this._negativeIndexSphericalHarmonics.disconnect(this._binauralMerger, 0, 0); this._negativeIndexSphericalHarmonics.disconnect(this._inverter); this._inverter.disconnect(this._binauralMerger, 0, 1); } /** * Assigns N HRIR AudioBuffers to N convolvers: Note that we use 2 stereo * convolutions for 4-channel direct convolution. Using mono convolver or * 4-channel convolver is not viable because mono convolution wastefully * produces the stereo outputs, and the 4-ch convolver does cross-channel * convolution. (See Web Audio API spec) * @param {AudioBuffer[]} hrirBufferList - An array of stereo AudioBuffers for * convolvers. */ setHRIRBufferList(hrirBufferList) { // After these assignments, the channel data in the buffer is immutable in // FireFox. (i.e. neutered) So we should avoid re-assigning buffers, otherwise // an exception will be thrown. if (this._isBufferLoaded) { return; } for (let i = 0; i < hrirBufferList.length; ++i) { this._convolvers[i].buffer = hrirBufferList[i]; } this._isBufferLoaded = true; } /** * Enable HOAConvolver instance. The audio graph will be activated and pulled by * the WebAudio engine. (i.e. consume CPU cycle) */ enable() { this._binauralMerger.connect(this._outputGain); this._active = true; } /** * Disable HOAConvolver instance. The inner graph will be disconnected from the * audio destination, thus no CPU cycle will be consumed. */ disable() { this._binauralMerger.disconnect(); this._active = false; } }
JavaScript
class HOARotator { /** * Higher-order-ambisonic decoder based on gain node network. We expect * the order of the channels to conform to ACN ordering. Below are the helper * methods to compute SH rotation using recursion. The code uses maths described * in the following papers: * [1] R. Green, "Spherical Harmonic Lighting: The Gritty Details", GDC 2003, * http://www.research.scea.com/gdc2003/spherical-harmonic-lighting.pdf * [2] J. Ivanic and K. Ruedenberg, "Rotation Matrices for Real * Spherical Harmonics. Direct Determination by Recursion", J. Phys. * Chem., vol. 100, no. 15, pp. 6342-6347, 1996. * http://pubs.acs.org/doi/pdf/10.1021/jp953350u * [2b] Corrections to initial publication: * http://pubs.acs.org/doi/pdf/10.1021/jp9833350 * @param {AudioContext} context - Associated AudioContext. * @param {Number} ambisonicOrder - Ambisonic order. */ constructor(context, ambisonicOrder) { this._context = context; this._ambisonicOrder = ambisonicOrder; // We need to determine the number of channels K based on the ambisonic order // N where K = (N + 1)^2. const numberOfChannels = (ambisonicOrder + 1) * (ambisonicOrder + 1); this._splitter = this._context.createChannelSplitter(numberOfChannels); this._merger = this._context.createChannelMerger(numberOfChannels); // Create a set of per-order rotation matrices using gain nodes. /** @type {GainNode[][]} */ this._gainNodeMatrix = []; for (let i = 1; i <= ambisonicOrder; i++) { // Each ambisonic order requires a separate (2l + 1) x (2l + 1) rotation // matrix. We compute the offset value as the first channel index of the // current order where // k_last = l^2 + l + m, // and m = -l // k_last = l^2 const orderOffset = i * i; // Uses row-major indexing. const rows = (2 * i + 1); this._gainNodeMatrix[i - 1] = []; for (let j = 0; j < rows; j++) { const inputIndex = orderOffset + j; for (let k = 0; k < rows; k++) { const outputIndex = orderOffset + k; const matrixIndex = j * rows + k; this._gainNodeMatrix[i - 1][matrixIndex] = this._context.createGain(); this._splitter.connect( this._gainNodeMatrix[i - 1][matrixIndex], inputIndex); this._gainNodeMatrix[i - 1][matrixIndex].connect( this._merger, 0, outputIndex); } } } // W-channel is not involved in rotation, skip straight to ouput. this._splitter.connect(this._merger, 0, 0); // Default Identity matrix. this.setRotationMatrix3(new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, -1])); // Input/Output proxy. this.input = this._splitter; this.output = this._merger; } dispose() { for (let i = 1; i <= ambisonicOrder; i++) { // Each ambisonic order requires a separate (2l + 1) x (2l + 1) rotation // matrix. We compute the offset value as the first channel index of the // current order where // k_last = l^2 + l + m, // and m = -l // k_last = l^2 const orderOffset = i * i; // Uses row-major indexing. const rows = (2 * i + 1); for (let j = 0; j < rows; j++) { const inputIndex = orderOffset + j; for (let k = 0; k < rows; k++) { const outputIndex = orderOffset + k; const matrixIndex = j * rows + k; this._splitter.disconnect( this._gainNodeMatrix[i - 1][matrixIndex], inputIndex); this._gainNodeMatrix[i - 1][matrixIndex].disconnect( this._merger, 0, outputIndex); } } } // W-channel is not involved in rotation, skip straight to ouput. this._splitter.disconnect(this._merger, 0, 0); } /** * Updates the rotation matrix with 3x3 matrix. * @param {Number[]} rotationMatrix3 - A 3x3 rotation matrix. (column-major) */ setRotationMatrix3(rotationMatrix3) { this._gainNodeMatrix[0][0].gain.value = rotationMatrix3[0]; this._gainNodeMatrix[0][1].gain.value = rotationMatrix3[1]; this._gainNodeMatrix[0][2].gain.value = rotationMatrix3[2]; this._gainNodeMatrix[0][3].gain.value = rotationMatrix3[3]; this._gainNodeMatrix[0][4].gain.value = rotationMatrix3[4]; this._gainNodeMatrix[0][5].gain.value = rotationMatrix3[5]; this._gainNodeMatrix[0][6].gain.value = rotationMatrix3[6]; this._gainNodeMatrix[0][7].gain.value = rotationMatrix3[7]; this._gainNodeMatrix[0][8].gain.value = rotationMatrix3[8]; computeHOAMatrices(this._gainNodeMatrix); } /** * Updates the rotation matrix with 4x4 matrix. * @param {Number[]} rotationMatrix4 - A 4x4 rotation matrix. (column-major) */ setRotationMatrix4(rotationMatrix4) { this._gainNodeMatrix[0][0].gain.value = rotationMatrix4[0]; this._gainNodeMatrix[0][1].gain.value = rotationMatrix4[1]; this._gainNodeMatrix[0][2].gain.value = rotationMatrix4[2]; this._gainNodeMatrix[0][3].gain.value = rotationMatrix4[4]; this._gainNodeMatrix[0][4].gain.value = rotationMatrix4[5]; this._gainNodeMatrix[0][5].gain.value = rotationMatrix4[6]; this._gainNodeMatrix[0][6].gain.value = rotationMatrix4[8]; this._gainNodeMatrix[0][7].gain.value = rotationMatrix4[9]; this._gainNodeMatrix[0][8].gain.value = rotationMatrix4[10]; computeHOAMatrices(this._gainNodeMatrix); } /** * Returns the current 3x3 rotation matrix. * @return {Number[]} - A 3x3 rotation matrix. (column-major) */ getRotationMatrix3() { const rotationMatrix3 = new Float32Array(9); rotationMatrix3[0] = this._gainNodeMatrix[0][0].gain.value; rotationMatrix3[1] = this._gainNodeMatrix[0][1].gain.value; rotationMatrix3[2] = this._gainNodeMatrix[0][2].gain.value; rotationMatrix3[3] = this._gainNodeMatrix[0][3].gain.value; rotationMatrix3[4] = this._gainNodeMatrix[0][4].gain.value; rotationMatrix3[5] = this._gainNodeMatrix[0][5].gain.value; rotationMatrix3[6] = this._gainNodeMatrix[0][6].gain.value; rotationMatrix3[7] = this._gainNodeMatrix[0][7].gain.value; rotationMatrix3[8] = this._gainNodeMatrix[0][8].gain.value; return rotationMatrix3; } /** * Returns the current 4x4 rotation matrix. * @return {Number[]} - A 4x4 rotation matrix. (column-major) */ getRotationMatrix4() { const rotationMatrix4 = new Float32Array(16); rotationMatrix4[0] = this._gainNodeMatrix[0][0].gain.value; rotationMatrix4[1] = this._gainNodeMatrix[0][1].gain.value; rotationMatrix4[2] = this._gainNodeMatrix[0][2].gain.value; rotationMatrix4[4] = this._gainNodeMatrix[0][3].gain.value; rotationMatrix4[5] = this._gainNodeMatrix[0][4].gain.value; rotationMatrix4[6] = this._gainNodeMatrix[0][5].gain.value; rotationMatrix4[8] = this._gainNodeMatrix[0][6].gain.value; rotationMatrix4[9] = this._gainNodeMatrix[0][7].gain.value; rotationMatrix4[10] = this._gainNodeMatrix[0][8].gain.value; return rotationMatrix4; } /** * Get the current ambisonic order. * @return {Number} */ getAmbisonicOrder = function () { return this._ambisonicOrder; } }
JavaScript
class HOARenderer { /** * Omnitone HOA renderer class. Uses the optimized convolution technique. * @param {AudioContext} context - Associated AudioContext. * @param {Object} config * @param {Number} [config.ambisonicOrder=3] - Ambisonic order. * @param {Array} [config.hrirPathList] - A list of paths to HRIR files. It * overrides the internal HRIR list if given. * @param {RenderingMode} [config.renderingMode='ambisonic'] - Rendering mode. */ constructor(context, config) { if (!isAudioContext(context)) { throwError('HOARenderer: Invalid BaseAudioContext.'); } this._context = context; this._config = { ambisonicOrder: 3, renderingMode: RenderingMode$1.AMBISONIC, }; if (config && config.ambisonicOrder) { if (SupportedAmbisonicOrder.includes(config.ambisonicOrder)) { this._config.ambisonicOrder = config.ambisonicOrder; } else { log( 'HOARenderer: Invalid ambisonic order. (got ' + config.ambisonicOrder + ') Fallbacks to 3rd-order ambisonic.'); } } this._config.numberOfChannels = (this._config.ambisonicOrder + 1) * (this._config.ambisonicOrder + 1); this._config.numberOfStereoChannels = Math.ceil(this._config.numberOfChannels / 2); if (config && config.hrirPathList) { if (Array.isArray(config.hrirPathList) && config.hrirPathList.length === this._config.numberOfStereoChannels) { this._config.pathList = config.hrirPathList; } else { throwError( 'HOARenderer: Invalid HRIR URLs. It must be an array with ' + this._config.numberOfStereoChannels + ' URLs to HRIR files.' + ' (got ' + config.hrirPathList + ')'); } } if (config && config.renderingMode) { if (Object.values(RenderingMode$1).includes(config.renderingMode)) { this._config.renderingMode = config.renderingMode; } else { log( 'HOARenderer: Invalid rendering mode. (got ' + config.renderingMode + ') Fallbacks to "ambisonic".'); } } this._buildAudioGraph(); } /** * Builds the internal audio graph. * @private */ _buildAudioGraph() { this.input = this._context.createGain(); this.output = this._context.createGain(); this._bypass = this._context.createGain(); this._hoaRotator = new HOARotator(this._context, this._config.ambisonicOrder); this._hoaConvolver = new HOAConvolver(this._context, this._config.ambisonicOrder); this.input.connect(this._hoaRotator.input); this.input.connect(this._bypass); this._hoaRotator.output.connect(this._hoaConvolver.input); this._hoaConvolver.output.connect(this.output); this.input.channelCount = this._config.numberOfChannels; this.input.channelCountMode = 'explicit'; this.input.channelInterpretation = 'discrete'; } dispose() { if (mode === RenderingMode$1.BYPASS) { this._bypass.connect(this.output); } this.input.disconnect(this._hoaRotator.input); this.input.disconnect(this._bypass); this._hoaRotator.output.disconnect(this._hoaConvolver.input); this._hoaConvolver.output.disconnect(this.output); this._hoaRotator.dispose(); this._hoaConvolver.dispose(); } /** * Initializes and loads the resource for the renderer. * @return {Promise} */ async initialize() { log( 'HOARenderer: Initializing... (mode: ' + this._config.renderingMode + ', ambisonic order: ' + this._config.ambisonicOrder + ')'); let bufferList; if (this._config.pathList) { bufferList = new BufferList(this._context, this._config.pathList, { dataType: 'url' }); } else { bufferList = this._config.ambisonicOrder === 2 ? new BufferList(this._context, OmnitoneSOAHrirBase64) : new BufferList(this._context, OmnitoneTOAHrirBase64); } try { const hrirBufferList = await bufferList.load(); this._hoaConvolver.setHRIRBufferList(hrirBufferList); this.setRenderingMode(this._config.renderingMode); log('HOARenderer: HRIRs loaded successfully. Ready.'); } catch (exp) { const errorMessage = 'HOARenderer: HRIR loading/decoding failed. Reason: ' + exp.message; throwError(errorMessage); } } /** * Updates the rotation matrix with 3x3 matrix. * @param {Number[]} rotationMatrix3 - A 3x3 rotation matrix. (column-major) */ setRotationMatrix3(rotationMatrix3) { this._hoaRotator.setRotationMatrix3(rotationMatrix3); } /** * Updates the rotation matrix with 4x4 matrix. * @param {Number[]} rotationMatrix4 - A 4x4 rotation matrix. (column-major) */ setRotationMatrix4(rotationMatrix4) { this._hoaRotator.setRotationMatrix4(rotationMatrix4); } /** * Set the decoding mode. * @param {RenderingMode} mode - Decoding mode. * - 'ambisonic': activates the ambisonic decoding/binaurl rendering. * - 'bypass': bypasses the input stream directly to the output. No ambisonic * decoding or encoding. * - 'off': all the processing off saving the CPU power. */ setRenderingMode(mode) { if (mode === this._config.renderingMode) { return; } switch (mode) { case RenderingMode$1.AMBISONIC: this._hoaConvolver.enable(); this._bypass.disconnect(); break; case RenderingMode$1.BYPASS: this._hoaConvolver.disable(); this._bypass.connect(this.output); break; case RenderingMode$1.OFF: this._hoaConvolver.disable(); this._bypass.disconnect(); break; default: log( 'HOARenderer: Rendering mode "' + mode + '" is not ' + 'supported.'); return; } this._config.renderingMode = mode; log('HOARenderer: Rendering mode changed. (' + mode + ')'); } }
JavaScript
class Encoder { /** * Spatially encodes input using weighted spherical harmonics. * @param {AudioContext} context * Associated {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioContext AudioContext}. * @param {Object} options * @param {Number} options.ambisonicOrder * Desired ambisonic order. Defaults to * {@linkcode Utils.DEFAULT_AMBISONIC_ORDER DEFAULT_AMBISONIC_ORDER}. * @param {Number} options.azimuth * Azimuth (in degrees). Defaults to * {@linkcode Utils.DEFAULT_AZIMUTH DEFAULT_AZIMUTH}. * @param {Number} options.elevation * Elevation (in degrees). Defaults to * {@linkcode Utils.DEFAULT_ELEVATION DEFAULT_ELEVATION}. * @param {Number} options.sourceWidth * Source width (in degrees). Where 0 degrees is a point source and 360 degrees * is an omnidirectional source. Defaults to * {@linkcode Utils.DEFAULT_SOURCE_WIDTH DEFAULT_SOURCE_WIDTH}. */ constructor(context, options) { // Public variables. /** * Mono (1-channel) input {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} input * @memberof Encoder * @instance */ /** * Ambisonic (multichannel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} output * @memberof Encoder * @instance */ // Use defaults for undefined arguments. if (options == undefined) { options = {}; } if (options.ambisonicOrder == undefined) { options.ambisonicOrder = DEFAULT_AMBISONIC_ORDER; } if (options.azimuth == undefined) { options.azimuth = DEFAULT_AZIMUTH; } if (options.elevation == undefined) { options.elevation = DEFAULT_ELEVATION; } if (options.sourceWidth == undefined) { options.sourceWidth = DEFAULT_SOURCE_WIDTH; } this._context = context; // Create I/O nodes. this.input = context.createGain(); this._channelGain = []; this._merger = undefined; this.output = context.createGain(); // Set initial order, angle and source width. this.setAmbisonicOrder(options.ambisonicOrder); this._azimuth = options.azimuth; this._elevation = options.elevation; this.setSourceWidth(options.sourceWidth); } /** * Set the desired ambisonic order. * @param {Number} ambisonicOrder Desired ambisonic order. */ setAmbisonicOrder(ambisonicOrder) { this._ambisonicOrder = Encoder.validateAmbisonicOrder(ambisonicOrder); this.input.disconnect(); for (let i = 0; i < this._channelGain.length; i++) { this._channelGain[i].disconnect(); } if (this._merger != undefined) { this._merger.disconnect(); } delete this._channelGain; delete this._merger; // Create audio graph. let numChannels = (this._ambisonicOrder + 1) * (this._ambisonicOrder + 1); this._merger = this._context.createChannelMerger(numChannels); this._channelGain = new Array(numChannels); for (let i = 0; i < numChannels; i++) { this._channelGain[i] = this._context.createGain(); this.input.connect(this._channelGain[i]); this._channelGain[i].connect(this._merger, 0, i); } this._merger.connect(this.output); } dispose() { this._merger.disconnect(this.output); let numChannels = (this._ambisonicOrder + 1) * (this._ambisonicOrder + 1); for (let i = 0; i < numChannels; ++i) { this._channelGain[i].disconnect(this._merger, 0, i); this.input.disconnect(this._channelGain[i]); } } /** * Set the direction of the encoded source signal. * @param {Number} azimuth * Azimuth (in degrees). Defaults to * {@linkcode Utils.DEFAULT_AZIMUTH DEFAULT_AZIMUTH}. * @param {Number} elevation * Elevation (in degrees). Defaults to * {@linkcode Utils.DEFAULT_ELEVATION DEFAULT_ELEVATION}. */ setDirection(azimuth, elevation) { // Format input direction to nearest indices. if (azimuth == undefined || isNaN(azimuth)) { azimuth = DEFAULT_AZIMUTH; } if (elevation == undefined || isNaN(elevation)) { elevation = DEFAULT_ELEVATION; } // Store the formatted input (for updating source width). this._azimuth = azimuth; this._elevation = elevation; // Format direction for index lookups. azimuth = Math.round(azimuth % 360); if (azimuth < 0) { azimuth += 360; } elevation = Math.round(Math.min(90, Math.max(-90, elevation))) + 90; // Assign gains to each output. this._channelGain[0].gain.value = MAX_RE_WEIGHTS[this._spreadIndex][0]; for (let i = 1; i <= this._ambisonicOrder; i++) { let degreeWeight = MAX_RE_WEIGHTS[this._spreadIndex][i]; for (let j = -i; j <= i; j++) { let acnChannel = (i * i) + i + j; let elevationIndex = i * (i + 1) / 2 + Math.abs(j) - 1; let val = SPHERICAL_HARMONICS[1][elevation][elevationIndex]; if (j != 0) { let azimuthIndex = SPHERICAL_HARMONICS_MAX_ORDER + j - 1; if (j < 0) { azimuthIndex = SPHERICAL_HARMONICS_MAX_ORDER + j; } val *= SPHERICAL_HARMONICS[0][azimuth][azimuthIndex]; } this._channelGain[acnChannel].gain.value = val * degreeWeight; } } } /** * Set the source width (in degrees). Where 0 degrees is a point source and 360 * degrees is an omnidirectional source. * @param {Number} sourceWidth (in degrees). */ setSourceWidth(sourceWidth) { // The MAX_RE_WEIGHTS is a 360 x (Tables.SPHERICAL_HARMONICS_MAX_ORDER+1) // size table. this._spreadIndex = Math.min(359, Math.max(0, Math.round(sourceWidth))); this.setDirection(this._azimuth, this._elevation); } }
JavaScript
class Listener { /** * Listener model to spatialize sources in an environment. * @param {AudioContext} context * Associated {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioContext AudioContext}. * @param {Object} options * @param {Number} options.ambisonicOrder * Desired ambisonic order. Defaults to * {@linkcode Utils.DEFAULT_AMBISONIC_ORDER DEFAULT_AMBISONIC_ORDER}. * @param {Float32Array} options.position * Initial position (in meters), where origin is the center of * the room. Defaults to * {@linkcode Utils.DEFAULT_POSITION DEFAULT_POSITION}. * @param {Float32Array} options.forward * The listener's initial forward vector. Defaults to * {@linkcode Utils.DEFAULT_FORWARD DEFAULT_FORWARD}. * @param {Float32Array} options.up * The listener's initial up vector. Defaults to * {@linkcode Utils.DEFAULT_UP DEFAULT_UP}. */ constructor(context, options) { // Public variables. /** * Position (in meters). * @member {Float32Array} position * @memberof Listener * @instance */ /** * Ambisonic (multichannel) input {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} input * @memberof Listener * @instance */ /** * Binaurally-rendered stereo (2-channel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} output * @memberof Listener * @instance */ /** * Ambisonic (multichannel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} ambisonicOutput * @memberof Listener * @instance */ // Use defaults for undefined arguments. if (options == undefined) { options = {}; } if (options.ambisonicOrder == undefined) { options.ambisonicOrder = DEFAULT_AMBISONIC_ORDER; } if (options.position == undefined) { options.position = DEFAULT_POSITION.slice(); } if (options.forward == undefined) { options.forward = DEFAULT_FORWARD.slice(); } if (options.up == undefined) { options.up = DEFAULT_UP.slice(); } // Member variables. this.position = new Float32Array(3); this._tempMatrix3 = new Float32Array(9); // Select the appropriate HRIR filters using 2-channel chunks since // multichannel audio is not yet supported by a majority of browsers. this._ambisonicOrder = Encoder.validateAmbisonicOrder(options.ambisonicOrder); // Create audio nodes. this._context = context; if (this._ambisonicOrder == 1) { this._renderer = createFOARenderer(context, {}); } else if (this._ambisonicOrder > 1) { this._renderer = createHOARenderer(context, { ambisonicOrder: this._ambisonicOrder, }); } // These nodes are created in order to safely asynchronously load Omnitone // while the rest of the scene is being created. this.input = context.createGain(); this.output = context.createGain(); this.ambisonicOutput = context.createGain(); // Initialize Omnitone (async) and connect to audio graph when complete. this._renderer.initialize().then(() => { // Connect pre-rotated soundfield to renderer. this.input.connect(this._renderer.input); // Connect rotated soundfield to ambisonic output. if (this._ambisonicOrder > 1) { this._renderer._hoaRotator.output.connect(this.ambisonicOutput); } else { this._renderer._foaRotator.output.connect(this.ambisonicOutput); } // Connect binaurally-rendered soundfield to binaural output. this._renderer.output.connect(this.output); }); // Set orientation and update rotation matrix accordingly. this.setOrientation( options.forward[0], options.forward[1], options.forward[2], options.up[0], options.up[1], options.up[2]); } dispose() { // Connect pre-rotated soundfield to renderer. this.input.disconnect(this._renderer.input); // Connect rotated soundfield to ambisonic output. if (this._ambisonicOrder > 1) { this._renderer._hoaRotator.output.disconnect(this.ambisonicOutput); } else { this._renderer._foaRotator.output.disconnect(this.ambisonicOutput); } // Connect binaurally-rendered soundfield to binaural output. this._renderer.output.disconnect(this.output); this._renderer.dispose(); } /** * Set the source's orientation using forward and up vectors. * @param {Number} forwardX * @param {Number} forwardY * @param {Number} forwardZ * @param {Number} upX * @param {Number} upY * @param {Number} upZ */ setOrientation(forwardX, forwardY, forwardZ, upX, upY, upZ) { let right = crossProduct([forwardX, forwardY, forwardZ], [upX, upY, upZ]); this._tempMatrix3[0] = right[0]; this._tempMatrix3[1] = right[1]; this._tempMatrix3[2] = right[2]; this._tempMatrix3[3] = upX; this._tempMatrix3[4] = upY; this._tempMatrix3[5] = upZ; this._tempMatrix3[6] = forwardX; this._tempMatrix3[7] = forwardY; this._tempMatrix3[8] = forwardZ; this._renderer.setRotationMatrix3(this._tempMatrix3); } /** * Set the listener's position and orientation using a Three.js Matrix4 object. * @param {Object} matrix4 * The Three.js Matrix4 object representing the listener's world transform. */ setFromMatrix(matrix4) { // Update ambisonic rotation matrix internally. this._renderer.setRotationMatrix4(matrix4.elements); // Extract position from matrix. this.position[0] = matrix4.elements[12]; this.position[1] = matrix4.elements[13]; this.position[2] = matrix4.elements[14]; } }
JavaScript
class Attenuation { /** * Distance-based attenuation filter. * @param {AudioContext} context * Associated {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioContext AudioContext}. * @param {Object} options * @param {Number} options.minDistance * Min. distance (in meters). Defaults to * {@linkcode Utils.DEFAULT_MIN_DISTANCE DEFAULT_MIN_DISTANCE}. * @param {Number} options.maxDistance * Max. distance (in meters). Defaults to * {@linkcode Utils.DEFAULT_MAX_DISTANCE DEFAULT_MAX_DISTANCE}. * @param {string} options.rolloff * Rolloff model to use, chosen from options in * {@linkcode Utils.ATTENUATION_ROLLOFFS ATTENUATION_ROLLOFFS}. Defaults to * {@linkcode Utils.DEFAULT_ATTENUATION_ROLLOFF DEFAULT_ATTENUATION_ROLLOFF}. */ constructor(context, options) { // Public variables. /** * Min. distance (in meters). * @member {Number} minDistance * @memberof Attenuation * @instance */ /** * Max. distance (in meters). * @member {Number} maxDistance * @memberof Attenuation * @instance */ /** * Mono (1-channel) input {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} input * @memberof Attenuation * @instance */ /** * Mono (1-channel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} output * @memberof Attenuation * @instance */ // Use defaults for undefined arguments. if (options == undefined) { options = {}; } if (options.minDistance == undefined) { options.minDistance = DEFAULT_MIN_DISTANCE; } if (options.maxDistance == undefined) { options.maxDistance = DEFAULT_MAX_DISTANCE; } if (options.rolloff == undefined) { options.rolloff = DEFAULT_ATTENUATION_ROLLOFF; } // Assign values. this.minDistance = options.minDistance; this.maxDistance = options.maxDistance; this.setRolloff(options.rolloff); // Create node. this._gainNode = context.createGain(); // Initialize distance to max distance. this.setDistance(options.maxDistance); // Input/Output proxy. this.input = this._gainNode; this.output = this._gainNode; } /** * Set distance from the listener. * @param {Number} distance Distance (in meters). */ setDistance(distance) { let gain = 1; if (this._rolloff == 'logarithmic') { if (distance > this.maxDistance) { gain = 0; } else if (distance > this.minDistance) { let range = this.maxDistance - this.minDistance; if (range > EPSILON_FLOAT) { // Compute the distance attenuation value by the logarithmic curve // "1 / (d + 1)" with an offset of |minDistance|. let relativeDistance = distance - this.minDistance; let attenuation = 1 / (relativeDistance + 1); let attenuationMax = 1 / (range + 1); gain = (attenuation - attenuationMax) / (1 - attenuationMax); } } } else if (this._rolloff == 'linear') { if (distance > this.maxDistance) { gain = 0; } else if (distance > this.minDistance) { let range = this.maxDistance - this.minDistance; if (range > EPSILON_FLOAT) { gain = (this.maxDistance - distance) / range; } } } this._gainNode.gain.value = gain; } /** * Set rolloff. * @param {string} rolloff * Rolloff model to use, chosen from options in * {@linkcode Utils.ATTENUATION_ROLLOFFS ATTENUATION_ROLLOFFS}. */ setRolloff(rolloff) { let isValidModel = ~ATTENUATION_ROLLOFFS.indexOf(rolloff); if (rolloff == undefined || !isValidModel) { if (!isValidModel) { log$1('Invalid rolloff model (\"' + rolloff + '\"). Using default: \"' + DEFAULT_ATTENUATION_ROLLOFF + '\".'); } rolloff = DEFAULT_ATTENUATION_ROLLOFF; } else { rolloff = rolloff.toString().toLowerCase(); } this._rolloff = rolloff; } }
JavaScript
class Source { /** * Source model to spatialize an audio buffer. * @param {ResonanceAudio} scene Associated ResonanceAudio instance. * @param {Source~SourceOptions} options * Options for constructing a new Source. */ constructor(scene, options) { // Public variables. /** * Mono (1-channel) input {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} input * @memberof Source * @instance */ /** * */ // Use defaults for undefined arguments. if (options == undefined) { options = {}; } if (options.position == undefined) { options.position = DEFAULT_POSITION.slice(); } if (options.forward == undefined) { options.forward = DEFAULT_FORWARD.slice(); } if (options.up == undefined) { options.up = DEFAULT_UP.slice(); } if (options.minDistance == undefined) { options.minDistance = DEFAULT_MIN_DISTANCE; } if (options.maxDistance == undefined) { options.maxDistance = DEFAULT_MAX_DISTANCE; } if (options.rolloff == undefined) { options.rolloff = DEFAULT_ATTENUATION_ROLLOFF; } if (options.gain == undefined) { options.gain = DEFAULT_SOURCE_GAIN; } if (options.alpha == undefined) { options.alpha = DEFAULT_DIRECTIVITY_ALPHA; } if (options.sharpness == undefined) { options.sharpness = DEFAULT_DIRECTIVITY_SHARPNESS; } if (options.sourceWidth == undefined) { options.sourceWidth = DEFAULT_SOURCE_WIDTH; } // Member variables. this._scene = scene; this._position = options.position; this._forward = options.forward; this._up = options.up; this._dx = new Float32Array(3); this._right = crossProduct(this._forward, this._up); // Create audio nodes. let context = scene._context; this.input = context.createGain(); this._directivity = new Directivity(context, { alpha: options.alpha, sharpness: options.sharpness, }); this._toEarly = context.createGain(); this._toLate = context.createGain(); this._attenuation = new Attenuation(context, { minDistance: options.minDistance, maxDistance: options.maxDistance, rolloff: options.rolloff, }); this._encoder = new Encoder(context, { ambisonicOrder: scene._ambisonicOrder, sourceWidth: options.sourceWidth, }); // Connect nodes. this.input.connect(this._toLate); this._toLate.connect(scene._room.late.input); this.input.connect(this._attenuation.input); this._attenuation.output.connect(this._toEarly); this._toEarly.connect(scene._room.early.input); this._attenuation.output.connect(this._directivity.input); this._directivity.output.connect(this._encoder.input); this._encoder.output.connect(scene._listener.input); // Assign initial conditions. this.setPosition( options.position[0], options.position[1], options.position[2]); this.input.gain.value = options.gain; } dispose() { this._encoder.output.disconnect(this._scene._listener.input); this._directivity.output.disconnect(this._encoder.input); this._attenuation.output.disconnect(this._directivity.input); this._toEarly.disconnect(this._scene._room.early.input); this._attenuation.output.disconnect(this._toEarly); this.input.disconnect(this._attenuation.input); this._toLate.disconnect(this._scene._room.late.input); this.input.disconnect(this._toLate); this._encoder.dispose(); } /** * Set source's position (in meters), where origin is the center of * the room. * @param {Number} x * @param {Number} y * @param {Number} z */ setPosition(x, y, z) { // Assign new position. this._position[0] = x; this._position[1] = y; this._position[2] = z; // Handle far-field effect. let distance = this._scene._room.getDistanceOutsideRoom( this._position[0], this._position[1], this._position[2]); let gain = _computeDistanceOutsideRoom(distance); this._toLate.gain.value = gain; this._toEarly.gain.value = gain; this._update(); } // Update the source when changing the listener's position. _update() { // Compute distance to listener. for (let i = 0; i < 3; i++) { this._dx[i] = this._position[i] - this._scene._listener.position[i]; } let distance = Math.sqrt(this._dx[0] * this._dx[0] + this._dx[1] * this._dx[1] + this._dx[2] * this._dx[2]); if (distance > 0) { // Normalize direction vector. this._dx[0] /= distance; this._dx[1] /= distance; this._dx[2] /= distance; } // Compuete angle of direction vector. let azimuth = Math.atan2(-this._dx[0], this._dx[2]) * RADIANS_TO_DEGREES; let elevation = Math.atan2(this._dx[1], Math.sqrt(this._dx[0] * this._dx[0] + this._dx[2] * this._dx[2])) * RADIANS_TO_DEGREES; // Set distance/directivity/direction values. this._attenuation.setDistance(distance); this._directivity.computeAngle(this._forward, this._dx); this._encoder.setDirection(azimuth, elevation); } /** * Set source's rolloff. * @param {string} rolloff * Rolloff model to use, chosen from options in * {@linkcode Utils.ATTENUATION_ROLLOFFS ATTENUATION_ROLLOFFS}. */ setRolloff(rolloff) { this._attenuation.setRolloff(rolloff); } /** * Set source's minimum distance (in meters). * @param {Number} minDistance */ setMinDistance(minDistance) { this._attenuation.minDistance = minDistance; } /** * Set source's maximum distance (in meters). * @param {Number} maxDistance */ setMaxDistance(maxDistance) { this._attenuation.maxDistance = maxDistance; } /** * Set source's gain (linear). * @param {Number} gain */ setGain(gain) { this.input.gain.value = gain; } /** * Set the source's orientation using forward and up vectors. * @param {Number} forwardX * @param {Number} forwardY * @param {Number} forwardZ * @param {Number} upX * @param {Number} upY * @param {Number} upZ */ setOrientation(forwardX, forwardY, forwardZ, upX, upY, upZ) { this._forward[0] = forwardX; this._forward[1] = forwardY; this._forward[2] = forwardZ; this._up[0] = upX; this._up[1] = upY; this._up[2] = upZ; this._right = crossProduct(this._forward, this._up); } // TODO(bitllama): Make sure this works with Three.js as intended. /** * Set source's position and orientation using a * Three.js modelViewMatrix object. * @param {Float32Array} matrix4 * The Matrix4 representing the object position and rotation in world space. */ setFromMatrix(matrix4) { this._right[0] = matrix4.elements[0]; this._right[1] = matrix4.elements[1]; this._right[2] = matrix4.elements[2]; this._up[0] = matrix4.elements[4]; this._up[1] = matrix4.elements[5]; this._up[2] = matrix4.elements[6]; this._forward[0] = matrix4.elements[8]; this._forward[1] = matrix4.elements[9]; this._forward[2] = matrix4.elements[10]; // Normalize to remove scaling. this._right = normalizeVector(this._right); this._up = normalizeVector(this._up); this._forward = normalizeVector(this._forward); // Update position. this.setPosition( matrix4.elements[12], matrix4.elements[13], matrix4.elements[14]); } /** * Set the source width (in degrees). Where 0 degrees is a point source and 360 * degrees is an omnidirectional source. * @param {Number} sourceWidth (in degrees). */ setSourceWidth(sourceWidth) { this._encoder.setSourceWidth(sourceWidth); this.setPosition(this._position[0], this._position[1], this._position[2]); } /** * Set source's directivity pattern (defined by alpha), where 0 is an * omnidirectional pattern, 1 is a bidirectional pattern, 0.5 is a cardiod * pattern. The sharpness of the pattern is increased exponentially. * @param {Number} alpha * Determines directivity pattern (0 to 1). * @param {Number} sharpness * Determines the sharpness of the directivity pattern (1 to Inf). */ setDirectivityPattern(alpha, sharpness) { this._directivity.setPattern(alpha, sharpness); this.setPosition(this._position[0], this._position[1], this._position[2]); } }
JavaScript
class LateReflections { /** * Late-reflections reverberation filter for Ambisonic content. * @param {AudioContext} context * Associated {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioContext AudioContext}. * @param {Object} options * @param {Array} options.durations * Multiband RT60 durations (in seconds) for each frequency band, listed as * {@linkcode Utils.DEFAULT_REVERB_FREQUENCY_BANDS * FREQUDEFAULT_REVERB_FREQUENCY_BANDSENCY_BANDS}. Defaults to * {@linkcode Utils.DEFAULT_REVERB_DURATIONS DEFAULT_REVERB_DURATIONS}. * @param {Number} options.predelay Pre-delay (in milliseconds). Defaults to * {@linkcode Utils.DEFAULT_REVERB_PREDELAY DEFAULT_REVERB_PREDELAY}. * @param {Number} options.gain Output gain (linear). Defaults to * {@linkcode Utils.DEFAULT_REVERB_GAIN DEFAULT_REVERB_GAIN}. * @param {Number} options.bandwidth Bandwidth (in octaves) for each frequency * band. Defaults to * {@linkcode Utils.DEFAULT_REVERB_BANDWIDTH DEFAULT_REVERB_BANDWIDTH}. * @param {Number} options.tailonset Length (in milliseconds) of impulse * response to apply a half-Hann window. Defaults to * {@linkcode Utils.DEFAULT_REVERB_TAIL_ONSET DEFAULT_REVERB_TAIL_ONSET}. */ constructor(context, options) { // Public variables. /** * Mono (1-channel) input {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} input * @memberof LateReflections * @instance */ /** * Mono (1-channel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} output * @memberof LateReflections * @instance */ // Use defaults for undefined arguments. if (options == undefined) { options = {}; } if (options.durations == undefined) { options.durations = DEFAULT_REVERB_DURATIONS.slice(); } if (options.predelay == undefined) { options.predelay = DEFAULT_REVERB_PREDELAY; } if (options.gain == undefined) { options.gain = DEFAULT_REVERB_GAIN; } if (options.bandwidth == undefined) { options.bandwidth = DEFAULT_REVERB_BANDWIDTH; } if (options.tailonset == undefined) { options.tailonset = DEFAULT_REVERB_TAIL_ONSET; } // Assign pre-computed variables. let delaySecs = options.predelay / 1000; this._bandwidthCoeff = options.bandwidth * LOG2_DIV2; this._tailonsetSamples = options.tailonset / 1000; // Create nodes. this._context = context; this.input = context.createGain(); this._predelay = context.createDelay(delaySecs); this._convolver = context.createConvolver(); this.output = context.createGain(); // Set reverb attenuation. this.output.gain.value = options.gain; // Disable normalization. this._convolver.normalize = false; // Connect nodes. this.input.connect(this._predelay); this._predelay.connect(this._convolver); this._convolver.connect(this.output); // Compute IR using RT60 values. this.setDurations(options.durations); } dispose() { this.input.disconnect(this._predelay); this._predelay.disconnect(this._convolver); this._convolver.disconnect(this.output); } /** * Re-compute a new impulse response by providing Multiband RT60 durations. * @param {Array} durations * Multiband RT60 durations (in seconds) for each frequency band, listed as * {@linkcode Utils.DEFAULT_REVERB_FREQUENCY_BANDS * DEFAULT_REVERB_FREQUENCY_BANDS}. */ setDurations(durations) { if (durations.length !== NUMBER_REVERB_FREQUENCY_BANDS) { log$1('Warning: invalid number of RT60 values provided to reverb.'); return; } // Compute impulse response. let durationsSamples = new Float32Array(NUMBER_REVERB_FREQUENCY_BANDS); let sampleRate = this._context.sampleRate; for (let i = 0; i < durations.length; i++) { // Clamp within suitable range. durations[i] = Math.max(0, Math.min(DEFAULT_REVERB_MAX_DURATION, durations[i])); // Convert seconds to samples. durationsSamples[i] = Math.round(durations[i] * sampleRate * DEFAULT_REVERB_DURATION_MULTIPLIER); } // Determine max RT60 length in samples. let durationsSamplesMax = 0; for (let i = 0; i < durationsSamples.length; i++) { if (durationsSamples[i] > durationsSamplesMax) { durationsSamplesMax = durationsSamples[i]; } } // Skip this step if there is no reverberation to compute. if (durationsSamplesMax < 1) { durationsSamplesMax = 1; } // Create impulse response buffer. let buffer = this._context.createBuffer(1, durationsSamplesMax, sampleRate); let bufferData = buffer.getChannelData(0); // Create noise signal (computed once, referenced in each band's routine). let noiseSignal = new Float32Array(durationsSamplesMax); for (let i = 0; i < durationsSamplesMax; i++) { noiseSignal[i] = Math.random() * 2 - 1; } // Compute the decay rate per-band and filter the decaying noise signal. for (let i = 0; i < NUMBER_REVERB_FREQUENCY_BANDS; i++) { // Compute decay rate. let decayRate = -LOG1000 / durationsSamples[i]; // Construct a standard one-zero, two-pole bandpass filter: // H(z) = (b0 * z^0 + b1 * z^-1 + b2 * z^-2) / (1 + a1 * z^-1 + a2 * z^-2) let omega = TWO_PI * DEFAULT_REVERB_FREQUENCY_BANDS[i] / sampleRate; let sinOmega = Math.sin(omega); let alpha = sinOmega * Math.sinh(this._bandwidthCoeff * omega / sinOmega); let a0CoeffReciprocal = 1 / (1 + alpha); let b0Coeff = alpha * a0CoeffReciprocal; let a1Coeff = -2 * Math.cos(omega) * a0CoeffReciprocal; let a2Coeff = (1 - alpha) * a0CoeffReciprocal; // We optimize since b2 = -b0, b1 = 0. // Update equation for two-pole bandpass filter: // u[n] = x[n] - a1 * x[n-1] - a2 * x[n-2] // y[n] = b0 * (u[n] - u[n-2]) let um1 = 0; let um2 = 0; for (let j = 0; j < durationsSamples[i]; j++) { // Exponentially-decaying white noise. let x = noiseSignal[j] * Math.exp(decayRate * j); // Filter signal with bandpass filter and add to output. let u = x - a1Coeff * um1 - a2Coeff * um2; bufferData[j] += b0Coeff * (u - um2); // Update coefficients. um2 = um1; um1 = u; } } // Create and apply half of a Hann window to the beginning of the // impulse response. let halfHannLength = Math.round(this._tailonsetSamples); for (let i = 0; i < Math.min(bufferData.length, halfHannLength); i++) { let halfHann = 0.5 * (1 - Math.cos(TWO_PI * i / (2 * halfHannLength - 1))); bufferData[i] *= halfHann; } this._convolver.buffer = buffer; } }
JavaScript
class EarlyReflections { /** * Ray-tracing-based early reflections model. * @param {AudioContext} context * Associated {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioContext AudioContext}. * @param {Object} options * @param {Utils~RoomDimensions} options.dimensions * Room dimensions (in meters). Defaults to * {@linkcode Utils.DEFAULT_ROOM_DIMENSIONS DEFAULT_ROOM_DIMENSIONS}. * @param {Object} options.coefficients * Frequency-independent reflection coeffs per wall. Defaults to * {@linkcode Utils.DEFAULT_REFLECTION_COEFFICIENTS * DEFAULT_REFLECTION_COEFFICIENTS}. * @param {Number} options.speedOfSound * (in meters / second). Defaults to {@linkcode Utils.DEFAULT_SPEED_OF_SOUND * DEFAULT_SPEED_OF_SOUND}. * @param {Float32Array} options.listenerPosition * (in meters). Defaults to * {@linkcode Utils.DEFAULT_POSITION DEFAULT_POSITION}. */ constructor(context, options) { // Public variables. /** * The room's speed of sound (in meters/second). * @member {Number} speedOfSound * @memberof EarlyReflections * @instance */ /** * Mono (1-channel) input {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} input * @memberof EarlyReflections * @instance */ /** * First-order ambisonic (4-channel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} output * @memberof EarlyReflections * @instance */ // Use defaults for undefined arguments. if (options == undefined) { options = {}; } if (options.speedOfSound == undefined) { options.speedOfSound = DEFAULT_SPEED_OF_SOUND; } if (options.listenerPosition == undefined) { options.listenerPosition = DEFAULT_POSITION.slice(); } if (options.coefficients == undefined) { options.coefficients = {}; Object.assign(options.coefficients, DEFAULT_REFLECTION_COEFFICIENTS); } // Assign room's speed of sound. this.speedOfSound = options.speedOfSound; // Create nodes. this.input = context.createGain(); this.output = context.createGain(); this._lowpass = context.createBiquadFilter(); this._delays = {}; this._gains = {}; // gainPerWall = (ReflectionCoeff / Attenuation) this._inverters = {}; // 3 of these are needed for right/back/down walls. this._merger = context.createChannelMerger(4); // First-order encoding only. // Connect audio graph for each wall reflection. for (let property in DEFAULT_REFLECTION_COEFFICIENTS) { if (DEFAULT_REFLECTION_COEFFICIENTS .hasOwnProperty(property)) { this._delays[property] = context.createDelay(DEFAULT_REFLECTION_MAX_DURATION); this._gains[property] = context.createGain(); } } this._inverters.right = context.createGain(); this._inverters.down = context.createGain(); this._inverters.back = context.createGain(); // Initialize lowpass filter. this._lowpass.type = 'lowpass'; this._lowpass.frequency.value = DEFAULT_REFLECTION_CUTOFF_FREQUENCY; this._lowpass.Q.value = 0; // Initialize encoder directions, set delay times and gains to 0. for (let property in DEFAULT_REFLECTION_COEFFICIENTS) { if (DEFAULT_REFLECTION_COEFFICIENTS .hasOwnProperty(property)) { this._delays[property].delayTime.value = 0; this._gains[property].gain.value = 0; } } // Initialize inverters for opposite walls ('right', 'down', 'back' only). this._inverters.right.gain.value = -1; this._inverters.down.gain.value = -1; this._inverters.back.gain.value = -1; // Connect nodes. this.input.connect(this._lowpass); for (let property in DEFAULT_REFLECTION_COEFFICIENTS) { if (DEFAULT_REFLECTION_COEFFICIENTS .hasOwnProperty(property)) { this._lowpass.connect(this._delays[property]); this._delays[property].connect(this._gains[property]); this._gains[property].connect(this._merger, 0, 0); } } // Connect gains to ambisonic channel output. // Left: [1 1 0 0] // Right: [1 -1 0 0] // Up: [1 0 1 0] // Down: [1 0 -1 0] // Front: [1 0 0 1] // Back: [1 0 0 -1] this._gains.left.connect(this._merger, 0, 1); this._gains.right.connect(this._inverters.right); this._inverters.right.connect(this._merger, 0, 1); this._gains.up.connect(this._merger, 0, 2); this._gains.down.connect(this._inverters.down); this._inverters.down.connect(this._merger, 0, 2); this._gains.front.connect(this._merger, 0, 3); this._gains.back.connect(this._inverters.back); this._inverters.back.connect(this._merger, 0, 3); this._merger.connect(this.output); // Initialize. this._listenerPosition = options.listenerPosition; this.setRoomProperties(options.dimensions, options.coefficients); } dipose() { // Connect nodes. this.input.disconnect(this._lowpass); for (let property in DEFAULT_REFLECTION_COEFFICIENTS) { if (DEFAULT_REFLECTION_COEFFICIENTS .hasOwnProperty(property)) { this._lowpass.disconnect(this._delays[property]); this._delays[property].disconnect(this._gains[property]); this._gains[property].disconnect(this._merger, 0, 0); } } // Connect gains to ambisonic channel output. // Left: [1 1 0 0] // Right: [1 -1 0 0] // Up: [1 0 1 0] // Down: [1 0 -1 0] // Front: [1 0 0 1] // Back: [1 0 0 -1] this._gains.left.disconnect(this._merger, 0, 1); this._gains.right.disconnect(this._inverters.right); this._inverters.right.disconnect(this._merger, 0, 1); this._gains.up.disconnect(this._merger, 0, 2); this._gains.down.disconnect(this._inverters.down); this._inverters.down.disconnect(this._merger, 0, 2); this._gains.front.disconnect(this._merger, 0, 3); this._gains.back.disconnect(this._inverters.back); this._inverters.back.disconnect(this._merger, 0, 3); this._merger.disconnect(this.output); } /** * Set the listener's position (in meters), * where [0,0,0] is the center of the room. * @param {Number} x * @param {Number} y * @param {Number} z */ setListenerPosition(x, y, z) { // Assign listener position. this._listenerPosition = [x, y, z]; // Determine distances to each wall. let distances = { left: DEFAULT_REFLECTION_MULTIPLIER * Math.max(0, this._halfDimensions.width + x) + DEFAULT_REFLECTION_MIN_DISTANCE, right: DEFAULT_REFLECTION_MULTIPLIER * Math.max(0, this._halfDimensions.width - x) + DEFAULT_REFLECTION_MIN_DISTANCE, front: DEFAULT_REFLECTION_MULTIPLIER * Math.max(0, this._halfDimensions.depth + z) + DEFAULT_REFLECTION_MIN_DISTANCE, back: DEFAULT_REFLECTION_MULTIPLIER * Math.max(0, this._halfDimensions.depth - z) + DEFAULT_REFLECTION_MIN_DISTANCE, down: DEFAULT_REFLECTION_MULTIPLIER * Math.max(0, this._halfDimensions.height + y) + DEFAULT_REFLECTION_MIN_DISTANCE, up: DEFAULT_REFLECTION_MULTIPLIER * Math.max(0, this._halfDimensions.height - y) + DEFAULT_REFLECTION_MIN_DISTANCE, }; // Assign delay & attenuation values using distances. for (let property in DEFAULT_REFLECTION_COEFFICIENTS) { if (DEFAULT_REFLECTION_COEFFICIENTS .hasOwnProperty(property)) { // Compute and assign delay (in seconds). let delayInSecs = distances[property] / this.speedOfSound; this._delays[property].delayTime.value = delayInSecs; // Compute and assign gain, uses logarithmic rolloff: "g = R / (d + 1)" let attenuation = this._coefficients[property] / distances[property]; this._gains[property].gain.value = attenuation; } } } /** * Set the room's properties which determines the characteristics of * reflections. * @param {Utils~RoomDimensions} dimensions * Room dimensions (in meters). Defaults to * {@linkcode Utils.DEFAULT_ROOM_DIMENSIONS DEFAULT_ROOM_DIMENSIONS}. * @param {Object} coefficients * Frequency-independent reflection coeffs per wall. Defaults to * {@linkcode Utils.DEFAULT_REFLECTION_COEFFICIENTS * DEFAULT_REFLECTION_COEFFICIENTS}. */ setRoomProperties(dimensions, coefficients) { if (dimensions == undefined) { dimensions = {}; Object.assign(dimensions, DEFAULT_ROOM_DIMENSIONS); } if (coefficients == undefined) { coefficients = {}; Object.assign(coefficients, DEFAULT_REFLECTION_COEFFICIENTS); } this._coefficients = coefficients; // Sanitize dimensions and store half-dimensions. this._halfDimensions = {}; this._halfDimensions.width = dimensions.width * 0.5; this._halfDimensions.height = dimensions.height * 0.5; this._halfDimensions.depth = dimensions.depth * 0.5; // Update listener position with new room properties. this.setListenerPosition(this._listenerPosition[0], this._listenerPosition[1], this._listenerPosition[2]); } }
JavaScript
class Room { constructor(context, options) { // Public variables. /** * EarlyReflections {@link EarlyReflections EarlyReflections} submodule. * @member {AudioNode} early * @memberof Room * @instance */ /** * LateReflections {@link LateReflections LateReflections} submodule. * @member {AudioNode} late * @memberof Room * @instance */ /** * Ambisonic (multichannel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} output * @memberof Room * @instance */ // Use defaults for undefined arguments. if (options == undefined) { options = {}; } if (options.listenerPosition == undefined) { options.listenerPosition = DEFAULT_POSITION.slice(); } if (options.dimensions == undefined) { options.dimensions = {}; Object.assign(options.dimensions, DEFAULT_ROOM_DIMENSIONS); } if (options.materials == undefined) { options.materials = {}; Object.assign(options.materials, DEFAULT_ROOM_MATERIALS); } if (options.speedOfSound == undefined) { options.speedOfSound = DEFAULT_SPEED_OF_SOUND; } // Sanitize room-properties-related arguments. options.dimensions = _sanitizeDimensions(options.dimensions); let absorptionCoefficients = _getCoefficientsFromMaterials(options.materials); let reflectionCoefficients = _computeReflectionCoefficients(absorptionCoefficients); let durations = _getDurationsFromProperties(options.dimensions, absorptionCoefficients, options.speedOfSound); // Construct submodules for early and late reflections. this.early = new EarlyReflections(context, { dimensions: options.dimensions, coefficients: reflectionCoefficients, speedOfSound: options.speedOfSound, listenerPosition: options.listenerPosition, }); this.late = new LateReflections(context, { durations: durations, }); this.speedOfSound = options.speedOfSound; // Construct auxillary audio nodes. this.output = context.createGain(); this.early.output.connect(this.output); this._merger = context.createChannelMerger(4); this.late.output.connect(this._merger, 0, 0); this._merger.connect(this.output); } dispose() { this.early.output.disconnect(this.output); this.late.output.disconnect(this._merger, 0, 0); this._merger.disconnect(this.output); } /** * Set the room's dimensions and wall materials. * @param {Utils~RoomDimensions} dimensions Room dimensions (in meters). Defaults to * {@linkcode Utils.DEFAULT_ROOM_DIMENSIONS DEFAULT_ROOM_DIMENSIONS}. * @param {Utils~RoomMaterials} materials Named acoustic materials per wall. Defaults to * {@linkcode Utils.DEFAULT_ROOM_MATERIALS DEFAULT_ROOM_MATERIALS}. */ setProperties(dimensions, materials) { // Compute late response. let absorptionCoefficients = _getCoefficientsFromMaterials(materials); let durations = _getDurationsFromProperties(dimensions, absorptionCoefficients, this.speedOfSound); this.late.setDurations(durations); // Compute early response. this.early.speedOfSound = this.speedOfSound; let reflectionCoefficients = _computeReflectionCoefficients(absorptionCoefficients); this.early.setRoomProperties(dimensions, reflectionCoefficients); } /** * Set the listener's position (in meters), where origin is the center of * the room. * @param {Number} x * @param {Number} y * @param {Number} z */ setListenerPosition(x, y, z) { this.early.speedOfSound = this.speedOfSound; this.early.setListenerPosition(x, y, z); // Disable room effects if the listener is outside the room boundaries. let distance = this.getDistanceOutsideRoom(x, y, z); let gain = 1; if (distance > EPSILON_FLOAT) { gain = 1 - distance / LISTENER_MAX_OUTSIDE_ROOM_DISTANCE; // Clamp gain between 0 and 1. gain = Math.max(0, Math.min(1, gain)); } this.output.gain.value = gain; } /** * Compute distance outside room of provided position (in meters). * @param {Number} x * @param {Number} y * @param {Number} z * @return {Number} * Distance outside room (in meters). Returns 0 if inside room. */ getDistanceOutsideRoom(x, y, z) { let dx = Math.max(0, -this.early._halfDimensions.width - x, x - this.early._halfDimensions.width); let dy = Math.max(0, -this.early._halfDimensions.height - y, y - this.early._halfDimensions.height); let dz = Math.max(0, -this.early._halfDimensions.depth - z, z - this.early._halfDimensions.depth); return Math.sqrt(dx * dx + dy * dy + dz * dz); } }
JavaScript
class ResonanceAudio { /** * Main class for managing sources, room and listener models. * @param {AudioContext} context * Associated {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioContext AudioContext}. * @param {ResonanceAudio~ResonanceAudioOptions} options * Options for constructing a new ResonanceAudio scene. */ constructor(context, options) { // Public variables. /** * Binaurally-rendered stereo (2-channel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode}. * @member {AudioNode} output * @memberof ResonanceAudio * @instance */ /** * Ambisonic (multichannel) input {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode} * (For rendering input soundfields). * @member {AudioNode} ambisonicInput * @memberof ResonanceAudio * @instance */ /** * Ambisonic (multichannel) output {@link * https://developer.mozilla.org/en-US/docs/Web/API/AudioNode AudioNode} * (For allowing external rendering / post-processing). * @member {AudioNode} ambisonicOutput * @memberof ResonanceAudio * @instance */ // Use defaults for undefined arguments. if (options == undefined) { options = {}; } if (options.ambisonicOrder == undefined) { options.ambisonicOrder = DEFAULT_AMBISONIC_ORDER; } if (options.listenerPosition == undefined) { options.listenerPosition = DEFAULT_POSITION.slice(); } if (options.listenerForward == undefined) { options.listenerForward = DEFAULT_FORWARD.slice(); } if (options.listenerUp == undefined) { options.listenerUp = DEFAULT_UP.slice(); } if (options.dimensions == undefined) { options.dimensions = {}; Object.assign(options.dimensions, DEFAULT_ROOM_DIMENSIONS); } if (options.materials == undefined) { options.materials = {}; Object.assign(options.materials, DEFAULT_ROOM_MATERIALS); } if (options.speedOfSound == undefined) { options.speedOfSound = DEFAULT_SPEED_OF_SOUND; } // Create member submodules. this._ambisonicOrder = Encoder.validateAmbisonicOrder(options.ambisonicOrder); /** @type {Source[]} */ this._sources = []; this._room = new Room(context, { listenerPosition: options.listenerPosition, dimensions: options.dimensions, materials: options.materials, speedOfSound: options.speedOfSound, }); this._listener = new Listener(context, { ambisonicOrder: options.ambisonicOrder, position: options.listenerPosition, forward: options.listenerForward, up: options.listenerUp, }); // Create auxillary audio nodes. this._context = context; this.output = context.createGain(); this.ambisonicOutput = context.createGain(); this.ambisonicInput = this._listener.input; // Connect audio graph. this._room.output.connect(this._listener.input); this._listener.output.connect(this.output); this._listener.ambisonicOutput.connect(this.ambisonicOutput); } dispose() { this._room.output.disconnect(this._listener.input); this._listener.output.disconnect(this.output); this._listener.ambisonicOutput.disconnect(this.ambisonicOutput); } /** * Create a new source for the scene. * @param {Source~SourceOptions} options * Options for constructing a new Source. * @return {Source} */ createSource(options) { // Create a source and push it to the internal sources array, returning // the object's reference to the user. let source = new Source(this, options); this._sources[this._sources.length] = source; return source; } /** * Remove an existing source for the scene. * @param {Source} source */ removeSource(source) { const sourceIdx = this._sources.findIndex((s) => s === source); if (sourceIdx > -1) { this._sources.splice(sourceIdx, 1); source.dispose(); } } /** * Set the scene's desired ambisonic order. * @param {Number} ambisonicOrder Desired ambisonic order. */ setAmbisonicOrder(ambisonicOrder) { this._ambisonicOrder = Encoder.validateAmbisonicOrder(ambisonicOrder); } /** * Set the room's dimensions and wall materials. * @param {Object} dimensions Room dimensions (in meters). * @param {Object} materials Named acoustic materials per wall. */ setRoomProperties(dimensions, materials) { this._room.setProperties(dimensions, materials); } /** * Set the listener's position (in meters), where origin is the center of * the room. * @param {Number} x * @param {Number} y * @param {Number} z */ setListenerPosition(x, y, z) { // Update listener position. this._listener.position[0] = x; this._listener.position[1] = y; this._listener.position[2] = z; this._room.setListenerPosition(x, y, z); // Update sources with new listener position. this._sources.forEach(function (element) { element._update(); }); } /** * Set the source's orientation using forward and up vectors. * @param {Number} forwardX * @param {Number} forwardY * @param {Number} forwardZ * @param {Number} upX * @param {Number} upY * @param {Number} upZ */ setListenerOrientation(forwardX, forwardY, forwardZ, upX, upY, upZ) { this._listener.setOrientation(forwardX, forwardY, forwardZ, upX, upY, upZ); } /** * Set the listener's position and orientation using a Three.js Matrix4 object. * @param {Object} matrix * The Three.js Matrix4 object representing the listener's world transform. */ setListenerFromMatrix(matrix) { this._listener.setFromMatrix(matrix); // Update the rest of the scene using new listener position. this.setListenerPosition(this._listener.position[0], this._listener.position[1], this._listener.position[2]); } /** * Set the speed of sound. * @param {Number} speedOfSound */ setSpeedOfSound(speedOfSound) { this._room.speedOfSound = speedOfSound; } }
JavaScript
class ResonanceSource extends BaseAnalyzed { /** * Creates a new spatializer that uses Google's Resonance Audio library. * @param {string} id * @param {MediaStream|HTMLAudioElement} stream * @param {number} bufferSize * @param {AudioContext} audioContext * @param {ResonanceAudio} res */ constructor(id, stream, bufferSize, audioContext, res) { const resNode = res.createSource(); super(id, stream, bufferSize, audioContext, resNode.input); this.resScene = res; this.resNode = resNode; Object.seal(this); } /** * Performs the spatialization operation for the audio source's latest location. * @param {Pose} loc */ update(loc) { super.update(loc); const { p, f, u } = loc; this.resNode.setMinDistance(this.minDistance); this.resNode.setMaxDistance(this.maxDistance); this.resNode.setPosition(p.x, p.y, p.z); this.resNode.setOrientation(f.x, f.y, f.z, u.x, u.y, u.z); } /** * Discard values and make this instance useless. */ dispose() { this.resScene.removeSource(this.resNode); this.resNode = null; super.dispose(); } }
JavaScript
class ResonanceScene extends BaseListener { /** * Creates a new audio positioner that uses Google's Resonance Audio library * @param {AudioContext} audioContext */ constructor(audioContext) { super(); this.scene = new ResonanceAudio(audioContext, { ambisonicOrder: 3 }); this.scene.output.connect(audioContext.destination); this.scene.setRoomProperties({ width: 10, height: 5, depth: 10, }, { left: "transparent", right: "transparent", front: "transparent", back: "transparent", down: "grass", up: "transparent", }); Object.seal(this); } /** * Performs the spatialization operation for the audio source's latest location. * @param {Pose} loc */ update(loc) { super.update(loc); const { p, f, u } = loc; this.scene.setListenerPosition(p.x, p.y, p.z); this.scene.setListenerOrientation(f.x, f.y, f.z, u.x, u.y, u.z); } /** * Creates a spatialzer for an audio source. * @private * @param {string} id * @param {MediaStream|HTMLAudioElement} stream - the audio element that is being spatialized. * @param {number} bufferSize - the size of the analysis buffer to use for audio activity detection * @param {AudioContext} audioContext * @param {Pose} dest * @return {BaseSource} */ createSource(id, stream, bufferSize, audioContext, dest) { return new ResonanceSource(id, stream, bufferSize, audioContext, this.scene); } }
JavaScript
class AudioManager extends EventBase { /** * Creates a new manager of audio sources, destinations, and their spatialization. **/ constructor() { super(); this.minDistance = 1; this.minDistanceSq = 1; this.maxDistance = 10; this.maxDistanceSq = 100; this.rolloff = 1; this.transitionTime = 0.5; /** @type {InterpolatedPose} */ this.pose = new InterpolatedPose(); /** @type {Map.<string, InterpolatedPose>} */ this.users = new Map(); /** @type {Map.<string, InterpolatedPose>} */ this.clips = new Map(); /** * Forwards on the audioActivity of an audio source. * @param {AudioActivityEvent} evt * @fires AudioManager#audioActivity */ this.onAudioActivity = (evt) => { audioActivityEvt$1.id = evt.id; audioActivityEvt$1.isActive = evt.isActive; this.dispatchEvent(audioActivityEvt$1); }; /** @type {AudioContext} */ this.audioContext = null; /** @type {BaseListener} */ this.listener = null; Object.seal(this); } /** * Perform the audio system initialization, after a user gesture **/ start() { this.createContext(); } update() { if (this.audioContext) { this.pose.update(this.currentTime); for (let pose of this.users.values()) { pose.update(this.currentTime); } for (let pose of this.clips.values()) { pose.update(this.currentTime); } } } /** * If no audio context is currently available, creates one, and initializes the * spatialization of its listener. * * If WebAudio isn't available, a mock audio context is created that provides * ersatz playback timing. **/ createContext() { if (!this.audioContext) { if (hasAudioContext$1) { try { this.audioContext = new AudioContext(); } catch (exp) { hasAudioContext$1 = false; console.warn("Could not create WebAudio AudioContext", exp); } } if (!hasAudioContext$1) { this.audioContext = new MockAudioContext(); } if (hasAudioContext$1 && attemptResonanceAPI) { try { this.listener = new ResonanceScene(this.audioContext); } catch (exp) { attemptResonanceAPI = false; console.warn("Resonance Audio API not available!", exp); } } if (hasAudioContext$1 && !attemptResonanceAPI && hasNewAudioListener) { try { this.listener = new AudioListenerNew(this.audioContext.listener); } catch (exp) { hasNewAudioListener = false; console.warn("No AudioListener.positionX property!", exp); } } if (hasAudioContext$1 && !attemptResonanceAPI && !hasNewAudioListener && hasOldAudioListener) { try { this.listener = new AudioListenerOld(this.audioContext.listener); } catch (exp) { hasOldAudioListener = false; console.warn("No WebAudio API!", exp); } } if (!hasOldAudioListener || !hasAudioContext$1) { this.listener = new BaseListener(); } this.pose.spatializer = this.listener; } } /** * Creates a spatialzer for an audio source. * @private * @param {string} id * @param {MediaStream|HTMLAudioElement} stream - the audio element that is being spatialized. * @param {number} bufferSize - the size of the analysis buffer to use for audio activity detection * @return {BaseSource} */ createSpatializer(id, stream, bufferSize) { if (!stream) { return Promise.reject("No stream or audio element given."); } else { const creator = (resolve) => { if (this.listener) { resolve(this.listener.createSource(id, stream, bufferSize, this.audioContext, this.pose.current)); } else { setTimeout(creator, 0, resolve); } }; return new Promise(creator); } } /** * Creates a new sound effect from a series of fallback paths * for media files. * @param {string} name - the name of the sound effect, to reference when executing playback. * @param {string[]} paths - a series of fallback paths for loading the media of the sound effect. * @returns {AudioManager} */ addClip(name, ...paths) { const pose = new InterpolatedPose(); const sources = paths .map((p) => { const s = document.createElement("source"); s.src = p; return s; }); const elem = document.createElement("audio"); elem.controls = false; elem.playsInline = true; elem.append(...sources); this.createSpatializer(name, elem) .then((source) => pose.spatializer = source); this.clips.set(name, pose); return this; } /** * Plays a named sound effect. * @param {string} name - the name of the effect to play. * @param {number} [volume=1] - the volume at which to play the effect. */ playClip(name, volume = 1) { if (this.clips.has(name)) { const pose = this.clips.get(name); const clip = pose.spatializer; clip.volume = volume; clip.play(); } } /** * Gets the current playback time. * @type {number} */ get currentTime() { return this.audioContext.currentTime; } /** * Create a new user for audio processing. * @param {string} id * @returns {InterpolatedPose} */ createUser(id) { if (!this.users.has(id)) { this.users.set(id, new InterpolatedPose()); } return this.users.get(id); } /** * Remove a user from audio processing. * @param {string} id - the id of the user to remove **/ removeUser(id) { if (this.users.has(id)) { const pose = this.users.get(id); pose.dispose(); this.users.delete(id); } } /** * @param {string} id * @param {MediaStream|HTMLAudioElement} stream **/ setSource(id, stream) { if (this.users.has(id)) { const pose = this.users.get(id); if (pose.spatializer) { pose.spatializer.removeEventListener("audioActivity", this.onAudioActivity); pose.spatializer = null; } if (stream) { this.createSpatializer(id, stream, BUFFER_SIZE) .then((source) => { pose.spatializer = source; if (source) { if (source.audio) { source.audio.autoPlay = true; source.audio.muted = !(source instanceof ManualVolume); source.audio.addEventListener("onloadedmetadata", () => source.audio.play()); source.audio.play(); } source.setAudioProperties(this.minDistance, this.maxDistance, this.rolloff, this.transitionTime); source.addEventListener("audioActivity", this.onAudioActivity); } }); } } } /** * Sets parameters that alter spatialization. * @param {number} minDistance * @param {number} maxDistance * @param {number} rolloff * @param {number} transitionTime **/ setAudioProperties(minDistance, maxDistance, rolloff, transitionTime) { this.minDistance = minDistance; this.maxDistance = maxDistance; this.transitionTime = transitionTime; this.rolloff = rolloff; for (let pose of this.users.values()) { if (pose.spatializer) { pose.spatializer.setAudioProperties(this.minDistance, this.maxDistance, this.rolloff, this.transitionTime); } } } /** * Set the position of the listener. * @param {number} x - the horizontal component of the position. * @param {number} y - the vertical component of the position. * @param {number} z - the lateral component of the position. */ setLocalPosition(x, y, z) { this.pose.setTargetPosition(x, y, z, this.currentTime, this.transitionTime); } /** * Set the orientation of the listener. * @param {number} fx - the horizontal component of the forward vector. * @param {number} fy - the vertical component of the forward vector. * @param {number} fz - the lateral component of the forward vector. * @param {number} ux - the horizontal component of the up vector. * @param {number} uy - the vertical component of the up vector. * @param {number} uz - the lateral component of the up vector. */ setLocalOrientation(fx, fy, fz, ux, uy, uz) { this.pose.setTargetOrientation(fx, fy, fz, ux, uy, uz, this.currentTime, this.transitionTime); } /** * Set the position and orientation of the listener. * @param {number} px - the horizontal component of the position. * @param {number} py - the vertical component of the position. * @param {number} pz - the lateral component of the position. * @param {number} fx - the horizontal component of the forward vector. * @param {number} fy - the vertical component of the forward vector. * @param {number} fz - the lateral component of the forward vector. * @param {number} ux - the horizontal component of the up vector. * @param {number} uy - the vertical component of the up vector. * @param {number} uz - the lateral component of the up vector. */ setLocalPose(px, py, pz, fx, fy, fz, ux, uy, uz) { this.pose.setTarget(px, py, pz, fx, fy, fz, ux, uy, uz, this.currentTime, this.transitionTime); } /** * @returns {Pose} **/ getLocalPose() { return this.pose.end; } /** * Set the position of an audio source. * @param {string} id - the id of the user for which to set the position. * @param {number} x - the horizontal component of the position. * @param {number} y - the vertical component of the position. * @param {number} z - the lateral component of the position. **/ setUserPosition(id, x, y, z) { if (this.users.has(id)) { const pose = this.users.get(id); pose.setTargetPosition(x, y, z, this.currentTime, this.transitionTime); } } /** * Set the position of an audio source. * @param {string} id - the id of the user for which to set the position. * @param {number} fx - the horizontal component of the forward vector. * @param {number} fy - the vertical component of the forward vector. * @param {number} fz - the lateral component of the forward vector. * @param {number} ux - the horizontal component of the up vector. * @param {number} uy - the vertical component of the up vector. * @param {number} uz - the lateral component of the up vector. **/ setUserOrientation(id, fx, fy, fz, ux, uy, uz) { if (this.users.has(id)) { const pose = this.users.get(id); pose.setTargetOrientation(fx, fy, fz, ux, uy, uz, this.currentTime, this.transitionTime); } } /** * Set the position of an audio source. * @param {string} id - the id of the user for which to set the position. * @param {number} px - the horizontal component of the position. * @param {number} py - the vertical component of the position. * @param {number} pz - the lateral component of the position. * @param {number} fx - the horizontal component of the forward vector. * @param {number} fy - the vertical component of the forward vector. * @param {number} fz - the lateral component of the forward vector. * @param {number} ux - the horizontal component of the up vector. * @param {number} uy - the vertical component of the up vector. * @param {number} uz - the lateral component of the up vector. **/ setUserPose(id, px, py, pz, fx, fy, fz, ux, uy, uz) { if (this.users.has(id)) { const pose = this.users.get(id); pose.setTarget(px, py, pz, fx, fy, fz, ux, uy, uz, this.currentTime, this.transitionTime); } } }
JavaScript
class CallaClient extends EventBase { /** * @param {string} JITSI_HOST * @param {string} JVB_HOST * @param {string} JVB_MUC */ constructor(JITSI_HOST, JVB_HOST, JVB_MUC) { super(); this.host = JITSI_HOST; this.bridgeHost = JVB_HOST; this.bridgeMUC = JVB_MUC; this._prepTask = null; this.joined = false; this.connection = null; this.conference = null; this.audio = new AudioManager(); this.audio.addEventListener("audioActivity", (evt) => { audioActivityEvt$2.id = evt.id; audioActivityEvt$2.isActive = evt.isActive; this.dispatchEvent(audioActivityEvt$2); }); this.hasAudioPermission = false; this.hasVideoPermission = false; /** @type {String} */ this.localUser = null; this.preInitEvtQ = []; /** @type {String} */ this.preferredAudioOutputID = null; /** @type {String} */ this.preferredAudioInputID = null; /** @type {String} */ this.preferredVideoInputID = null; this.addEventListener("participantJoined", (evt) => { this.userInitRequest(evt.id); }); this.addEventListener("userInitRequest", (evt) => { const pose = this.audio.getLocalPose(); const { p, f, u } = pose; this.userInitResponse(evt.id, { id: this.localUser, px: p.x, py: p.y, pz: p.z, fx: f.x, fy: f.y, fz: f.z, ux: u.x, uy: u.y, uz: u.z }); }); this.addEventListener("userInitResponse", (evt) => { if (isNumber(evt.x) && isNumber(evt.y) && isNumber(evt.z)) { this.audio.setUserPosition(evt.id, evt.x, evt.y, evt.z); } else if (isNumber(evt.fx) && isNumber(evt.fy) && isNumber(evt.fz) && isNumber(evt.ux) && isNumber(evt.uy) && isNumber(evt.uz)) { if (isNumber(evt.px) && isNumber(evt.py) && isNumber(evt.pz)) { this.audio.setUserPose(evt.id, evt.px, evt.py, evt.pz, evt.fx, evt.fy, evt.fz, evt.ux, evt.uy, evt.uz); } else { this.audio.setUserOrientation(evt.id, evt.fx, evt.fy, evt.fz, evt.ux, evt.uy, evt.uz); } } }); this.addEventListener("userMoved", (evt) => { this.audio.setUserPosition(evt.id, evt.x, evt.y, evt.z); }); this.addEventListener("userTurned", (evt) => { this.audio.setUserOrientation(evt.id, evt.fx, evt.fy, evt.fz, evt.ux, evt.uy, evt.uz); }); this.addEventListener("userPosed", (evt) => { this.audio.setUserPose(evt.id, evt.px, evt.py, evt.pz, evt.fx, evt.fy, evt.fz, evt.ux, evt.uy, evt.uz); }); this.addEventListener("participantLeft", (evt) => { this.removeUser(evt.id); }); const onAudioChange = (evt) => { const evt2 = Object.assign(new Event("audioChanged"), { id: evt.id, stream: evt.stream }); this.dispatchEvent(evt2); }; const onVideoChange = (evt) => { const evt2 = Object.assign(new Event("videoChanged"), { id: evt.id, stream: evt.stream }); this.dispatchEvent(evt2); }; this.addEventListener("audioAdded", onAudioChange); this.addEventListener("audioRemoved", onAudioChange); this.addEventListener("videoAdded", onVideoChange); this.addEventListener("videoRemoved", onVideoChange); this.addEventListener("audioMuteStatusChanged", (evt) => { if (evt.id === this.localUser) { const evt2 = Object.assign(new Event("localAudioMuteStatusChanged"), { id: evt.id, muted: evt.muted }); this.dispatchEvent(evt2); } }); this.addEventListener("videoMuteStatusChanged", (evt) => { if (evt.id === this.localUser) { const evt2 = Object.assign(new Event("localVideoMuteStatusChanged"), { id: evt.id, muted: evt.muted }); this.dispatchEvent(evt2); } }); const dispose = () => this.dispose(); window.addEventListener("beforeunload", dispose); window.addEventListener("unload", dispose); window.addEventListener("pagehide", dispose); Object.seal(this); } get appFingerPrint() { return "Calla"; } userIDs() { return Object.keys(this.conference.participants); } userExists(id) { return !!this.conference.participants[id]; } users() { return Object.keys(this.conference.participants) .map(k => [k, this.conference.participants[k].getDisplayName()]); } update() { this.audio.update(); } _prepareAsync() { if (!this._prepTask) { console.info("Connecting to:", this.host); this._prepTask = import(`https://${this.host}/libs/lib-jitsi-meet.min.js`); } return this._prepTask; } /** * @param {string} roomName * @param {string} userName */ async join(roomName, userName) { await this.leaveAsync(); await this._prepareAsync(); roomName = roomName.toLocaleLowerCase(); JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.ERROR); JitsiMeetJS.init(); this.connection = new JitsiMeetJS.JitsiConnection(null, null, { hosts: { domain: this.bridgeHost, muc: this.bridgeMUC }, serviceUrl: `https://${this.host}/http-bind`, enableLipSync: true }); const { CONNECTION_ESTABLISHED, CONNECTION_FAILED, CONNECTION_DISCONNECTED } = JitsiMeetJS.events.connection; setLoggers(this.connection, JitsiMeetJS.events.connection); const onConnect = (connectionID) => { this.conference = this.connection.initJitsiConference(roomName, { openBridgeChannel: true }); const { TRACK_ADDED, TRACK_REMOVED, CONFERENCE_JOINED, CONFERENCE_LEFT, USER_JOINED, USER_LEFT, DISPLAY_NAME_CHANGED, ENDPOINT_MESSAGE_RECEIVED } = JitsiMeetJS.events.conference; setLoggers(this.conference, JitsiMeetJS.events.conference); this.conference.addEventListener(CONFERENCE_JOINED, async () => { const id = this.conference.myUserId(); this.joined = true; this.setDisplayName(userName); this.dispatchEvent(Object.assign( new Event("videoConferenceJoined"), { id, roomName, displayName: userName, pose: this.audio.pose })); await this.setPreferredDevicesAsync(); }); this.conference.addEventListener(CONFERENCE_LEFT, () => { this.dispatchEvent(Object.assign( new Event("videoConferenceLeft"), { roomName })); this.conference = null; this.joined = false; }); const onTrackMuteChanged = (track, muted) => { const userID = track.getParticipantId() || this.localUser, trackKind = track.getType(), muteChangedEvtName = trackKind + "MuteStatusChanged", evt = Object.assign( new Event(muteChangedEvtName), { id: userID, muted }); this.dispatchEvent(evt); }; const onTrackChanged = (track) => { onTrackMuteChanged(track, track.isMuted()); }; this.conference.addEventListener(USER_JOINED, (id, user) => { const evt = Object.assign( new Event("participantJoined"), { id, displayName: user.getDisplayName(), pose: this.audio.createUser(id) }); this.dispatchEvent(evt); }); this.conference.addEventListener(USER_LEFT, (id) => { const evt = Object.assign( new Event("participantLeft"), { id }); this.dispatchEvent(evt); }); this.conference.addEventListener(DISPLAY_NAME_CHANGED, (id, displayName) => { const evt = Object.assign( new Event("displayNameChange"), { id, displayName }); this.dispatchEvent(evt); }); this.conference.addEventListener(TRACK_ADDED, (track) => { const userID = track.getParticipantId() || this.localUser, isLocal = track.isLocal(), trackKind = track.getType(), trackAddedEvt = Object.assign(new Event(trackKind + "Added"), { id: userID, stream: track.stream }); setLoggers(track, JitsiMeetJS.events.track); track.addEventListener(JitsiMeetJS.events.track.TRACK_MUTE_CHANGED, onTrackChanged); if (!userInputs.has(userID)) { userInputs.set(userID, new Map()); } const inputs = userInputs.get(userID); if (inputs.has(trackKind)) { inputs.get(trackKind).dispose(); inputs.delete(trackKind); } inputs.set(trackKind, track); if (trackKind === "audio" && !isLocal) { this.audio.setSource(userID, track.stream); } this.dispatchEvent(trackAddedEvt); onTrackMuteChanged(track, false); }); this.conference.addEventListener(TRACK_REMOVED, (track) => { const userID = track.getParticipantId() || this.localUser, isLocal = track.isLocal(), trackKind = track.getType(), trackRemovedEvt = Object.assign(new Event(trackKind + "Removed"), { id: userID, stream: null }); if (userInputs.has(userID)) { const inputs = userInputs.get(userID); if (inputs.has(trackKind)) { inputs.get(trackKind).dispose(); inputs.delete(trackKind); } } if (trackKind === "audio" && !isLocal) { this.audio.setSource(userID, null); } track.dispose(); onTrackMuteChanged(track, true); this.dispatchEvent(trackRemovedEvt); }); this.conference.addEventListener(ENDPOINT_MESSAGE_RECEIVED, (user, data) => { this.rxGameData({ user, data }); }); this.conference.join(); }; const onFailed = (evt) => { console.error("Connection failed", evt); onDisconnect(); }; const onDisconnect = () => { this.connection.removeEventListener(CONNECTION_ESTABLISHED, onConnect); this.connection.removeEventListener(CONNECTION_FAILED, onFailed); this.connection.removeEventListener(CONNECTION_DISCONNECTED, onDisconnect); this.connection = null; }; this.connection.addEventListener(CONNECTION_ESTABLISHED, onConnect); this.connection.addEventListener(CONNECTION_FAILED, onFailed); this.connection.addEventListener(CONNECTION_DISCONNECTED, onDisconnect); setLoggers(JitsiMeetJS.mediaDevices, JitsiMeetJS.events.mediaDevices); this.connection.connect(); } dispatchEvent(evt) { if (this.localUser !== null) { if (evt.id === null || evt.id === undefined || evt.id === "local") { evt.id = this.localUser; } super.dispatchEvent(evt); if (evt.type === "videoConferenceLeft") { this.localUser = null; } } else if (evt.type === "videoConferenceJoined") { this.localUser = evt.id; this.dispatchEvent(evt); for (evt of this.preInitEvtQ) { this.dispatchEvent(evt); } arrayClear(this.preInitEvtQ); } else { this.preInitEvtQ.push(evt); } } async setPreferredDevicesAsync() { await this.setPreferredAudioInputAsync(true); await this.setPreferredVideoInputAsync(false); await this.setPreferredAudioOutputAsync(true); } /** * @param {boolean} allowAny */ async getPreferredAudioOutputAsync(allowAny) { const devices = await this.getAudioOutputDevicesAsync(); const device = arrayScan( devices, (d) => d.deviceId === this.preferredAudioOutputID, (d) => d.deviceId === "communications", (d) => d.deviceId === "default", (d) => allowAny && d && d.deviceId); return device; } /** * @param {boolean} allowAny */ async setPreferredAudioOutputAsync(allowAny) { const device = await this.getPreferredAudioOutputAsync(allowAny); if (device) { await this.setAudioOutputDeviceAsync(device); } } /** * @param {boolean} allowAny */ async getPreferredAudioInputAsync(allowAny) { const devices = await this.getAudioInputDevicesAsync(); const device = arrayScan( devices, (d) => d.deviceId === this.preferredAudioInputID, (d) => d.deviceId === "communications", (d) => d.deviceId === "default", (d) => allowAny && d && d.deviceId); return device; } /** * @param {boolean} allowAny */ async setPreferredAudioInputAsync(allowAny) { const device = await this.getPreferredAudioInputAsync(allowAny); if (device) { await this.setAudioInputDeviceAsync(device); } } /** * @param {boolean} allowAny */ async getPreferredVideoInputAsync(allowAny) { const devices = await this.getVideoInputDevicesAsync(); const device = arrayScan(devices, (d) => d.deviceId === this.preferredVideoInputID, (d) => allowAny && d && /front/i.test(d.label), (d) => allowAny && d && d.deviceId); return device; } /** * @param {boolean} allowAny */ async setPreferredVideoInputAsync(allowAny) { const device = await this.getPreferredVideoInputAsync(allowAny); if (device) { await this.setVideoInputDeviceAsync(device); } } dispose() { if (this.localUser && userInputs.has(this.localUser)) { const tracks = userInputs.get(this.localUser); for (let track of tracks.values()) { track.dispose(); } } } /** * * @param {string} userName */ setDisplayName(userName) { this.conference.setDisplayName(userName); } async leaveAsync() { if (this.conference) { if (this.localUser !== null && userInputs.has(this.localUser)) { const inputs = userInputs.get(this.localUser); if (inputs.has("video")) { const removeTrackTask = once(this, "videoRemoved"); this.conference.removeTrack(inputs.get("video")); await removeTrackTask; } if (inputs.has("audio")) { const removeTrackTask = once(this, "audioRemoved"); this.conference.removeTrack(inputs.get("audio")); await removeTrackTask; } } await this.conference.leave(); await this.connection.disconnect(); } } async _getDevicesAsync() { await this._prepareAsync(); const devices = await navigator.mediaDevices.enumerateDevices(); for (let device of devices) { if (device.deviceId.length > 0) { this.hasAudioPermission |= device.kind === "audioinput" && device.label.length > 0; this.hasVideoPermission |= device.kind === "videoinput" && device.label.length > 0; } } return devices; } async getAvailableDevicesAsync() { let devices = await this._getDevicesAsync(); for (let i = 0; i < 3 && !this.hasAudioPermission; ++i) { devices = null; try { const _ = await navigator.mediaDevices.getUserMedia({ audio: !this.hasAudioPermission, video: !this.hasVideoPermission }); } catch (exp) { console.warn(exp); } devices = await this._getDevicesAsync(); } return { audioOutput: canChangeAudioOutput ? devices.filter(d => d.kind === "audiooutput") : [], audioInput: devices.filter(d => d.kind === "audioinput"), videoInput: devices.filter(d => d.kind === "videoinput") }; } async getAudioOutputDevicesAsync() { if (!canChangeAudioOutput) { return []; } const devices = await this.getAvailableDevicesAsync(); return devices && devices.audioOutput || []; } async getAudioInputDevicesAsync() { const devices = await this.getAvailableDevicesAsync(); return devices && devices.audioInput || []; } async getVideoInputDevicesAsync() { const devices = await this.getAvailableDevicesAsync(); return devices && devices.videoInput || []; } /** * * @param {MediaDeviceInfo} device */ async setAudioOutputDeviceAsync(device) { if (!canChangeAudioOutput) { return; } this.preferredAudioOutputID = device && device.deviceId || null; await JitsiMeetJS.mediaDevices.setAudioOutputDevice(this.preferredAudioOutputID); } taskOf(evt) { return when(this, evt, (evt) => evt.id === this.localUser, 5000); } getCurrentMediaTrack(type) { if (this.localUser === null) { return null; } if (!userInputs.has(this.localUser)) { return null; } const inputs = userInputs.get(this.localUser); if (!inputs.has(type)) { return null; } return inputs.get(type); } /** * * @param {MediaDeviceInfo} device */ async setAudioInputDeviceAsync(device) { this.preferredAudioInputID = device && device.deviceId || null; const cur = this.getCurrentMediaTrack("audio"); if (cur) { const removeTask = this.taskOf("audioRemoved"); this.conference.removeTrack(cur); await removeTask; } if (this.joined && this.preferredAudioInputID) { const addTask = this.taskOf("audioAdded"); const tracks = await JitsiMeetJS.createLocalTracks({ devices: ["audio"], micDeviceId: this.preferredAudioInputID }); for (let track of tracks) { this.conference.addTrack(track); } await addTask; } } /** * * @param {MediaDeviceInfo} device */ async setVideoInputDeviceAsync(device) { this.preferredVideoInputID = device && device.deviceId || null; const cur = this.getCurrentMediaTrack("video"); if (cur) { const removeTask = this.taskOf("videoRemoved"); this.conference.removeTrack(cur); await removeTask; } if (this.joined && this.preferredVideoInputID) { const addTask = this.taskOf("videoAdded"); const tracks = await JitsiMeetJS.createLocalTracks({ devices: ["video"], cameraDeviceId: this.preferredVideoInputID }); for (let track of tracks) { this.conference.addTrack(track); } await addTask; } } async getCurrentAudioInputDeviceAsync() { const cur = this.getCurrentMediaTrack("audio"), devices = await this.getAudioInputDevicesAsync(), device = devices.filter((d) => cur !== null && d.deviceId === cur.deviceId); if (device.length === 0) { return null; } else { return device[0]; } } /** * @return {Promise.<MediaDeviceInfo>} */ async getCurrentAudioOutputDeviceAsync() { if (!canChangeAudioOutput) { return null; } const deviceId = JitsiMeetJS.mediaDevices.getAudioOutputDevice(), devices = await this.getAudioOutputDevicesAsync(), device = devices.filter((d) => d.deviceId === deviceId); if (device.length === 0) { return null; } else { return device[0]; } } async getCurrentVideoInputDeviceAsync() { const cur = this.getCurrentMediaTrack("video"), devices = await this.getVideoInputDevicesAsync(), device = devices.filter((d) => cur !== null && d.deviceId === cur.deviceId); if (device.length === 0) { return null; } else { return device[0]; } } async toggleAudioMutedAsync() { const changeTask = this.taskOf("audioMuteStatusChanged"); const cur = this.getCurrentMediaTrack("audio"); if (cur) { const muted = cur.isMuted(); if (muted) { await cur.unmute(); } else { await cur.mute(); } } else { await this.setPreferredAudioInputAsync(true); } const evt = await changeTask; return evt.muted; } async toggleVideoMutedAsync() { const changeTask = this.taskOf("videoMuteStatusChanged"); const cur = this.getCurrentMediaTrack("video"); if (cur) { await this.setVideoInputDeviceAsync(null); } else { await this.setPreferredVideoInputAsync(true); } const evt = await changeTask; return evt.muted; } isMediaMuted(type) { const cur = this.getCurrentMediaTrack(type); return cur === null || cur.isMuted(); } get isAudioMuted() { return this.isMediaMuted("audio"); } get isVideoMuted() { return this.isMediaMuted("video"); } txGameData(toUserID, data) { this.conference.sendMessage(data, toUserID); } /// A listener to add to JitsiExternalAPI::endpointTextMessageReceived event /// to receive Calla messages from the Jitsi Meet data channel. rxGameData(evt) { if (evt.data.hax === this.appFingerPrint) { this.receiveMessageFrom(evt.user.getId(), evt.data.command, evt.data.value); } } /// Send a Calla message through the Jitsi Meet data channel. sendMessageTo(toUserID, command, value) { this.txGameData(toUserID, { hax: this.appFingerPrint, command, value }); } receiveMessageFrom(fromUserID, command, value) { const evt = new CallaClientEvent(command, fromUserID, value); this.dispatchEvent(evt); } /** * Sets parameters that alter spatialization. * @param {number} minDistance * @param {number} maxDistance * @param {number} rolloff * @param {number} transitionTime */ setAudioProperties(minDistance, maxDistance, rolloff, transitionTime) { this.audio.setAudioProperties(minDistance, maxDistance, rolloff, transitionTime); } /** * Set the position of the listener. * @param {number} x - the horizontal component of the position. * @param {number} y - the vertical component of the position. * @param {number} z - the lateral component of the position. */ setLocalPosition(x, y, z) { this.audio.setLocalPosition(x, y, z); for (let toUserID of this.userIDs()) { this.sendMessageTo(toUserID, "userMoved", { x, y, z }); } } /** * Set the position of the listener. * @param {number} fx - the horizontal component of the forward vector. * @param {number} fy - the vertical component of the forward vector. * @param {number} fz - the lateral component of the forward vector. * @param {number} ux - the horizontal component of the up vector. * @param {number} uy - the vertical component of the up vector. * @param {number} uz - the lateral component of the up vector. */ setLocalOrientation(fx, fy, fz, ux, uy, uz) { this.audio.setLocalOrientation(fx, fy, fz, ux, uy, uz); for (let toUserID of this.userIDs()) { this.sendMessageTo(toUserID, "userTurned", { x, y, z }); } } /** * Set the position of the listener. * @param {number} px - the horizontal component of the position. * @param {number} py - the vertical component of the position. * @param {number} pz - the lateral component of the position. * @param {number} fx - the horizontal component of the forward vector. * @param {number} fy - the vertical component of the forward vector. * @param {number} fz - the lateral component of the forward vector. * @param {number} ux - the horizontal component of the up vector. * @param {number} uy - the vertical component of the up vector. * @param {number} uz - the lateral component of the up vector. */ setLocalPose(px, py, pz, fx, fy, fz, ux, uy, uz) { this.audio.setLocalPose(px, py, pz, fx, fy, fz, ux, uy, uz); for (let toUserID of this.userIDs()) { this.sendMessageTo(toUserID, "userPosed", { px, py, pz, fx, fy, fz, ux, uy, uz }); } } removeUser(id) { this.audio.removeUser(id); } /** * * @param {boolean} muted */ async setAudioMutedAsync(muted) { let isMuted = this.isAudioMuted; if (muted !== isMuted) { isMuted = await this.toggleAudioMutedAsync(); } return isMuted; } /** * * @param {boolean} muted */ async setVideoMutedAsync(muted) { let isMuted = this.isVideoMuted; if (muted !== isMuted) { isMuted = await this.toggleVideoMutedAsync(); } return isMuted; } /// Add a listener for Calla events that come through the Jitsi Meet data channel. /** * * @param {string} evtName * @param {function} callback * @param {AddEventListenerOptions} opts */ addEventListener(evtName, callback, opts) { if (eventNames.indexOf(evtName) === -1) { throw new Error(`Unsupported event type: ${evtName}`); } super.addEventListener(evtName, callback, opts); } /** * * @param {string} toUserID */ userInitRequest(toUserID) { this.sendMessageTo(toUserID, "userInitRequest"); } /** * * @param {string} toUserID */ async userInitRequestAsync(toUserID) { return await until(this, "userInitResponse", () => this.userInitRequest(toUserID), (evt) => evt.id === toUserID && isGoodNumber(evt.x) && isGoodNumber(evt.y) && isGoodNumber(evt.z), 1000); } /** * * @param {string} toUserID * @param {User} fromUserState */ userInitResponse(toUserID, fromUserState) { this.sendMessageTo(toUserID, "userInitResponse", fromUserState); } set avatarEmoji(emoji) { for (let toUserID of this.userIDs()) { this.sendMessageTo(toUserID, "setAvatarEmoji", emoji); } } set avatarURL(url) { for (let toUserID of this.userIDs()) { this.sendMessageTo(toUserID, "avatarChanged", { url }); } } emote(emoji) { for (let toUserID of this.userIDs()) { this.sendMessageTo(toUserID, "emote", emoji); } } startAudio() { this.audio.start(); } }
JavaScript
class HtmlAttr { /** * Creates a new setter functor for HTML Attributes * @param {string} key - the attribute name. * @param {string} value - the value to set for the attribute. * @param {...string} tags - the HTML tags that support this attribute. */ constructor(key, value, ...tags) { this.key = key; this.value = value; this.tags = tags.map(t => t.toLocaleUpperCase()); Object.freeze(this); } /** * Set the attribute value on an HTMLElement * @param {HTMLElement} elem - the element on which to set the attribute. */ apply(elem) { const isValid = this.tags.length === 0 || this.tags.indexOf(elem.tagName) > -1; if (!isValid) { console.warn(`Element ${elem.tagName} does not support Attribute ${this.key}`); } else if (this.key === "style") { Object.assign(elem[this.key], this.value); } else if (!isBoolean(value)) { elem[this.key] = this.value; } else if (this.value) { elem.setAttribute(this.key, ""); } else { elem.removeAttribute(this.key); } } }
JavaScript
class CssProp { /** * Creates a new CSS property that will be applied to an element's style attribute. * @param {string} key - the property name. * @param {string} value - the value to set for the property. */ constructor(key, value) { this.key = key; this.value = value; Object.freeze(this); } /** * Set the attribute value on an HTMLElement * @param {HTMLElement} elem - the element on which to set the attribute. */ apply(elem) { elem.style[this.key] = this.value; } }
JavaScript
class HtmlEvt { /** * Creates a new setter functor for an HTML element event. * @param {string} name - the name of the event to attach to. * @param {Function} callback - the callback function to use with the event handler. * @param {(boolean|AddEventListenerOptions)=} opts - additional attach options. */ constructor(name, callback, opts) { if (!isFunction(callback)) { throw new Error("A function instance is required for this parameter"); } this.name = name; this.callback = callback; this.opts = opts; Object.freeze(this); } /** * Add the encapsulate callback as an event listener to the give HTMLElement * @param {HTMLElement} elem */ add(elem) { elem.addEventListener(this.name, this.callback, this.opts); } /** * Remove the encapsulate callback as an event listener from the give HTMLElement * @param {HTMLElement} elem */ remove(elem) { elem.removeEventListener(this.name, this.callback); } }
JavaScript
class HtmlCustomTag extends EventBase { /** * Creates a new pseudo-element * @param {string} tagName - the type of tag that will contain the elements in the custom tag. * @param {...TagChild} rest - optional attributes, child elements, and text */ constructor(tagName, ...rest) { super(); if (rest.length === 1 && rest[0] instanceof Element) { /** @type {HTMLElement} */ this.element = rest[0]; } else { /** @type {HTMLElement} */ this.element = tag(tagName, ...rest); } } /** * Gets the ID attribute of the container element. * @type {string} **/ get id() { return this.element.id; } /** * Retrieves the desired element for attaching events. * @returns {HTMLElement} **/ get eventTarget() { return this.element; } /** * Determine if an event type should be forwarded to the container element. * @param {string} name * @returns {boolean} */ isForwardedEvent(name) { return true; } /** * Adds an event listener to the container element. * @param {string} name - the name of the event to attach to. * @param {Function} callback - the callback function to use with the event handler. * @param {(boolean|AddEventListenerOptions)=} opts - additional attach options. */ addEventListener(name, callback, opts) { if (this.isForwardedEvent(name)) { this.eventTarget.addEventListener(name, callback, opts); } else { super.addEventListener(name, callback, opts); } } /** * Removes an event listener from the container element. * @param {string} name - the name of the event to attach to. * @param {Function} callback - the callback function to use with the event handler. */ removeEventListener(name, callback) { if (this.isForwardedEvent(name)) { this.eventTarget.removeEventListener(name, callback); } else { super.removeEventListener(name, callback); } } /** * Gets the style attribute of the underlying select box. * @type {ElementCSSInlineStyle} */ get style() { return this.element.style; } get tagName() { return this.element.tagName; } get disabled() { return this.element.disabled; } set disabled(v) { this.element.disabled = v; } /** * Moves cursor focus to the underyling element. **/ focus() { this.element.focus(); } /** * Removes cursor focus from the underlying element. **/ blur() { this.element.blur(); } }
JavaScript
class LabeledInputTag extends HtmlCustomTag { /** * Creates an input box that has a label attached to it. * @param {string} id - the ID to use for the input box * @param {string} inputType - the type to use for the input box (number, text, etc.) * @param {string} labelText - the text to display in the label * @param {...TagChild} rest - optional attributes, child elements, and text to use on the select element * @returns {LabeledInputTag} */ constructor(id, inputType, labelText, ...rest) { super("div"); this.label = Label( htmlFor(id), labelText); this.input = Input( type(inputType), ...rest); this.element.append( this.label, this.input); Object.seal(this); } /** * Retrieves the desired element for attaching events. * @returns {HTMLElement} **/ get eventTarget() { return this.input; } /** * Gets the value attribute of the input element * @type {string} */ get value() { return this.input.value; } /** * Sets the value attribute of the input element * @param {string} v */ set value(v) { this.input.value = v; } /** * Gets whether or not the input element is checked, if it's a checkbox or radio button. * @type {boolean} */ get checked() { return this.input.checked; } /** * Sets whether or not the input element is checked, if it's a checkbox or radio button. * @param {boolean} v */ set checked(v) { this.input.checked = v; } /** * Sets whether or not the input element should be disabled. * @param {boolean} value */ setLocked(value) { setLocked(this.input, value); } }
JavaScript
class OptionPanelTag extends HtmlCustomTag { /** * Creates a new panel that can be opened with a button click, * living in a collection of panels that will be hidden when * this panel is opened. * @param {string} panelID - the ID to use for the panel element. * @param {string} name - the text to use on the button. * @param {...any} rest */ constructor(panelID, name, ...rest) { super("div", id(panelID), padding("1em"), P(...rest)); this.button = Button( id(panelID + "Btn"), onClick(() => this.dispatchEvent(selectEvt)), name); } isForwardedEvent(name) { return name !== "select"; } /** * Gets whether or not the panel is visible * @type {boolean} **/ get visible() { return this.element.style.display !== null; } /** * Sets whether or not the panel is visible * @param {boolean} v **/ set visible(v) { setOpen(this.element, v); styles( borderStyle("solid"), borderWidth("2px"), backgroundColor(v ? "#ddd" : "transparent"), borderTop(v ? "" : "none"), borderRight(v ? "" : "none"), borderBottomColor(v ? "#ddd" : ""), borderLeft(v ? "" : "none")) .apply(this.button); } }
JavaScript
class SelectBoxTag extends HtmlCustomTag { /** * Creates a select box that can bind to collections * @param {string} noSelectionText - the text to display when no items are available. * @param {makeItemValueCallback} makeID - a function that evalutes a databound item to create an ID for it. * @param {makeItemValueCallback} makeLabel - a function that evalutes a databound item to create a label for it. * @param {...TagChild} rest - optional attributes, child elements, and text to use on the select element */ constructor(noSelectionText, makeID, makeLabel, ...rest) { super("select", ...rest); if (!isFunction(makeID)) { throw new Error("makeID parameter must be a Function"); } if (!isFunction(makeLabel)) { throw new Error("makeLabel parameter must be a Function"); } this.noSelectionText = noSelectionText; this.makeID = (v) => v !== null && makeID(v) || null; this.makeLabel = (v) => v !== null && makeLabel(v) || "None"; this.emptySelectionEnabled = true; Object.seal(this); } /** * Gets whether or not the select box will have a vestigial entry for "no selection" or "null" in the select box. * @type {boolean} **/ get emptySelectionEnabled() { return this._emptySelectionEnabled; } /** * Sets whether or not the select box will have a vestigial entry for "no selection" or "null" in the select box. * @param {boolean} value **/ set emptySelectionEnabled(value) { this._emptySelectionEnabled = value; render(this); } /** * Gets the collection to which the select box was databound **/ get values() { if (!values.has(this)) { values.set(this, []); } return values.get(this); } /** * Sets the collection to which the select box will be databound **/ set values(newItems) { const curValue = this.selectedValue; const values = this.values; values.splice(0, values.length, ...newItems); render(this); this.selectedValue = curValue; } /** * Returns the collection of HTMLOptionElements that are stored in the select box * @type {HTMLOptionsCollection} */ get options() { return this.element.options; } /** * Gets the index of the item that is currently selected in the select box. * The index is offset by -1 if the select box has `emptySelectionEnabled` * set to true, so that the indices returned are always in range of the collection * to which the select box was databound * @type {number} */ get selectedIndex() { let i = this.element.selectedIndex; if (this.emptySelectionEnabled) { --i; } return i; } /** * Sets the index of the item that should be selected in the select box. * The index is offset by -1 if the select box has `emptySelectionEnabled` * set to true, so that the indices returned are always in range of the collection * to which the select box was databound * @param {number} i */ set selectedIndex(i) { if (this.emptySelectionEnabled) { ++i; } this.element.selectedIndex = i; } /** * Gets the item at `selectedIndex` in the collection to which the select box was databound * @type {any} */ get selectedValue() { if (0 <= this.selectedIndex && this.selectedIndex < this.values.length) { return this.values[this.selectedIndex]; } else { return null; } } /** * Gets the index of the given item in the select box's databound collection, then * sets that index as the `selectedIndex`. * @param {any) value */ set selectedValue(value) { this.selectedIndex = this.indexOf(value); } /** * Returns the index of the given item in the select box's databound collection. * @param {any} value * @returns {number} */ indexOf(value) { return this.values .findIndex(v => value !== null && this.makeID(value) === this.makeID(v)); } /** * Checks to see if the value exists in the databound collection. * @param {any} value * @returns {boolean} */ contains(value) { return this.indexOf(value) >= 0. } }
JavaScript
class BaseAvatar { /** * Encapsulates a resource to use as an avatar. * @param {boolean} canSwim */ constructor(canSwim) { this.canSwim = canSwim; this.element = Canvas(128, 128); this.g = this.element.getContext("2d"); } /** * Render the avatar at a certain size. * @param {CanvasRenderingContext2D} g - the context to render to * @param {number} width - the width the avatar should be rendered at * @param {number} height - the height the avatar should be rendered at. * @param {boolean} isMe - whether the avatar is the local user */ draw(g, width, height, isMe) { const aspectRatio = this.element.width / this.element.height, w = aspectRatio > 1 ? width : aspectRatio * height, h = aspectRatio > 1 ? width / aspectRatio : height, dx = (width - w) / 2, dy = (height - h) / 2; g.drawImage( this.element, dx, dy, w, h); } }
JavaScript
class EmojiAvatar extends BaseAvatar { /** * Creatse a new avatar that uses a Unicode emoji as its representation. * @param {Emoji} emoji */ constructor(emoji) { super(isSurfer(emoji)); this.value = emoji.value; this.desc = emoji.desc; const emojiText = new TextImage("sans-serif"); emojiText.color = emoji.color || "black"; emojiText.fontSize = 256; emojiText.value = this.value; setContextSize(this.g, emojiText.width, emojiText.height); emojiText.draw(this.g, 0, 0); } }
JavaScript
class PhotoAvatar extends BaseAvatar { /** * Creates a new avatar that uses an Image as its representation. * @param {(URL|string)} url */ constructor(url) { super(false); const img = new Image(); img.addEventListener("load", () => { const offset = (img.width - img.height) / 2, sx = Math.max(0, offset), sy = Math.max(0, -offset), dim = Math.min(img.width, img.height); setContextSize(this.g, dim, dim); this.g.drawImage(img, sx, sy, dim, dim, 0, 0, dim, dim); }); /** @type {string} */ this.url = img.src = url && url.href || url; } }
JavaScript
class VideoAvatar extends BaseAvatar { /** * Creates a new avatar that uses a MediaStream as its representation. * @param {MediaStream|HTMLVideoElement} stream */ constructor(stream) { super(false); let video = null; if (stream instanceof HTMLVideoElement) { video = stream; } else if (stream instanceof MediaStream) { video = Video( autoPlay, playsInline, muted, volume(0), srcObject(stream)); } else { throw new Error("Can only create a video avatar from an HTMLVideoElement or MediaStream."); } this.video = video; if (!isIOS) { video.play(); once(video, "canplay") .then(() => video.play()); } } /** * Render the avatar at a certain size. * @param {CanvasRenderingContext2D} g - the context to render to * @param {number} width - the width the avatar should be rendered at * @param {number} height - the height the avatar should be rendered at. * @param {boolean} isMe - whether the avatar is the local user */ draw(g, width, height, isMe) { if (this.video.videoWidth > 0 && this.video.videoHeight > 0) { const offset = (this.video.videoWidth - this.video.videoHeight) / 2, sx = Math.max(0, offset), sy = Math.max(0, -offset), dim = Math.min(this.video.videoWidth, this.video.videoHeight); setContextSize(this.g, dim, dim); this.g.save(); if (isMe) { this.g.translate(dim, 0); this.g.scale(-1, 1); } this.g.drawImage( this.video, sx, sy, dim, dim, 0, 0, dim, dim); this.g.restore(); } super.draw(g, width, height, isMe); } }
JavaScript
class CompanyController { /** * Retrieve a Company [GET /companies/{id}] * * @static * @public * @param {string} id The Company ID * @return {Promise<CompanyModel>} */ static getOne(id) { return new Promise((resolve, reject) => { RequestHelper.getRequest(`/companies/${id}`) .then((result) => { let resolveValue = (function(){ return CompanyModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Update a Company [PATCH /companies/{id}] * * @static * @public * @param {string} id The Company ID * @param {CompanyController.UpdateData} updateData The Company Update Data * @return {Promise<CompanyModel>} */ static update(id, updateData) { return new Promise((resolve, reject) => { RequestHelper.patchRequest(`/companies/${id}`, updateData) .then((result) => { let resolveValue = (function(){ return CompanyModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Delete a Company [DELETE /companies/{id}] * * @static * @public * @param {string} id The Company ID * @return {Promise<boolean>} */ static delete(id) { return new Promise((resolve, reject) => { RequestHelper.deleteRequest(`/companies/${id}`) .then((result) => { resolve(result ?? true); }) .catch(error => reject(error)); }); } /** * List all Companies [GET /companies] * * @static * @public * @param {CompanyController.GetAllQueryParameters} [queryParameters] The Optional Query Parameters * @return {Promise<CompanyModel[]>} */ static getAll(queryParameters = {}) { return new Promise((resolve, reject) => { RequestHelper.getRequest(`/companies`, queryParameters) .then((result) => { let resolveValue = (function(){ if(Array.isArray(result) !== true) { return []; } return result.map((resultItem) => { return (function(){ return CompanyModel.fromJSON(resultItem); }()); }); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Create a Company [POST /companies] * * @static * @public * @param {CompanyController.CreateData} createData The Company Create Data * @return {Promise<CompanyModel>} */ static create(createData) { return new Promise((resolve, reject) => { RequestHelper.postRequest(`/companies`, createData) .then((result) => { let resolveValue = (function(){ return CompanyModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } }
JavaScript
class DrawerScreen extends PureComponent { render() { const { router, navigation, childNavigationProps, screenProps } = this.props; const { routes, index } = navigation.state; const childNavigation = childNavigationProps[routes[index].key]; const Content = router.getComponentForRouteName(routes[index].routeName); return <SceneView screenProps={screenProps} component={Content} navigation={childNavigation} />; } }
JavaScript
class GpxGenerator { /** * This method fetches the details of the activity * and generates a GPX file * @param {Activity} selectedActivity the activity * received from allActivities */ async generateGpxFromActivity(selectedActivity){ console.log(selectedActivity); let heartrateData = await activity .getHeartrateData(selectedActivity.startdate, selectedActivity.enddate); let locationData = await activity .getLocationData(selectedActivity.startdate, selectedActivity.enddate); return this.generateGpx(locationData, heartrateData); } /** * This method generates a GPX file * @param {object} locationData The locationdata received from withings * @param {object} heartrateData The heartrate data received from withings * @return {string} contents of the GPX file */ generateGpx(locationData, heartrateData){ var result = '<?xml version="1.0" encoding="UTF-8"?><gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1/gpx.xsd"><trk><name>test</name><trkseg>'; for(var i = 0; i < locationData.vasistas.length; i++){ let timestamp = locationData.dates[i]; let latitude = locationData.vasistas[i][0]; let longitude = locationData.vasistas[i][1]; result += '<trkpt lat="' + latitude + '" lon="' + longitude + '"><time>'; result += new Date(timestamp*1000).toISOString(); result += '</time>'; var heartrateDelta = 99999; var heartrate = 0; for(var j = 0; j < heartrateData.dates.length; j++){ let heartrateTime = heartrateData.dates[j] let delta = Math.abs(timestamp - heartrateTime); if(delta < heartrateDelta){ heartrateDelta = delta; heartrate = heartrateData.vasistas[j][0]; } } if(heartrateDelta < 10){ result += '<extensions><gpxtpx:TrackPointExtension><gpxtpx:hr>'; result += heartrate; result += '</gpxtpx:hr></gpxtpx:TrackPointExtension></extensions>'; } result += '</trkpt>'; } result += '</trkseg></trk></gpx>'; return result; } }
JavaScript
class AppBoundary extends React.Component { constructor(props) { super(props); this.state = { error: false, }; } componentDidCatch(error, info) { this.setState({ error: error, info: info, }); } goback() { this.setState({ error: false }); } render() { if (this.state.error !== false) { return ( <Fragment> <h2>something went wrong</h2> <p>{this.state.error.message}</p> <pre>{this.state.info.componentStack.slice(1)}</pre> {this.state.showStack ? ( <Fragment> <p> <a href="#" onClick={() => this.setState({ showStack: false })}> hide stack </a> </p> <pre>{this.state.error.stack}</pre> </Fragment> ) : ( <p> <a href="#" onClick={() => this.setState({ showStack: true })}> show stack </a> </p> )} <p> <a href="#" onClick={() => this.goback()}> go back </a> </p> </Fragment> ); } return this.props.children; } }
JavaScript
class Table { /** * Creates table * @param {object} table - table as json data * @param {Controls} controls */ constructor(table, controls) { this.controls = controls; var header = this.createHeader(table); var body = this.createBody(table.columns); var collapseWrapper = this.createCollapseWrapper(table.name); collapseWrapper.append(body); this.content = this.createCard(header, collapseWrapper); } /** * Combines together header and body of table * @param {object} header - table header, collapsable div * @param {object} body - table body, html tables with report */ createCard(header, body) { var card = $('<div class="card"></div>'); card.append(header, body); return card; } /** * Creates table header - collapsable div * @param {object} table - table as json data * @returns {object} table header - collapsable div */ createHeader(table) { return `<div class="card-header" id="headingOne"> <h5 class="mb-0"> <div class ="btn btn-link collapsed table-header-btn" data-toggle="collapse" data-target="#collapse${table.name}" aria-expanded="true" aria-controls="collapse${table.name}"> <div> Table name: <span class="table-header-name">${table.name}</span> </div> <div class="table-header-numbers-container"> <div> Number of columns: <span class="table-header-numbers">${table.columns.length}</span> </div> <div> Number of records: <span class="table-header-numbers">${table.records}</span> </div> </div> </div> </h5> </div>`; } /** * Creates table body - html tables (column sorted by type) with report data * @param {Array<object>} columns - table columns as json data * @returns {object} table body - html table with report data */ createBody(columns) { var cardBody = $(`<div class="card-body"></div>`); var numericColumns = columns.filter((column) => column.type === 'numeric'); var characterColumns = columns.filter((column) => column.type === 'character'); var dateColumns = columns.filter((column) => column.type === 'datetime'); var otherColumns = columns.filter((column) => ['numeric', 'character', 'datetime'].indexOf(column.type) < 0 ); cardBody.append(this.createColumns(numericColumns, 'Numeric columns'), this.createColumns(characterColumns, 'Character columns'), this.createColumns(dateColumns, 'Datetime columns'), this.createColumns(otherColumns, 'Other columns')) return cardBody; } /** * Creates report for columns of specific type (numeric, character, date or other) * @param {Array<object>} columns - table columns of specific type as json data * @param {string} header - header for table with typed columns report * @returns {object} table body - html div with report */ createColumns(columns, header) { if(columns.length == 0) { return; } var notEmpty = false; var thead = this.createColumnTableHeader(columns[0], header); var tbody = $('<tbody></tbody>'); columns.forEach(column => { if(this.showColumn(column)) { tbody.append(this.createColumnRow(column)); notEmpty = true; } }) if(!notEmpty) { return; } var table = $('<table class="table table-striped"></table>').append(thead, tbody); var header = $(`<h5 class="normal-text"><div class="icon ${header.toLowerCase()}"></div>${header}</h5>`); return $('<div class="column-table"></div>').append(header, table); } /** * Creates data header for columns table report * @param {object} column - any column (as json data) of specific type * @returns {object} thead with data headers */ createColumnTableHeader(column, header) { var row = $('<tr></tr>'); column.data.forEach(function (data) { row.append(`<th>${data.key}</th>`); }); return $(`<thead class="thead-dark-${header.toLowerCase()}"></thead>`).append(row); } /** * Checks whether the column should be shown * @param {object} column - column as json data * @returns {boolean} if the column should be shown */ showColumn(column) { var showOnlyMatching = this.controls.input.searchType.val() === "column" && this.controls.input.matchingColumns.is(':checked'); return !showOnlyMatching || this.getColumnName(column).toLowerCase().indexOf(controls.input.searchValue.val()) >= 0; } /** * Creates report table row for column * @param {object} column - column as json data * @returns {object} html row with column data */ createColumnRow(column) { var row = $('<tr></tr>'); column.data.forEach(data => { var cssClass = this.getClass(data); var value = data.value instanceof Array ? data.value.map(this.nullToString).join('</br>') : this.nullToString(data.value); row.append(`<td class=${cssClass}>${value}</td>`); }); return row; } /** * Collapsable wrapper for table report body * @param {string} tableName - table name * @returns {object} html div which is a wrapper for report body */ createCollapseWrapper(tableName) { return $(`<div id="collapse${tableName}" class="collapse" aria-labelledby="heading${tableName}" data-parent="#output-results"></div>`); } /** * Helper method. Change null to string 'null' * @param {object} value * @returns {object} string 'null' if value is null, value otherwise */ nullToString(value) { return value == null ? "null" : value; } /** * Gets (creates if non existing) column name * @param {object} column - column as json data * @return {string} - column name */ getColumnName(column) { if (!column.name) { column.name = column.data.find(data => data.key == 'Name').value; } return column.name; } /** * Gets styles for data * @param {object} data - key value data * @return {string} - css class name */ getClass(data) { if (data.key === "Empty") { var value = parseInt(data.value); if (value < 10) { return 'good'; } else if (value >= 50) { return 'bad'; } else { return 'mediocer'; } } return ''; } }
JavaScript
class ZoneMacroTaskWrapper { /** * @param {?} request * @return {?} */ wrap(request) { return new Observable((observer) => { /** @type {?} */ let task = (/** @type {?} */ (null)); /** @type {?} */ let scheduled = false; /** @type {?} */ let sub = null; /** @type {?} */ let savedResult = null; /** @type {?} */ let savedError = null; /** @type {?} */ const scheduleTask = (_task) => { task = _task; scheduled = true; /** @type {?} */ const delegate = this.delegate(request); sub = delegate.subscribe(res => savedResult = res, err => { if (!scheduled) { throw new Error('An http observable was completed twice. This shouldn\'t happen, please file a bug.'); } savedError = err; scheduled = false; task.invoke(); }, () => { if (!scheduled) { throw new Error('An http observable was completed twice. This shouldn\'t happen, please file a bug.'); } scheduled = false; task.invoke(); }); }; /** @type {?} */ const cancelTask = (_task) => { if (!scheduled) { return; } scheduled = false; if (sub) { sub.unsubscribe(); sub = null; } }; /** @type {?} */ const onComplete = () => { if (savedError !== null) { observer.error(savedError); } else { observer.next(savedResult); observer.complete(); } }; // MockBackend for Http is synchronous, which means that if scheduleTask is by // scheduleMacroTask, the request will hit MockBackend and the response will be // sent, causing task.invoke() to be called. /** @type {?} */ const _task = Zone.current.scheduleMacroTask('ZoneMacroTaskWrapper.subscribe', onComplete, {}, () => null, cancelTask); scheduleTask(_task); return () => { if (scheduled && task) { task.zone.cancelTask(task); scheduled = false; } if (sub) { sub.unsubscribe(); sub = null; } }; }); } }
JavaScript
class NgQName extends NgClass{ constructor(uri, localName) { super(NgQName); this.className = 'NgQName'; this.uri = uri; this.localName = localName; } }
JavaScript
class Task extends Component { constructor(props) { super(props); this.state = { title: props.title }; this.onTitleChange = this.onTitleChange.bind(this); } onTitleChange(event) { // lifting up state this.props.onTitleChange(this.props.id, event.target.value); event.preventDefault(); } componentDidMount() { // focus input after rendering // keep a dom reference using ref this.titleInput.focus(); } render() { return ( <div className="task"> <div className="task__input" > <input type="text" defaultValue={this.props.title} ref={(input) => { this.titleInput = input; }} onChange={this.onTitleChange} /> </div> <div className="task__delete" > <DeleteButton id={this.props.id} onTaskDelete={this.props.onTaskDelete} /> </div> </div> ); } }
JavaScript
class ModelVisitor { /** * Visitor design pattern * @param {Object} thing - the object being visited * @param {Object} parameters - the parameter * @return {Object} the result of visiting or null * @private */ visit(thing, parameters) { if (thing instanceof EnumDeclaration) { return this.visitEnumDeclaration(thing, parameters); } else if (thing instanceof ClassDeclaration) { return this.visitClassDeclaration(thing, parameters); } else if (thing instanceof Field) { return this.visitField(thing, parameters); } else if (thing instanceof RelationshipDeclaration) { return this.visitRelationshipDeclaration(thing, parameters); } else if (thing instanceof EnumValueDeclaration) { return this.visitEnumValueDeclaration(thing, parameters); } else { throw new Error('Unrecognised type: ' + typeof thing + ', value: ' + util.inspect(thing, { showHidden: true, depth: 1 })); } } /** * Visitor design pattern * @param {EnumDeclaration} enumDeclaration - the object being visited * @param {Object} parameters - the parameter * @return {Object} the result of visiting or null * @private */ visitEnumDeclaration(enumDeclaration, parameters) { let result = {}; result.$class = NS_PREFIX_TemplateMarkModel + 'EnumVariableDefinition'; result.name = parameters.type; return result; } /** * Visitor design pattern * @param {ClassDeclaration} classDeclaration - the object being visited * @param {Object} parameters - the parameter * @return {Object} the result of visiting or null * @private */ visitClassDeclaration(classDeclaration, parameters) { let result = {}; result.$class = NS_PREFIX_TemplateMarkModel + 'WithDefinition'; result.name = parameters.name; result.nodes = []; let first = true; classDeclaration.getProperties().forEach((property,index) => { if (!first) { let textNode = {}; textNode.$class = NS_PREFIX_CommonMarkModel + 'Text'; textNode.text = ' '; result.nodes.push(textNode); } result.nodes.push(property.accept(this, parameters)); first = false; }); return result; } /** * Visitor design pattern * @param {Field} field - the object being visited * @param {Object} parameters - the parameter * @return {Object} the result of visiting or null * @private */ visitField(field, parameters) { const fieldName = field.getName(); let result = {}; result.$class = NS_PREFIX_TemplateMarkModel + 'VariableDefinition'; result.name = fieldName; if(field.isArray()) { if (field.isPrimitive()) { result.name = 'this'; } const arrayResult = {}; arrayResult.$class = NS_PREFIX_TemplateMarkModel + 'JoinDefinition'; arrayResult.separator = ' '; // XXX {{#join }} arrayResult.name = fieldName; arrayResult.nodes = [result]; result = arrayResult; } if(field.isOptional()) { if (field.isPrimitive()) { result.name = 'this'; } const optionalResult = {}; optionalResult.$class = NS_PREFIX_TemplateMarkModel + 'OptionalDefinition'; optionalResult.name = fieldName; optionalResult.whenSome = [result]; optionalResult.whenNone = []; result = optionalResult; } return result; } /** * Visitor design pattern * @param {EnumValueDeclaration} enumValueDeclaration - the object being visited * @param {Object} parameters - the parameter * @return {Object} the result of visiting or null * @private */ visitEnumValueDeclaration(enumValueDeclaration, parameters) { throw new Error('visitEnumValueDeclaration not handled'); } /** * Visitor design pattern * @param {Relationship} relationship - the object being visited * @param {Object} parameters - the parameter * @return {Object} the result of visiting or null * @private */ visitRelationshipDeclaration(relationship, parameters) { throw new Error('visitRelationshipDeclaration'); } }
JavaScript
class Heap { constructor(comparatorFunction) { if (new.target === Heap) { throw new TypeError('Cannot construct Heap instance directly'); } this.heapContainer = []; this.compare = new Comparator(comparatorFunction); } peek() { const topNode = this.heapContainer[0]; return topNode || null; } getParentIndex(index) { return Math.floor((index - 1) / 2); } getParent(index) { return this.heapContainer[this.getParentIndex(index)]; } hasParent(index) { return this.getParentIndex(index) >= 0; } getLeftChildIndex(index) { return (index * 2) + 1; } getLeftChild(index) { return this.heapContainer[this.getLeftChildIndex(index)]; } hasLeftChild(index) { return this.getLeftChildIndex(index) < this.heapContainer.length; } getRightChildIndex(index) { return (index * 2) + 2; } getRightChild(index) { return this.heapContainer[this.getRightChildIndex(index)]; } hasRightChild(index) { return this.getRightChildIndex(index) < this.heapContainer.length; } swap(indexOne, indexTwo) { const temp = this.heapContainer[indexOne]; this.heapContainer[indexOne] = this.heapContainer[indexTwo]; this.heapContainer[indexTwo] = temp; } heapUp(startIndex) { let index = startIndex || this.heapContainer.length - 1; while ( this.hasParent(index) && this.pairIsInCorrectOrder(this.heapContainer[index], this.getParent(index)) ) { const parentIndex = this.getParentIndex(index); this.swap(parentIndex, index); index = parentIndex; } } poll() { if (this.heapContainer.length === 0) { return null; } if (this.heapContainer.length === 1) { return this.heapContainer.pop(); } const item = this.heapContainer[0]; // Move the last element from the end to the head. this.heapContainer[0] = this.heapContainer.pop(); this.heapDown(); return item; } heapDown(customStartIndex = 0) { // Compare the parent element to its children and swap parent with the appropriate // child (smallest child for MinHeap, largest child for MaxHeap). // Do the same for next children after swap. let currentIndex = customStartIndex; let nextIndex = null; while (this.hasLeftChild(currentIndex)) { if ( this.hasRightChild(currentIndex) && this.pairIsInCorrectOrder( this.getRightChild(currentIndex), this.getLeftChild(currentIndex), ) ) { nextIndex = this.getRightChildIndex(currentIndex); } else { nextIndex = this.getLeftChildIndex(currentIndex); } if (this.pairIsInCorrectOrder( this.heapContainer[currentIndex], this.heapContainer[nextIndex], )) { break; } this.swap(currentIndex, nextIndex); currentIndex = nextIndex; } } add(val) { this.heapContainer.push(val); this.heapUp(); } isEmpty() { return this.heapContainer.length === 0; } toString() { return this.heapContainer.join(','); } find(val, customCompare) { const arr = []; this.heapContainer.forEach((v, i) => { if (customCompare) { if (customCompare.equal(v, val)) { arr.push(i); } } else { if (v === val) { arr.push(i); } } }); return arr; } pairIsInCorrectOrder(firstElement, secondElement) { throw new Error(` You have to implement heap pair comparision method for ${firstElement} and ${secondElement} values. `); } remove(val, customCompare) { const itemsToRemove = this.find(val, customCompare).length; for (let itteration = 0; itteration < itemsToRemove; itteration += 1) { const indexToRemove = this.find(val, customCompare).pop(); if (indexToRemove === this.heapContainer.length - 1) { this.heapContainer.pop(); } else { this.heapContainer[indexToRemove] = this.heapContainer.pop(); this.heapDown(indexToRemove); } } return this; } }
JavaScript
class AnnounceService { constructor (network, minlt) { // network parameters (regtest/testnet/mainnet) this.network = network // mininum locktime value this.minlt = minlt } /* Validate that the redeem script contains the public keys given and match the format exepected */ validate (pubkey, redeemScript) { const cltv = CLTVScript.fromHex(redeemScript) if (cltv.payeePubkey !== pubkey) { throw new OurKeyNotInMultisigError() } // TODO: make this relative to the current block... // ... this will probably make this function async if (cltv.locktime < this.minlt) { throw new BadLocktimeError(this.minlt) } } saveDB (redeemScript, transaction, signature) { const p2sh = createPayToHash(redeemScript) const address = pubkeyToAddress(p2sh.hashScript, this.network.scriptHash, true) const transactions = [{ timestamp: Date.now(), tx: transaction.toString('hex'), signature: signature.toString('hex'), ref: 0 }] return db.savePaymentChannel(address, { redeemScript: redeemScript.toString('hex'), utxo: null, transactions, state: PaymentChannelState.Announced }) } }
JavaScript
class SvgCodeLoader extends SvgContentLoader { /** @var {Number} */ @bindable maxCodeChunks = 3; /** * Attached Event */ attached(...args) { super.attached && super.attached(...args); let clipPath = this.element.querySelector('clipPath'); let rects = Array.prototype.slice.call(this.element.querySelectorAll('clipPath > rect')); clipPath.innerHTML = rects.map(rect => rect.innerHTML).join(''); this.addClass('svg-loader__inner--code'); } /** * https://stackoverflow.com/questions/8495687/split-array-into-chunks * @return {Array{Array}} */ codeRanges() { return this.lineRange.map(() => { let chunkNr = Math.ceil(Math.random() * 5); let chunkRange = this.arrayRangeFromNumber(chunkNr) .map(() => Math.ceil(Math.random() * this.width)) .sort((a, b) => a - b); return chunkRange.map((value, i) => { if (i > 0) { let length = value - chunkRange[i - 1] - this.lineHeight; return { start: chunkRange[i - 1] + this.lineHeight, length: length > 0 ? length : 0 }; } return { start: 0, length: value }; }); }); } }
JavaScript
class StdLib { /** * StdLib() * * @this {StdLib} */ constructor() { this.stdio = new StdIO(); [this.argc, this.argv] = this.parseArgs(process.argv); } /** * getArgs(s) * * @this {StdLib} * @param {string} [s] * @returns {Array} [argc, argv] */ getArgs(s) { if (s) { let args = s.split(' '); return this.parseArgs(args, 0); } return [this.argc, this.argv]; } /** * parseArgs(args, i) * * Any argument value preceded by a double-hyphen or long-dash switch (eg, "--option value") is * saved in argv with the switch as the key (eg, argv["option"] == "value"). * * If there are multiple arguments preceded by the same double-hyphen switch, then the argv entry * becomes an array (eg, argv["option"] == ["value1","value2"]). * * If a double-hyphen switch is followed by another switch (or by nothing, if it's the last argument), * then the value of the switch will be a boolean instead of a string (eg, argv["option"] == true). * * Single-hyphen switches are different: every character following a single hyphen is transformed into * a boolean value (eg, "-abc" produces argv["a"] == true, argv["b"] == true, and argv["c"] == true). * * Only arguments NOT preceded by (or part of) a switch are pushed onto the argv array; they can be * accessed as argv[i], argv[i+1], etc. * * In addition, when the initial i >= 1, then argv[0] is set to the concatenation of all args, starting * with args[i], and the first non-switch argument begins at argv[1]. * * @this {StdLib} * @param {Array.<string>} [args] * @param {number} [i] (default is 1, because if you're passing process.argv, process.argv[0] is useless) * @returns {Array} [argc, argv] */ parseArgs(args, i = 1) { let argc = 0; let argv = []; if (i) argv.push(args.slice(i++).join(' ')); while (i < args.length) { let j, sSep; let sArg = args[i++]; if (!sArg.indexOf(sSep = "--") || !sArg.indexOf(sSep = "—")) { sArg = sArg.substr(sSep.length); let sValue = true; j = sArg.indexOf("="); if (j > 0) { sValue = sArg.substr(j + 1); sArg = sArg.substr(0, j); sValue = (sValue == "true") ? true : ((sValue == "false") ? false : sValue); } else if (i < args.length && args[i][0] != '-') { sValue = args[i++]; } if (!argv.hasOwnProperty(sArg)) { argv[sArg] = sValue; } else { if (!Array.isArray(argv[sArg])) { argv[sArg] = [argv[sArg]]; } argv[sArg].push(sValue); } continue; } if (!sArg.indexOf("-")) { for (j = 1; j < sArg.length; j++) { let ch = sArg.charAt(j); if (argv[ch] === undefined) { argv[ch] = true; } } continue; } argv.push(sArg); } argc = argv.length; return [argc, argv]; } /** * printf(format, ...args) * * @this {StdLib} * @param {string} format * @param {...} args */ printf(format, ...args) { process.stdout.write(this.stdio.sprintf(format, ...args)); } }
JavaScript
class ManualRowMove extends BasePlugin { constructor(hotInstance) { super(hotInstance); privatePool.set(this, { guideClassName: 'manualRowMoverGuide', handleClassName: 'manualRowMover', startOffset: null, pressed: null, startRow: null, endRow: null, currentRow: null, startX: null, startY: null }); /** * DOM element representing the horizontal guide line. * * @type {HTMLElement} */ this.guideElement = null; /** * DOM element representing the move handle. * * @type {HTMLElement} */ this.handleElement = null; /** * Currently processed TH element. * * @type {HTMLElement} */ this.currentTH = null; /** * Manual column positions array. * * @type {Array} */ this.rowPositions = []; /** * Event Manager object. * * @type {Object} */ this.eventManager = eventManagerObject(this); } /** * Check if plugin is enabled. * * @returns {boolean} */ isEnabled() { return !!this.hot.getSettings().manualRowMove; } /** * Enable the plugin. */ enablePlugin() { let priv = privatePool.get(this); let initialSettings = this.hot.getSettings().manualRowMove; let loadedManualRowPositions = this.loadManualRowPositions(); this.handleElement = document.createElement('DIV'); this.handleElement.className = priv.handleClassName; this.guideElement = document.createElement('DIV'); this.guideElement.className = priv.guideClassName; this.addHook('modifyRow', (row) => this.onModifyRow(row)); this.addHook('afterRemoveRow', (index, amount) => this.onAfterRemoveRow(index, amount)); this.addHook('afterCreateRow', (index, amount) => this.onAfterCreateRow(index, amount)); this.addHook('init', () => this.onInit()); this.registerEvents(); if (typeof loadedManualRowPositions != 'undefined') { this.rowPositions = loadedManualRowPositions; } else if (Array.isArray(initialSettings)) { this.rowPositions = initialSettings; } else if (!initialSettings || this.rowPositions === void 0) { this.rowPositions = []; } super.enablePlugin(); } /** * Update the plugin. */ updatePlugin() { this.disablePlugin(); this.enablePlugin(); super.updatePlugin(); } /** * Disable the plugin. */ disablePlugin() { let pluginSetting = this.hot.getSettings().manualRowMove; if (Array.isArray(pluginSetting)) { this.unregisterEvents(); this.rowPositions = []; } super.disablePlugin(); } /** * Bind the events used by the plugin. * * @private */ registerEvents() { this.eventManager.addEventListener(this.hot.rootElement, 'mouseover', (event) => this.onMouseOver(event)); this.eventManager.addEventListener(this.hot.rootElement, 'mousedown', (event) => this.onMouseDown(event)); this.eventManager.addEventListener(window, 'mousemove', (event) => this.onMouseMove(event)); this.eventManager.addEventListener(window, 'mouseup', (event) => this.onMouseUp(event)); } /** * Unbind the events used by the plugin. * * @private */ unregisterEvents() { this.eventManager.clear(); } /** * Save the manual row positions. */ saveManualRowPositions() { Handsontable.hooks.run(this.hot, 'persistentStateSave', 'manualRowPositions', this.rowPositions); } /** * Load the manual row positions. * * @returns {Object} Stored state. */ loadManualRowPositions() { let storedState = {}; Handsontable.hooks.run(this.hot, 'persistentStateLoad', 'manualRowPositions', storedState); return storedState.value; } /** * Complete the manual column positions array to match its length to the column count. */ completeSettingsArray() { let rowCount = this.hot.countRows(); if (this.rowPositions.length === rowCount) { return; } rangeEach(0, rowCount - 1, (i) => { if (this.rowPositions.indexOf(i) === -1) { this.rowPositions.push(i); } }); } /** * Setup the moving handle position. * * @param {HTMLElement} TH Currently processed TH element. */ setupHandlePosition(TH) { let priv = privatePool.get(this); let row = this.hot.view.wt.wtTable.getCoords(TH).row; // getCoords returns WalkontableCellCoords this.currentTH = TH; if (row >= 0) { // if not row header let box = this.currentTH.getBoundingClientRect(); priv.currentRow = row; priv.startOffset = box.top; this.handleElement.style.top = priv.startOffset + 'px'; this.handleElement.style.left = box.left + 'px'; this.hot.rootElement.appendChild(this.handleElement); } } /** * Refresh the moving handle position. * * @param {HTMLElement} TH TH element with the handle. * @param {Number} delta Difference between the related rows. */ refreshHandlePosition(TH, delta) { let box = TH.getBoundingClientRect(); let handleHeight = 6; if (delta > 0) { this.handleElement.style.top = (box.top + box.height - handleHeight) + 'px'; } else { this.handleElement.style.top = box.top + 'px'; } } /** * Setup the moving handle position. */ setupGuidePosition() { let box = this.currentTH.getBoundingClientRect(); let priv = privatePool.get(this); addClass(this.handleElement, 'active'); addClass(this.guideElement, 'active'); this.guideElement.style.height = box.height + 'px'; this.guideElement.style.width = this.hot.view.maximumVisibleElementWidth(0) + 'px'; this.guideElement.style.top = priv.startOffset + 'px'; this.guideElement.style.left = this.handleElement.style.left; this.hot.rootElement.appendChild(this.guideElement); } /** * Refresh the moving guide position. * * @param {Number} diff Difference between the starting and current cursor position. */ refreshGuidePosition(diff) { let priv = privatePool.get(this); this.guideElement.style.top = priv.startOffset + diff + 'px'; } /** * Hide both the moving handle and the moving guide. */ hideHandleAndGuide() { removeClass(this.handleElement, 'active'); removeClass(this.guideElement, 'active'); } /** * Check if the provided element is in the row header. * * @param {HTMLElement} element The DOM element to be checked. * @returns {Boolean} */ checkRowHeader(element) { if (element != this.hot.rootElement) { let parent = element.parentNode; if (parent.tagName === 'TBODY') { return true; } return this.checkRowHeader(parent); } return false; } /** * Create the initial row position data. * * @param {Number} len The desired length of the array. */ createPositionData(len) { let positionArr = this.rowPositions; if (positionArr.length < len) { rangeEach(positionArr.length, len - 1, (i) => { positionArr[i] = i; }); } } /** * Get the TH parent element from the provided DOM element. * * @param {HTMLElement} element The DOM element to work on. * @returns {HTMLElement|null} The TH element or null, if element has no TH parents. */ getTHFromTargetElement(element) { if (element.tagName != 'TABLE') { if (element.tagName == 'TH') { return element; } else { return this.getTHFromTargetElement(element.parentNode); } } return null; } /** * Change the row position. It puts the `rowIndex` row after the `destinationIndex` row. * * @param {Number} rowIndex Index of the row to move. * @param {Number} destinationIndex Index of the destination row. */ changeRowPositions(rowIndex, destinationIndex) { let maxLength = Math.max(rowIndex, destinationIndex); if (maxLength > this.rowPositions.length - 1) { this.createPositionData(maxLength + 1); } this.rowPositions.splice(destinationIndex, 0, this.rowPositions.splice(rowIndex, 1)[0]); } /** * Get the visible row index from the provided logical index. * * @param {Number} row Logical row index. * @returns {Number} Visible row index. */ getVisibleRowIndex(row) { if (row > this.rowPositions.length - 1) { this.createPositionData(row); } return this.rowPositions.indexOf(row); } /** * Get the logical row index from the provided visible index. * * @param {Number} row Visible row index. * @returns {Number|undefined} Logical row index. */ getLogicalRowIndex(row) { return this.rowPositions[row]; } /** * 'mouseover' event callback. * * @private * @param {MouseEvent} event The event object. */ onMouseOver(event) { let priv = privatePool.get(this); if (this.checkRowHeader(event.target)) { let th = this.getTHFromTargetElement(event.target); if (th) { if (priv.pressed) { priv.endRow = this.hot.view.wt.wtTable.getCoords(th).row; this.refreshHandlePosition(th, priv.endRow - priv.startRow); } else { this.setupHandlePosition(th); } } } } /** * 'mousedown' event callback. * * @private * @param {MouseEvent} event The event object. */ onMouseDown(event) { let priv = privatePool.get(this); if (hasClass(event.target, priv.handleClassName)) { priv.startY = pageY(event); this.setupGuidePosition(); priv.pressed = this.hot; priv.startRow = priv.currentRow; priv.endRow = priv.currentRow; } } /** * 'mousemove' event callback. * * @private * @param {MouseEvent} event The event object. */ onMouseMove(event) { let priv = privatePool.get(this); if (priv.pressed) { this.refreshGuidePosition(pageY(event) - priv.startY); } } /** * 'mouseup' event callback. * * @private * @param {MouseEvent} event The event object. */ onMouseUp(event) { let priv = privatePool.get(this); if (priv.pressed) { this.hideHandleAndGuide(); priv.pressed = false; this.createPositionData(this.hot.countRows()); this.changeRowPositions(priv.startRow, priv.endRow); Handsontable.hooks.run(this.hot, 'beforeRowMove', priv.startRow, priv.endRow); this.hot.forceFullRender = true; this.hot.view.render(); // updates all this.saveManualRowPositions(); Handsontable.hooks.run(this.hot, 'afterRowMove', priv.startRow, priv.endRow); this.setupHandlePosition(this.currentTH); } } /** * 'modifyRow' hook callback. * * @private * @param {Number} row Row index. * @returns {Number} Modified row index. */ onModifyRow(row) { if (typeof this.getVisibleRowIndex(row) === 'undefined') { this.createPositionData(row + 1); } return this.getLogicalRowIndex(row); } /** * `afterRemoveRow` hook callback. * * @private * @param {Number} index Index of the removed row. * @param {Number} amount Amount of removed rows. */ onAfterRemoveRow(index, amount) { if (!this.isEnabled()) { return; } let rmindx; let rowpos = this.rowPositions; // We have removed rows, we also need to remove the indicies from manual row array rmindx = rowpos.splice(index, amount); // We need to remap rowPositions so it remains constant linear from 0->nrows rowpos = arrayMap(rowpos, function(value, index) { let newpos = value; arrayEach(rmindx, (elem, index) => { if (value > elem) { newpos--; } }); return newpos; }); this.rowPositions = rowpos; } /** * `afterCreateRow` hook callback. * * @private * @param {Number} index Index of the created row. * @param {Number} amount Amount of created rows. */ onAfterCreateRow(index, amount) { if (!this.isEnabled()) { return; } let rowpos = this.rowPositions; if (!rowpos.length) { return; } let addindx = []; for (var i = 0; i < amount; i++) { addindx.push(index + i); } if (index >= rowpos.length) { rowpos.concat(addindx); } else { // We need to remap rowPositions so it remains constant linear from 0->nrows rowpos = arrayMap(rowpos, function(value, ind) { return (value >= index) ? (value + amount) : value; }); // We have added rows, we also need to add new indicies to manualrow position array rowpos.splice.apply(rowpos, [index, 0].concat(addindx)); } this.rowPositions = rowpos; } /** * `init` hook callback. */ onInit() { this.completeSettingsArray(); } }
JavaScript
class BaseResource { constructor (args) { this._p = args this._Client = Client this._Interface = Interface } static Interface = Interface static Client = Client static GlobalStatus = Global /** * In child class you need to * override these static vars */ static Kind = null static IsReplicated = false static IsZoned = true static IsWorkspaced = false /** * Public */ static async GetEvent (args, asTable = false) { try { let res = await Interface.GetEvents({ zone: args.zone, resource_kind: args.kind.toLowerCase(), resource_id: args.resource_id }) if (res.err !== null) { return res } return {err: null, data: res} } catch (err) { return {err: true, data: err} } } static async WriteEvent (args, asTable = false) { try { let res = await Interface.WriteEvent(args) if (res.err !== null) { return res } } catch (err) { return {err: true, data: err} } } static async DeleteEvents (args, asTable = false) { try { let res = await Interface.DeleteEvents(args) if (res.err !== null) { return res } } catch (err) { return {err: true, data: err} } } static async GetVersion (args, asTable = false) { try { let res = await Interface.GetVersions({ zone: args.zone, resource_kind: args.kind.toLowerCase(), resource_id: args.resource_id }) if (res.err !== null) { return res } return {err: null, data: res} } catch (err) { return {err: true, data: err} } } static async WriteVersion (args) { try { let res = await Interface.WriteVersion(args) if (res.err !== null) { return res } } catch (err) { return {err: true, data: err} } } static async Get (args, asTable = false, Class) { try { let res = await Interface.Read(this.Kind, this._PartitionKeyFromArgsForRead(args)) if (res.err !== null) { return res } res = this._Parse(res.data) if (asTable === true) { return {err: null, data: await this._Format(res)} } return {err: null, data: res} } catch (err) { return {err: true, data: err} } } static async GetOne (args, asTable = false) { try { let res = await Interface.Read(this.Kind, this._PartitionKeyFromArgsForRead(args)) if (res.err !== null) { return res } res = this._Parse(res.data) if (asTable === true) { return {err: null, data: await this._Format(res)} } return {err: null, data: res} } catch (err) { return {err: err, data: err} } } /** * Properties * accessor */ id () { return this._p.id } name () { return this._p.name } workspace () { return this._p.workspace } zone () { return this._p.zone } desired () { return this._p.desired } resource () { return this._p.resource } resource_hash () { return this._p.resource_hash } computed () { return (this._p.computed == undefined || this._p.computed == null) ? { } : this._p.computed } observed () { return (this._p.observed == undefined || this._p.observed == null) ? { } : this._p.observed } async save () { try { this._p.insdate = (new Date()).toISOString() let res = await Interface.Create(this.constructor.Kind, this.constructor._DumpOne(this._p)) return {err: null, data: res.data} } catch (err) { return {err: true, data: err} } } async updateDesired () { try { let res = await Interface.Update(this.constructor.Kind, this.constructor._PartitionKeyFromArgs(this._p), 'desired', this._p.desired) return {err: null, data: res.data} } catch (err) { return {err: true, data: err} } } async updateObserved () { try { let res = await Interface.Update(this.constructor.Kind, this.constructor._PartitionKeyFromArgs(this._p), 'observed', this.constructor._DumpOneField(this._p.observed)) return {err: null, data: res.data} } catch (err) { return {err: true, data: err} } } async updateComputed () { try { let res = await Interface.Update(this.constructor.Kind, this.constructor._PartitionKeyFromArgs(this._p), 'computed', this.constructor._DumpOneField(this._p.computed)) return {err: null, data: res.data} } catch (err) { return {err: true, data: err} } } async updateResource () { try { let res = await Interface.Update(this.constructor.Kind, this.constructor._PartitionKeyFromArgs(this._p), 'resource', this.constructor._DumpOneField(this._p.resource)) return {err: null, data: res.data} } catch (err) { return {err: true, data: err} } } async updateMeta () { try { let res = await Interface.Update(this.constructor.Kind, this.constructor._PartitionKeyFromArgs(this._p), 'meta', this.constructor._DumpOneField(this._p.meta)) return {err: null, data: res.data} } catch (err) { return {err: true, data: err} } } async updateResourceHash () { try { let res = await Interface.Update(this.constructor.Kind, this.constructor._PartitionKeyFromArgs(this._p), 'resource_hash', this.constructor._ComputeResourceHash(this._p.resource)) return {err: null, data: res.data} } catch (err) { return {err: true, data: err} } } async updateKey (key, value) { try { let res = await Interface.Update(this.constructor.Kind, this.constructor._PartitionKeyFromArgs(this._p), key, value) return {err: null, data: res.data} } catch (err) { return {err: true, data: err} } } async apply () { this._p.desired = 'run' return await this.save() } /** * Must override for everything * in order to drain cascade related * resources */ async drain (Class) { this._p.desired = 'drain' return await this.updateDesired() } /** * Set internal _p status */ set (key, value) { this._p[key] = value } properties () { return this.constructor._ParseOne(this._p) } /** * Internal */ $validate (checks) { const check = checks.filter((c) => { return c.result == false }).map((c) => { return c.desc }) if (check.length !== 0) { return {err: true, data: check} } else { return {err: null, data: check} } } // To override (calling super before) // for each resource kind // // You need to call this after // calling translate $check () { // Check base fields let checkAry = [] this._check(checkAry, check.not.equal(this._p.kind, null), 'Resource kind must not be null') this._check(checkAry, check.not.equal(this._p.kind, undefined), 'Resource kind must not be undefined') this._check(checkAry, check.equal(this._p.kind.toLowerCase(), this.constructor.Kind.toLowerCase()), 'Resource kind is of the right type') this._check(checkAry, check.not.equal(this._p.name, null), 'Resource name must not be null') this._check(checkAry, check.not.equal(this._p.name, undefined), 'Resource name must not be undefined') return checkAry } async $checkDependencies () { let checkAry = [] return {err: null, data: checkAry} } static $Translate (apiVersion, src) { let toReturn = null switch (apiVersion) { case 'v1': toReturn = v1.translate(src) break default: toReturn = src } return toReturn } async $delete () { try { let res = await Interface.Delete(this.constructor.Kind, this.constructor._PartitionKeyFromArgs(this._p)) return {err: null, data: res.data} } catch (err) { return {err: true, data: err} } } async $exist () { try { let res = await this.constructor.GetOne(this._p) if (res.data.length == 1) { return {err: null, data: {exist: true, data: this.constructor._ParseOne(res.data[0])}} } else if (res.data.length == 0) { return {err: null, data: {exist: false, data: null}} } else { return {err: true, data: {exist: false, data: 'More than one result'}} } } catch (err) { return {err: true, data: err} } } async $load(ClassKind) { try { let res = await this.constructor.GetOne(this._p) if (res.data.length == 1) { //return {err: null, data: {exist: true, data: this.constructor._ParseOne(res.data[0])}} return new ClassKind(this.constructor._ParseOne(res.data[0])) } else { throw 'Cannot load container' } } catch (err) { throw err } } /** * Private */ async _checkOneDependency (kind, args) { try { let res = await Interface.Read(kind, args) if (res.err == null) { return res.data } else { return null } } catch (err) { return null } } // To override for each class type static _PartitionKeyFromArgs (args) { let pargs = {} pargs.kind = args.kind || this.Kind.toLowerCase() if (args.name !== undefined) { pargs.name = args.name } return pargs } // To override for each class type static _PartitionKeyFromArgsForRead (args) { let pargs = {} pargs.kind = args.kind || this.Kind.toLowerCase() if (args.name !== undefined) { pargs.name = args.name } return pargs } static async _Format (data) { let formattedData = [] for (var i = 0; i < data.length; i += 1) { formattedData.push(await this._FormatOne(data[i])) } return formattedData } _format () { } static async _FormatOne (data) { return { kind: data.kind, name: data.name, desired: data.desired } } _formatOne () { } static _Parse (data) { return data.map((d) => { return this._ParseOne(d) }) } static _ParseOne (d) { let parsed try { parsed = d parsed.resource = JSON.parse(parsed.resource) parsed.observed = JSON.parse(parsed.observed) parsed.computed = JSON.parse(parsed.computed) parsed.meta = JSON.parse(parsed.meta) return d } catch (err) { return parsed } } static _DumpOne (d) { let parsed try { parsed = d parsed.observed = JSON.stringify(parsed.observed) parsed.computed = JSON.stringify(parsed.computed) parsed.meta = JSON.stringify(parsed.meta) if (parsed.resource !== undefined) { parsed.resource_hash = this._ComputeResourceHash(parsed.resource) parsed.resource = JSON.stringify(parsed.resource) } if (!this.IsWorkspaced) { delete d.workspace } if (!this.IsZoned) { delete d.zone } return d } catch (err) { console.log('Base._DumpOne', err) return parsed } } static _DumpOneField (d) { try { return JSON.stringify(d) } catch (err) { return d } } // Can be overridden static _ComputeResourceHash (resource) { try { return md5(this._DumpOneField(resource)) } catch (err) { return d } } _check (checkAry, expr, checkDesc) { checkAry.push({result: expr, desc: checkDesc}) } }
JavaScript
class TodoList extends Component { constructor(props){ //当组件的 state 或者 props 发生变化时,会调取 render super(props); this.state = { list:[], inputValue:'' } this.handleInputChange = this.handleInputChange.bind(this); this.handleBtnClick = this.handleBtnClick.bind(this); this.handleDelete = this.handleDelete.bind(this); } componentDidMount() { // axios.get('/api/todolist') // .then(()=>{alert('success')}) // .catch(()=>{alert('failed')}) } //子通过 props 接受,父通过属性 render() { return ( <Fragment > <div > <label htmlFor="insertArea">输入内容</label> <input id= "insertArea" className='input' value={this.state.inputValue} onChange={this.handleInputChange} ref={(input) =>{this.input = input}} /> <button onClick={this.handleBtnClick}>add</button> </div> <ul>{this.getToDoItem()}</ul> {/*<Test content={this.state.inputValue}></Test>*/} </Fragment> ); } handleBtnClick(){ this.setState({ list:[...this.state.list,this.state.inputValue], inputValue:'' }) // this.state.list.push('hello word'); // alert('click'); } handleInputChange(){ const value = this.input.value; //es6的 return 简写 this.setState(()=>({ inputValue:value })); // this.setState(()=>{ // return { // inputValue:e.target.value // } // }) // this.setState({ // inputValue:e.target.value // }) } handleItemClick(index){ this.setState((prevState)=>({ list:[...prevState.list,prevState.inputValue], inputValue:'' })); // const list = [...this.state.list]; // list.splice(index,1); // this.setState({ // list // }) } handleDelete(index){ // const list = [...this.state.list]; this.setState((prevState)=>{ const list = [...prevState.list]; list.splice(index,1); return{ list} }); } getToDoItem(){ return this.state.list.map((item,index) => { // return <li key={index} onClick={this.handleItemClick.bind(this,index)}>{item}</li> return ( <TodoItem key={item } deleteM ={this.handleDelete} index={index} content ={item} /> ) }) } }
JavaScript
class LogAxExercise { constructor (term, exerciseType, properties) { this.type = exerciseType this.titleKey = properties.titleKey this.titleParams = properties.titleParams this.prefix = '[]' this.steps = new LogAxStepCollection(term.proof) this.lemmas = term.lemmas === undefined ? [] : term.lemmas const lastStep = this.steps.steps[this.steps.steps.length - 1] this.theorem = lastStep.term this.theoremKatex = lastStep.termKatex } getObject () { const object = { proof: this.steps.getObject(), lemmas: this.lemmas } return object } /** Gets the current/Last step of the exercise @return {LogAxStep} - The current/last step of the exercise */ getCurrentStep () { return this.steps.getCurrentStep() } /** Gets the previous step of the exercise (last but one) @return {LogAxStep} - The previous step of the exercise (last but one) */ getPreviousStep () { return this.steps.getPreviousStep() } }
JavaScript
class AddProcessDialog extends React.Component { static propTypes = { categories: PropTypes.array.isRequired, isOpen: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, isSubprocess: PropTypes.bool, visualizationPath: PropTypes.string.isRequired } initialState(props) { return {processId: '', processCategory: _.head(props.categories) || ''} } constructor(props) { super(props) this.state = this.initialState(props) } closeDialog = () => { this.setState(this.initialState(this.props)) this.props.onClose() } confirm = () => { const processId = this.state.processId HttpService.createProcess(this.state.processId, this.state.processCategory, this.props.isSubprocess).then((response) => { this.closeDialog() history.push(VisualizationUrl.visualizationUrl(processId)) }) } render() { const headerStyles = EspModalStyles.headerStyles("#2d8e54", "white") return ( <Modal isOpen={this.props.isOpen} className="espModal" shouldCloseOnOverlayClick={false} onRequestClose={this.closeDialog}> <div className="modalHeader" style={headerStyles}> <span>Create new process</span> </div> <div className="modalContentDark"> <div className="node-table"> <div className="node-table-body"> <div className="node-row"> <div className="node-label">Process id</div> <div className="node-value"><input type="text" id="newProcessId" className="node-input" value={this.state.processId} onChange={(e) => this.setState({processId: e.target.value})}/></div> </div> <div className="node-row"> <div className="node-label">Process category</div> <div className="node-value"> <select id="processCategory" className="node-input" onChange={(e) => this.setState({processCategory: e.target.value})}> {this.props.categories.map((cat, index) => (<option key={index} value={cat}>{cat}</option>))} </select> </div> </div> </div> </div> </div> <div className="modalFooter"> <div className="footerButtons"> <button type="button" title="Cancel" className='modalButton' onClick={this.closeDialog}>Cancel</button> <button type="button" title="Create" className='modalButton' onClick={this.confirm}>Create</button> </div> </div> </Modal> ); } }
JavaScript
class Badge extends PIXI.Sprite { constructor(badgeName) { super(PIXI.loader.resources[badgeName].texture); } pending() { const colorMatrix = new PIXI.filters.ColorMatrixFilter(); this.filters = [colorMatrix]; colorMatrix.desaturate(); } }
JavaScript
class RouteClient { /** * @param {RestClient} base * @param {string} route The relative route for this RouteClient */ constructor(base, route) { pv.present(arguments, 'base', 'route'); pv.require(this._base = base, 'base').isInstanceOf(Object); //.isInstanceOf(RestClient); pv.require(this._route = route, 'route').isString().isNotEmpty(); if (this._route.endsWith('/')) { this._route = this._route.substring(0, this._route.length - 1); } if (this._route.startsWith('/')) { this._route = this._route.substring(1); } } /** * The base RestClient * @returns {RestClient} */ get base() { return this._base; } set base(_) { throw new Error('base is read-only'); } /** * The relative route for this route client * @returns {string} */ get route() { return this._route; } set route(_) { throw new Error('route is read-only'); } /** * @returns {Loader} */ get loader() { return this._base._loader; } set loader(_) { throw new Error('loader is read-only'); } /** * Combines the relative route path of this RouteClient and the relative URI provided. * If uri starts with a forward slash, it is treated as an absolute uri relative to * the endpoint uri and is not combined with the route path * @param {...any} uri The relative URI parts * @returns {string} */ relativeUri(...uri) { if (uri == null || uri.length == 0) { // Base route return this._route; } let joined = uri.join('/'); if (joined.startsWith('/')) { // Absolute uri (relative to endpoint) return joined; } return this._route + '/' + joined; } getId(itemOrID) { if (itemOrID == null) return null; if (itemOrID.id) return itemOrID.id; return itemOrID; } wrapRecord(...records) { return { records }; } unwrapRecord(data) { return data.records[0]; } }
JavaScript
class KnexConnector { /** * Bind current connector with the given table * @param {String} tableName The table name */ constructor({ tableName, }) { this.tableName = tableName; } /** * Generate a knex targeting the current table * @returns {Object} Knex connector */ getKnex() { return knex(this.tableName); } /** * Create one or more docs into the database. * @param {Object} items The object you want to create in the database * @returns {*} The result of the operation */ create(items) { return this.getKnex().insert(items); } /** * Find one or more document into your mongoDb database. * @param {Query} query The ilorm query you want to run on your Database. * @returns {Promise} Every documents who match the query */ find(query) { return applyQueryOnKnex(query, query[KNEX]); } /** * Find one document from your database * @param {Query} query The ilorm query you want to run on your Database. * @returns {*|Promise.<Model>|*} The document first found */ findOne(query) { return applyQueryOnKnex(query, query[KNEX]) .limit(1) .then(items => (items && items.length ? items[0] : null)); } /** * Count the number of document who match the query * @param {Query} query The ilorm query you want to run on your Database. * @returns {Promise.<Number>} The number of document found */ count(query) { return applyQueryOnKnex(query, query[KNEX]) .count('*'); } /** * Update one or more document who match query * @param {Query} query The ilorm query you want to run on your Database. * @returns {*} The number of document updated */ update(query) { applyQueryOnKnex(query, query[KNEX]); return applyUpdateOnKnex(query, query[KNEX]); } /** * Update one document who match query * @param {Query} query The ilorm query you want to run on your Database. * @returns {*} Return true if a document was updated */ updateOne(query) { query[KNEX] .limit(1); applyQueryOnKnex(query, query[KNEX]); return applyUpdateOnKnex(query, query[KNEX]); } /** * Remove one or document who match the query * @param {Query} query The ilorm query you want to run on your Database. * @returns {Promise.<Number>} The number of document removed */ remove(query) { applyQueryOnKnex(query, query[KNEX]); return query[KNEX].del(); } /** * Remove one document who match the query * @param {Query} query The ilorm query you want to run on your Database. * @returns {Promise.<Boolean>} Return true if a document was removed */ removeOne(query) { query[KNEX] .limit(1); applyQueryOnKnex(query, query[KNEX]); return query[KNEX].del(); } /** * Create a stream object from the query * @param {Query} query The ilorm query you want to use to generate the stream * @returns {Stream} The stream associated with the query/ */ stream(query) { return applyQueryOnKnex(query, query[KNEX]) .stream(); } /** * Create a new KnexModel from the given params * @param {Model} ParentModel The ilorm global Model used as parent of ModelConnector * @returns {KnexModel} The result KnexModel */ modelFactory({ ParentModel, schema, }) { initTable({ connector: this, knex, ParentModel, schema, }); return modelFactory({ ParentModel, }); } /** * Create a new KnexQuery from the given params * @param {Query} ParentQuery The ilorm global Query used as parent of QueryConnector * @returns {KnexQuery} The result KnexQuery */ queryFactory({ ParentQuery, }) { return queryFactory({ ParentQuery, }); } }
JavaScript
class AuthenticationForm { /** * A default constructor for AuthenticationForm */ constructor() { this.objectType = 'authenticationForm'; }; /** * * @param {string} formType Type of templated Authentication form, which will generate * @param {Object} formData Array of objects which will rendered inside template * @return {string} HTML string, which will generated after templating */ getHtmlString = ({formType, formData, styles}) => { return authenticationFormTemplate({ formType: formType, formData: formData, styles: styles, buttonStyles: buttonStyles, textStyles: textStyles, linkStyles: linkStyles, }); }; }
JavaScript
class InlineObject93 { /** * Constructs a new <code>InlineObject93</code>. * @alias module:model/InlineObject93 */ constructor() { InlineObject93.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>InlineObject93</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/InlineObject93} obj Optional instance to populate. * @return {module:model/InlineObject93} The populated <code>InlineObject93</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new InlineObject93(); if (data.hasOwnProperty('color')) { obj['color'] = ApiClient.convertToType(data['color'], 'String'); } if (data.hasOwnProperty('description')) { obj['description'] = ApiClient.convertToType(data['description'], 'String'); } if (data.hasOwnProperty('new_name')) { obj['new_name'] = ApiClient.convertToType(data['new_name'], 'String'); } } return obj; } }
JavaScript
class Scroll extends Two5 { constructor (config = {}) { super(config); this.config.root = this.config.root || window; this.config.resetProgress = this.config.resetProgress || this.resetProgress.bind(this); } /** * Reset progress in the DOM and inner state to given x and y. * * @param {Object} progress * @param {number} progress.x * @param {number} progress.y */ resetProgress ({x, y}) { this.progress.x = x; this.progress.y = y; this.progress.vx = 0; this.progress.vy = 0; if ( this.config.animationActive) { this.currentProgress.x = x; this.currentProgress.y = y; this.currentProgress.vx = 0; this.currentProgress.vy = 0; } this.config.root.scrollTo(x, y); } /** * Initializes and returns scroll controller. * * @return {function[]} */ getEffects () { return [getScrollController(this.config)]; } /** * Register scroll position measuring. */ setupEvents () { const config = { root: this.config.root, progress: this.progress }; this.measures.push(getScroll(config).handler); } /** * Remove scroll measuring handler. */ teardownEvents () { this.measures.length = 0; } teardownEffects () { this.effects.forEach(effect => effect.destroy && effect.destroy()); super.teardownEffects(); } }
JavaScript
class ErrorHandler { /** * @param {Logger} appLogger To log the received errors. * @param {ResponsesBuilder} responsesBuilder To generate the JSON response. * @param {boolean} showErrors If `false`, unknown errors will show a * generic message instead of real * message. And if `true`, * it will not only show all kind of * errors but it will also show the error * stack. * @param {ClassAppError} AppError To validate if the received errors are * known or not. * @param {ErrorHandlerOptions} [options={}] Custom options to modify the * middleware behavior. */ constructor(appLogger, responsesBuilder, showErrors, AppError, options = {}) { /** * A local reference for the `appLogger` service. * * @type {Logger} * @access protected * @ignore */ this._appLogger = appLogger; /** * A local reference for the `responsesBuilder` service. * * @type {ResponsesBuilder} * @access protected * @ignore */ this._responsesBuilder = responsesBuilder; /** * Whether or not to show unknown errors real messages. * * @type {boolean} * @access protected * @ignore */ this._showErrors = showErrors; /** * A local reference for the class the app uses to generate errors. * * @type {ClassAppError} * @access protected * @ignore */ this._AppError = AppError; /** * These are the "settings" the middleware will use in order to display the errors. * * @type {ErrorHandlerOptions} * @access protected * @ignore */ this._options = ObjectUtils.merge( { default: { message: 'Oops! Something went wrong, please try again', status: statuses['internal server error'], }, }, options, ); } /** * Returns the Express middleware that shows the errors. * * @returns {ExpressMiddleware} */ middleware() { return (err, req, res, next) => { // If the middleware received an error... if (err) { // Define the error response basic template. let data = { error: true, message: this._options.default.message, }; // Define the error response default status. let { status } = this._options.default; // Validate if the error is known or not. const knownError = err instanceof this._AppError; // If the `showErrors` flag is enabled or the error is a known error... if (this._showErrors || knownError) { // ...set the error real message on the response. data.message = err.message; // If the error type is known... if (knownError) { // Try to get any extra information that should be included on the response. data = Object.assign(data, err.response); // Try to obtain the response status from the error status = err.status || statuses['bad request']; } // If the `showErrors` flag is enabled... if (this._showErrors) { // Get the error stack and format it into an `Array`. const stack = err.stack.split('\n').map((line) => line.trim()); // Add the stack to the response. data.stack = stack; // Remove the first item of the stack, since it's the same as the message. stack.splice(0, 1); // Log the error. this._appLogger.error(`ERROR: ${err.message}`); this._appLogger.info(stack); } } // Send the response. this._responsesBuilder.json(res, data, status); } else { // ...otherwise, move to the next middleware. next(); } }; } /** * The options used to customize the middleware behavior. * * @returns {ErrorHandlerOptions} */ get options() { return this._options; } }
JavaScript
@connect( state => ({ // Needs to get all the threads on the active board currentBoard: state.boards.currentBoard, auth: state.auth }), /* actions to check if board is available and list of boards */ { ...notifActions, ...BoardsActions } ) class Board extends Component { static propTypes = { // Define the proptypes being used here. currentBoard: PropTypes.shape({ tag: PropTypes.string, name: PropTypes.string, threads: PropTypes.array }), auth: PropTypes.objectOf(PropTypes.any).isRequired, match: PropTypes.shape({ params: PropTypes.shape({ boardTag: PropTypes.string.isRequired }) }), getBoard: PropTypes.func.isRequired, notifSend: PropTypes.func.isRequired }; static defaultProps = { // Define any defaults like Board tag currentBoard: null, match: null }; constructor(props) { super(props); this.state = { showPopupForm: false }; } componentDidMount() { // Call board actions and gets data based on URL/Location const { match, getBoard } = this.props; getBoard(match.params.boardTag); } componentDidUpdate(prevProps) { const { match, getBoard, currentBoard } = this.props; if ((currentBoard && !(match.params.boardTag === currentBoard.tag)) || !prevProps.currentBoard) { getBoard(match.params.boardTag); } } successSubmit = () => { const { notifSend } = this.props; notifSend({ message: 'Thread submitted !', kind: 'success', dismissAfter: 2000 }); }; errorSubmit = error => { const { notifSend } = this.props; notifSend({ message: `Thread submit error:\n${error.detail}`, kind: 'danger', dismissAfter: 2000 }); }; createThread = async data => { this.toggleForm(); // this.successSubmit(); const { createThread } = this.props; try { const result = await createThread(data); this.successSubmit(); return result; } catch (error) { this.errorSubmit(error); } }; toggleForm() { const { showPopupForm } = this.state; this.setState({ showPopupForm: !showPopupForm }); } render() { const styles = require('./Boards.scss'); const { currentBoard, match, auth } = this.props; const { showPopupForm } = this.state; const popup = showPopupForm ? ( <div className={`${styles.popupForm}`}> <ThreadForm onSubmit={this.createThread} board={currentBoard.tag} poster={auth.user.id} /> </div> ) : ( <button type="button" className={`${styles.popupButton}`} onClick={() => this.toggleForm()}> + </button> ); /* Creates a list of threads. */ const mappedThreads = currentBoard.threads.map(thread => ( <ThreadBlock key={thread.id} threadID={thread.id} boardTag={match.params.boardTag} image={thread.image} title={thread.title} blurb={thread.blurb} user={thread.poster} date={thread.created} /> )); return ( <div> {/* Conditional statement is needed to prevent the page from loading if there's no board based on the ID. */} {currentBoard !== null && ( <div> <Helmet title={`boards - /${currentBoard.tag}/`} /> <div className={`${styles.threads} card-columns`}> {mappedThreads} {/* Conditional statement is needed to prevent nonauthenticated users from filling out a thread create form. */} </div> {auth.user !== null && <div className={`${styles.popupWrapper}`}>{popup}</div>} </div> )} {currentBoard == null && ( <div> <NotAvailable /> </div> )} </div> ); } }
JavaScript
class IssuedOrdersController extends LocalizedController { initializeModel = () => ({ pharmacy: undefined, }); // uninitialized blank model constructor(...args) { super(false, ...args); super.bindLocale(this, "issuedOrders"); this.model = this.initializeModel(); const wizard = require('wizard'); const participantManager = wizard.Managers.getParticipantManager(); this.issuedOrderManager = wizard.Managers.getIssuedOrderManager(participantManager); this.table = this.element.querySelector('pdm-ion-table'); HistoryNavigator.registerTab({ 'tab-issued-orders': this.translate('title') }) let self = this; // the HomeController takes care of sending refresh events for each tab. self.on(EVENT_REFRESH, (evt) => { console.log(evt); evt.preventDefault(); evt.stopImmediatePropagation(); self.table.refresh(); }, {capture: true}); // pressing "NEW" to create a new Issued Order self.onTagClick("new-issued-order", () => { self.navigateToTab('tab-order'); }); } }
JavaScript
class Wrapper extends Component { render() { const id = this.props.id; if ( !this.props.tooltip || !this.props.show ) { return this.props.children; } const tooltip = <Tooltip id={id} >{this.props.tooltip}</Tooltip>; return ( <OverlayTrigger placement={this.props.placement} overlay={tooltip} > {this.props.children} </OverlayTrigger> ); } }
JavaScript
class IncidentUpdate { /** * Constructs a new <code>IncidentUpdate</code>. * @alias module:model/IncidentUpdate * @param description {String} */ constructor(description) { IncidentUpdate.initialize(this, description); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, description) { obj['description'] = description; } /** * Constructs a <code>IncidentUpdate</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/IncidentUpdate} obj Optional instance to populate. * @return {module:model/IncidentUpdate} The populated <code>IncidentUpdate</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new IncidentUpdate(); if (data.hasOwnProperty('attributes')) { obj['attributes'] = ApiClient.convertToType(data['attributes'], {'String': Object}); } if (data.hasOwnProperty('category')) { obj['category'] = ApiClient.convertToType(data['category'], 'String'); } if (data.hasOwnProperty('description')) { obj['description'] = ApiClient.convertToType(data['description'], 'String'); } if (data.hasOwnProperty('impact')) { obj['impact'] = ApiClient.convertToType(data['impact'], 'String'); } if (data.hasOwnProperty('priority')) { obj['priority'] = ApiClient.convertToType(data['priority'], 'String'); } if (data.hasOwnProperty('severity')) { obj['severity'] = ApiClient.convertToType(data['severity'], 'String'); } if (data.hasOwnProperty('state')) { obj['state'] = ApiClient.convertToType(data['state'], 'String'); } if (data.hasOwnProperty('subcategory')) { obj['subcategory'] = ApiClient.convertToType(data['subcategory'], 'String'); } if (data.hasOwnProperty('tenant')) { obj['tenant'] = ApiClient.convertToType(data['tenant'], 'String'); } if (data.hasOwnProperty('urgency')) { obj['urgency'] = ApiClient.convertToType(data['urgency'], 'String'); } } return obj; } }
JavaScript
class CriticalFailureModifier extends ComparisonModifier { /** * Create a `CriticalFailureModifier` instance. * * @param {ComparePoint} [comparePoint] The comparison object * * @throws {TypeError} comparePoint must be a `ComparePoint` object */ constructor(comparePoint) { super(comparePoint); // set the modifier's sort order this.order = 9; } /* eslint-disable class-methods-use-this */ /** * The name of the modifier. * * @returns {string} 'critical-failure' */ get name() { return 'critical-failure'; } /* eslint-enable class-methods-use-this */ /** * The modifier's notation. * * @returns {string} */ get notation() { return `cf${super.notation}`; } /** * Run the modifier on the results. * * @param {RollResults} results The results to run the modifier against * @param {StandardDice|RollGroup} _context The object that the modifier is attached to * * @returns {RollResults} The modified results */ run(results, _context) { results.rolls .forEach((roll) => { // add the modifier flag if (this.isComparePoint(roll.value)) { roll.modifiers.add('critical-failure'); } return roll; }); return results; } }
JavaScript
class ActorSFRPG extends Actor { /** @override */ getRollData() { const data = super.getRollData(); let casterLevel = 0; data.classes = this.data.items.reduce((obj, i) => { if (i.type === "class") { const classData = { keyAbilityMod: this.data.data.abilities[i.data.kas].mod, levels: i.data.levels, keyAbilityScore: i.data.kas, skillRanksPerLevel: i.data.skillRanks.value }; if (i.data.isCaster) { casterLevel += i.data.levels } obj[i.name.slugify({replacement: "_", strict: true})] = classData; } return obj; }, {}); data.cl = casterLevel; return data; } /** * Augment the basic actor data with additional dynamic data. * * @param {Object} actorData The data for the actor * @returns {Object} The actors data */ prepareData() { super.prepareData(); const actorData = this.data; const data = actorData.data; const flags = actorData.flags; const actorType = actorData.type; this._ensureHasModifiers(data); const modifiers = this.getAllModifiers(); const items = actorData.items; const armor = items.find(item => item.type === "equipment" && item.data.equipped); const weapons = items.filter(item => item.type === "weapon" && item.data.equipped); const races = items.filter(item => item.type === "race"); const classes = items.filter(item => item.type === "class" || item.type === "chassis"); const theme = items.find(item => item.type === "theme"); const mods = items.filter(item => item.type === "mod"); const armorUpgrades = items.filter(item => item.type === "upgrade"); const asis = items.filter(item => item.type === "asi"); game.sfrpg.engine.process("process-actors", { data, armor, weapons, races, classes, flags, type: actorType, modifiers, theme, mods, armorUpgrades, asis }); } /** * TODO: Use these two methods to properly setup actor data for use * in the new Active Effects API. */ prepareBaseData() { super.prepareBaseData(); } prepareDerivedData() { super.prepareDerivedData(); } /** * Check to ensure that this actor has a modifiers data object set, if not then set it. * These will always be needed from hence forth, so we'll just make sure that they always exist. * * @param {Object} data The actor data to check against. * @param {String|Null} prop A specific property name to check. * * @returns {Object} The modified data object with the modifiers data object added. */ _ensureHasModifiers(data, prop = null) { if (!hasProperty(data, "modifiers")) { console.log(`SFRPG | ${this.name} does not have the modifiers data object, attempting to create them...`); data.modifiers = []; } return data; } /** * Extend the default update method to enhance data before submission. * See the parent Entity.update method for full details. * * @param {Object} data The data with which to update the Actor * @param {Object} options Additional options which customize the update workflow * @return {Promise} A Promise which resolves to the updated Entity */ async update(data, options = {}) { const newSize = data['data.traits.size']; if (newSize && (newSize !== getProperty(this.data, "data.traits.size"))) { let size = CONFIG.SFRPG.tokenSizes[data['data.traits.size']]; if (this.isToken) this.token.update({ height: size, width: size }); else if (!data["token.width"] && !hasProperty(data, "token.width")) { setProperty(data, 'token.height', size); setProperty(data, 'token.width', size); } } return super.update(data, options); } /** * Extend OwnedItem creation logic for the SFRPG system to make weapons proficient by default when dropped on a NPC sheet * See the base Actor class for API documentation of this method * * @param {String} embeddedName The type of Entity being embedded. * @param {Object} itemData The data object of the item * @param {Object} options Any options passed in * @returns {Promise} */ async createEmbeddedEntity(embeddedName, itemData, options) { if (!this.hasPlayerOwner) { let t = itemData.type; let initial = {}; if (t === "weapon") initial['data.proficient'] = true; if (["weapon", "equipment"].includes(t)) initial['data.equipped'] = true; if (t === "spell") initial['data.prepared'] = true; mergeObject(itemData, initial); } return super.createEmbeddedEntity(embeddedName, itemData, options); } async useSpell(item, { configureDialog = true } = {}) { if (item.data.type !== "spell") throw new Error("Wrong item type"); let lvl = item.data.data.level; const usesSlots = (lvl > 0) && item.data.data.preparation.mode === ""; if (!usesSlots) return item.roll(); let consume = true; if (configureDialog) { const spellFormData = await SpellCastDialog.create(this, item); lvl = parseInt(spellFormData.get("level")); consume = Boolean(spellFormData.get("consume")); if (lvl !== item.data.data.level) { item = item.constructor.createOwned(mergeObject(item.data, { "data.level": lvl }, { inplace: false }), this); } } if (consume && (lvl > 0)) { await this.update({ [`data.spells.spell${lvl}.value`]: Math.max(parseInt(this.data.data.spells[`spell${lvl}`].value) - 1, 0) }); } return item.roll(); } /** * Edit a skill's fields * @param {string} skillId The skill id (e.g. "ins") * @param {Object} options Options which configure how the skill is edited */ async editSkill(skillId, options = {}) { // Keeping this here for later // this.update({"data.skills.-=skillId": null}); // use this to delete any unwanted skills. const skill = duplicate(this.data.data.skills[skillId]); const isNpc = this.data.type === "npc"; const formData = await AddEditSkillDialog.create(skillId, skill, true, isNpc), isTrainedOnly = Boolean(formData.get('isTrainedOnly')), hasArmorCheckPenalty = Boolean(formData.get('hasArmorCheckPenalty')), value = Boolean(formData.get('value')) ? 3 : 0, misc = Number(formData.get('misc')), ranks = Number(formData.get('ranks')), ability = formData.get('ability'), remove = Boolean(formData.get('remove')); if (remove) return this.update({ [`data.skills.-=${skillId}`]: null }); let updateObject = { [`data.skills.${skillId}.ability`]: ability, [`data.skills.${skillId}.ranks`]: ranks, [`data.skills.${skillId}.value`]: value, [`data.skills.${skillId}.misc`]: misc, [`data.skills.${skillId}.isTrainedOnly`]: isTrainedOnly, [`data.skills.${skillId}.hasArmorCheckPenalty`]: hasArmorCheckPenalty }; if (isNpc) updateObject[`data.skills.${skillId}.enabled`] = Boolean(formData.get('enabled')); if ("subname" in skill) { updateObject[`data.skills.${skillId}.subname`] = formData.get('subname'); } return this.update(updateObject); } /** * Add a modifier to this actor. * * @param {Object} data The data needed to create the modifier * @param {String} data.name The name of this modifier. Used to identify the modfier. * @param {Number|String} data.modifier The modifier value. * @param {String} data.type The modifiers type. Used to determine stacking. * @param {String} data.modifierType Used to determine if this modifier is a constant value (+2) or a Roll formula (1d4). * @param {String} data.effectType The category of things that might be effected by this modifier. * @param {String} data.subtab What subtab should this modifier show under on the character sheet. * @param {String} data.valueAffected The specific value being modified. * @param {Boolean} data.enabled Is this modifier activated or not. * @param {String} data.source Where did this modifier come from? An item, ability or something else? * @param {String} data.notes Any notes or comments about the modifier. * @param {String} data.condition The condition, if any, that this modifier is associated with. * @param {String|null} data.id Override the randomly generated id with this. */ async addModifier({ name = "", modifier = 0, type = SFRPGModifierTypes.UNTYPED, modifierType = SFRPGModifierType.CONSTANT, effectType = SFRPGEffectType.SKILL, subtab = "misc", valueAffected = "", enabled = true, source = "", notes = "", condition = "", id = null } = {}) { const data = this._ensureHasModifiers(duplicate(this.data.data)); const modifiers = data.modifiers; modifiers.push(new SFRPGModifier({ name, modifier, type, modifierType, effectType, valueAffected, enabled, source, notes, subtab, condition, id })); await this.update({["data.modifiers"]: modifiers}); } /** * Delete a modifier for this Actor. * * @param {String} id The id for the modifier to delete */ async deleteModifier(id) { const modifiers = this.data.data.modifiers.filter(mod => mod._id !== id); await this.update({"data.modifiers": modifiers}); } /** * Edit a modifier for an Actor. * * @param {String} id The id for the modifier to edit */ editModifier(id) { const modifiers = duplicate(this.data.data.modifiers); const modifier = modifiers.find(mod => mod._id === id); new SFRPGModifierApplication(modifier, this).render(true); } /** * Returns an array of all modifiers on this actor. This will include items such as equipment, feat, classes, race, theme, etc. * * @param {Boolean} ignoreTemporary Should we ignore temporary modifiers? Defaults to false. * @param {Boolean} ignoreEquipment Should we ignore equipment modifiers? Defaults to false. */ getAllModifiers(ignoreTemporary = false, ignoreEquipment = false) { let allModifiers = this.data.data.modifiers.filter(mod => { return (!ignoreTemporary || mod.subtab == "permanent"); }); for (let item of this.data.items) { let modifiersToConcat = []; switch (item.type) { default: if (item.data.equipped !== false) { modifiersToConcat = item.data.modifiers; } break; case "augmentation": modifiersToConcat = item.data.modifiers; break; case "feat": if (item.data.activation?.type === "") { modifiersToConcat = item.data.modifiers; } break; case "equipment": case "weapon": if (!ignoreEquipment && item.data.equipped) { modifiersToConcat = item.data.modifiers; } break; } if (modifiersToConcat && modifiersToConcat.length > 0) { allModifiers = allModifiers.concat(modifiersToConcat); } } return allModifiers; } /** * Toggles what NPC skills are shown on the sheet. */ async toggleNpcSkills() { const skills = duplicate(this.data.data.skills); const formData = await NpcSkillToggleDialog.create(skills); let enabledSkills = {}; const delta = Object.entries(skills).reduce((obj, curr) => { if (curr[1].enabled) obj[`data.skills.${curr[0]}.enabled`] = !curr[1].enabled; return obj; }, {}); for (let [key, value] of formData.entries()) { enabledSkills[`data.${key}`] = Boolean(value); } enabledSkills = mergeObject(enabledSkills, delta, {overwrite: false, inplace: false}); return await this.update(enabledSkills); } /** * Add a new skill * @param {Object} options Options which configure how the skill is added */ async addSkill(options = {}) { const skill = { ability: "int", ranks: 0, value: 0, misc: 0, isTrainedOnly: false, hasArmorCheckPenalty: false, subname: "" }; let skillId = "pro"; let counter = 0; while (this.data.data.skills[skillId]) { skillId = `pro${++counter}`; } const formData = await AddEditSkillDialog.create(skillId, skill, false, this.hasPlayerOwner, this.owner), isTrainedOnly = Boolean(formData.get('isTrainedOnly')), hasArmorCheckPenalty = Boolean(formData.get('hasArmorCheckPenalty')), value = Boolean(formData.get('value')) ? 3 : 0, misc = Number(formData.get('misc')), ranks = Number(formData.get('ranks')), ability = formData.get('ability'), subname = formData.get('subname'); let newSkillData = { [`data.skills.${skillId}`]: {}, [`data.skills.${skillId}.isTrainedOnly`]: isTrainedOnly, [`data.skills.${skillId}.hasArmorCheckPenalty`]: hasArmorCheckPenalty, [`data.skills.${skillId}.value`]: value, [`data.skills.${skillId}.misc`]: misc, [`data.skills.${skillId}.ranks`]: ranks, [`data.skills.${skillId}.ability`]: ability, [`data.skills.${skillId}.subname`]: subname, [`data.skills.${skillId}.mod`]: value + misc + ranks, [`data.skills.${skillId}.enabled`]: true }; return this.update(newSkillData); } /** * Roll a Skill Check * Prompt the user for input regarding Advantage/Disadvantage and any Situational Bonus * @param {string} skillId The skill id (e.g. "ins") * @param {Object} options Options which configure how the skill check is rolled */ async rollSkill(skillId, options = {}) { const skl = this.data.data.skills[skillId]; if (!this.hasPlayerOwner) { return await this.rollSkillCheck(skillId, skl, options); } if (skl.isTrainedOnly && !(skl.ranks > 0)) { let content = `${CONFIG.SFRPG.skills[skillId.substring(0, 3)]} is a trained only skill, but ${this.name} is not trained in that skill. Would you like to roll anyway?`; return new Promise(resolve => { new Dialog({ title: `${CONFIG.SFRPG.skills[skillId.substring(0, 3)]} is trained only`, content: content, buttons: { yes: { label: "Yes", callback: () => resolve(this.rollSkillCheck(skillId, skl, options)) }, cancel: { label: "No" } }, default: "cancel" }).render(true); }); } else { return await this.rollSkillCheck(skillId, skl, options); } } /** * Roll a generic ability test. * * @param {String} abilityId The ability id (e.g. "str") * @param {Object} options Options which configure how ability tests are rolled */ async rollAbility(abilityId, options = {}) { const label = CONFIG.SFRPG.abilities[abilityId]; const abl = this.data.data.abilities[abilityId]; let parts = []; let data = this.getRollData(); if (abl.rolledMods) { parts.push(...abl.rolledMods.map(x => x.mod)); } //Include ability check bonus only if it's not 0 if(abl.abilityCheckBonus) { parts.push('@abilityCheckBonus'); data.abilityCheckBonus = abl.abilityCheckBonus; } parts.push('@mod') mergeObject(data, { mod: abl.mod }); return await DiceSFRPG.d20Roll({ event: options.event, actor: this, parts: parts, data: data, flavor: game.settings.get('sfrpg', 'useCustomChatCard') ? `${label}` : `Ability Check - ${label}`, title: `Ability Check`, speaker: ChatMessage.getSpeaker({ actor: this }) }); } /** * Roll a save check * * @param {String} saveId The save id (e.g. "will") * @param {Object} options Options which configure how saves are rolled */ async rollSave(saveId, options = {}) { const label = CONFIG.SFRPG.saves[saveId]; const save = this.data.data.attributes[saveId]; let parts = []; let data = this.getRollData(); if (save.rolledMods) { parts.push(...save.rolledMods.map(x => x.mod)); } parts.push('@mod'); mergeObject(data, { mod: save.bonus }); return await DiceSFRPG.d20Roll({ event: options.event, actor: this, parts: parts, data: data, title: `Save`, flavor: game.settings.get('sfrpg', 'useCustomChatCard') ? `${label}` : `Save - ${label}`, speaker: ChatMessage.getSpeaker({ actor: this }) }); } async rollSkillCheck(skillId, skill, options = {}) { let parts = []; let data = this.getRollData(); if (skill.rolledMods) { parts.push(...skill.rolledMods.map(x => x.mod)); } parts.push('@mod'); mergeObject(data, { mod: skill.mod }); return await DiceSFRPG.d20Roll({ actor: this, event: options.event, parts: parts, data: data, title: 'Skill Check', flavor: game.settings.get('sfrpg', 'useCustomChatCard') ? `${CONFIG.SFRPG.skills[skillId.substring(0, 3)]}`: `Skill Check - ${CONFIG.SFRPG.skills[skillId.substring(0, 3)]}`, speaker: ChatMessage.getSpeaker({ actor: this }) }); } static async applyDamage(roll, multiplier) { let value = Math.floor(parseFloat(roll.find('.dice-total').text()) * multiplier); const promises = []; for (let t of canvas.tokens.controlled) { if (t.actor.data.type === "starship") { ui.notifications.warn("Cannot currently apply damage to starships using the context menu"); continue; } else if (t.actor.data.type === "vehicle") { ui.notifications.warn("Cannot currently apply damage to vehicles using the context menu"); continue; } let a = t.actor, hp = a.data.data.attributes.hp, sp = a.data.data.attributes.sp, tmp = parseInt(hp.temp) | 0, dt = value > 0 ? Math.min(tmp, value) : 0, tmpd = tmp - dt, // stamina doesn't get healed like hit points do, so skip it if we're appling // healing instead of damage. spd = value > 0 ? Math.clamped(sp.value - (value - dt), 0, sp.max) : sp.value; dt = value > 0 ? value - Math.clamped((value - dt) - sp.value, 0, value) : 0; let hpd = Math.clamped(hp.value - (value - dt), 0, hp.max); promises.push(t.actor.update({ "data.attributes.hp.temp": tmpd, "data.attributes.sp.value": spd, "data.attributes.hp.value": hpd })); } return Promise.all(promises); } /** * Cause this Actor to take a Short 10 minute Rest * During a Short Rest resources and limited item uses may be recovered * @param {boolean} dialog Present a dialog window which allows for spending Resolve Points as part of the Short Rest * @param {boolean} chat Summarize the results of the rest workflow as a chat message * @return {Promise} A Promise which resolves once the short rest workflow has completed */ async shortRest({ dialog = true, chat = true } = {}) { const data = this.data.data; // Ask user to confirm if they want to rest, and if they want to restore stamina points let sp = data.attributes.sp; let rp = data.attributes.rp; let canRestoreStaminaPoints = rp.value > 0 && sp.value < sp.max; let restoreStaminaPoints = false; if (dialog) { const restingResults = await ShortRestDialog.shortRestDialog({ actor: this, canRestoreStaminaPoints: canRestoreStaminaPoints }); if (!restingResults.resting) return; restoreStaminaPoints = restingResults.restoreStaminaPoints; } let drp = 0; let dsp = 0; if (restoreStaminaPoints && canRestoreStaminaPoints) { drp = 1; let updatedRP = Math.max(rp.value - drp, 0); dsp = Math.min(sp.max - sp.value, sp.max); this.update({ "data.attributes.sp.value": sp.max, "data.attributes.rp.value": updatedRP }); } // Restore resources that reset on short rests const updateData = {}; for (let [k, r] of Object.entries(data.resources)) { if (r.max && r.sr) { updateData[`data.resources.${k}.value`] = r.max; } } await this.update(updateData); // Reset items that restore their uses on a short rest const items = this.items.filter(item => item.data.data.uses && (item.data.data.uses.per === "sr")); const updateItems = items.map(item => { return { "id": item.data.id, "data.uses.value": item.data.data.uses.max } }); await this.updateEmbeddedEntity("OwnedItem", updateItems); // Notify chat what happened if (chat) { let msg = game.i18n.format("SFRPG.RestSChatMessage", { name: this.name }); if (drp > 0) { msg = game.i18n.format("SFRPG.RestSChatMessageRestored", { name: this.name, spentRP: drp, regainedSP: dsp }); } ChatMessage.create({ user: game.user._id, speaker: { actor: this, alias: this.name }, content: msg, type: CONST.CHAT_MESSAGE_TYPES.OTHER }); } return { drp: drp, dsp: dsp, updateData: updateData, updateItems: updateItems } } /** * Cause this Actor to repair itself following drone repairing rules * During a drone repair, some amount of drone HP may be recovered. * @param {boolean} dialog Present a dialog window which allows for utilizing the Repair Drone (Ex) feat while repairing. * @param {boolean} chat Summarize the results of the repair workflow as a chat message * @return {Promise} A Promise which resolves once the repair workflow has completed */ async repairDrone({ dialog = true, chat = true } = {}) { const data = this.data.data; let hp = data.attributes.hp; if (hp.value >= hp.max) { let message = game.i18n.format("SFRPG.RepairDroneUnnecessary", { name: this.name }); ui.notifications.info(message); return; } let improvedRepairFeat = false; if (dialog) { const dialogResults = await DroneRepairDialog.droneRepairDialog({ actor: this, improvedRepairFeat: improvedRepairFeat }); if (!dialogResults.repairing) return; improvedRepairFeat = dialogResults.improvedRepairFeat; } let oldHP = hp.value; let maxRepairAmount = Math.floor(improvedRepairFeat ? hp.max * 0.25 : hp.max * 0.1); let newHP = Math.min(hp.max, hp.value + maxRepairAmount); let dhp = newHP - oldHP; const updateData = {}; updateData["data.attributes.hp.value"] = newHP; await this.update(updateData); // Notify chat what happened if (chat) { let msg = game.i18n.format("SFRPG.RepairDroneChatMessage", { name: this.name, regainedHP: dhp }); ChatMessage.create({ user: game.user._id, speaker: { actor: this, alias: this.name }, content: msg, type: CONST.CHAT_MESSAGE_TYPES.OTHER }); } return { dhp: dhp, updateData: updateData }; } async removeFromCrew() { await this.unsetFlag('sfrpg', 'crewMember'); } async setCrewMemberRole(shipId, role) { return this.setFlag('sfrpg', 'crewMember', { shipId: shipId, role: role }); } /** * Take a long nights rest, recovering HP, SP, RP, resources, and spell slots * @param {boolean} dialog Present a confirmation dialog window whether or not to take a long rest * @param {boolean} chat Summarize the results of the rest workflow as a chat message * @return {Promise} A Promise which resolves once the long rest workflow has completed */ async longRest({ dialog = true, chat = true } = {}) { const data = duplicate(this.data.data); const updateData = {}; if (dialog) { try { await ShortRestDialog.longRestDialog(this); } catch (err) { return; } } // Recover HP, SP, and RP let dhp = data.attributes.hp.max === data.attributes.hp.value ? 0 : data.details.level.value > (data.attributes.hp.max - data.attributes.hp.value) ? data.attributes.hp.max - data.attributes.hp.value : data.details.level.value; let dsp = data.attributes.sp.max - data.attributes.sp.value; let drp = data.attributes.rp.max - data.attributes.rp.value; updateData['data.attributes.hp.value'] = Math.min(data.attributes.hp.value + data.details.level.value, data.attributes.hp.max); updateData['data.attributes.sp.value'] = data.attributes.sp.max; updateData['data.attributes.rp.value'] = data.attributes.rp.max; // Heal Ability damage for (let [abl, ability] of Object.entries(data.abilities)) { if (ability.damage && ability.damage > 0) { updateData[`data.abilities.${abl}.damage`] = --ability.damage; } } for (let [k, r] of Object.entries(data.resources)) { if (r.max && (r.sr || r.lr)) { updateData[`data.resources.${k}.value`] = r.max; } } for (let [k, v] of Object.entries(data.spells)) { if (!v.max) continue; updateData[`data.spells.${k}.value`] = v.max; } const items = this.items.filter(i => i.data.data.uses && ["sr", "lr", "day"].includes(i.data.data.uses.per)); const updateItems = items.map(item => { return { "_id": item.data._id, "data.uses.value": item.data.data.uses.max } }); await this.update(updateData); await this.updateEmbeddedEntity("OwnedItem", updateItems); if (chat) { ChatMessage.create({ user: game.user._id, speaker: { actor: this, alias: this.name }, content: `${this.name} takes a night's rest and recovers ${dhp} Hit points, ${dsp} Stamina points, and ${drp} Resolve points.` }); } return { dhp: dhp, dsp: dsp, drp: drp, updateData: updateData, updateItems: updateItems } } }
JavaScript
class VcfOnboarding extends ElementMixin(ThemableMixin(GestureEventListeners(PolymerElement))) { static get template() { return html` <style> [part='step'] { display: none; } [part='step'].active { display: block; } [part='step-button'] { width: 100%; margin: var(--lumo-space-l) 0; display: none; } [part='step-button'].active { display: block; } [part='step-indicators'] { display: flex; align-items: center; justify-content: center; } [part='step-indicator'] { width: 8px; height: 8px; margin: 0 5px; border-radius: 50%; background-color: var(--lumo-shade-30pct); display: inline-block; transition: all 0.25s; cursor: pointer; } [part='step-indicators'] .active { background-color: var(--lumo-primary-color); cursor: default; } </style> <vaadin-dialog id="onboarding-dialog" theme="full-screen-on-mobile" no-close-on-outside-click no-close-on-esc> <template> <div part="steps-container" class$="step-[[activeStep]]-active" on-track="handleTrack"> <template is="dom-repeat" items="[[steps]]"> <div part="step" class$="[[_getActiveClass(index, activeStep)]]"> <div part="step-content" inner-h-t-m-l="[[item.innerHTML]]"></div> </div> </template> <div part="onboarding-footer"> <template is="dom-repeat" items="[[steps]]"> <vaadin-button part="step-button" class$="[[_getActiveClass(index, activeStep)]]" tab-index$="[[_getTabIndex(index, activeStep)]]" theme="primary" on-click="nextStep" >[[_getButtonText(item)]]</vaadin-button > </template> <div part="step-indicators"> <template is="dom-repeat" items="[[steps]]"> <span part="step-indicator" class$="[[_getActiveClass(index, activeStep)]]" on-click="updateStep" data-index="[[index]]" ></span> </template> </div> </div> </div> </template> </vaadin-dialog> `; } static get is() { return 'vcf-onboarding'; } static get properties() { return { steps: { type: Array, value: () => [] }, buttons: { type: Array, value: () => [] }, activeStep: { type: Number, value: 0 } }; } ready() { super.ready(); if (!localStorage.getItem('vcf-onboarding')) { this.openDialog(); } const stepElements = this.querySelectorAll('[onboarding-step]'); this.steps = [...stepElements]; this.innerHTML = ''; } _getActiveClass(i, activeStep) { if (i === activeStep) { return 'active'; } return ''; } _getTabIndex(i, activeStep) { if (i === activeStep) { return 0; } return -1; } _getButtonText(step) { return step.getAttribute('button-text'); } nextStep() { if (this.activeStep < this.steps.length - 1) { this.activeStep += 1; } else { this.closeDialog(); } } updateStep(e) { this.activeStep = e.target.dataIndex; } openDialog() { this.$['onboarding-dialog'].opened = true; } closeDialog() { this.$['onboarding-dialog'].opened = false; localStorage.setItem('vcf-onboarding', 'visited'); } handleTrack(e) { switch (e.detail.state) { case 'start': this.trackStart = { x: e.detail.x, y: e.detail.y }; break; case 'end': if (this.trackStart) { const deltaX = e.detail.x - this.trackStart.x; const deltaY = e.detail.y - this.trackStart.y; if (Math.abs(deltaX) > Math.abs(deltaY)) { if (deltaX > 0 && this.activeStep > 1) { this.activeStep = this.activeStep - 1; } else if (deltaX < 0 && this.activeStep < 3) { this.activeStep = this.activeStep + 1; } } this.trackStart = undefined; } break; } } }
JavaScript
class TaskForm extends Component { constructor(props) { super(props); this.state = { name: '', hours: 0, priority: 0, desc: '', start_date: '', due_date: '', loadedProps: false } this.addTask = this.addTask.bind(this); } componentDidMount() { /** can be improved **/ /* currently only re-renders on page reload, not on value state change */ if (this.props.values !== undefined && this.state.loadedProps === false) { this.setState({name: this.props.values.name}); this.setState({hours: this.props.values.hours}); this.setState({priority: this.props.values.priority}); this.setState({desc: this.props.values.desc}); this.setState({start_date: this.props.values.start_date}); this.setState({due_date: this.props.values.due_date}); if (this.props.values.subList) { this.setState({subList: this.props.values.subList}); } else { this.setState({subList: []}); } this.setState({loadedProps: true}); } } // function to handle input change // name of input field is set to its id // that name is later used to modify the correct state handleInputChange(e) { let name = e.target.id; let value = e.target.value; this.setState({[name]: value}); } addTask(e) { e.preventDefault(); let added_date = new Date(); // get it in yyyy/mm/dd format let temp = added_date.toISOString().slice(0, 10); // validate user input if (this.state.name === undefined || this.state.name.trim() === "") { alert("Please do not leave the task name blank.") return false; } if (this.state.hours < 0 || isNaN(this.state.hours)) { alert("Please enter the number of hours this task will take.") return false; } // keep description, start date and due date optional // build task object let task = { name: this.state.name, hours: parseInt(this.state.hours, 10), priority: parseInt(this.state.priority, 10), desc: this.state.desc, added_date: temp, start_date: this.state.start_date, due_date: this.state.due_date, subList: this.state.subList }; // send validated task to parent this.props.addTask(task); // toggle form this.props.toggleForm(); } render () { return ( <div className="col-md-6 my-2"> <h2>Save Task</h2> <form> <div className="row"> <div className="col"> <label htmlFor="name" className="col-form-label">Name:</label> <input type="text" className="form-control" id="name" value={this.state.name} onChange={(e) => this.handleInputChange(e)} /> </div> </div> <div className="row"> <div className="col"> <label htmlFor="hours" className="col-form-label">Hours:</label> <input type="number" className="form-control" id="hours" value={this.state.hours} onChange={(e) => this.handleInputChange(e)} /> </div> <div className="col"> <label htmlFor="priority" className="col-form-label">Priority:</label> <input type="number" className="form-control" id="priority" value={this.state.priority} onChange={(e) => this.handleInputChange(e)} /> </div> </div> <div className="form-group"> <label htmlFor="desc" className="col-form-label">Description:</label> <textarea className="form-control" id="desc" value={this.state.desc} onChange={(e) => this.handleInputChange(e)}></textarea> </div> <div className="row"> <div className="col"> <label htmlFor="start_date" className="col-form-label">Start Date:</label> <input type="date" className="form-control" id="start_date" value={this.state.start_date} onChange={(e) => this.handleInputChange(e)}/> </div> <div className="col"> <label htmlFor="due_date" className="col-form-label">Due Date:</label> <input type="date" className="form-control" id="due_date" value={this.state.due_date} onChange={(e) => this.handleInputChange(e)}/> </div> </div> <div className="form-group d-flex justify-content-between"> <button className="btn btn-danger my-2" onClick={this.props.toggleForm}>Cancel</button> <button className="btn btn-primary my-2" onClick={this.addTask}>Save</button> </div> </form> </div> ) } }
JavaScript
class Logger { /** * Creates a new logger instance from interface implementation * @param {object} other Object implementing Logger interface * @return {Logger} Logger instance */ static from(other) { let logger = new Logger(); other = extend({},other); Object.keys(other).forEach(k=>{ logger[k] = other[k]; }); return logger; } constructor() {} /** * Use this logger instance * @param {Logger} newInstance Logger instance */ setInstance(newInstance) {} /** * Sets file transport * @param {object} opts File transport options */ setFileTransport(opts) {} /** * Sets log level * @param {string} level Log level (silly,debug,info,warn,error) */ setLevel(level) {} /** * Logs info messages * @param {object} args Arguments */ info(...args) {} /** * Logs debug messages * @param {object} args Arguments */ debug(...args) {} /** * Logs silly messages * @param {object} args Arguments */ trace(...args) {} /** * Logs silly messages * @param {object} args Arguments */ silly(...args) {} /** * Logs messages * @param {string} level Level name * @param {object} args Arguments */ log(level,...args) {} /** * Logs error messages * @param {object} args Arguments */ error(...args) {} /** * Logs warning messages * @param {object} args Arguments */ warn(...args) {} /** * Logs warning messages * @param {object} args Arguments */ warning(...args) {} }
JavaScript
class CanvasMapRenderer extends MapRenderer { /** * @param {module:ol/PluggableMap} map Map. */ constructor(map) { super(map); const container = map.getViewport(); /** * @private * @type {CanvasRenderingContext2D} */ this.context_ = createCanvasContext2D(); /** * @private * @type {HTMLCanvasElement} */ this.canvas_ = this.context_.canvas; this.canvas_.style.width = '100%'; this.canvas_.style.height = '100%'; this.canvas_.style.display = 'block'; this.canvas_.className = CLASS_UNSELECTABLE; container.insertBefore(this.canvas_, container.childNodes[0] || null); /** * @private * @type {boolean} */ this.renderedVisible_ = true; /** * @private * @type {module:ol/transform~Transform} */ this.transform_ = createTransform(); } /** * @param {module:ol/render/EventType} type Event type. * @param {module:ol/PluggableMap~FrameState} frameState Frame state. */ dispatchRenderEvent(type, frameState) { const map = this.getMap(); const context = this.context_; if (map.hasListener(type)) { const extent = frameState.extent; const pixelRatio = frameState.pixelRatio; const viewState = frameState.viewState; const rotation = viewState.rotation; const transform = this.getTransform(frameState); const vectorContext = new CanvasImmediateRenderer(context, pixelRatio, extent, transform, rotation); const composeEvent = new RenderEvent(type, vectorContext, frameState, context, null); map.dispatchEvent(composeEvent); } } /** * @param {module:ol/PluggableMap~FrameState} frameState Frame state. * @protected * @return {!module:ol/transform~Transform} Transform. */ getTransform(frameState) { const viewState = frameState.viewState; const dx1 = this.canvas_.width / 2; const dy1 = this.canvas_.height / 2; const sx = frameState.pixelRatio / viewState.resolution; const sy = -sx; const angle = -viewState.rotation; const dx2 = -viewState.center[0]; const dy2 = -viewState.center[1]; return composeTransform(this.transform_, dx1, dy1, sx, sy, angle, dx2, dy2); } /** * @inheritDoc */ renderFrame(frameState) { if (!frameState) { if (this.renderedVisible_) { this.canvas_.style.display = 'none'; this.renderedVisible_ = false; } return; } const context = this.context_; const pixelRatio = frameState.pixelRatio; const width = Math.round(frameState.size[0] * pixelRatio); const height = Math.round(frameState.size[1] * pixelRatio); if (this.canvas_.width != width || this.canvas_.height != height) { this.canvas_.width = width; this.canvas_.height = height; } else { context.clearRect(0, 0, width, height); } const rotation = frameState.viewState.rotation; this.calculateMatrices2D(frameState); this.dispatchRenderEvent(RenderEventType.PRECOMPOSE, frameState); const layerStatesArray = frameState.layerStatesArray; stableSort(layerStatesArray, sortByZIndex); if (rotation) { context.save(); rotateAtOffset(context, rotation, width / 2, height / 2); } const viewResolution = frameState.viewState.resolution; let i, ii, layer, layerRenderer, layerState; for (i = 0, ii = layerStatesArray.length; i < ii; ++i) { layerState = layerStatesArray[i]; layer = layerState.layer; layerRenderer = /** @type {module:ol/renderer/canvas/Layer} */ (this.getLayerRenderer(layer)); if (!visibleAtResolution(layerState, viewResolution) || layerState.sourceState != SourceState.READY) { continue; } if (layerRenderer.prepareFrame(frameState, layerState)) { layerRenderer.composeFrame(frameState, layerState, context); } } if (rotation) { context.restore(); } this.dispatchRenderEvent(RenderEventType.POSTCOMPOSE, frameState); if (!this.renderedVisible_) { this.canvas_.style.display = ''; this.renderedVisible_ = true; } this.scheduleRemoveUnusedLayerRenderers(frameState); this.scheduleExpireIconCache(frameState); } /** * @inheritDoc */ forEachLayerAtPixel(pixel, frameState, hitTolerance, callback, thisArg, layerFilter, thisArg2) { let result; const viewState = frameState.viewState; const viewResolution = viewState.resolution; const layerStates = frameState.layerStatesArray; const numLayers = layerStates.length; const coordinate = applyTransform( frameState.pixelToCoordinateTransform, pixel.slice()); let i; for (i = numLayers - 1; i >= 0; --i) { const layerState = layerStates[i]; const layer = layerState.layer; if (visibleAtResolution(layerState, viewResolution) && layerFilter.call(thisArg2, layer)) { const layerRenderer = /** @type {module:ol/renderer/canvas/Layer} */ (this.getLayerRenderer(layer)); result = layerRenderer.forEachLayerAtCoordinate( coordinate, frameState, hitTolerance, callback, thisArg); if (result) { return result; } } } return undefined; } /** * @inheritDoc */ registerLayerRenderers(constructors) { super.registerLayerRenderers(constructors); for (let i = 0, ii = constructors.length; i < ii; ++i) { const ctor = constructors[i]; if (!includes(layerRendererConstructors, ctor)) { layerRendererConstructors.push(ctor); } } } }
JavaScript
class Configs { constructor (states, start, accept, reject, alpha, tapeAlpha) { this.states = states; this.start = start; this.accept = accept; this.reject = reject; this.alpha = alpha; this.tapeAlpha = tapeAlpha; } }