language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class VignetteEffect extends Effect { /** * Constructs a new vignette effect. * * @param {Object} [options] - The options. * @param {BlendFunction} [options.blendFunction=BlendFunction.NORMAL] - The blend function of this effect. * @param {Boolean} [options.eskil=false] - Enables Eskil's vignette technique. * @param {Number} [options.offset=0.5] - The vignette offset. * @param {Number} [options.darkness=0.5] - The vignette darkness. */ constructor(options = {}) { const settings = Object.assign({ blendFunction: BlendFunction.NORMAL, eskil: false, offset: 0.5, darkness: 0.5 }, options); super("VignetteEffect", fragmentShader, { blendFunction: settings.blendFunction, uniforms: new Map([ ["offset", new Uniform(settings.offset)], ["darkness", new Uniform(settings.darkness)] ]) }); this.eskil = settings.eskil; } /** * Indicates whether Eskil's vignette technique is enabled. * * @type {Boolean} */ get eskil() { return this.defines.has("ESKIL"); } /** * Enables or disables Eskil's vignette technique. * * @type {Boolean} */ set eskil(value) { if(this.eskil !== value) { if(value) { this.defines.set("ESKIL", "1"); } else { this.defines.delete("ESKIL"); } this.setChanged(); } } }
JavaScript
class Log { constructor({id} = {}) { this.id = id; this.VERSION = VERSION; this._startTs = getTimestamp(); this._deltaTs = getTimestamp(); // TODO - fix support from throttling groups this.LOG_THROTTLE_TIMEOUT = 0; // Time before throttled messages are logged again this._storage = new LocalStorage(`__probe-${this.id}__`, DEFAULT_SETTINGS); this.userData = {}; this.timeStamp(`${this.id} started`); autobind(this); Object.seal(this); } set priority(newPriority) { this._storage.updateConfiguration({priority: newPriority}); return this; } get priority() { return this._storage.config.priority; } isEnabled() { return this._storage.config.enabled; } getPriority() { return this._storage.config.priority; } getLevel() { return this._storage.config.priority; } // @return {Number} milliseconds, with fractions getTotal() { return Number((getTimestamp() - this._startTs).toPrecision(10)); } // @return {Number} milliseconds, with fractions getDelta() { return Number((getTimestamp() - this._deltaTs).toPrecision(10)); } // Configure enable(enabled = true) { this._storage.updateConfiguration({enabled}); return this; } setLevel(level) { this._storage.updateConfiguration({priority: level}); return this; } // Unconditional logging // Warn, but only once, no console flooding warn(message, ...args) { return this._getLogFunction({ message, args, method: originalConsole.warn, once: true }); } // Print an error error(message, ...args) { return this._getLogFunction({message, args, method: originalConsole.error}); } deprecated(oldUsage, newUsage) { return this.warn(`\`${oldUsage}\` is deprecated and will be removed \ in a later version. Use \`${newUsage}\` instead`); } removed(oldUsage, newUsage) { return this.error(`\`${oldUsage}\` has been removed. Use \`${newUsage}\` instead`); } // Conditional logging // Log to a group probe(priority, message, ...args) { return this._getLogFunction({ priority, message, args, method: originalConsole.log, time: true, once: true }); } // Log a debug message log(priority, message, ...args) { return this._getLogFunction({ priority, message, args, method: originalConsole.debug }); } // Log a normal message info(priority, message, ...args) { return this._getLogFunction({ priority, message, args, method: console.info }); } // Log a normal message, but only once, no console flooding once(priority, message, ...args) { return this._getLogFunction({ priority, message, args, method: originalConsole.debug || originalConsole.info, once: true }); } // Logs an object as a table table(priority, table, columns) { if (table) { const tag = getTableHeader(table); return this._getLogFunction({ priority, message: table, args: columns && [columns], tag, method: console.table || noop }); } return noop; } // logs an image under Chrome image({priority, image, message = '', scale = 1}) { if (priority > this.getPriority()) { return noop; } return isBrowser ? this._logImageInBrowser({image, message, scale}) : this._logImageInNode({image, message, scale}); } // Use the asciify module to log an image under node.js _logImageInNode({image, message = '', scale = 1}) { // Note: Runtime load of the "asciify-image" module, avoids including in browser bundles let asciify = null; try { asciify = module.require('asciify-image'); } catch (error) { // asciify not installed, silently ignore } if (asciify) { return () => asciify(image, {fit: 'box', width: `${Math.round(80 * scale)}%`}) .then(data => console.log(data)); } return noop; } _logImageInBrowser({image, message = '', scale = 1}) { if (typeof image === 'string') { const img = new Image(); img.onload = () => { const args = formatImage(img, message, scale); console.log(...args); }; img.src = image; return noop; } const element = image.nodeName || ''; if (element.toLowerCase() === 'img') { console.log(...formatImage(image, message, scale)); return noop; } if (element.toLowerCase() === 'canvas') { const img = new Image(); img.onload = () => console.log(...formatImage(img, message, scale)); img.src = image.toDataURL(); return noop; } return noop; } time(priority, message) { return this._getLogFunction({ priority, message, method: console.time ? console.time : console.info }); } timeEnd(priority, message) { return this._getLogFunction({ priority, message, method: console.timeEnd ? console.timeEnd : console.info }); } timeStamp(priority, message) { return this._getLogFunction({ priority, message, method: console.timeStamp || noop }); } group(priority, message, opts = {collapsed: false}) { opts = this._normalizeArguments({priority, message, opts}); const {collapsed} = opts; return this._getLogFunction({ priority, message, opts, method: (collapsed ? console.groupCollapsed : console.group) || console.info }); } groupCollapsed(priority, message, opts = {}) { return this.group(priority, message, Object.assign({}, opts, {collapsed: true})); } groupEnd(priority) { return this._getLogFunction({ priority, message: '', method: console.groupEnd || noop }); } // EXPERIMENTAL withGroup(priority, message, func) { const opts = this._normalizeArguments({ priority, message }); this.group(opts); try { func(); } finally { this.groupEnd(opts.message); } } trace() { if (console.trace) { console.trace(); } } // PRIVATE METHODS _shouldLog(priority) { priority = this._normalizePriority(priority); return priority === 0 || (this.isEnabled() && this.getPriority() >= priority); } _getElapsedTime() { const total = this.getTotal(); const delta = this.getDelta(); // reset delta timer this._deltaTs = getTimestamp(); return {total, delta}; } _getLogFunction(opts) { if (this._shouldLog(opts.priority)) { const {method} = opts; opts = this._parseArguments(opts); assert(method); let {message} = opts; const tag = opts.tag || opts.message; if (opts.once) { if (!cache[tag]) { cache[tag] = getTimestamp(); } else { return noop; } } // TODO - Make throttling work with groups // if (opts.nothrottle || !throttle(tag, this.LOG_THROTTLE_TIMEOUT)) { // return noop; // } message = this._decorateMessage(message, opts); // Bind console function so that it can be called after being returned return method.bind(console, message, ...opts.args); } return noop; } _parseArguments(options) { const normOpts = this._normalizeArguments(options); const {delta, total} = this._getElapsedTime(); // normalized opts + timings return Object.assign(options, normOpts, { delta, total }); } // Get priority from first argument: // - log(priority, message, args) => priority // - log(message, args) => 0 // - log({priority, ...}, message, args) => priority // - log({priority, message, args}) => priority _normalizePriority(priority) { let resolvedPriority; switch (typeof priority) { case 'number': resolvedPriority = priority; break; case 'object': resolvedPriority = priority.priority || 0; break; default: resolvedPriority = 0; } // 'log priority must be a number' assert(Number.isFinite(resolvedPriority) && resolvedPriority >= 0); return resolvedPriority; } // "Normalizes" the various argument patterns into an object with known types // - log(priority, message, args) => {priority, message, args} // - log(message, args) => {priority: 0, message, args} // - log({priority, ...}, message, args) => {priority, message, args} // - log({priority, message, args}) => {priority, message, args} _normalizeArguments({priority, message, args = [], opts}) { const newOpts = { priority: this._normalizePriority(priority), message, args }; switch (typeof priority) { case 'string': case 'function': if (message !== undefined) { args.unshift(message); } Object.assign(newOpts, {message: priority}); break; case 'object': Object.assign(newOpts, priority); break; default: } // Resolve functions into strings by calling them if (typeof newOpts.message === 'function') { newOpts.message = this._shouldLog(newOpts.priority) ? newOpts.message() : ''; } // 'log message must be a string' or object assert(typeof newOpts.message === 'string' || typeof newOpts.message === 'object'); // original opts + normalized opts + opts arg + fixed up message return Object.assign(newOpts, opts); } _decorateMessage(message, opts) { if (typeof message === 'string') { let time = ''; if (opts.time) { const {total} = this._getElapsedTime(); time = leftPad(formatTime(total)); } message = opts.time ? `${this.id}: ${time} ${message}` : `${this.id}: ${message}`; message = addColor(message, opts.color, opts.background); } return message; } }
JavaScript
class BasicCheckboxRenderer extends PureComponent { render() { const {indeterminate, checked, color} = this.props; return ( <Icon name={ indeterminate ? 'indeterminate-check-box' : checked ? 'check-box' : 'check-box-outline-blank' } color={color} /> ); } }
JavaScript
class CoreCheckbox extends PureComponent { static defaultProps = { disabled: false, checked: false, indeterminate: false, accent: false, }; render() { const { materialTheme, disabled, checked, indeterminate, accent, animated: animatedOverride, colorized: colorizedOverride, // unchecked box has active color disabledColor: disabledColorOverride, normalColor: normalColorOverride, tintColor: tintColorOverride, style, } = this.props; const animated = animatedOverride || materialTheme.checkbox.animated; const colorized = colorizedOverride || materialTheme.checkbox.colorized; const disabledColor = disabledColorOverride || materialTheme.checkbox.disabledColor; const normalColor = normalColorOverride || materialTheme.checkbox.normalColor; const tintColor = tintColorOverride || (accent ? materialTheme.checkbox.accentColor : materialTheme.checkbox.tintColor); const color = ( (disabled && disabledColor) || ((checked || indeterminate) && tintColor) || (colorized ? tintColor : normalColor) ); const CheckboxRenderer = animated ? AnimatedCheckboxRenderer : BasicCheckboxRenderer; return ( <View style={[ style, styles.root ]}> <CheckboxRenderer {...{indeterminate, checked, color}} /> </View> ); } }
JavaScript
class ServiceAuthConfiguration { /** * Create a ServiceAuthConfiguration. * @member {string} primaryAuthKeyHash The primary auth key hash. This is not * returned in response of GET/PUT on the resource.. To see this please call * listKeys API. * @member {string} secondaryAuthKeyHash The secondary auth key hash. This is * not returned in response of GET/PUT on the resource.. To see this please * call listKeys API. */ constructor() { } /** * Defines the metadata of ServiceAuthConfiguration * * @returns {object} metadata of ServiceAuthConfiguration * */ mapper() { return { required: false, serializedName: 'ServiceAuthConfiguration', type: { name: 'Composite', className: 'ServiceAuthConfiguration', modelProperties: { primaryAuthKeyHash: { required: true, serializedName: 'primaryAuthKeyHash', type: { name: 'String' } }, secondaryAuthKeyHash: { required: true, serializedName: 'secondaryAuthKeyHash', type: { name: 'String' } } } } }; } }
JavaScript
class Invoicex { // Put the access modifier in constructor constructor(client, details, amount) { this.client = client; this.details = details; this.amount = amount; } format() { return `${this.client} owes $ ${this.amount} for ${this.details}`; } }
JavaScript
class Profile extends Component { constructor() { super(); this.state = { authenticated: false, user: null, loading: true, }; this.socket=openSocket('http://172.21.241.15:5000'); } componentDidMount() { var socket=null; $.get( '/authenticated',(res)=>{ this.setState( { authenticated: res.authenticated,user: res.user,loading:false, // socket: socketIOClient('http://localhost:5000') }); // socket=io.connect('http://localhost:5000',{query: "id="+res.user.id}); }); this.socket.on('logout',(data)=>this.setState({authenticated: false})); } render() { this.socket.on('fuck',(data)=>alert(data.given)); if(this.state.loading) return <Loading type='bars' color='crimson' />; if(!this.state.authenticated) return <div>You are not authorized to view this page <Link to={`/home/login/${window.location.href.split('/').pop()}` } > Click Here</Link> </div> ; return ( <div > <Nav user={this.state.user} socket={this.socket}/> <div className='row'> <div className="col s12 l10 row" style={{ height:'100%',position: 'fixed','left': '0',overflow: 'auto',padding: '10px 10px 10px 10px'}}> <Switch> <Route path="/profile/feed" render={()=>(<div className='white z-depth-2' style={{ height: '100%'}}> </div>)} /> <Route exact path="/profile/messenger" component={()=><Messenger socket={this.socket} user={this.state.user} url={url}/>} /> <Route exact path="/profile/myposts" component={()=><MyPosts user={this.state.user} url={url}/>} /> <Route exact path="/profile/timeline/:id?" component={()=><Timeline user={this.state.user} socket={this.socket } url={url} /> } /> <Route exact path="/profile/search" component={()=><Search user={this.state.user} url={url} />} /> <Route component={Error404} /> </Switch> </div> <div className="col l2 hide-on-med-and-down z-depth-2" style={{ marginTop: '5px',position: 'fixed', 'height': '100%',right: '0',padding: '0' }}> <div className="people-container light-grey lighten-2" style={{ height: 'calc(100vh - 140px)', overflow: 'auto'}}> <Row className='card blue-grey darken-3' style={{ marginTop: '-5px',padding: '5px 5px 5px 5px'}}> <h6 className='white-text'>Online Users</h6> </Row> <Collection className='online-users'> <CollectionItem > <Row style={{ cursor: 'pointer '}} > <Col s={12} > <img src="https://upload.wikimedia.org/wikipedia/commons/d/d9/Edsger_Wybe_Dijkstra.jpg" alt="none" className="small-dp" /> </Col> computerScienceGOD <span className="badge green-text">Online</span> </Row> </CollectionItem> <CollectionItem>friend1</CollectionItem> <CollectionItem>friend1</CollectionItem> <CollectionItem>friend1</CollectionItem> <CollectionItem>friend1</CollectionItem> <CollectionItem>friend1</CollectionItem> </Collection> </div> <div className='Messenger'> <Input type="search" icon="search" style={{ marginLeft: '-10px'}} placeholder="Type here to search"/> </div> </div> </div> </div> ); } }
JavaScript
class RoleSectionHead extends RoleStructure { /** * @param {boolean|undefined} expanded */ set expanded(expanded) { this.setAttr(AriaExpanded, expanded) } /** * @returns {boolean|undefined} */ get expanded() { return this.getAttr(AriaExpanded) } }
JavaScript
class TCText extends React.Component { constructor(props) { super(props); console.log(this.props); this.ttxt = ''; } render () { const langprefs = this.props.langprefs; if (langprefs === 'english') { this.ttxt = this.props.englishtext; } else if (langprefs === 'spanish') { this.ttxt = this.props.spanishtext; } else { this.ttxt = this.props.spanishtext; } return ( <div>{this.ttxt}</div> ); } }
JavaScript
class ResourceLoan extends Deferred { /** * * @param {any} pooledResource the PooledResource this loan belongs to * @return {any} [description] */ constructor(pooledResource, Promise) { super(Promise); this._creationTimestamp = Date.now(); this.pooledResource = pooledResource; } reject() { /** * Loans can only be resolved at the moment */ } }
JavaScript
class PreConfigurator { /** * These limits define up to which node count the specific setting is considered as practical. * It also defines a fall-back GraphModelManager setting that is used, if the default GMM * is not practical anymore. */ get preConfigurationLimits() { return { simpleSvgStyles: { defaultGmm: { view: 2000, move: 500, edit: 500 }, levelOfDetailGmm: { view: 2000, move: 500, edit: 500 }, staticGmm: { view: 2000, move: 2000, edit: 2000 }, svgImageGmm: { view: 2000, move: 2000, edit: 2000 }, CanvasImageWithDrawCallbackGmm: { view: 15000, move: 15000, edit: 15000 }, CanvasImageWithItemStylesGmm: { view: 15000, move: 15000, edit: 15000 }, StaticCanvasImageGmm: { view: 15000, move: 15000, edit: 15000 }, StaticWebglImageGmm: { view: 20000, move: 20000, edit: 20000 } }, complexSvgStyles: { defaultGmm: { view: 500, move: 500, edit: 500 }, levelOfDetailGmm: { view: 2000, move: 500, edit: 500 }, staticGmm: { view: 2000, move: 2000, edit: 2000 }, svgImageGmm: { view: 2000, move: 5000, edit: 2000 }, CanvasImageWithDrawCallbackGmm: { view: 15000, move: 15000, edit: 15000 }, CanvasImageWithItemStylesGmm: { view: 15000, move: 15000, edit: 5000 }, StaticCanvasImageGmm: { view: 15000, move: 15000, edit: 5000 }, StaticWebglImageGmm: { view: 20000, move: 20000, edit: 20000 } }, simpleCanvasStyles: { defaultGmm: { view: 11000, move: 5000, edit: 5000 }, levelOfDetailGmm: { view: 2000, move: 500, edit: 500 }, staticGmm: { view: 11000, move: 11000, edit: 11000 }, svgImageGmm: { view: 20000, move: 15000, edit: 15000 }, CanvasImageWithDrawCallbackGmm: { view: 20000, move: 15000, edit: 15000 }, CanvasImageWithItemStylesGmm: { view: 20000, move: 15000, edit: 15000 }, StaticCanvasImageGmm: { view: 2000, move: 2000, edit: 2000 }, StaticWebglImageGmm: { view: 20000, move: 20000, edit: 20000 } }, complexCanvasStyles: { defaultGmm: { view: 500, move: 500, edit: 500 }, levelOfDetailGmm: { view: 2000, move: 500, edit: 500 }, staticGmm: { view: 500, move: 500, edit: 500 }, svgImageGmm: { view: 20000, move: 15000, edit: 15000 }, CanvasImageWithDrawCallbackGmm: { view: 20000, move: 15000, edit: 15000 }, CanvasImageWithItemStylesGmm: { view: 20000, move: 5000, edit: 5000 }, StaticCanvasImageGmm: { view: 2000, move: 2000, edit: 2000 }, StaticWebglImageGmm: { view: 20000, move: 20000, edit: 20000 } }, WebGLStyles: { defaultGmm: { view: 11000, move: 5000, edit: 5000 }, levelOfDetailGmm: { view: 11000, move: 5000, edit: 5000 }, staticGmm: { view: 11000, move: 11000, edit: 11000 }, svgImageGmm: { view: 20000, move: 15000, edit: 15000 }, CanvasImageWithDrawCallbackGmm: { view: 20000, move: 15000, edit: 15000 }, CanvasImageWithItemStylesGmm: { view: 20000, move: 15000, edit: 15000 }, StaticCanvasImageGmm: { view: 2000, move: 2000, edit: 2000 }, StaticWebglImageGmm: { view: 20000, move: 20000, edit: 20000 } } } } /** * Constructs a new instance and registers listeners to the graph item styles radio buttons. */ constructor(graphComponent) { this.graphItemStylesSettings = document.getElementById('settingsGraphItemStyles') this.warningRadios = document.getElementsByClassName('mayHaveWarning') const radioButtons = this.graphItemStylesSettings.getElementsByTagName('input') for (let i = 0; i < radioButtons.length; i++) { radioButtons[i].addEventListener('click', this.updatePreConfiguration.bind(this)) } this.graphComponent = graphComponent this.modeMapping = ['view', 'move', 'edit'] } /** * On change of graph or graph item style, the pre configuration is loaded and applied. */ updatePreConfiguration() { const nodeCount = this.graphComponent.graph.nodes.size // remove unrecommended classes const unrecommendedLabels = document.getElementsByClassName('unrecommended') while (unrecommendedLabels.length > 0) { const label = unrecommendedLabels[0] label.className = label.className.replace(/\s?\bunrecommended\b/, '') } // get current graph item style let graphItemStyle for (let i = 0; i < this.graphItemStylesSettings.childElementCount; i++) { const node = this.graphItemStylesSettings.children[i] if (node.checked) { graphItemStyle = node.value break } } const editMode = this.modeMapping[document.getElementById('modeChooserBox').selectedIndex] // get style specific limits const styleLimits = this.preConfigurationLimits[graphItemStyle] // set unrecommended classes Object.keys(styleLimits).forEach(gmmOptimization => { const styleLimit = styleLimits[gmmOptimization][editMode] if ( {}.hasOwnProperty.call(styleLimits, gmmOptimization) && typeof styleLimit === 'number' && styleLimit < nodeCount ) { document.getElementById(`${gmmOptimization}-radio`).nextElementSibling.className += ' unrecommended' } }) } /** * Adds the warning class to the respective items. */ addWarningCssClass() { for (let i = 0; i < this.warningRadios.length; i++) { const warningLabel = this.warningRadios[i].nextElementSibling if (warningLabel.className.indexOf('warning') < 0) { warningLabel.className = `${warningLabel.className} warning` } } } /** * Removes the warning class from the respective items. */ removeWarningCssClass() { for (let i = 0; i < this.warningRadios.length; i++) { const warningLabel = this.warningRadios[i].nextElementSibling warningLabel.className = warningLabel.className.replace(/\s?\bwarning\b/, '') } } }
JavaScript
class UserController { /** * Show a list of all users. * * GET auth/users * * @method index * * @return {Object} users */ async index() { const users = await User.all(); return users; } /** * Passing the uid from the client-side form, Adonis Persona finds the user using the uid and then fires a `forgot::password` event with a temporary token used to verify the password reset request * * GET auth/forgot/password * * @method forgotPassword * * @param {String} uid * * @return {void} * */ async forgotPassword({ request }) { return await Persona.forgotPassword(request.input("uid")); } /** * Using the auth object, a token is generated for the currently authorized user. * * GET auth/user * * @method getCurrentUser * * @param {Object} auth * * @return {Object} user * */ async getCurrentUser({ auth }) { const user = await auth.getUser(); const token = await auth.getAuthHeader(); return user; } /** * Verify the user using the uid and password passed from the client-side form. * Return a token to the client to sync authentication with server. * * POST auth/login * * @method login * * @param {Object} request, auth * * @return {String} token * */ async login({ request, auth }) { const payload = request.only(["uid", "password"]); const user = await Persona.verify(payload); const token = await auth.generate(user); return token; } /** * Revoke authentication for user using token. * * POST auth/logout * * @method logout * * @param {Object} auth * * @return {Object} user * */ async logout({ auth }) { const user = await auth.getUser(); const token = await auth.getAuthHeader(); // revoke token await user.tokens().where("token", token).update({ is_revoked: true }); return user; } /** * Passing inputs from client-side registration form, create full name and profile image then add the user to the user's table. * Adonis Persona generates an email verification token and fires a user::created event. * * POST auth/register * * @method register * * @param {Object} request, auth * * @return {String} token * */ async register({ request, auth }) { const payload = request.only([ "email", "first_name", "last_name", "password", "password_confirmation", ]); const { first_name, last_name } = payload; // create full_name payload.full_name = `${first_name} ${last_name}`; // set default profile image to user initials payload.profile_image_source = `https://ui-avatars.com/api/?name=${first_name}+${last_name}`; // add the newly registered user to the user table, triggers mail event, returns user const user = await Persona.register(payload); const token = await auth.generate(user); return token; } /** * Show a user profile matching the id in the query string param. * * GET /users/:id * * @method show * * @param {Object} auth, params * * @return {Object} user * */ async show({ auth, params }) { const { id } = params; const user = await auth.getUser(); // verify current user id matches id from query params if (user.id !== Number(id)) { // if no match, log error. No return of user data. return "You cannot view another user's profile"; } return user; } /** * Passing inputs from client-side profile edit form, update the user's profile information. * Use Adonis Persona to update the user in the user table. * * PATCH auth/update * * @method update * * @param {Object} request, auth * * @return {Object} updatedUser * */ async update({ request, auth }) { // TODO: allow partial update with only some fields const user = await auth.getUser(); const payload = request.only(["first_name", "last_name"]); // create full name field payload.full_name = `${payload.first_name} ${payload.last_name}`; await Persona.updateProfile(user, payload); const updatedUser = await auth.getUser(); return updatedUser; } /** * Passing inputs from client-side profile edit form, update the user's email * Use Adonis Persona to update the user's email, generate a email verification token, and triggers an email::changed event * * PATCH auth/update/email * * @method updateEmail * * @param {Object} request, auth * * @return {Object} updatedUser * */ async updateEmail({ request, auth }) { const payload = request.only(["email"]); const user = await auth.user; const updatedUser = await Persona.updateProfile(user, payload); return updatedUser; } /** * Passing profile pic from client-side upload form, move file to public folder and update user's profile image source field. * * POST auth/update/profile-pic * * @method updateProfilePic * * @param {Object} request, auth * * @return {Object} user * */ async updateProfilePic({ request, auth }) { const user = await auth.user; // create file from client upload const file = await request.file("profileImage"); // if file is not null or undefined, move the image file to the static/images folder if (file) { // move the image to the public images folder and name with format `first-last-1.filetype` (ex. jeremy-bratcher-1.jpg) overwriting any images with the same name await file.move(Helpers.appRoot("public/images"), { name: `${user.first_name}-${user.last_name}-${user.id}.${file.subtype}`, overwrite: true, }); // if the file wasn't able to be moved, respond to client with the error response if (!file.moved()) { return file.error(); } // Update the image link in the user's image source column user.profile_image_source = `${Env.get("APP_URL")}/images/${ user.first_name }-${user.last_name}-${user.id}.${file.subtype}`; user.save(); return user; } // if there in no file, log message and return return "No file uploaded"; } /** * Passing old, new, and confirmation of new password from client-side form, update user's password. * Triggers a password::changed event. * * PATCH auth/update/password * * @method updatePassword * * @param {Object} request, auth * * @return {Object} updatedUser * */ async updatePassword({ request, auth }) { const payload = request.only([ "old_password", "password", "password_confirmation", ]); const user = await auth.getUser(); const updatedUser = await Persona.updatePassword(user, payload); return updatedUser; } /** * Passing old, new, and confirmation of new password from client-side form, update the user's password. * Adonis Persona verifies the token, ensures the password is confirmed and updates the user's password. * A password::recovered event is fired. * * POST auth/update/password-by-token * * @method updatePasswordByToken * * @param {Object} request * * @return {Object} user * */ async updatePasswordByToken({ request }) { const token = decodeURIComponent(request.input("token")); const payload = request.only(["password", "password_confirmation"]); const user = await Persona.updatePasswordByToken(token, payload); return user; } /** * Using the email token from a new registration email link, activate the user's account. * Adonis Persona removes the email token from the tokens table and changes the account status of the user to 'active'. * * GET auth/verify-email * * @method verifyEmail * * @param {Object} request * * @return {Object} user * */ async verifyEmail({ request }) { // get token from query string params in URL const token = request.input("token"); const user = await Persona.verifyEmail(token); // respond to client with updated user data object return user; } }
JavaScript
class MainRouter extends PureComponent { render() { // TODOS: temporarily remove router // /create // /report // <IndexRoute component={List} /> // <Route path="create" component={Create} /> return ( <Router history={this.props.history}> <Route path="*" component={Portal} /> </Router> ); } }
JavaScript
class Login extends Component { render() { return ( <div className="centered" style={{}}> <form className="logina" onSubmit={this.handleSubmit}> <h3>Sign In</h3> <div className="form-group"> <label>Email address</label> <input type="email" className="form-control" placeholder="Enter email" /> </div> <div className="form-group"> <label>Password</label> <input type="password" className="form-control" placeholder="Enter password" /> </div> <div className="form-group"> <div className="custom-control custom-checkbox"> <input type="checkbox" className="custom-control-input" id="customCheck1" /> <label className="custom-control-label" htmlFor="customCheck1">Remember me</label> </div> </div> <Link to="/"> <Button type="submit" className="btn btn-primary btn-block">Submit</Button> </Link> </form> </div> ); } }
JavaScript
class TransactionHeader extends PureComponent { static propTypes = { /** * Object containing current page title and url */ currentPageInformation: PropTypes.object, /** * String representing the selected network */ networkType: PropTypes.string }; /** * Returns a small circular indicator, red if the current selected network is offline, green if it's online. *= * @return {element} - JSX view element */ renderNetworkStatusIndicator = () => { const { networkType } = this.props; const networkStatusIndicatorColor = (networkList[networkType] && networkList[networkType].color) || colors.red; const networkStatusIndicator = ( <View style={[styles.networkStatusIndicator, { backgroundColor: networkStatusIndicatorColor }]} /> ); return networkStatusIndicator; }; /** * Returns a secure icon next to the dApp URL. Lock for https protocol, warning sign otherwise. *= * @return {element} - JSX image element */ renderSecureIcon = () => { const { url } = this.props.currentPageInformation; const secureIcon = ( <FontAwesome name={getUrlObj(url).protocol === 'https:' ? 'lock' : 'warning'} size={15} style={styles.secureIcon} /> ); return secureIcon; }; render() { const { currentPageInformation: { url }, networkType } = this.props; const title = getHost(url); const networkName = networkList[networkType].shortName; return ( <View style={styles.transactionHeader}> <WebsiteIcon style={styles.domainLogo} viewStyle={styles.assetLogo} title={title} url={url} /> <View style={styles.domanUrlContainer}> {this.renderSecureIcon()} <Text style={styles.domainUrl}>{title}</Text> </View> <View style={styles.networkContainer}> {this.renderNetworkStatusIndicator()} <Text style={styles.network}>{networkName}</Text> </View> </View> ); } }
JavaScript
class Command extends Piece { /** * @typedef {PieceOptions} CommandOptions * @property {(string|Function)} [description=''] The help description for the command * @property {boolean} [guarded=false] If the command can be disabled on a guild level (does not effect global disable) */ /** * @since 0.0.1 * @param {CommandStore} store The Command store * @param {Array} file The path from the pieces folder to the command file * @param {string} directory The base directory to the pieces folder * @param {CommandOptions} [options={}] Optional Command settings */ constructor(store, file, directory, options = {}) { super(store, file, directory, options); this.name = this.name.toLowerCase(); /** * Whether this command should not be able to be disabled in a guild or not * @since 0.5.0 * @type {boolean} */ this.guarded = options.guarded; /** * The full category for the command * @since 0.0.1 * @type {string[]} */ this.fullCategory = file.slice(0, -1); } /** * The run method to be overwritten in actual commands * @since 0.0.1 * @param {string} message The command message mapped on top of the message used to trigger this command * @param {any[]} params The fully resolved parameters based on your usage / usageDelim * @returns {string|string[]} You should return the response message whenever possible * @abstract */ async run() { // Defined in extension Classes throw new Error(`The run method has not been implemented by ${this.type}:${this.name}.`); } /** * Defines the JSON.stringify behavior of this command. * @returns {Object} */ toJSON() { return { ...super.toJSON(), guarded: this.guarded, fullCategory: this.fullCategory }; } }
JavaScript
class TableHeader extends DOMComponent { static propTypes = { children: PropTypes.arrayOf(PropTypes.object).isRequired, } render() { return this.props.children; } static transform(DOM) { return DOM.map((item) => { if (item.ref instanceof TableHeaderItem) { return item.ref.constructor.transform(item.value); } const blankTableItem = new TableHeaderItem(); const transform = blankTableItem.constructor.transform(blankTableItem.render()); return transform; }); } }
JavaScript
class ClientTransmitter { /** * @param {string} address the IP or hostname of the server container to transmit to */ constructor(address) { this.address = address; /** * A function for transmitting state to the server container * @param {string} req the name of the request to transmit to the server * @param {any[]} params any parameters to pass to the request function */ this.transmitState = (req, params) => { try { let request = require(`../requests/${req}`); request.run(this.address, ...params); } catch (err) { console.error(`Request ${req} failed to run!`); } }; } }
JavaScript
class UrlMapping { constructor(prefix) { this.prefix_ = prefix; } /** * This method checks if a given URL is a canonical page and * should be transformed, or if it should be served as a valid AMP. * * @param {string} url to be checked if it is AMP. * @returns {boolean} true, if the url is an AMP url. */ isAmpUrl(url) { const parsedUrl = URL.parse(url); const searchParams = this.parseUrlSearchParams_(parsedUrl); return searchParams.has(this.prefix_); } /** * Given a canonical URL, transforms it to the AMP equivalent. * * @param {string} canonicalUrl the canonical URL * @returns {string} the equivalent AMP url for that page. */ toAmpUrl(canonicalUrl) { const parsedUrl = URL.parse(canonicalUrl); const searchParams = this.parseUrlSearchParams_(parsedUrl); searchParams.set(this.prefix_, '1'); return this.formatUrl_(parsedUrl, searchParams); } /** * Given an AMP URL, returns the canonical equivalent * * @param {string} ampUrl the AMP URL * @returns {string} the equivalent canonical URL for the AMP page. */ toCanonicalUrl(ampUrl) { const parsedUrl = URL.parse(ampUrl); const searchParams = this.parseUrlSearchParams_(parsedUrl); searchParams.delete(this.prefix_); return this.formatUrl_(parsedUrl, searchParams); } formatUrl_(parsedUrl, searchParams) { parsedUrl.search = searchParams.toString(); return URL.format(parsedUrl); } parseUrlSearchParams_(parsedUrl) { return new URLSearchParams(parsedUrl.search || ''); } }
JavaScript
class RPN { constructor() { this._arInputs = []; } get InputArray() { return this._arInputs; } /** * Save to string */ toString() { return this._arInputs.join(' '); } /** * Build the express to PRN format * @param exp Express string, like 3*(4+5) */ buildExpress(exp) { let skOp = new Array(); const operations = "+-*/"; let digit = ""; for (let i = 0; i < exp.length; i++) { let token = exp.charAt(i); if (!Number.isNaN(+token)) // Digitials { digit += token; } else if (operations.indexOf(token) >= 0) { if (digit.length > 0) { this._arInputs.push(digit); digit = ""; } while (skOp.length > 0) { var opInStack = skOp.pop(); if (opInStack === '(' || RPNOperationPriority(opInStack) < RPNOperationPriority(token)) { skOp.push(opInStack); break; } else { this._arInputs.push(opInStack); } } skOp.push(token); } else if (token === '(') { skOp.push(token); } else if (token === ')') { if (digit.length > 0) { this._arInputs.push(digit); digit = ""; } while (skOp.length > 0) { var opInStack = skOp.pop(); if (opInStack === '(') { break; } else { this._arInputs.push(opInStack); } } } } if (digit.length > 0) { this._arInputs.push(digit); } while (skOp.length > 0) { var opInStack = skOp.pop(); this._arInputs.push(opInStack); } return this._arInputs.toString(); } /** * Workout the final result */ WorkoutResult() { let stack = new Array(); let result = 0; for (let i = 0; i < this._arInputs.length; i++) { let c = this._arInputs[i]; if (!Number.isNaN(+c)) { stack.push(c); } else if (c === '+' || c === '-' || c === '*' || c === '/') { var nextNum = parseFloat(stack.pop()); var prevNum = parseFloat(stack.pop()); result = RPNGetOperatorResult(prevNum, nextNum, c); stack.push(result); } } return result; } // integer // fraction // decimal fraction VerifyResult(allowNegative, allowDecimal) { let stack = new Array(); let result = 0; for (let i = 0; i < this._arInputs.length; i++) { let c = this._arInputs[i]; if (!Number.isNaN(+c)) { stack.push(c); } else if (c === '+' || c === '-' || c === '*' || c === '/') { let nextNum = parseFloat(stack.pop()); if (!Number.isInteger(nextNum) && !allowDecimal) { return false; } if (nextNum < 0 && !allowNegative) { return false; } let prevNum = parseFloat(stack.pop()); if (!Number.isInteger(prevNum) && !allowDecimal) { return false; } if (prevNum < 0 && !allowNegative) { return false; } result = RPNGetOperatorResult(prevNum, nextNum, c); if (!Number.isInteger(result) && !allowDecimal) { return false; } if (result < 0 && !allowNegative) { return false; } stack.push(result); } } return true; } }
JavaScript
class ProductsDisplayContainer extends Component { render () { return ( <ProductsDisplay {...this.props} paramId={this.props.paramId} /> ); } }
JavaScript
class ModalDialog { constructor() { // The modal help group. this.modalHelpGroup = ""; // The modal output function. this.modalOutputFn = null; // The modal final function. this.modalFinalFn = null; // The modal temporary help objects. this.modalHelpTemps = []; // The modal general help object. let _this = this; this.modalHelpGeneral = new bootstrap.Popover(document.getElementById("modalHelp"), { content: function() { return _this.modalHelpContent(this); }, title: function() { return _this.modalHelpTitle(this); }, customClass: "div-popover", html: true }); document.getElementById("divModal").addEventListener("click", e => this.modalClick(e), true); // Capture document.getElementById("modalBody").addEventListener("keyup", e => this.modalKeyUp(e)); document.getElementById("modalClose").addEventListener("click", () => this.modalClose(false)); document.getElementById("modalCancel").addEventListener("click", () => this.modalClose(false)); document.getElementById("modalOK").addEventListener("click", () => this.modalClose(true)); } /** * Show a modal dialog. * @param {string} title The modal dialog title. * @param {string} helpGroup The modal help group. * @param {object} body The modal dialog body. * @param {object} options The options structure. */ modalShow(title, helpGroup, body, options = {}) { let modalTitle = document.getElementById("modalTitle"); let modalBody = document.getElementById("modalBody"); modalTitle.innerHTML = title; modalBody.innerHTML = body; this.modalHelpGroup = helpGroup; this.modalOutputFn = options.outputFn; this.modalFinalFn = options.finalFn; let btnCancel = document.getElementById("modalCancel"); let btnOK = document.getElementById("modalOK"); btnOK.innerHTML = options.textOK ? options.textOK : "OK"; btnCancel.innerHTML = options.textCancel ? options.textCancel : ""; btnCancel.style.display = options.textCancel ? "inline-block" : "none"; let divBackground = document.getElementById("divBackground"); let divModal = document.getElementById("divModal"); divModal.classList.remove("div-modal"); divModal.classList.remove("div-modal-lg"); divModal.classList.add(options.largeModal ? "div-modal-lg" : "div-modal"); divBackground.style.display = "block"; divModal.style.display = "block"; this.modalHelpTemps = []; let _this = this; let elems = document.getElementsByClassName("btnHelp"); for (let elem of elems) { this.modalHelpTemps.push(new bootstrap.Popover(elem, { content: function() { return _this.modalHelpContent(this); }, title: function() { return _this.modalHelpTitle(this); }, customClass: "div-popover", html: true })); } elems = document.getElementsByClassName("btnHelpDefault"); for (let elem of elems) { this.modalHelpTemps.push(new bootstrap.Popover(elem, { customClass: "div-popover", html: true })); } if (options.inputFn) { options.inputFn(options.inputData); } let firstInput = modalBody.querySelector("input,select"); if (firstInput) firstInput.focus(); } /** * Close the currently open modal dialog. * @param {bool} isOK The OK button was pressed. */ modalClose(isOK) { this.modalHelpGeneral.hide(); for (let help of this.modalHelpTemps) { help.dispose(); } this.modalHelpTemps = []; let result = null; if (this.modalOutputFn) { result = this.modalOutputFn(isOK); if (!result) return; } let divBackground = document.getElementById("divBackground"); let divModal = document.getElementById("divModal"); divBackground.style.display = "none"; divModal.style.display = "none"; let modalTitle = document.getElementById("modalTitle"); let modalBody = document.getElementById("modalBody"); modalTitle.innerHTML = ""; modalBody.innerHTML = ""; let finalFn = this.modalFinalFn; this.modalHelpGroup = ""; this.modalOutputFn = null; this.modalFinalFn = null; if (finalFn) { result = finalFn(isOK, result); // A recursive call to modalShow can be done here } } /** * Called for help content with a modal dialog. * @param {object} elem Element for popover. */ modalHelpContent(elem) { let helpGroup = this.modalHelpGroup; let helpKey = elem.dataset.help; let helpElem = null; for (let elem of global.config.helpForms) { if (elem.group === helpGroup && elem.name === helpKey) { helpElem = elem; break; } } if (!helpElem) return ""; let result = ""; for (let s of helpElem.value) { if (result.length > 0) result += " "; result += s; } return result; } /** * Called for help title with a modal dialog. * @param {object} elem Element for popover. */ modalHelpTitle(elem) { let helpGroup = this.modalHelpGroup; let helpKey = elem.dataset.help; return helpGroup + "/" + helpKey; } /** * Create template events, refresh display, and show parameters. * @param {object} self Self object. * @param {string} event Event name. */ createTemplateEventsShowParameters(self, event) { let paramCount = updater.createTemplateEvents(self, event); if (paramCount === 0) return; setTimeout(function() { showParameters(self, rowIndex, constant.TABLE_EVENT); }, 100); } /** * Event type output callback. * @param {object} self Self object. * @param {number} rowIndex Event row index. */ extensionOutput(self, rowIndex) { if (self.activeTabIndex < 0) return; let tab = self.tabs[self.activeTabIndex]; let row = tab.eventValues[rowIndex]; let extension = JSON.parse(JSON.stringify(row.extension)); // Copy if ("current-value" in extension) { let ext = extension["current-value"]; let cvEom = document.getElementById("cvEom"); ext["eom"] = cvEom.checked ? true : false; let cvPassive = document.getElementById("cvPassive"); ext["passive"] = cvPassive.checked ? true : false; let cvPresent = document.getElementById("cvPresent"); ext["present"] = cvPresent.checked ? true : false; } else if ("interest-change" in extension) { let ext = extension["interest-change"]; let icMethod = document.getElementById("icMethod"); ext["interest-method"] = icMethod.options[icMethod.selectedIndex].value; let icDayCount = document.getElementById("icDayCount"); ext["day-count-basis"] = icDayCount.options[icDayCount.selectedIndex].value let icDaysInYear = document.getElementById("icDaysInYear"); let val = parseInt(icDaysInYear.value); ext["days-in-year"] = isNaN(val) ? "0" : val.toString(); let icEffFreq = document.getElementById("icEffFreq"); ext["effective-frequency"] = icEffFreq.options[icEffFreq.selectedIndex].value let icIntFreq = document.getElementById("icIntFreq"); ext["interest-frequency"] = icIntFreq.options[icIntFreq.selectedIndex].value let icRoundBal = document.getElementById("icRoundBal"); ext["round-balance"] = icRoundBal.options[icRoundBal.selectedIndex].value let icRoundDD = document.getElementById("icRoundDD"); val = parseFloat(icRoundDD.value); ext["round-decimal-digits"] = isNaN(val) ? "0" : val.toString(); } else if ("statistic-value" in extension) { let ext = extension["statistic-value"]; let svName = document.getElementById("svName"); ext["name"] = svName.value; let svEom = document.getElementById("svEom"); ext["eom"] = svEom.checked ? true : false; let svFinal = document.getElementById("svFinal"); ext["final"] = svFinal.checked ? true : false; } else { let ext = extension["principal-change"]; let pcType = document.getElementById("pcType"); ext["principal-type"] = pcType.options[pcType.selectedIndex].value let pcEom = document.getElementById("pcEom"); ext["eom"] = pcEom.checked ? true : false; let pcPrinFirst = document.getElementById("pcPrinFirst"); ext["principal-first"] = pcPrinFirst.checked ? true : false; let pcBalStats = document.getElementById("pcBalStats"); ext["statistics"] = pcBalStats.checked ? true : false; let pcAuxiliary = document.getElementById("pcAuxiliary"); ext["auxiliary"] = pcAuxiliary.checked ? true : false; let pcAuxPassive = document.getElementById("pcAuxPassive"); ext["passive"] = pcAuxPassive.checked ? true : false; } return extension; } /** * Event type output callback. * @param {object} self Self object. * @param {number} rowIndex Event row index. * @param {object} data Output data. */ extensionFinal(self, rowIndex, data) { if (self.activeTabIndex < 0) return; let tab = self.tabs[self.activeTabIndex]; let row = tab.eventValues[rowIndex]; let extension = data; let result = self.engine.set_extension_values(self.activeTabIndex, rowIndex, JSON.stringify(extension)); if (result.length > 0) { row.extension = extension; let gridRow = tab.grdEventOptions.api.getDisplayedRowAtIndex(tab.lastFocused.rowIndex); gridRow.setDataValue(tab.lastFocused.colDef.col_name, result); updater.refreshAmResults(self); updater.updateTabLabel(self, self.activeTabIndex, true); } } /** * Respond to the modal click capture event. * @param {object} e Event object. */ modalClick(e) { if (e && e.target && ( e.target.hasAttribute("aria-describedby") || e.target.parentElement && e.target.parentElement.hasAttribute("aria-describedby"))) return; this.modalHelpGeneral.hide(); for (let help of this.modalHelpTemps) { help.hide(); } } /** * Respond to the modal dialog key up. * @param {object} e Event object. */ modalKeyUp(e) { if (e.keyCode === 27) { // Escape this.modalClick(null); return; } if (e.keyCode !== 13 || e.shiftKey || e.ctrlKey || e.altKey) return; this.modalClose(true); } /** * Show a chart in a modal dialog. * @param {object} self Self object. * @param {object} chartDef The chart definition. */ showChart(self, chartDef) { let body = `<canvas id="canvasChart" class="max-element"></canvas>`; this.modalShow(chartDef.description, constant.HelpChart, body, { largeModal: true, inputFn: chartUtility.inputChartFn, inputData: { self: self, chartDef: chartDef } }); } /** * Show a confirmation modal dialog. * @param {object} self Self object. * @param {string} text The confirmation text. * @param {object} confirmFn The function to call if OK. * @param {object} cancelFn The function to call if Cancel. * @param {number} index The tab index. */ showConfirm(self, text, confirmFn, cancelFn, index) { this.modalShow(updater.getResource(self, constant.MODAL_CONFIRMATION), constant.HelpConfirm, text, { textCancel: updater.getResource(self, constant.MODAL_NO), textOK: updater.getResource(self, constant.MODAL_YES), finalFn: (isOK) => { if (isOK) { setTimeout(function() { confirmFn(self, index); }, 100); } else { setTimeout(function() { cancelFn(self, index); }, 100); } } }); } /** * Show a descriptor list in a modal dialog. * @param {object} self Self object. * @param {number} rowIndex The row index. * @param {number} tableType The type of table. */ showDescriptors(self, rowIndex, tableType) { let body = `<div class="row align-items-center"> <div class="col-2"> <strong>${updater.getResource(self, constant.MODAL_DESC_GROUP)}</strong> </div> <div class="col-2"> <strong>${updater.getResource(self, constant.MODAL_DESC_NAME)}</strong> </div> <div class="col-1"> <strong>${updater.getResource(self, constant.MODAL_DESC_TYPE)}</strong> </div> <div class="col-1"> <strong>${updater.getResource(self, constant.MODAL_DESC_CODE)}</strong> </div> <div class="col-5"> <strong>${updater.getResource(self, constant.MODAL_DESC_VALUE)}</strong> </div> <div class="col-1"> <strong>${updater.getResource(self, constant.MODAL_DESC_PROPAGATE)}</strong> </div> </div>`; let list = self.engine.parse_descriptors(self.activeTabIndex, rowIndex, tableType); for (let elem of list) { body += `<div class="row align-items-center"> <div class="col-2"> ${elem.group} </div> <div class="col-2"> ${elem.name} </div> <div class="col-1"> ${elem.desc_type} </div> <div class="col-1"> ${elem.code} </div> <div class="col-5"> ${elem.value} </div> <div class="col-1"> ${elem.propagate} </div> </div>`; } this.modalShow(updater.getResource(self, constant.MODAL_DESCRIPTOR_LIST), constant.HelpDescriptor, body, { largeModal: true }); } /** * Show an extension in a modal dialog. * @param {object} self Self object. * @param {number} rowIndex Row index. * @param {number} tableType The type of table. * @param {object} options The options structure. */ showExtension(self, rowIndex, tableType, options = {}) { let enable = tableType === constant.TABLE_EVENT; let extension; if (tableType === constant.TABLE_EVENT) { extension = self.tabs[self.activeTabIndex].eventValues[rowIndex].extension; } else if (self.tabs[self.activeTabIndex].expanded) { extension = self.tabs[self.activeTabIndex].amValues.expanded[rowIndex].extension; } else { extension = self.tabs[self.activeTabIndex].amValues.compressed[rowIndex].extension; } if ("current-value" in extension) { let ext = extension["current-value"]; this.modalShow(updater.getResource(self, constant.MODAL_CURRENT_VALUE), constant.HelpCurrentValue, `<div class="row align-items-center"> <div class="col-6"> <label for="cvEom" class="col-form-label">${updater.getResource(self, constant.MODAL_CV_EOM)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="eom"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input class="form-check-input" type="checkbox" id="cvEom" ${ext["eom"] ? 'checked' : ''} ${enable ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="cvPassive" class="col-form-label">${updater.getResource(self, constant.MODAL_CV_PASSIVE)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="passive"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input class="form-check-input" type="checkbox" id="cvPassive" ${ext["passive"] ? 'checked' : ''} ${enable ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="cvPresent" class="col-form-label">${updater.getResource(self, constant.MODAL_CV_PRESENT)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="present"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input class="form-check-input" type="checkbox" id="cvPresent" ${ext["present"] ? 'checked' : ''} ${enable ? '' : 'disabled'}> </div> </div>`, options ); return; } if ("interest-change" in extension) { let ext = extension["interest-change"]; let form = `<div class="row align-items-center"> <div class="col-6"> <label for="icMethod" class="col-form-label">${updater.getResource(self, constant.MODAL_IC_METHOD)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="interest-method"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <select id="icMethod" class="form-select form-select-sm" ${enable ? '' : 'disabled'}> <option value="actuarial" ${ext["interest-method"] === 'actuarial' ? 'selected' : ''}>${updater.getResource(self, constant.METHOD_ACTUARIAL)}</option> <option value="simple-interest" ${ext["interest-method"] === 'simple-interest' ? 'selected' : ''}>${updater.getResource(self, constant.METHOD_SIMPLE_INTEREST)}</option> </select> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="icDayCount" class="col-form-label">${updater.getResource(self, constant.MODAL_IC_DAY_COUNT)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="day-count-basis"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <select id="icDayCount" class="form-select form-select-sm" ${enable ? '' : 'disabled'}> <option value="periodic" ${ext["day-count-basis"] === 'periodic' ? 'selected' : ''}>${updater.getResource(self, constant.DAY_COUNT_PERIODIC)}</option> <option value="rule-of-78" ${ext["day-count-basis"] === 'rule-of-78' ? 'selected' : ''}>${updater.getResource(self, constant.DAY_COUNT_RULE_OF_78)}</option> <option value="actual" ${ext["day-count-basis"] === 'actual' ? 'selected' : ''}>${updater.getResource(self, constant.DAY_COUNT_ACTUAL)}</option> <option value="actual-actual-isma" ${ext["day-count-basis"] === 'actual-actual-isma' ? 'selected' : ''}>${updater.getResource(self, constant.DAY_COUNT_ACTUAL_ISMA)}</option> <option value="actual-actual-afb" ${ext["day-count-basis"] === 'actual-actual-afb' ? 'selected' : ''}>${updater.getResource(self, constant.DAY_COUNT_ACTUAL_AFB)}</option> <option value="actual-365L" ${ext["day-count-basis"] === 'actual-365L' ? 'selected' : ''}>${updater.getResource(self, constant.DAY_COUNT_ACTUAL_365L)}</option> <option value="30" ${ext["day-count-basis"] === '30' ? 'selected' : ''}>${updater.getResource(self, constant.DAY_COUNT_30)}</option> <option value="30E" ${ext["day-count-basis"] === '30E' ? 'selected' : ''}>${updater.getResource(self, constant.DAY_COUNT_30E)}</option> <option value="30EP" ${ext["day-count-basis"] === '30EP' ? 'selected' : ''}>${updater.getResource(self, constant.DAY_COUNT_30EP)}</option> </select> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="icDaysInYear" class="col-form-label">${updater.getResource(self, constant.MODAL_IC_DAYS_IN_YEAR)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="days-in-year"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="icDaysInYear" class="form-control form-control-sm" value="${ext["days-in-year"]}" ${enable ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="icEffFreq" class="col-form-label">${updater.getResource(self, constant.MODAL_IC_EFF_FREQ)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="effective-frequency"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <select id="icEffFreq" class="form-select form-select-sm" ${enable ? '' : 'disabled'}> <option value="none" ${ext["effective-frequency"] === 'none' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_NONE)}</option> <option value="1-year" ${ext["effective-frequency"] === '1-year' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_1_YEAR)}</option> <option value="6-months" ${ext["effective-frequency"] === '6-months' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_6_MONTHS)}</option> <option value="4-months" ${ext["effective-frequency"] === '4-months' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_4_MONTHS)}</option> <option value="3-months" ${ext["effective-frequency"] === '3-months' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_3_MONTHS)}</option> <option value="2-months" ${ext["effective-frequency"] === '2-months' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_2_MONTHS)}</option> <option value="1-month" ${ext["effective-frequency"] === '1-month' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_1_MONTH)}</option> <option value="half-month" ${ext["effective-frequency"] === 'half-month' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_HALF_MONTH)}</option> <option value="4-weeks" ${ext["effective-frequency"] === '4-weeks' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_4_WEEKS)}</option> <option value="2-weeks" ${ext["effective-frequency"] === '2-weeks' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_2_WEEKS)}</option> <option value="1-week" ${ext["effective-frequency"] === '1-week' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_1_WEEK)}</option> <option value="1-day" ${ext["effective-frequency"] === '1-day' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_1_DAY)}</option> <option value="continuous" ${ext["effective-frequency"] === 'continuous' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_CONTINUOUS)}</option> </select> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="icIntFreq" class="col-form-label">${updater.getResource(self, constant.MODAL_IC_INT_FREQ)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="interest-frequency"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <select id="icIntFreq" class="form-select form-select-sm" ${enable ? '' : 'disabled'}> <option value="none" ${ext["interest-frequency"] === 'none' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_NONE)}</option> <option value="1-year" ${ext["interest-frequency"] === '1-year' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_1_YEAR)}</option> <option value="6-months" ${ext["interest-frequency"] === '6-months' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_6_MONTHS)}</option> <option value="4-months" ${ext["interest-frequency"] === '4-months' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_4_MONTHS)}</option> <option value="3-months" ${ext["interest-frequency"] === '3-months' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_3_MONTHS)}</option> <option value="2-months" ${ext["interest-frequency"] === '2-months' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_2_MONTHS)}</option> <option value="1-month" ${ext["interest-frequency"] === '1-month' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_1_MONTH)}</option> <option value="half-month" ${ext["interest-frequency"] === 'half-month' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_HALF_MONTH)}</option> <option value="4-weeks" ${ext["interest-frequency"] === '4-weeks' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_4_WEEKS)}</option> <option value="2-weeks" ${ext["interest-frequency"] === '2-weeks' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_2_WEEKS)}</option> <option value="1-week" ${ext["interest-frequency"] === '1-week' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_1_WEEK)}</option> <option value="1-day" ${ext["interest-frequency"] === '1-day' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_1_DAY)}</option> <option value="continuous" ${ext["interest-frequency"] === 'continuous' ? 'selected' : ''}>${updater.getResource(self, constant.FREQ_CONTINUOUS)}</option> </select> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="icRoundBal" class="col-form-label">${updater.getResource(self, constant.MODAL_IC_ROUND_BAL)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="round-balance"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <select id="icRoundBal" class="form-select form-select-sm" ${enable ? '' : 'disabled'}> <option value="none" ${ext["round-balance"] === 'none' ? 'selected' : ''}>${updater.getResource(self, constant.ROUNDING_NONE)}</option> <option value="bankers" ${ext["round-balance"] === 'bankers' ? 'selected' : ''}>${updater.getResource(self, constant.ROUNDING_BANKERS)}</option> <option value="bias-up" ${ext["round-balance"] === 'bias-up' ? 'selected' : ''}>${updater.getResource(self, constant.ROUNDING_BIAS_UP)}</option> <option value="bias-down" ${ext["round-balance"] === 'bias-down' ? 'selected' : ''}>${updater.getResource(self, constant.ROUNDING_BIAS_DOWN)}</option> <option value="up" ${ext["round-balance"] === 'up' ? 'selected' : ''}>${updater.getResource(self, constant.ROUNDING_UP)}</option> <option value="truncate" ${ext["round-balance"] === 'truncate' ? 'selected' : ''}>${updater.getResource(self, constant.ROUNDING_TRUNCATE)}</option> </select> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="icRoundDD" class="col-form-label">${updater.getResource(self, constant.MODAL_IC_ROUND_DD)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="round-decimal-digits"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="icRoundDD" class="form-control form-control-sm" value="${ext["round-decimal-digits"]}" ${enable ? '' : 'disabled'}> </div> </div>`; let stat = ext["interest-statistics"]; if (stat) { form += `<div class="row align-items-center"> <div class="col-6"> <label for="icStatNar" class="col-form-label">${updater.getResource(self, constant.MODAL_IC_STAT_NAR)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="nominal-annual-rate"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="icStatNar class="form-control form-control-sm" value="${stat["nar"]}" disabled> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="icStatEar" class="col-form-label">${updater.getResource(self, constant.MODAL_IC_STAT_EAR)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="effective-annual-rate"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="icStatEar class="form-control form-control-sm" value="${stat["ear"]}" disabled> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="icStatPr" class="col-form-label">${updater.getResource(self, constant.MODAL_IC_STAT_PR)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="periodic-rate"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="icStatPr class="form-control form-control-sm" value="${stat["pr"]}" disabled> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="icStatDr" class="col-form-label">${updater.getResource(self, constant.MODAL_IC_STAT_DR)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="daily-rate"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="icStatDr class="form-control form-control-sm" value="${stat["dr"]}" disabled> </div> </div>`; } this.modalShow(updater.getResource(self, constant.MODAL_INTEREST_CHANGE), constant.HelpInterestChange, form, options); return; } if ("statistic-value" in extension) { let ext = extension["statistic-value"]; this.modalShow(updater.getResource(self, constant.MODAL_STATISTIC_CHANGE), constant.HelpStatisticValue, `<div class="row align-items-center"> <div class="col-6"> <label for="svName" class="col-form-label">${updater.getResource(self, constant.MODAL_SV_NAME)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="name"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="svName" class="form-control form-control-sm" value="${ext["name"]}" ${enable ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="svEom" class="col-form-label">${updater.getResource(self, constant.MODAL_SV_EOM)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="eom"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input class="form-check-input" type="checkbox" id="svEom" ${ext["eom"] ? 'checked' : ''} ${enable ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="svFinal" class="col-form-label">${updater.getResource(self, constant.MODAL_SV_FINAL)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="final"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input class="form-check-input" type="checkbox" id="svFinal" ${ext["final"] ? 'checked' : ''} ${enable ? '' : 'disabled'}> </div> </div>`, options ); return; } let ext = extension["principal-change"]; this.modalShow(updater.getResource(self, constant.MODAL_PRINCIPAL_CHANGE), constant.HelpPrincipalChange, `<div class="row align-items-center"> <div class="col-6"> <label for="pcType" class="col-form-label">${updater.getResource(self, constant.MODAL_PC_TYPE)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="principal-type"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <select id="pcType" class="form-select form-select-sm" ${enable ? '' : 'disabled'}> <option ${ext["principal-type"] === 'positive' ? 'selected' : ''}>positive</option> <option ${ext["principal-type"] === 'negative' ? 'selected' : ''}>negative</option> <option ${ext["principal-type"] === 'increase' ? 'selected' : ''}>increase</option> <option ${ext["principal-type"] === 'decrease' ? 'selected' : ''}>decrease</option> </select> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="pcEom" class="col-form-label">${updater.getResource(self, constant.MODAL_PC_EOM)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="eom"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input class="form-check-input" type="checkbox" id="pcEom" ${ext["eom"] ? 'checked' : ''} ${enable ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="pcPrinFirst" class="col-form-label">${updater.getResource(self, constant.MODAL_PC_PRIN_FIRST)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="principal-first"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input class="form-check-input" type="checkbox" id="pcPrinFirst" ${ext["principal-first"] ? 'checked' : ''} ${enable ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="pcBalStats" class="col-form-label">${updater.getResource(self, constant.MODAL_PC_BAL_STAT)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="statistics"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input class="form-check-input" type="checkbox" id="pcBalStats" ${ext["statistics"] ? 'checked' : ''} ${enable ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="pcAuxiliary" class="col-form-label">${updater.getResource(self, constant.MODAL_PC_AUXILIARY)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="auxiliary"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input class="form-check-input" type="checkbox" id="pcAuxiliary" ${ext["auxiliary"] ? 'checked' : ''} ${enable ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="pcAuxPassive" class="col-form-label">${updater.getResource(self, constant.MODAL_PC_AUX_PASSIVE)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="passive"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input class="form-check-input" type="checkbox" id="pcAuxPassive" ${ext["passive"] ? 'checked' : ''} ${enable ? '' : 'disabled'}> </div> </div>`, options ); } /** * Show an insert event modal dialog. * @param {object} self Self object. */ showInsertEvent(self) { let tab = self.tabs[self.activeTabIndex]; let templateEvents = self.engine.get_template_event_names(tab.group); let body = ""; let index = 0; for (let event of templateEvents) { body += ` <div class="form-check"> <input class="form-check-input" type="radio" name="radioEvent" id="radioEvent${index}" value="${event}"> <label class="form-check-label" for="radioEvent${index}"> ${event} </label> </div> `; ++index; } let _this = this; this.modalShow(updater.getResource(self, constant.MODAL_INSERT_EVENT), constant.HelpInsertEvent, body, { textCancel: updater.getResource(self, constant.MODAL_CANCEL), textOK: updater.getResource(self, constant.MODAL_SUBMIT), outputFn: (isOK) => { if (!isOK) return {}; let event = ""; var radios = document.getElementsByName("radioEvent"); for (let radio of radios) { if (radio.checked) { event = radio.value; break; } } let valid = event.length > 0; if (!valid) { toaster.toastError(updater.getResource(self, constant.MSG_SELECT_TEMPLATE_EVENT)); return null; } return { event: event }; }, finalFn(isOK, data) { if (!isOK || !data.event) return; _this.createTemplateEventsShowParameters(self, data.event); } }); } /** * Show a new cashflow modal dialog. * @param {object} self Self object. */ showNewCashflow(self) { let templateGroups = self.engine.get_template_names(); let body = `<div class="row align-items-center"> <div class="col-6"> <label for="cfName" class="col-form-label">${updater.getResource(self, constant.MODAL_NC_NAME)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="name"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="cfName" class="form-control form-control-sm"> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="cfTemplate" class="col-form-label">${updater.getResource(self, constant.MODAL_NC_TEMPLATE)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="template"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <select id="cfTemplate" class="form-select form-select-sm"> `; for (let group of templateGroups) { body += `<option value="${group}">${group}</option>`; } body += ` </select> </div> </div>`; let _this = this; this.modalShow(updater.getResource(self, constant.MODAL_NEW_CASHFLOW), constant.HelpNewCashflow, body, { textCancel: updater.getResource(self, constant.MODAL_CANCEL), textOK: updater.getResource(self, constant.MODAL_SUBMIT), outputFn: (isOK) => { if (!isOK) return {}; let cfName = document.getElementById("cfName").value; let cfTemplate = document.getElementById("cfTemplate").value; let valid = cfName.length > 0 && cfTemplate.length > 0; if (!valid) { toaster.toastError(updater.getResource(self, constant.MSG_SELECT_CASHFLOW_TEMPLATE)); return null; } return { cfName: cfName, cfTemplate: cfTemplate }; }, finalFn(isOK, data) { if (!isOK || !data.cfName) return; let initialName = self.engine.create_cashflow_from_template_group(data.cfTemplate, data.cfName); if (initialName.length > 0) { self.loadCashflow(data.cfName); if (initialName === "*") return; _this.createTemplateEventsShowParameters(self, initialName); } } }); } /** * Show a parameter list in a modal dialog. * @param {object} self Self object. * @param {number} rowIndex The row index. * @param {number} tableType The type of table. */ showParameters(self, rowIndex, tableType) { let enable = tableType === constant.TABLE_EVENT; let list = self.engine.parse_parameters(self.activeTabIndex, rowIndex, tableType); let body = ""; for (let elem of list) { body += `<div class="row align-items-center"> <div class="col-6"> ${elem.label.length > 0 ? elem.label : elem.name} <a class="btn btnHelpDefault" role="button" tabindex="-1" data-bs-toggle="popover" title="${updater.getResource(self, constant.MODAL_PARAMETER_LIST)}" data-bs-content="${elem.description}"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" class="form-control form-control-sm parameter" value="${elem.sym_type === 'integer' ? elem.int_value : elem.sym_type === 'decimal' ? elem.dec_value : elem.str_value}" ${enable ? '' : 'disabled'}> </div> </div>`; } this.modalShow(updater.getResource(self, constant.MODAL_PARAMETER_LIST), constant.HelpParameter, body, { textCancel: enable ? updater.getResource(self, constant.MODAL_CANCEL) : "", textOK: enable ? updater.getResource(self, constant.MODAL_SUBMIT) : updater.getResource(self, constant.MODAL_OK), outputFn: (isOK) => { if (!enable || !isOK) return {}; let parameters = document.getElementsByClassName("parameter"); let params = ""; let index = 0; for (let parameter of parameters) { if (params.length > 0) params += "|"; params += parameter.value; ++index; } return { "parameters": params }; }, finalFn: (isOK, data) => { if (!enable || !isOK || !data.parameters) return; if (self.engine.set_parameter_values(self.activeTabIndex, rowIndex, data.parameters)) { updater.refreshAmResults(self); updater.updateTabLabel(self, self.activeTabIndex, true); } } }); } /** * Show a preferences a modal dialog. * @param {object} self Self object. * @param {number} cfIndex Cashflow index or -1 for user preferences. */ showPreferences(self, cfIndex) { let pref = self.engine.get_preferences(cfIndex); this.modalShow(updater.getResource(self, cfIndex < 0 ? constant.MODAL_USER_PREFERENCES : constant.MODAL_CASHFLOW_PREFERENCES), constant.HelpPreferences, `<div class="row align-items-center"> <div class="col-6"> <label for="prefLocale" class="col-form-label">${updater.getResource(self, constant.MODAL_PREF_LOCALE)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="locale-str"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="prefLocale" class="form-control form-control-sm" value="${pref["locale_str"]}" disabled> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="prefGroup" class="col-form-label">${updater.getResource(self, constant.MODAL_PREF_GROUP)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="group"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="prefGroup" class="form-control form-control-sm" value="${pref["group"]}" disabled> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="prefCrossRate" class="col-form-label">${updater.getResource(self, constant.MODAL_PREF_CROSS_RATE)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="cross-rate-code"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="prefCrossRate" class="form-control form-control-sm" value="${pref["cross_rate_code"]}" ${cfIndex >= 0 ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="prefEncoding" class="col-form-label">${updater.getResource(self, constant.MODAL_PREF_ENCODING)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="default-encoding"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="prefEncoding" class="form-control form-control-sm" value="${pref["default_encoding"]}" ${cfIndex >= 0 ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="prefFiscalYear" class="col-form-label">${updater.getResource(self, constant.MODAL_PREF_FISCAL_YEAR)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="fiscal-year-start"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="number" id="prefFiscalYear" class="form-control form-control-sm" value="${pref["fiscal_year_start"]}" ${cfIndex >= 0 ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="prefDecimalDigits" class="col-form-label">${updater.getResource(self, constant.MODAL_PREF_DECIMAL_DIGITS)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="decimal-digits"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="number" id="prefDecimalDigits" class="form-control form-control-sm" value="${pref["decimal_digits"]}" ${cfIndex >= 0 ? '' : 'disabled'}> </div> </div> <div class="row align-items-center"> <div class="col-6"> <label for="prefTargetValue" class="col-form-label">${updater.getResource(self, constant.MODAL_PREF_TARGET_VALUE)}</label> <a class="btn btnHelp" role="button" tabindex="-1" data-bs-toggle="popover" data-help="target-value"><i class="bi-question-circle"></i></a> </div> <div class="col-6"> <input type="text" spellcheck="false" id="prefTargetValue" class="form-control form-control-sm" value="${pref["target"]}" ${cfIndex >= 0 ? '' : 'disabled'}> </div> </div>`, { textCancel: cfIndex >= 0 ? updater.getResource(self, constant.MODAL_CANCEL) : "", textOK: cfIndex >= 0 ? updater.getResource(self, constant.MODAL_SUBMIT) : updater.getResource(self, constant.MODAL_OK), outputFn: (isOK) => { if (cfIndex < 0 || !isOK) return {}; return new WasmElemPreferences( "", // Not set "", // Not set document.getElementById("prefCrossRate").value, document.getElementById("prefEncoding").value, parseInt(document.getElementById("prefFiscalYear").value), parseInt(document.getElementById("prefDecimalDigits").value), document.getElementById("prefTargetValue").value ); }, finalFn: (isOK, data) => { if (cfIndex < 0 || !isOK || !data) return; if (self.engine.set_preferences(cfIndex, data)) { updater.refreshEvents(self, "", 0); updater.refreshAmResults(self); updater.updateTabLabel(self, self.activeTabIndex, true); } } } ); } /** * Show a frequency list in a modal dialog. * @param {object} self Self object. * @param {number} rowIndex The row index. * @param {number} tableType The type of table. */ showSkipPeriods(self, rowIndex, tableType) { if (self.activeTabIndex < 0) return; let tab = self.tabs[self.activeTabIndex]; let enable = tableType === constant.TABLE_EVENT; let row; if (tableType === constant.TABLE_EVENT) { row = tab.eventValues[rowIndex]; } else { if (tab.expanded) { row = tab.amValues.expanded[rowIndex]; } else { row = tab.amValues.compressed[rowIndex]; } } let startDate = self.engine.format_date_in(row["Date"]); let frequency = row["Frequency"]; let periods = row["Periods"] ? parseInt(self.engine.format_integer_in(row["Periods"])) : 1; let intervals = row["Intervals"] ? parseInt(self.engine.format_integer_in(row["Intervals"])) : 1; let eom = updater.getEom(self, rowIndex, tableType); let skipPeriods = row["Skip-periods"]; let body = ` <div class="row align-items-center"> <div class="col-10"> <input type="range" class="form-range" min="0" max="${periods}" value="${skipPeriods.length}" id="skipPeriodsRange" ${enable ? '' : 'disabled'}> </div> <div class="col-2"> <input class="max-width" type="number" min="0" max="${periods}" value="${skipPeriods.length}" id="skipPeriodsRangeValue" ${enable ? '' : 'disabled'}> </div> </div> <div id="divSkipPeriods"></div> `; let skipPeriodsChangeInfo = { startDate: startDate, frequency: frequency, periods: periods, intervals: intervals, eom: eom, skipPeriods: skipPeriods, newValue: skipPeriods.length, tableType: tableType }; let _this = this; this.modalShow(updater.getResource(self, constant.MODAL_SKIP_PERIODS), constant.HelpSkipPeriods, body, { textCancel: updater.getResource(self, constant.MODAL_CANCEL), textOK: updater.getResource(self, constant.MODAL_SUBMIT), inputFn: (inputData) => { _this.showSkipPeriodsRangeChange(inputData.self, skipPeriodsChangeInfo, true); document.getElementById("skipPeriodsRange").addEventListener("input", (e) => _this.showSkipPeriodsInput(e, inputData.self, skipPeriodsChangeInfo)); document.getElementById("skipPeriodsRangeValue").addEventListener("change", (e) => _this.showSkipPeriodsChange(e, inputData.self, skipPeriodsChangeInfo)); }, inputData: { self: self }, outputFn: (isOK) => { document.getElementById("skipPeriodsRange").removeEventListener("input", (e) => _this.showSkipPeriodsInput(e, inputData.self, skipPeriodsChangeInfo)); document.getElementById("skipPeriodsRangeValue").addEventListener("change", (e) => _this.showSkipPeriodsChange(e, inputData.self, skipPeriodsChangeInfo)); if (!isOK) return {}; for (let colDef of tab.eventColumns) { if (colDef.col_name === "Skip-periods") { let skipPeriods = ""; let elems = document.getElementsByClassName("chkSkipPeriods"); for (let elem of elems) { skipPeriods += (elem.checked ? "1" : "0"); } return { skipPeriods: skipPeriods }; } } return {}; }, finalFn: (isOK, data) => { if (!isOK || !data.hasOwnProperty("skipPeriods")) return; skipPeriodsChangeInfo.skipPeriods = data.skipPeriods; let colDef = tab.lastFocused.colDef; let rowIndex = tab.lastFocused.rowIndex; let tokens = self.engine.set_event_value( colDef.col_name_index, colDef.col_type, colDef.code, self.activeTabIndex, rowIndex, skipPeriodsChangeInfo.skipPeriods).split('|'); if (tokens.length === 3) { let value = tokens[2]; let gridRow = tab.grdEventOptions.api.getDisplayedRowAtIndex(rowIndex); gridRow.setDataValue(colDef.col_name, value); updater.refreshAmResults(self); updater.updateTabLabel(self, self.activeTabIndex, true); } } }); } /** * Respond to the skip periods input value changing. * @param {object} e Input event. * @param {object} self Self event. * @param {object} skipPeriodsChangeInfo Skip periods change info. */ showSkipPeriodsInput(e, self, skipPeriodsChangeInfo) { skipPeriodsChangeInfo.newValue = e.target.value; let rangeValue = document.getElementById("skipPeriodsRangeValue"); rangeValue.value = skipPeriodsChangeInfo.newValue; this.showSkipPeriodsRangeChange(self, skipPeriodsChangeInfo); } /** * Respond to the skip periods slider value changing. * @param {object} e Change event. * @param {object} self Self event. * @param {object} skipPeriodsChangeInfo Skip periods change info. */ showSkipPeriodsChange(e, self, skipPeriodsChangeInfo) { skipPeriodsChangeInfo.newValue = e.target.value; let range = document.getElementById("skipPeriodsRange"); range.value = skipPeriodsChangeInfo.newValue; this.showSkipPeriodsRangeChange(self, skipPeriodsChangeInfo); } /** * Skip periods range change. * @param {object} self Self object. * @param {object} skipPeriodsChangeInfo Skip periods change information. * @param {bool} isInit Initial skip periods. */ showSkipPeriodsRangeChange(self, skipPeriodsChangeInfo, isInit = false) { let enable = skipPeriodsChangeInfo.tableType === constant.TABLE_EVENT; let skipPeriods = ""; if (isInit) { skipPeriods = skipPeriodsChangeInfo.skipPeriods; } else { let elems = document.getElementsByClassName("chkSkipPeriods"); for (let elem of elems) { skipPeriods += (elem.checked ? "1" : "0"); } } if (skipPeriodsChangeInfo.newValue > skipPeriods.length) { skipPeriods = skipPeriods.slice(0, skipPeriodsChangeInfo.newValue - 1); } else { let index = skipPeriodsChangeInfo.newValue - skipPeriods.length; while (index > 0) { skipPeriods += "0"; --index; } } let newDate = skipPeriodsChangeInfo.startDate; let str = ""; for (let index = 0; index < skipPeriodsChangeInfo.newValue; ++index) { str += ` <div class="row align-items-center"> <div class="col-6"> <label for="chkSkipPeriods${index}" class="col-form-label">${self.engine.format_date_out(newDate)}</label> </div> <div class="col-6"> <input class="form-check-input chkSkipPeriods" type="checkbox" id="chkSkipPeriods${index}" ${skipPeriods[index] === '1' ? 'checked' : ''} ${enable ? '' : 'disabled'}> </div> </div> `; newDate = self.engine.format_date_in(self.engine.date_new( skipPeriodsChangeInfo.startDate, newDate, skipPeriodsChangeInfo.frequency, skipPeriodsChangeInfo.intervals, skipPeriodsChangeInfo.eom)); } document.getElementById("divSkipPeriods").innerHTML = str; } /** * Show a cashflow summary in a modal dialog. * @param {object} self Self object. * @param {object} summary Summary items. */ showSummary(self, summary) { let body = ""; for (let sum of summary) { body += `<div class="row align-items-center"> <div class="col-6"> ${sum.label} </div> <div class="col-6"> ${sum.result} </div> </div>` } this.modalShow(updater.getResource(self, constant.MODAL_CASHFLOW_SUMMARY), constant.HelpSummary, body); } }
JavaScript
class yzecoriolisActorSheet extends ActorSheet { /** @override */ static get defaultOptions() { return mergeObject(super.defaultOptions, { classes: ["yzecoriolis", "sheet", "actor"], template: "systems/yzecoriolis/templates/actor/actor-sheet.html", width: 1000, height: 800, resizable: false, tabs: [{ navSelector: ".navigation", contentSelector: ".sheet-panels", initial: "stats" }] }); } /* -------------------------------------------- */ /** @override */ getData() { const data = super.getData(); data.dtypes = ["String", "Number", "Boolean"]; if (this.actor.data.type === 'character' || this.actor.data.type === 'npc') { // prepare items this._prepareCharacterItems(data); this._prepCharacterStats(data); } data.config = CONFIG.YZECORIOLIS; return data; } _prepCharacterStats(sheetData) { const actorData = sheetData.actor; const data = actorData.data; actorData.radiationBlocks = prepDataBarBlocks(data.radiation.value, data.radiation.max); actorData.xpBlocks = prepDataBarBlocks(data.experience.value, data.experience.max);; actorData.repBlocks = prepDataBarBlocks(data.reputation.value, data.reputation.max); actorData.hpBlocks = prepDataBarBlocks(data.hitPoints.value, data.hitPoints.max); actorData.mindBlocks = prepDataBarBlocks(data.mindPoints.value, data.mindPoints.max); } _prepareCharacterItems(sheetData) { const actorData = sheetData.actor; // Initialize our containers const gear = []; const armor = []; const talents = {}; const weapons = []; const explosives = []; const injuries = []; let totalWeightPoints = 0; const gearDataSet = { "type": "gear", "weight": "L", "quantity": 1, "defaultname": game.i18n.localize('YZECORIOLIS.NewGear'), } for (let k of Object.keys(CONFIG.YZECORIOLIS.talentCategories)) { talents[k] = { "dataset": { "type": "talent", "defaultname": game.i18n.localize('YZECORIOLIS.NewTalent'), "category": k }, "items": [] }; } const weaponDataSet = { "type": "weapon", "weight": "L", "defaultname": game.i18n.localize('YZECORIOLIS.NewWeapon') }; const explosiveDataSet = { "type": "weapon", "weight": "L", "quantity": 1, "explosive": true, "blastRadius": "close", "blastPower": 1, "defaultname": game.i18n.localize('YZECORIOLIS.NewExplosive') }; const armorDataSet = { "type": "armor", "weight": "L", "armorRating": 1, "extraFeatures": 0, "defaultname": game.i18n.localize('YZECORIOLIS.NewArmor'), } const injuryDataSet = { "type": "injury", "defaultname": game.i18n.localize('YZECORIOLIS.NewCriticalInjury'), } for (let i of sheetData.items) { let item = i.data; i.img = i.img || DEFAULT_TOKEN; // setup equipped status const isActive = getProperty(i.data, "equipped"); item.toggleClass = isActive ? "equipped" : ""; // append to gear if (i.type === 'gear') { gear.push(i); totalWeightPoints += CONFIG.YZECORIOLIS.gearWeightPoints[item.weight] * item.quantity; } // append to talents if (i.type === "talent") { talents[item.category].items.push(i); } // append to weapons and explosives if (i.type === "weapon") { if (item.explosive) { explosives.push(i); } else { weapons.push(i); } totalWeightPoints += CONFIG.YZECORIOLIS.gearWeightPoints[item.weight] * item.quantity; } if (i.type === "armor") { armor.push(i); totalWeightPoints += CONFIG.YZECORIOLIS.gearWeightPoints[item.weight]; // we assume 1 quantity. } if (i.type === "injury") { injuries.push(i); } } // assign and return actorData.gear = gear; actorData.gearDataSet = gearDataSet; actorData.weapons = weapons; actorData.weaponDataSet = weaponDataSet; actorData.explosives = explosives; actorData.explosiveDataSet = explosiveDataSet; actorData.armor = armor; actorData.armorDataSet = armorDataSet; actorData.talents = talents; actorData.encumbrance = this._computeEncumbrance(totalWeightPoints); actorData.injuries = injuries; actorData.injuryDataSet = injuryDataSet; } /** @override */ activateListeners(html) { super.activateListeners(html); // hook up scalable input fields html.find('.expandable-info').click(event => this._onItemSummary(event)); html.find('.skills .toggle').click(function () { $(this.parentNode.parentNode).toggleClass('collapsed'); }); // Everything below here is only needed if the sheet is editable if (!this.options.editable) return; // Add Inventory Item html.find('.item-create').click(this._onItemCreate.bind(this)); // Add relationship html.find('.relationship-create').click(this._onRelationshipCreate.bind(this)); // delete relationship html.find('.relationship-delete').click(this._onRelationshipDelete.bind(this)); // Add meeting html.find('.meeting-create').click(this._onMeetingCreate.bind(this)); // delete meeting html.find('.meeting-delete').click(this._onMeetingDelete.bind(this)); // Add Critical Injury html.find('.injury-create').click(this._onCriticalInjuryCreate.bind(this)); // Delete a Critical Injury html.find('.injury-delete').click(this._onCriticalInjuryDelete.bind(this)); // databar editing html.find('.bar-segment').click(this._onClickBarSegment.bind(this)); html.find('.bar-segment').mouseenter(onHoverBarSegmentIn); html.find('.bar').mouseleave(onHoverBarOut); // Update Inventory Item html.find('.item-edit').click(ev => { const li = $(ev.currentTarget).parents(".item"); const item = this.actor.getOwnedItem(li.data("itemId")); item.sheet.render(true); }); // Item State Toggling html.find('.item-toggle').click(this._onToggleItem.bind(this)); // update gear quantity directly from sheet. html.find('.gear-quantity-input').change(this._onGearQuantityChanged.bind(this)); // Delete Inventory Item html.find('.item-delete').click(ev => { const li = $(ev.currentTarget).parents(".item"); this.actor.deleteOwnedItem(li.data("itemId")); li.slideUp(200, () => this.render(false)); }); // Rollable abilities. html.find('.rollable').click(this._onRoll.bind(this)); // drag events for macros if (this.actor.owner) { let handler = ev => this._onDragStart(ev); html.find('li.item').each((i, li) => { // ignore for the header row if (li.classList.contains("item-header")) return; // add draggable attribute and drag start listener li.setAttribute("draggable", true); li.addEventListener("dragstart", handler, false); }); } } /* -------------------------------------------- */ _computeEncumbrance(totalWeight) { // your max is strength * 2. // We are doubling that value so we can avoid having to deal with fractions & floats // for smaller items. // totalWeight already has the doubling factored in. const strengthValue = this.actor.data.data.attributes.strength.value * 2 * 2; // for display purposes we'll halve everything so that encumbrance makes // sense to users that are familiar with the rules. let enc = { max: strengthValue / 2, value: totalWeight / 2 }; let pct = (enc.value / enc.max) * 100; if (enc.value === 0) { pct = 0; } enc.percentage = Math.min(pct, 100); enc.encumbered = pct > 100; return enc; } /** * Handle changing the quantity of a gear item from the sheet directly. * @param {} event */ async _onGearQuantityChanged(event) { event.preventDefault(); const input = event.target; let value = input.value; const li = $(event.currentTarget).parents(".item"); const item = this.actor.getOwnedItem(li.data("itemId")); if (value < 0) { value = 0; } return item.update({ 'data.quantity': value }); } _onClickBarSegment(event) { event.preventDefault(); const targetSegment = event.currentTarget; // Get the type of item to create. const index = Number(targetSegment.dataset.index); const curValue = Number(targetSegment.dataset.current); const minValue = Number(targetSegment.dataset.min); const maxValue = Number(targetSegment.dataset.max); const targetField = targetSegment.dataset.name; // Grab any data associated with this control. let newRad = computeNewBarValue(index, curValue, minValue, maxValue); let update = {}; update[targetField] = newRad; return this.actor.update(update); } _onRelationshipCreate(event) { event.preventDefault(); const person = { buddy: false, name: '' }; let relationships = {}; if (this.actor.data.data.relationships) { relationships = duplicate(this.actor.data.data.relationships); } let key = getID(); relationships['r' + key] = person; return this.actor.update({ 'data.relationships': relationships }); } async _onRelationshipDelete(event) { const li = $(event.currentTarget).parents(".relation"); let relations = duplicate(this.actor.data.data.relationships); let targetKey = li.data("itemId"); delete relations[targetKey]; li.slideUp(200, () => { this.render(false); }); this._setRelations(relations); } async _setRelations(relations) { await this.actor.update({ "data.relationships": null }); await this.actor.update({ 'data.relationships': relations }); } _onMeetingCreate(event) { event.preventDefault(); const meeting = { name: '', concept: '', notes: '' }; let meetings = {}; if (this.actor.data.data.meetings) { meetings = duplicate(this.actor.data.data.meetings); } let key = getID(); meetings['m' + key] = meeting; return this.actor.update({ 'data.meetings': meetings }); } async _onMeetingDelete(event) { const li = $(event.currentTarget).parents(".meeting"); let meetings = duplicate(this.actor.data.data.meetings); let targetKey = li.data("itemId"); delete meetings[targetKey]; li.slideUp(200, () => { this.render(false); }); this._setMeetings(meetings); } async _setMeetings(meetings) { await this.actor.update({ "data.meetings": null }); await this.actor.update({ 'data.meetings': meetings }); } /** * Handle creating a new Owned Item for the actor using initial data defined in the HTML dataset * @param {Event} event The originating click event * @private */ _onItemCreate(event) { event.preventDefault(); const header = event.currentTarget; // Get the type of item to create. const type = header.dataset.type; // Grab any data associated with this control. const data = duplicate(header.dataset); // Initialize a default name. const name = data.defaultname;// `New ${type.capitalize()}`; // Prepare the item object. const itemData = { name: name, type: type, data: data }; // Remove the type from the dataset since it's in the itemData.type prop. delete itemData.data["type"]; // no need to keep ahold of defaultname after creation. delete itemData.data["defaultname"]; // Finally, create the item! return this.actor.createOwnedItem(itemData); } _onCriticalInjuryCreate(event) { event.preventDefault(); const critData = { name: '', description: '' } let injuries = {}; if (this.actor.data.data.criticalInjuries) { injuries = duplicate(this.actor.data.data.criticalInjuries); } let key = getID(); injuries['ci' + key] = critData; return this.actor.update({ 'data.criticalInjuries': injuries }); } async _onCriticalInjuryDelete(event) { const li = $(event.currentTarget).parents(".injury"); let injuries = duplicate(this.actor.data.data.criticalInjuries); let targetKey = li.data("itemId"); delete injuries[targetKey]; li.slideUp(200, () => { this.render(false); }); this._setInjuries(injuries); } async _setInjuries(injuries) { await this.actor.update({ "data.criticalInjuries": null }); await this.actor.update({ 'data.criticalInjuries': injuries }); } /** * Handle toggling the state of an Owned Item within the Actor * @param {Event} event The triggering click event * @private */ _onToggleItem(event) { event.preventDefault(); const itemId = event.currentTarget.closest(".item").dataset.itemId; const item = this.actor.getOwnedItem(itemId); const attr = "data.equipped"; return item.update({ [attr]: !getProperty(item.data, attr) }); } /** * Handle clickable rolls. * @param {Event} event The originating click event * @private */ _onRoll(event) { event.preventDefault(); const element = event.currentTarget; const dataset = element.dataset; const actorData = this.actor.data.data; const rollData = { rollType: dataset.rolltype, skillKey: dataset.skillkey, skill: dataset.skillkey ? actorData.skills[dataset.skillkey].value : 0, attributeKey: dataset.attributekey, attribute: dataset.attributekey ? actorData.attributes[dataset.attributekey].value : 0, modifier: 0, bonus: dataset.bonus ? Number(dataset.bonus) : 0, rollTitle: dataset.label, pushed: false, actor: this.actor } const chatOptions = this.actor._prepareChatRollOptions('systems/yzecoriolis/templates/sidebar/roll.html', dataset.rolltype); coriolisModifierDialog((modifier) => { rollData.modifier = modifier; coriolisRoll(chatOptions, rollData); }); } /** * Handle showing an item's description in the character sheet as an easy fold out. * @private */ _onItemSummary(event) { event.preventDefault(); let li = $(event.currentTarget).parents(".item"); let item = this.actor.getOwnedItem(li.data("item-id")); let chatData = item.getChatData({ secrets: this.actor.owner }); // Toggle summary if (li.hasClass("expanded")) { let summary = li.children(".item-summary"); summary.slideUp(200, () => { summary.remove() }); } else { let div = $(`<div class="item-summary"><div class="item-summary-wrapper"><div>${chatData.description}</div></div></div>`); let props = $(`<div class="item-properties"></div>`); chatData.properties.forEach(p => props.append(`<span class="tag">${p}</span>`)); $(div).find(".item-summary-wrapper").append(props); // div.append(props); li.append(div.hide()); div.slideDown(200); } li.toggleClass("expanded"); } }
JavaScript
class Header { // render the content async render () { return ` <header class="header"> <nav class="nav row align-items-center justify-content-between"> <div class="nav_logo"> <a href="${routes.HOME}" data-navigo> <img src="${pgmLogo}" alt="Logo Graduaat Programmeren"> </a> </div> <div class="nav_btn btn-hamburger"><i class="fas fa-bars"></i></div> <ul class="nav__list row justify-content-between"> <li class="nav__item"><a href="${routes.OPLEIDING}" data-navigo>Opleiding</a></li> <li class="nav__item"><a href="${routes.PGMTEAM}" data-navigo>PGM-Team</a></li> <li class="nav__item"><a href="${routes.PORTFOLIO}" data-navigo>Portfolio</a></li> <li class="nav__item"><a href="${routes.NIEUWS}" data-navigo>Nieuws</a></li> <li class="nav__item"><a href="${routes.WERKPLEKLEREN}" data-navigo>Werkplekleren</a></li> <li class="nav__item"><a href="${routes.CONTACT}" data-navigo>Contact</a></li> </ul> <ul class="nav_hamb"> <li class="nav__item"><a href="${routes.OPLEIDING}" data-navigo>Opleiding</a></li> <li class="nav__item"><a href="${routes.PGMTEAM}" data-navigo>PGM-Team</a></li> <li class="nav__item"><a href="${routes.PORTFOLIO}" data-navigo>Portfolio</a></li> <li class="nav__item"><a href="${routes.NIEUWS}" data-navigo>Nieuws</a></li> <li class="nav__item"><a href="${routes.WERKPLEKLEREN}" data-navigo>Werkplekleren</a></li> <li class="nav__item"><a href="${routes.CONTACT}" data-navigo>Contact</a></li> </ul> </nav> </header> `; } async afterRender () { // Connect the listeners const btnHamburger = document.querySelector('.btn-hamburger'); btnHamburger.addEventListener('click', (ev) => { const hambNav = document.querySelector('.nav_hamb'); if (hambNav.style.display === 'block') { hambNav.style.display = 'none'; } else { hambNav.style.display = 'block'; } }); return this; } // update the navigation to check which link is active updateActiveLink (route) { const prevActiveMenuItemElement = document.querySelector(`.nav__list > .nav__item > a[class*="active"]`); if (prevActiveMenuItemElement) { prevActiveMenuItemElement.classList.remove('active', 'underline'); } const link = route.replace('#!', ''); const menuItemElement = document.querySelector(`.nav__list > .nav__item > a[href*="${link}"]`); if (menuItemElement) { menuItemElement.classList.add('active', 'underline'); } } // update the mobile navigation to check which link is active updateMobileActiveLink (route) { const prevActiveMenuItemElement = document.querySelector(`.nav_hamb > .nav__item > a[class*="active"]`); if (prevActiveMenuItemElement) { prevActiveMenuItemElement.classList.remove('active', 'underline'); } const link = route.replace('#!', ''); const menuItemElement = document.querySelector(`.nav_hamb > .nav__item > a[href*="${link}"]`); if (menuItemElement) { menuItemElement.classList.add('active', 'underline'); } } }
JavaScript
class HMAC extends Hash { constructor(hash, _key) { super(); this.oHash = void 0; this.iHash = void 0; this.blockLen = void 0; this.outputLen = void 0; this.finished = false; this.destroyed = false; assertHash(hash); const key = toBytes(_key); this.iHash = hash.create(); if (!(this.iHash instanceof Hash)) throw new TypeError('Expected instance of class which extends utils.Hash'); const blockLen = this.blockLen = this.iHash.blockLen; this.outputLen = this.iHash.outputLen; const pad = new Uint8Array(blockLen); // blockLen can be bigger than outputLen pad.set(key.length > this.iHash.blockLen ? hash.create().update(key).digest() : key); for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36; this.iHash.update(pad); // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone this.oHash = hash.create(); // Undo internal XOR && apply outer XOR for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c; this.oHash.update(pad); pad.fill(0); } update(buf) { if (this.destroyed) throw new Error('instance is destroyed'); this.iHash.update(buf); return this; } digestInto(out) { if (this.destroyed) throw new Error('instance is destroyed'); if (!(out instanceof Uint8Array) || out.length !== this.outputLen) throw new Error('HMAC: Invalid output buffer'); if (this.finished) throw new Error('digest() was already called'); this.finished = true; this.iHash.digestInto(out); this.oHash.update(out); this.oHash.digestInto(out); this.destroy(); } digest() { const out = new Uint8Array(this.oHash.outputLen); this.digestInto(out); return out; } _cloneInto(to) { // Create new instance without calling constructor since key already in state and we don't know it. to || (to = Object.create(Object.getPrototypeOf(this), {})); const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; to = to; to.finished = finished; to.destroyed = destroyed; to.blockLen = blockLen; to.outputLen = outputLen; to.oHash = oHash._cloneInto(to.oHash); to.iHash = iHash._cloneInto(to.iHash); return to; } destroy() { this.destroyed = true; this.oHash.destroy(); this.iHash.destroy(); } }
JavaScript
class ModuleA { /** * Sample constructor */ constructor() { console.log('This is Module A mock'); } }
JavaScript
class UndockInitiator { constructor(element, undockededCallback, thresholdPixels) { if (!thresholdPixels) { thresholdPixels = 7; } this.element = element; this._undockededCallback = undockededCallback; this.thresholdPixels = thresholdPixels; this._enabled = false; } get enabled() { return this._enabled; } set enabled(value) { this._enabled = value; if (this._enabled) { if (this.mouseDownHandler) { this.mouseDownHandler.cancel(); delete this.mouseDownHandler; } if (this.touchDownHandler) { this.touchDownHandler.cancel(); delete this.touchDownHandler; } this.mouseDownHandler = new EventHandler(this.element, 'mousedown', this.onMouseDown.bind(this)); this.touchDownHandler = new EventHandler(this.element, 'touchstart', this.onMouseDown.bind(this), { passive: false }); } else { if (this.mouseDownHandler) { this.mouseDownHandler.cancel(); delete this.mouseDownHandler; } if (this.touchDownHandler) { this.touchDownHandler.cancel(); delete this.touchDownHandler; } if (this.mouseUpHandler) { this.mouseUpHandler.cancel(); delete this.mouseUpHandler; } if (this.touchUpHandler) { this.touchUpHandler.cancel(); delete this.touchUpHandler; } if (this.mouseMoveHandler) { this.mouseMoveHandler.cancel(); delete this.mouseMoveHandler; } if (this.touchMoveHandler) { this.touchMoveHandler.cancel(); delete this.touchMoveHandler; } } } onMouseDown(e) { e.preventDefault(); // Make sure we dont do this on floating dialogs if (this.enabled) { if (e.touches) { if (e.touches.length > 1) return; e = e.touches[0]; } if (this.mouseUpHandler) { this.mouseUpHandler.cancel(); delete this.mouseUpHandler; } if (this.touchUpHandler) { this.touchUpHandler.cancel(); delete this.touchUpHandler; } if (this.mouseMoveHandler) { this.mouseMoveHandler.cancel(); delete this.mouseMoveHandler; } if (this.touchMoveHandler) { this.touchMoveHandler.cancel(); delete this.touchMoveHandler; } this.mouseUpHandler = new EventHandler(window, 'mouseup', this.onMouseUp.bind(this)); this.touchUpHandler = new EventHandler(window, 'touchend', this.onMouseUp.bind(this)); this.mouseMoveHandler = new EventHandler(window, 'mousemove', this.onMouseMove.bind(this)); this.touchMoveHandler = new EventHandler(window, 'touchmove', this.onMouseMove.bind(this)); this.dragStartPosition = new Point(e.clientX, e.clientY); } } onMouseUp() { if (this.mouseUpHandler) { this.mouseUpHandler.cancel(); delete this.mouseUpHandler; } if (this.touchUpHandler) { this.touchUpHandler.cancel(); delete this.touchUpHandler; } if (this.mouseMoveHandler) { this.mouseMoveHandler.cancel(); delete this.mouseMoveHandler; } if (this.touchMoveHandler) { this.touchMoveHandler.cancel(); delete this.touchMoveHandler; } } onMouseMove(e) { if (e.touches) { if (e.touches.length > 1) return; e = e.touches[0]; } let position = new Point(e.clientX, e.clientY); let dy = position.y - this.dragStartPosition.y; if (dy > this.thresholdPixels || dy < -this.thresholdPixels) { this.enabled = false; this._requestUndock(e); } } _requestUndock(e) { let top = 0; let left = 0; let currentElement = this.element; do { top += currentElement.offsetTop || 0; left += currentElement.offsetLeft || 0; currentElement = currentElement.offsetParent; } while (currentElement); let dragOffsetX = this.dragStartPosition.x - left; let dragOffsetY = this.dragStartPosition.y - top; let dragOffset = new Point(dragOffsetX, dragOffsetY); this._undockededCallback(e, dragOffset); } }
JavaScript
class ImageBase extends React.Component { static displayName = "ImageBase"; static propTypes = { fade: PropTypes.bool, onLoadEnd: PropTypes.func, height: PropTypes.number, width: PropTypes.number, /** set the border radius to be fully round (given an equal height/width) **/ circular: PropTypes.bool, style: PropTypes.any, source: PropTypes.object.isRequired, resizeMode: PropTypes.string, /** the border radius of the image **/ rounded: PropTypes.number }; static defaultProps = { fade: true, resizeMode: "cover", rounded: false, circular: false }; state = { fade: new Animated.Value(0) }; onLoad() { if (this.props.onLoadEnd) { this.props.onLoadEnd(); } if (this.props.fade) { Animated.timing(this.state.fade, { toValue: 1, duration: 250 }).start(); } } render() { const { style, source, height, width, circular, rounded, resizeMode, ...other } = this.props; const sx = [ { height, width, opacity: this.state.fade }, style ]; return ( <Base {...other} baseStyle={sx} onLoadEnd={() => { this.onLoad(); }} rounded={circular ? height / 2 : rounded} source={source} resizeMode={resizeMode} Component={Animated.Image} /> ); } }
JavaScript
class FlattenCompressedExonsTransform extends FlowNode { get behavior() { return BEHAVIOR_CLONES; } /** * * @param {FlattenCompressedExonsParams} params */ constructor(params) { super(); const exonsAccessor = field(params.exons ?? "exons"); const startAccessor = field(params.start ?? "start"); const [exonStart, exonEnd] = params.as || ["exonStart", "exonEnd"]; /** * * @param {any} datum */ this.handle = (datum) => { let upper = startAccessor(datum); let lower = upper; let inExon = true; const exons = exonsAccessor(datum); for (const token of numberExtractor(exons)) { if (inExon) { lower = upper + token; } else { upper = lower + token; const newRow = Object.assign({}, datum); newRow[exonStart] = lower; newRow[exonEnd] = upper; this._propagate(newRow); } inExon = !inExon; } }; } }
JavaScript
class IonicGestureConfig extends HammerGestureConfig { /** * @param {?} element * @return {?} */ buildHammer(element) { const /** @type {?} */ mc = new ((window)).Hammer(element); for (let /** @type {?} */ eventName in this.overrides) { mc.get(eventName).set(this.overrides[eventName]); } return mc; } }
JavaScript
class Alerts extends Component { dismiss() { } render() { return ( <div> { this.props.alerts.map(alert => { return ( <Alert onDismiss={this.dismiss.bind(this)} text={alert.text} /> ) })} </div> ) } }
JavaScript
class TmCubeImageTop extends mixinBehaviors([TmCubeImageBehavior], PolymerElement) { constructor() { super(); this.baseSize = 136; this.baseScale = 0.25 } static get template() { return html` <style> :host { display: inline-block; box-sizing: border-box; //border: solid blue 1px; width: 150px; height: 150px; } svg { box-sizing: border-box; //border: solid red 1px; width: 100%; height: 100%; } </style> <svg version='1.1' id="svg" viewBox='-0.9 -0.9 1.8 1.8'> <defs> <marker id="arrow" markerWidth="3" markerHeight="3" refX="1.8" refY="1.5" orient="auto" markerUnits="strokeWidth"> <path d="M0,0 L0,3 L3,1.5 z" fill="#f00" /> </marker> </defs> <g id="cube" transform="scale(1) " id="topface"> <!-- Border --> <g style='stroke-width:0.1;stroke-linejoin:round;opacity:1'> <polygon fill='#000000' stroke='#000000' points='-0.522222222222,-0.522222222222 0.522222222222,-0.522222222222 0.522222222222,0.522222222222 -0.522222222222,0.522222222222'/> </g> <!-- Background --> <g style='opacity:1;stroke-opacity:0.5;stroke-width:0;stroke-linejoin:round'> <polygon fill$="[[_getColor(colors,0)]]" stroke='#000000' points='-0.527777777778,-0.527777777778 -0.212962962963,-0.527777777778 -0.212962962963,-0.212962962963 -0.527777777778,-0.212962962963'/> <polygon fill$="[[_getColor(colors,1)]]" stroke='#000000' points='-0.157407407407,-0.527777777778 0.157407407407,-0.527777777778 0.157407407407,-0.212962962963 -0.157407407407,-0.212962962963'/> <polygon fill$="[[_getColor(colors,2)]]" stroke='#000000' points='0.212962962963,-0.527777777778 0.527777777778,-0.527777777778 0.527777777778,-0.212962962963 0.212962962963,-0.212962962963'/> <polygon fill$="[[_getColor(colors,3)]]" stroke='#000000' points='-0.527777777778,-0.157407407407 -0.212962962963,-0.157407407407 -0.212962962963,0.157407407407 -0.527777777778,0.157407407407'/> <polygon fill$="[[_getColor(colors,4)]]" stroke='#000000' points='-0.157407407407,-0.157407407407 0.157407407407,-0.157407407407 0.157407407407,0.157407407407 -0.157407407407,0.157407407407'/> <polygon fill$="[[_getColor(colors,5)]]" stroke='#000000' points='0.212962962963,-0.157407407407 0.527777777778,-0.157407407407 0.527777777778,0.157407407407 0.212962962963,0.157407407407'/> <polygon fill$="[[_getColor(colors,6)]]" stroke='#000000' points='-0.527777777778,0.212962962963 -0.212962962963,0.212962962963 -0.212962962963,0.527777777778 -0.527777777778,0.527777777778'/> <polygon fill$="[[_getColor(colors,7)]]" stroke='#000000' points='-0.157407407407,0.212962962963 0.157407407407,0.212962962963 0.157407407407,0.527777777778 -0.157407407407,0.527777777778'/> <polygon fill$="[[_getColor(colors,8)]]" stroke='#000000' points='0.212962962963,0.212962962963 0.527777777778,0.212962962963 0.527777777778,0.527777777778 0.212962962963,0.527777777778'/> </g> <!-- Edges --> <g style='opacity:1;stroke-opacity:1;stroke-width:0.02;stroke-linejoin:round'> <polygon fill$="[[_getColor(colors,17)]]" stroke='#000000' points='-0.544061302682,0.554406130268 -0.195913154534,0.554406130268 -0.183908045977,0.718390804598 -0.508045977011,0.718390804598'/> <polygon fill$="[[_getColor(colors,16)]]" stroke='#000000' points='-0.174457215837,0.554406130268 0.173690932312,0.554406130268 0.161685823755,0.718390804598 -0.16245210728,0.718390804598'/> <polygon fill$="[[_getColor(colors,15)]]" stroke='#000000' points='0.195146871009,0.554406130268 0.543295019157,0.554406130268 0.507279693487,0.718390804598 0.183141762452,0.718390804598'/> <polygon fill$="[[_getColor(colors,20)]]" stroke='#000000' points='-0.554406130268,-0.544061302682 -0.554406130268,-0.195913154534 -0.718390804598,-0.183908045977 -0.718390804598,-0.508045977011'/> <polygon fill$="[[_getColor(colors,19)]]" stroke='#000000' points='-0.554406130268,-0.174457215837 -0.554406130268,0.173690932312 -0.718390804598,0.161685823755 -0.718390804598,-0.16245210728'/> <polygon fill$="[[_getColor(colors,18)]]" stroke='#000000' points='-0.554406130268,0.195146871009 -0.554406130268,0.543295019157 -0.718390804598,0.507279693487 -0.718390804598,0.183141762452'/> <polygon fill$="[[_getColor(colors,11)]]" stroke='#000000' points='0.544061302682,-0.554406130268 0.195913154534,-0.554406130268 0.183908045977,-0.718390804598 0.508045977011,-0.718390804598'/> <polygon fill$="[[_getColor(colors,10)]]" stroke='#000000' points='0.174457215837,-0.554406130268 -0.173690932312,-0.554406130268 -0.161685823755,-0.718390804598 0.16245210728,-0.718390804598'/> <polygon fill$="[[_getColor(colors,9)]]" stroke='#000000' points='-0.195146871009,-0.554406130268 -0.543295019157,-0.554406130268 -0.507279693487,-0.718390804598 -0.183141762452,-0.718390804598'/> <polygon fill$="[[_getColor(colors,14)]]" stroke='#000000' points='0.554406130268,0.544061302682 0.554406130268,0.195913154534 0.718390804598,0.183908045977 0.718390804598,0.508045977011'/> <polygon fill$="[[_getColor(colors,13)]]" stroke='#000000' points='0.554406130268,0.174457215837 0.554406130268,-0.173690932312 0.718390804598,-0.161685823755 0.718390804598,0.16245210728'/> <polygon fill$="[[_getColor(colors,12)]]" stroke='#000000' points='0.554406130268,-0.195146871009 0.554406130268,-0.543295019157 0.718390804598,-0.507279693487 0.718390804598,-0.183141762452'/> </g> <g id="arrows" style='opacity:1;stroke-opacity:1;stroke-width:0.02;stroke-linejoin:round'> </g> </g> </svg> `; } static get properties() { return { arrows: { type: String, observer: '_arrowsChanged' }, flips: { type: String, observer: '_flipsChanged' }, noArrows: { type: Boolean, value: false }, noMove: { type: Boolean, value: false }, debug: { type: Boolean, value: false }, stickers: { type: String, notify: true }, payload: { type: Object } }; } _tap(e) { if (e.shiftKey) { this.rotateLeft(); } else if (e.metaKey) { this.rotateRight(); } else { this.move(); } const payload = this.payload; this.dispatchEvent(new CustomEvent('select', {detail: payload})); } rotateLeft() { this._moveWithArrows('1>7,7>9,9>3,3>1,2>4,4>8,8>6,6>2'); } rotateRight() { this._moveWithArrows('1>3,3>9,9>7,7>1,2>6,6>8,8>4,4>2'); } _flipsChanged(flips) { } _arrowsChanged(arrows) { if (this.noArrows) { return; } if (arrows === undefined || arrows === "") { d3.select(this.$.arrows).selectAll('line').remove(); return; } const svg = d3.select(this.$.arrows); const self = this; this.arrows.replace(' ', '').split(',').forEach(function(arrow) { const points = arrow.split('>'); self._addArrow(svg, points[0],points[1]); }); } move() { if (this.noMove) { return; } if (this.flips !== undefined && this.flips !== '') { this._moveWithFlips(this.flips); } else if (this.arrows !== undefined && this.arrows !== '') { this._moveWithArrows(this.arrows); } } _moveWithFlips(flips) { if (flips === undefined || flips === "") return; const origColors = this.colors.map(c => c); const newColors = this.colors.map(c => c); let moves = this.flips.split('') .map(ch => (ch === '|' ? ',' : ch)) .filter(ch => ch !== ' ') .join('') .split(',') .map(m => m.split('>')); moves.forEach(move => { newColors[move[1]] = origColors[move[0]] }); this.set('colors', newColors); } _moveWithArrows(arrows) { if (arrows === undefined || arrows === "") return; let moves = arrows.split('') .filter(c => c !== ' ') .join('') .split(',') .map(m => m.split('>')); const origColors = this.colors.map(c => c); const newColors = this.colors.map(c => c); moves.forEach(move => { let from = EDGE_MAP[move[0]]; let to = EDGE_MAP[move[1]]; from = (Array.isArray(from) ? from : [from]); to = (Array.isArray(to) ? to : [to]); from.forEach((m,i) => { newColors[to[i]] = origColors[from[i]] }); }); this.set('colors', newColors); } applyMoves(movesString) { const moves = movesString.split('') .map(c => (c==='|' ? ',' : c)) .filter(c => c !== ' ') .join('') .split(',') .map(m => m.split('>')); const origColors = this.colors.map(c => c); const newColors = this.colors.map(c => c); moves.forEach(move => newColors[move[1]] = origColors[move[0]]); this.set('colors', newColors); } ready() { super.ready(); this._scaleImage(this.$.arrows); if (this.stickers === undefined || this.stickers === '') { this.set('stickers', 'yyy yyy yyy | rrr bbb ooo ggg'); } if (this.payload === undefined) { this.payload = { stickers: this.stickers, arrows: this.arrows, flips: this.flips }; } this.$.cube.addEventListener('click', e => this._tap(e)); } _addArrow(svg, from, to) { const x1 = -(1-((from-1)%3))*SQUARE_SIZE; const y1 = -(2-(Math.ceil(from/3)))*SQUARE_SIZE const x2 = -(1-((to-1)%3))*SQUARE_SIZE; const y2 = -(2-(Math.ceil(to/3)))*SQUARE_SIZE svg.append("line") .attr("x1", x1) .attr("y1", y1) .attr("x2", x2) .attr("y2", y2) .attr("class", "arrow") .attr("stroke-width", 0.05) .attr("stroke", "RED") .attr("marker-end", "url(#arrow)"); } }
JavaScript
class Animal { constructor(name, age) { this.name = name; this.age = age; } speak(word) { console.log(`hi my name is ${this.name}, ${word}`); } }
JavaScript
class Cat extends Animal { speak() { console.log('meow meow meow') } }
JavaScript
class MigrationLogger { /** * Creates a new MigrationLogger. * * @param {KbnServer.server} server - A server instance. * @param {String} name - The logger name. */ constructor(server, name) { this._name = name; this._server = server; } error(message) { this._server.log(['error', this._name], message); } warning(message) { this._server.log(['warning', this._name], message); } debug(message) { this._server.log(['info', this._name], message); } info(message) { this._server.log(['info', this._name], message); } }
JavaScript
class DataImporter extends FormApplication { /** @override */ static get defaultOptions() { return mergeObject(super.defaultOptions, { id: "data-importer", classes: ["starwarsffg", "data-import"], title: "Data Importer", template: "systems/starwarsffg/templates/importer/data-importer.html", }); } /** * Return a reference to the target attribute * @type {String} */ get attribute() { return this.options.name; } /** @override */ async getData() { let data = await FilePicker.browse("data", "", { bucket: null, extensions: [".zip", ".ZIP"], wildcard: false }); const files = data.files.map((file) => { return decodeURIComponent(file); }); $(".import-progress").addClass("import-hidden"); if (!CONFIG?.temporary) { CONFIG.temporary = {}; } return { data, files, cssClass: "data-importer-window", }; } /** @override */ activateListeners(html) { super.activateListeners(html); $(`<span class="debug"><label><input type="checkbox" /> Generate Log</label></span>`).insertBefore("#data-importer header a"); html.find(".dialog-button").on("click", this._dialogButton.bind(this)); } _importLog = []; _importLogger(message) { if ($(".debug input:checked").length > 0) { this._importLog.push(`[${new Date().getTime()}] ${message}`); } } async _dialogButton(event) { event.preventDefault(); event.stopPropagation(); const a = event.currentTarget; const action = a.dataset.button; // if clicking load file reset default $("input[type='checkbox'][name='imports']").attr("disabled", true); // load the requested file if (action === "load") { try { const selectedFile = $("#import-file").val(); let zip; if (selectedFile) { zip = await fetch(`/${selectedFile}`) .then(function (response) { if (response.status === 200 || response.status === 0) { return Promise.resolve(response.blob()); } else { return Promise.reject(new Error(response.statusText)); } }) .then(JSZip.loadAsync); } else { const form = $("form.data-importer-window")[0]; if (form.data.files.length) { zip = await ImportHelpers.readBlobFromFile(form.data.files[0]).then(JSZip.loadAsync); } } this._enableImportSelection(zip.files, "Talents"); this._enableImportSelection(zip.files, "Force Abilities"); this._enableImportSelection(zip.files, "Gear"); this._enableImportSelection(zip.files, "Weapons"); this._enableImportSelection(zip.files, "Armor"); this._enableImportSelection(zip.files, "Specializations", true); this._enableImportSelection(zip.files, "Careers", true); this._enableImportSelection(zip.files, "Species", true); this._enableImportSelection(zip.files, "Vehicles", true); this._enableImportSelection(zip.files, "ItemDescriptors"); this._enableImportSelection(zip.files, "SigAbilityNodes"); this._enableImportSelection(zip.files, "Skills"); } catch (err) { ui.notifications.warn("There was an error trying to load the import file, check the console log for more information."); console.error(err); } } if (action === "import") { CONFIG.logger.debug("Importing Data Files"); this._importLogger(`Starting import`); const importFiles = $("input:checkbox[name=imports]:checked") .map(function () { return { file: $(this).val(), label: $(this).data("name"), type: $(this).data("type"), itemtype: $(this).data("itemtype") }; }) .get(); const selectedFile = $("#import-file").val(); this._importLogger(`Using ${selectedFile} for import source`); let zip; if (selectedFile) { zip = await fetch(`/${selectedFile}`) .then(function (response) { if (response.status === 200 || response.status === 0) { return Promise.resolve(response.blob()); } else { return Promise.reject(new Error(response.statusText)); } }) .then(JSZip.loadAsync); } else { const form = $("form.data-importer-window")[0]; if (form.data.files.length) { zip = await ImportHelpers.readBlobFromFile(form.data.files[0]).then(JSZip.loadAsync); } } const promises = []; let isSpecialization = false; let isVehicle = false; let skillsFileName; try { skillsFileName = importFiles.find((item) => item.file.includes("Skills.xml")).file; } catch (err) { CONFIG.logger.warn(`Not importing skills.`); } let createSkillJournalEntries = true; if (!skillsFileName) { skillsFileName = await this._enableImportSelection(zip.files, "Skills", false, true); createSkillJournalEntries = false; } if (skillsFileName) { // load skills for reference let data = await zip.file(skillsFileName).async("text"); const xmlDoc = ImportHelpers.stringToXml(data); await this._loadSkillsList(xmlDoc, createSkillJournalEntries); } const itemDescriptors = importFiles.find((item) => item.file.includes("ItemDescriptors.xml")); if (itemDescriptors) { let data = await zip.file(itemDescriptors.file).async("text"); const xmlDoc = ImportHelpers.stringToXml(data); await this._loadItemDescriptors(xmlDoc); } await this.asyncForEach(importFiles, async (file) => { if (zip.files[file.file] && !zip.files[file.file].dir) { const data = await zip.file(file.file).async("text"); const xmlDoc = ImportHelpers.stringToXml(data); promises.push(this._handleGear(xmlDoc, zip)); promises.push(this._handleWeapons(xmlDoc, zip)); promises.push(this._handleArmor(xmlDoc, zip)); promises.push(this._handleTalents(xmlDoc, zip)); promises.push(this._handleForcePowers(xmlDoc, zip)); promises.push(this._handleSignatureAbilties(xmlDoc, zip)); } else { if (file.file.includes("/Specializations/")) { isSpecialization = true; } if (file.file.includes("/Careers/")) { promises.push(this._handleCareers(zip)); } if (file.file.includes("/Species/")) { promises.push(this._handleSpecies(zip)); } if (file.file.includes("/Vehicles/")) { isVehicle = true; } } }); await Promise.all(promises); if (isSpecialization) { await this._handleSpecializations(zip); } if (isVehicle) { await this._handleVehicles(zip); } if ($(".debug input:checked").length > 0) { saveDataToFile(this._importLog.join("\n"), "text/plain", "import-log.txt"); } CONFIG.temporary = {}; this.close(); } } async _loadSkillsList(xmlDoc, create) { const skills = xmlDoc.getElementsByTagName("Skill"); if (skills.length > 0) { CONFIG.temporary["skills"] = {}; let totalCount = skills.length; let currentCount = 0; let pack; if (create) { pack = await this._getCompendiumPack("JournalEntry", `oggdude.SkillDescriptions`); $(".import-progress.skills").toggleClass("import-hidden"); } for (let i = 0; i < skills.length; i += 1) { const skill = skills[i]; const importkey = skill.getElementsByTagName("Key")[0]?.textContent; let name = skill.getElementsByTagName("Name")[0]?.textContent; name = name.replace(" - ", ": "); if (["CORE", "EDU", "LORE", "OUT", "UND", "WARF", "XEN"].includes(importkey)) { name = `Knowledge: ${name}`; } CONFIG.temporary.skills[importkey] = name; if (create) { try { const d = JXON.xmlToJs(skill); let item = { name: d.Name, flags: { ffgimportid: d.Key, }, content: d?.Description?.length && d.Description.length > 0 ? d.Description : "Dataset did not have a description", }; item.content += ImportHelpers.getSources(d?.Sources ?? d?.Source); let compendiumItem; await pack.getIndex(); let entry = pack.index.find((e) => e.name === item.name); if (!entry) { CONFIG.logger.debug(`Importing Skill Description - JournalEntry`); compendiumItem = new JournalEntry(item, { temporary: true }); this._importLogger(`New Skill Description ${d.Name} : ${JSON.stringify(compendiumItem)}`); let id = await pack.importEntity(compendiumItem); } else { CONFIG.logger.debug(`Updating Skill Description - JournalEntry`); let updateData = item; updateData["_id"] = entry._id; this._importLogger(`Updating Skill Description ${d.Name} : ${JSON.stringify(updateData)}`); pack.updateEntity(updateData); } //} currentCount += 1; $(".skills .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing Skill Description ${d.Name}`); } catch (err) { CONFIG.logger.error(`Error importing record : `, err); } } } } } async _handleSignatureAbilties(xmlDoc, zip) { try { const sigAbilityNode = xmlDoc.getElementsByTagName("SigAbilityNode"); if (sigAbilityNode.length > 0) { const signatureAbilityUpgrades = JXON.xmlToJs(xmlDoc); const signatureAbilityFiles = Object.values(zip.files).filter((file) => { return !file.dir && file.name.split(".").pop() === "xml" && file.name.includes("/SigAbilities/"); }); if (signatureAbilityUpgrades.SigAbilityNodes?.SigAbilityNode?.length > 0 && signatureAbilityFiles.length > 0) { $(".import-progress.signatureabilities").toggleClass("import-hidden"); let pack = await this._getCompendiumPack("Item", `oggdude.SignatureAbilities`); let totalCount = signatureAbilityFiles.length; let currentCount = 0; this._importLogger(`Beginning import of ${signatureAbilityFiles.length} signature abilities`); await this.asyncForEach(signatureAbilityFiles, async (file) => { try { const data = await zip.file(file.name).async("text"); const xmlDoc1 = ImportHelpers.stringToXml(data); const sa = JXON.xmlToJs(xmlDoc1); let signatureAbility = { name: sa.SigAbility.Name, type: "signatureability", flags: { ffgimportid: sa.SigAbility.Key, }, data: { description: sa.SigAbility.Description, attributes: {}, upgrades: {}, }, }; signatureAbility.data.description += ImportHelpers.getSources(sa?.SigAbility?.Sources ?? sa?.SigAbility?.Source); for (let i = 1; i < sa.SigAbility.AbilityRows.AbilityRow.length; i += 1) { try { const row = sa.SigAbility.AbilityRows.AbilityRow[i]; row.Abilities.Key.forEach((keyName, index) => { let rowAbility = {}; let rowAbilityData = signatureAbilityUpgrades.SigAbilityNodes.SigAbilityNode.find((a) => { return a.Key === keyName; }); rowAbility.name = rowAbilityData.Name; rowAbility.description = rowAbilityData.Description; rowAbility.visible = true; rowAbility.attributes = {}; if (row.Directions.Direction[index].Up) { rowAbility["links-top-1"] = true; } switch (row.AbilitySpan.Span[index]) { case "1": rowAbility.size = "single"; break; case "2": rowAbility.size = "double"; if (index < 3 && row.Directions.Direction[index + 1].Up) { rowAbility["links-top-2"] = true; } break; case "3": rowAbility.size = "triple"; if (index < 2 && row.Directions.Direction[index + 1].Up) { rowAbility["links-top-2"] = true; } if (index < 2 && row.Directions.Direction[index + 2].Up) { rowAbility["links-top-3"] = true; } break; case "4": rowAbility.size = "full"; if (index < 1 && row.Directions.Direction[index + 1].Up) { rowAbility["links-top-2"] = true; } if (index < 1 && row.Directions.Direction[index + 2].Up) { rowAbility["links-top-3"] = true; } if (index < 1 && row.Directions.Direction[index + 3].Up) { rowAbility["links-top-4"] = true; } break; default: rowAbility.size = "single"; rowAbility.visible = false; } if (row.Directions.Direction[index].Right) { rowAbility["links-right"] = true; } const talentKey = `upgrade${(i - 1) * 4 + index}`; signatureAbility.data.upgrades[talentKey] = rowAbility; }); } catch (err) { CONFIG.logger.error(`Error importing record : `, err); } } let imgPath = await ImportHelpers.getImageFilename(zip, "SigAbilities", "", signatureAbility.flags.ffgimportid); if (imgPath) { signatureAbility.img = await ImportHelpers.importImage(imgPath.name, zip, pack); } let compendiumItem; await pack.getIndex(); let entry = pack.index.find((e) => e.name === signatureAbility.name); if (!entry) { CONFIG.logger.debug(`Importing Signature Ability - Item`); compendiumItem = new Item(signatureAbility, { temporary: true }); this._importLogger(`New Signature Ability ${signatureAbility.name} : ${JSON.stringify(compendiumItem)}`); pack.importEntity(compendiumItem); } else { CONFIG.logger.debug(`Updating Signature Ability - Item`); //let updateData = ImportHelpers.buildUpdateData(power); let updateData = signatureAbility; updateData["_id"] = entry._id; this._importLogger(`Updating Signature Ability ${signatureAbility.name} : ${JSON.stringify(updateData)}`); pack.updateEntity(updateData); } currentCount += 1; $(".signatureabilities .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing Signature Ability ${sa.SigAbility.Name}`); } catch (err) { CONFIG.logger.error(`Error importing record : `, err); } }); this._importLogger(`Completed Signature Ability Import`); } else { CONFIG.logger.error(`Error importing signature abilities, found ${signatureAbilityFiles.length} signature ability files and ${signatureAbilityUpgrades.SigAbilityNodes?.SigAbilityNode?.length} upgrades in data set`); this._importLogger(`Error importing signature abilities, found ${signatureAbilityFiles.length} signature ability files and ${signatureAbilityUpgrades.SigAbilityNodes?.SigAbilityNode?.length} upgrades in data set`); } } } catch (err) { CONFIG.logger.error(`Failed to import signature abilities`, err); this._importLogger(`Failed to import signature abilities`, err); } } async _loadItemDescriptors(xmlDoc) { this._importLogger(`Starting Item Qualities Import`); const descriptors = xmlDoc.getElementsByTagName("ItemDescriptor"); if (descriptors.length > 0) { let totalCount = descriptors.length; let currentCount = 0; $(".import-progress.itemdescriptors").toggleClass("import-hidden"); let pack = await this._getCompendiumPack("JournalEntry", `oggdude.ItemQualities`); CONFIG.temporary["descriptors"] = {}; await this.asyncForEach(descriptors, async (descriptor) => { try { const d = JXON.xmlToJs(descriptor); //if (d.Type) { let itemDescriptor = { name: d.Name, flags: { ffgimportid: d.Key, }, content: d?.Description?.length && d.Description.length > 0 ? d.Description : "Dataset did not have a description", }; itemDescriptor.content += ImportHelpers.getSources(d?.Sources ?? d?.Source); let compendiumItem; await pack.getIndex(); let entry = pack.index.find((e) => e.name === itemDescriptor.name); if (!entry) { CONFIG.logger.debug(`Importing Item Quality - JournalEntry`); compendiumItem = new JournalEntry(itemDescriptor, { temporary: true }); this._importLogger(`New item quality ${d.Name} : ${JSON.stringify(compendiumItem)}`); let id = await pack.importEntity(compendiumItem); CONFIG.temporary["descriptors"][d.Key] = id.id; } else { CONFIG.logger.debug(`Updating Item Quality - JournalEntry`); //let updateData = ImportHelpers.buildUpdateData(itemDescriptor); let updateData = itemDescriptor; updateData["_id"] = entry._id; CONFIG.temporary["descriptors"][d.Key] = entry._id; this._importLogger(`Updating item quality ${d.Name} : ${JSON.stringify(updateData)}`); pack.updateEntity(updateData); } //} currentCount += 1; $(".itemdescriptors .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing item quality ${d.Name}`); } catch (err) { CONFIG.logger.error(`Error importing record : `, err); } }); } this._importLogger(`Completed Item Qualities Import`); } async _handleTalents(xmlDoc, zip) { this._importLogger(`Starting Talent Import`); const talents = xmlDoc.getElementsByTagName("Talent"); if (talents.length > 0) { let totalCount = talents.length; let currentCount = 0; this._importLogger(`Beginning import of ${talents.length} talents`); $(".import-progress.talents").toggleClass("import-hidden"); let pack = await this._getCompendiumPack("Item", `oggdude.Talents`); for (let i = 0; i < talents.length; i += 1) { try { const talent = talents[i]; const importkey = talent.getElementsByTagName("Key")[0]?.textContent; const name = talent.getElementsByTagName("Name")[0]?.textContent; const description = talent.getElementsByTagName("Description")[0]?.textContent; const ranked = talent.getElementsByTagName("Ranked")[0]?.textContent === "true" ? true : false; const activationValue = talent.getElementsByTagName("ActivationValue")[0]?.textContent; this._importLogger(`Start importing talent ${name}`); let activation = "Passive"; switch (activationValue) { case "taManeuver": activation = "Active (Maneuver)"; break; case "taAction": activation = "Active (Action)"; break; case "taIncidental": activation = "Active (Incidental)"; break; case "taIncidentalOOT": activation = "Active (Incidental, Out of Turn)"; break; default: activation = "Passive"; } const forcetalent = talent.getElementsByTagName("ForceTalent")[0]?.textContent === "true" ? true : false; const conflicttalent = talent.getElementsByTagName("Conflict")[0]?.textContent?.length > 0 ? true : false; const item = { name, type: "talent", flags: { ffgimportid: importkey, }, data: { attributes: {}, description, ranks: { ranked, }, activation: { value: activation, }, isForceTalent: forcetalent, isConflictTalent: conflicttalent, }, }; const d = JXON.xmlToJs(talents[i]); item.data.description += ImportHelpers.getSources(d?.Sources ?? d?.Source); const attributes = talent.getElementsByTagName("Attributes")[0]; if (attributes) { item.data.attributes = Object.assign(item.data.attributes, ImportHelpers.getAttributeObject(attributes)); } const careerskills = talent.getElementsByTagName("ChooseCareerSkills")[0]; if (careerskills) { const cs = JXON.xmlToJs(careerskills); const funcAddCareerSkill = (s) => { if (Object.keys(CONFIG.temporary.skills).includes(s)) { const skill = CONFIG.temporary.skills[s]; const careerKey = Object.keys(item.data.attributes).length + 1; item.data.attributes[`attr${careerKey}`] = { mod: skill, modtype: "Career Skill", value: true, }; } }; if (cs?.NewSkills?.Key) { if (Array.isArray(cs.NewSkills.Key)) { cs.NewSkills.Key.forEach((s) => { funcAddCareerSkill(s); }); } else { funcAddCareerSkill(cs.NewSkills.Key); } } } const diemodifiers = talent.getElementsByTagName("DieModifiers")[0]; if (diemodifiers) { const diemod = JXON.xmlToJs(diemodifiers); if (diemod.DieModifier) { if (!Array.isArray(diemod.DieModifier)) { diemod.DieModifier = [diemod.DieModifier]; } diemod.DieModifier.forEach((mod) => { const attr = ImportHelpers.getBaseModAttributeObject({ Key: mod.SkillKey, ...mod, }); if (attr) { item.data.attributes[attr.type] = attr.value; } }); } } // does an image exist? let imgPath = await ImportHelpers.getImageFilename(zip, "Talent", "", item.flags.ffgimportid); if (imgPath) { item.img = await ImportHelpers.importImage(imgPath.name, zip, pack); } let compendiumItem; await pack.getIndex(); let entry = pack.index.find((e) => e.name === item.name); if (!entry) { CONFIG.logger.debug(`Importing Talent - Item`); compendiumItem = new Item(item, { temporary: true }); this._importLogger(`New talent ${name} : ${JSON.stringify(compendiumItem)}`); pack.importEntity(compendiumItem); } else { CONFIG.logger.debug(`Update Talent - Item`); //let updateData = ImportHelpers.buildUpdateData(item); let updateData = item; updateData["_id"] = entry._id; this._importLogger(`Updating talent ${name} : ${JSON.stringify(updateData)}`); pack.updateEntity(updateData); } currentCount += 1; $(".talents .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing talent ${name}`); } catch (err) { CONFIG.logger.error(`Error importing record : `, err); this._importLogger(`Error importing talent: ${JSON.stringify(err)}`); } } } this._importLogger(`Completed Talent Import`); } async _handleForcePowers(xmlDoc, zip) { this._importLogger(`Starting Force Power Import`); const forceabilities = xmlDoc.getElementsByTagName("ForceAbility"); if (forceabilities.length > 0) { $(".import-progress.force").toggleClass("import-hidden"); let pack = await this._getCompendiumPack("Item", `oggdude.ForcePowers`); const fa = JXON.xmlToJs(xmlDoc); // now we need to loop through the files in the Force Powers folder const forcePowersFiles = Object.values(zip.files).filter((file) => { return !file.dir && file.name.split(".").pop() === "xml" && file.name.includes("/Force Powers/"); }); let totalCount = forcePowersFiles.length; let currentCount = 0; this._importLogger(`Beginning import of ${forcePowersFiles.length} force powers`); await this.asyncForEach(forcePowersFiles, async (file) => { try { const data = await zip.file(file.name).async("text"); const xmlDoc1 = ImportHelpers.stringToXml(data); const fp = JXON.xmlToJs(xmlDoc1); // setup the base information let power = { name: fp.ForcePower.Name, type: "forcepower", flags: { ffgimportid: fp.ForcePower.Key, }, data: { attributes: {}, upgrades: {}, }, }; this._importLogger(`Start importing force power ${fp.ForcePower.Name}`); // get the basic power informatio const importKey = fp.ForcePower.AbilityRows.AbilityRow[0].Abilities.Key[0]; let forceAbility = fa.ForceAbilities.ForceAbility.find((ability) => { return ability.Key === importKey; }); power.data.description = forceAbility.Description; power.data.description += ImportHelpers.getSources(fp?.ForcePower?.Sources ?? fp?.ForcePower?.Source); if (forceAbility?.DieModifiers?.DieModifier) { if (!Array.isArray(forceAbility.DieModifiers.DieModifier)) { forceAbility.DieModifiers.DieModifier = [forceAbility.DieModifiers.DieModifier]; } forceAbility.DieModifiers.DieModifier.forEach((mod) => { const attr = ImportHelpers.getBaseModAttributeObject({ Key: mod.SkillKey, ...mod, }); if (attr) { power.data.attributes[attr.type] = attr.value; } }); } // next we will parse the rows for (let i = 1; i < fp.ForcePower.AbilityRows.AbilityRow.length; i += 1) { try { const row = fp.ForcePower.AbilityRows.AbilityRow[i]; row.Abilities.Key.forEach((keyName, index) => { let rowAbility = {}; let rowAbilityData = fa.ForceAbilities.ForceAbility.find((a) => { return a.Key === keyName; }); rowAbility.name = rowAbilityData.Name; rowAbility.description = rowAbilityData.Description; rowAbility.cost = row.Costs.Cost[index]; rowAbility.visible = true; rowAbility.attributes = {}; if (row.Directions.Direction[index].Up) { rowAbility["links-top-1"] = true; } switch (row.AbilitySpan.Span[index]) { case "1": rowAbility.size = "single"; break; case "2": rowAbility.size = "double"; if (index < 3 && row.Directions.Direction[index + 1].Up) { rowAbility["links-top-2"] = true; } break; case "3": rowAbility.size = "triple"; if (index < 2 && row.Directions.Direction[index + 1].Up) { rowAbility["links-top-2"] = true; } if (index < 2 && row.Directions.Direction[index + 2].Up) { rowAbility["links-top-3"] = true; } break; case "4": rowAbility.size = "full"; if (index < 1 && row.Directions.Direction[index + 1].Up) { rowAbility["links-top-2"] = true; } if (index < 1 && row.Directions.Direction[index + 2].Up) { rowAbility["links-top-3"] = true; } if (index < 1 && row.Directions.Direction[index + 3].Up) { rowAbility["links-top-4"] = true; } break; default: rowAbility.size = "single"; rowAbility.visible = false; } if (row.Directions.Direction[index].Right) { rowAbility["links-right"] = true; } const funcAddUpgradeDieModifier = (mod) => { if (Object.keys(CONFIG.temporary.skills).includes(mod.SkillKey)) { // only handling boosts initially if (mod.BoostCount || mod.SetbackCount || mod.AddSetbackCount || mod.ForceCount) { const skill = CONFIG.temporary.skills[mod.SkillKey]; const modKey = Object.keys(rowAbility.attributes).length + 1; let modtype = "Skill Boost"; let count = 0; if (mod.AddSetbackCount) { modtype = "Skill Setback"; count = mod.AddSetbackCount; } if (mod.SetbackCount) { modtype = "Skill Remove Setback"; count = mod.SetbackCount; } if (mod.ForceCount) { modtype = "Force Boost"; count = true; } if (mod.BoostCount) { count = mod.BoostCount; } rowAbility.attributes[`attr${keyName}${modKey}`] = { mod: skill, modtype, value: count, }; } } }; if (rowAbilityData?.DieModifiers?.DieModifier) { if (Array.isArray(rowAbilityData.DieModifiers.DieModifier)) { rowAbilityData.DieModifiers.DieModifier.forEach((mod) => { funcAddUpgradeDieModifier(mod); }); } else { if (Object.keys(CONFIG.temporary.skills).includes(rowAbilityData.DieModifiers.DieModifier.SkillKey)) { funcAddUpgradeDieModifier(rowAbilityData.DieModifiers.DieModifier); } } } const talentKey = `upgrade${(i - 1) * 4 + index}`; power.data.upgrades[talentKey] = rowAbility; }); } catch (err) { CONFIG.logger.error(`Error importing record : `, err); } } if (fp.ForcePower.AbilityRows.AbilityRow.length < 5) { for (let i = fp.ForcePower.AbilityRows.AbilityRow.length; i < 5; i += 1) { for (let index = 0; index < 4; index += 1) { const talentKey = `upgrade${(i - 1) * 4 + index}`; let rowAbility = { visible: false }; power.data.upgrades[talentKey] = rowAbility; } } } // does an image exist? let imgPath = await ImportHelpers.getImageFilename(zip, "ForcePowers", "", power.flags.ffgimportid); if (imgPath) { power.img = await ImportHelpers.importImage(imgPath.name, zip, pack); } let compendiumItem; await pack.getIndex(); let entry = pack.index.find((e) => e.name === power.name); if (!entry) { CONFIG.logger.debug(`Importing Force Power - Item`); compendiumItem = new Item(power, { temporary: true }); this._importLogger(`New force power ${fp.ForcePower.Name} : ${JSON.stringify(compendiumItem)}`); pack.importEntity(compendiumItem); } else { CONFIG.logger.debug(`Updating Force Power - Item`); //let updateData = ImportHelpers.buildUpdateData(power); let updateData = power; updateData["_id"] = entry._id; this._importLogger(`Updating force power ${fp.ForcePower.Name} : ${JSON.stringify(updateData)}`); pack.updateEntity(updateData); } currentCount += 1; $(".force .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing force power ${fp.ForcePower.Name}`); } catch (err) { CONFIG.logger.error(`Error importing record : `, err); } }); } this._importLogger(`Completed Force Power Import`); } async _handleGear(xmlDoc, zip) { this._importLogger(`Starting Gear Import`); const gear = xmlDoc.getElementsByTagName("Gear"); if (gear.length > 0) { let totalCount = gear.length; let currentCount = 0; this._importLogger(`Beginning import of ${gear.length} gear`); $(".import-progress.gear").toggleClass("import-hidden"); let pack = await this._getCompendiumPack("Item", `oggdude.Gear`); for (let i = 0; i < gear.length; i += 1) { try { const item = gear[i]; const importkey = item.getElementsByTagName("Key")[0]?.textContent; const name = item.getElementsByTagName("Name")[0]?.textContent; const description = item.getElementsByTagName("Description")[0]?.textContent; const price = item.getElementsByTagName("Price")[0]?.textContent; const rarity = item.getElementsByTagName("Rarity")[0]?.textContent; const encumbrance = item.getElementsByTagName("Encumbrance")[0]?.textContent; const type = item.getElementsByTagName("Type")[0]?.textContent; const restricted = item.getElementsByTagName("Restricted")[0]?.textContent === "true" ? true : false; this._importLogger(`Start importing gear ${name}`); const newItem = { name, type: "gear", flags: { ffgimportid: importkey, }, data: { attributes: {}, description, encumbrance: { value: encumbrance, }, price: { value: price, }, rarity: { value: rarity, isrestricted: restricted, }, }, }; const d = JXON.xmlToJs(item); newItem.data.description += ImportHelpers.getSources(d?.Sources ?? d?.Source); const baseMods = item.getElementsByTagName("BaseMods")[0]; if (baseMods) { const mods = await ImportHelpers.getBaseModObject(baseMods); if (mods) { newItem.data.attributes = mods; } } // does an image exist? let imgPath = await ImportHelpers.getImageFilename(zip, "Equipment", "Gear", newItem.flags.ffgimportid); if (imgPath) { newItem.img = await ImportHelpers.importImage(imgPath.name, zip, pack); } let compendiumItem; await pack.getIndex(); let entry = pack.index.find((e) => e.name === newItem.name); if (!entry) { CONFIG.logger.debug(`Importing Gear - Item`); compendiumItem = new Item(newItem, { temporary: true }); this._importLogger(`New gear ${name} : ${JSON.stringify(compendiumItem)}`); pack.importEntity(compendiumItem); } else { CONFIG.logger.debug(`Updating Gear - Item`); //let updateData = ImportHelpers.buildUpdateData(newItem); let updateData = newItem; updateData["_id"] = entry._id; this._importLogger(`Updating gear ${name} : ${JSON.stringify(updateData)}`); pack.updateEntity(updateData); } currentCount += 1; $(".gear .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing gear ${name}`); } catch (err) { CONFIG.logger.error(`Error importing record : `, err); this._importLogger(`Error importing gear: ${JSON.stringify(err)}`); } } } this._importLogger(`Completed Gear Import`); } async _handleWeapons(xmlDoc, zip) { this._importLogger(`Starting Weapon Import`); const weapons = xmlDoc.getElementsByTagName("Weapon"); if (weapons.length > 0) { let totalCount = weapons.length; let currentCount = 0; this._importLogger(`Beginning import of ${weapons.length} weapons`); $(".import-progress.weapons").toggleClass("import-hidden"); let pack = await this._getCompendiumPack("Item", `oggdude.Weapons`); for (let i = 0; i < weapons.length; i += 1) { try { const weapon = weapons[i]; const importkey = weapon.getElementsByTagName("Key")[0]?.textContent; const name = weapon.getElementsByTagName("Name")[0]?.textContent; const description = weapon.getElementsByTagName("Description")[0]?.textContent; const price = weapon.getElementsByTagName("Price")[0]?.textContent; const rarity = weapon.getElementsByTagName("Rarity")[0]?.textContent; const encumbrance = weapon.getElementsByTagName("Encumbrance")[0]?.textContent; const damage = weapon.getElementsByTagName("Damage")[0]?.textContent; const damageAdd = weapon.getElementsByTagName("DamageAdd")[0]?.textContent; const crit = weapon.getElementsByTagName("Crit")[0]?.textContent; const skillkey = weapon.getElementsByTagName("SkillKey")[0]?.textContent; const range = weapon.getElementsByTagName("RangeValue")[0]?.textContent.replace("wr", ""); const hardpoints = weapon.getElementsByTagName("HP")[0]?.textContent; const weaponType = weapon.getElementsByTagName("Type")[0]?.textContent; const restricted = weapon.getElementsByTagName("Restricted")[0]?.textContent === "true" ? true : false; this._importLogger(`Start importing weapon ${name}`); let skill = ""; switch (skillkey) { case "RANGLT": skill = "Ranged: Light"; break; case "RANGHVY": skill = "Ranged: Heavy"; break; case "GUNN": skill = "Gunnery"; break; case "BRAWL": skill = "Brawl"; break; case "MELEE": skill = "Melee"; break; case "LTSABER": skill = "Lightsaber"; break; default: } const fp = JXON.xmlToJs(weapon); let newItem = { name, type: weaponType === "Vehicle" ? "shipweapon" : "weapon", flags: { ffgimportid: importkey, }, data: { attributes: {}, description, encumbrance: { value: encumbrance, }, price: { value: price, }, rarity: { value: rarity, isrestricted: restricted, }, damage: { value: !damage ? damageAdd : damage, }, crit: { value: crit, }, special: { value: "", }, skill: { value: skill, }, range: { value: range, }, hardpoints: { value: hardpoints, }, }, }; const d = JXON.xmlToJs(weapon); newItem.data.description += ImportHelpers.getSources(d?.Sources ?? d?.Source); const qualities = []; if (fp?.Qualities?.Quality && !Array.isArray(fp?.Qualities?.Quality)) { fp.Qualities.Quality = [fp.Qualities.Quality]; } if (fp?.Qualities?.Quality && fp.Qualities.Quality.length > 0) { await this.asyncForEach(fp.Qualities.Quality, async (quality) => { let descriptor = await ImportHelpers.findCompendiumEntityByImportId("JournalEntry", quality.Key); if (descriptor?.compendium?.metadata) { qualities.push(`<a class="entity-link" draggable="true" data-pack="${descriptor.compendium.metadata.package}.${descriptor.compendium.metadata.name}" data-id="${descriptor.id}"> ${quality.Key} ${quality.Count ? quality.Count : ""}</a>`); } else { qualities.push(`${quality.Key} ${quality.Count ? quality.Count : ""}`); } if (quality.Key === "DEFENSIVE") { const nk = Object.keys(newItem.data.attributes).length + 1; const count = quality.Count ? parseInt(quality.Count) : 0; newItem.data.attributes[`attr${nk}`] = { isCheckbox: false, mod: "Defence-Melee", modtype: "Stat", value: count, }; } }); } newItem.data.special.value = qualities.join(", "); if ((skill.includes("Melee") || skill.includes("Brawl") || skill.includes("Lightsaber")) && damage === "0") { newItem.data.skill.useBrawn = true; } const baseMods = weapon.getElementsByTagName("BaseMods")[0]; if (baseMods) { const mods = await ImportHelpers.getBaseModObject(baseMods); if (mods) { newItem.data.attributes = mods; } } if (damageAdd && parseInt(damageAdd, 10) > 0 && newItem.type === "weapon") { const nk = Object.keys(newItem.data.attributes).length + 1; newItem.data.attributes[`attr${nk}`] = { isCheckbox: false, mod: "damage", modtype: "Weapon Stat", value: damageAdd, }; } // does an image exist? let imgPath = await ImportHelpers.getImageFilename(zip, "Equipment", "Weapon", newItem.flags.ffgimportid); if (imgPath) { newItem.img = await ImportHelpers.importImage(imgPath.name, zip, pack); } let compendiumItem; await pack.getIndex(); let entry = pack.index.find((e) => e.name === newItem.name); if (!entry) { CONFIG.logger.debug(`Importing Weapon - Item`); compendiumItem = new Item(newItem, { temporary: true }); this._importLogger(`New weapon ${name} : ${JSON.stringify(compendiumItem)}`); pack.importEntity(compendiumItem); } else { CONFIG.logger.debug(`Updating Weapon - Item`); //let updateData = ImportHelpers.buildUpdateData(newItem); let updateData = newItem; updateData["_id"] = entry._id; this._importLogger(`Updating weapon ${name} : ${JSON.stringify(updateData)}`); pack.updateEntity(updateData); } currentCount += 1; $(".weapons .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing weapon ${name}`); } catch (err) { CONFIG.logger.error(`Error importing record (${weapons[i].getElementsByTagName("Name")[0]?.textContent}) : `, err); this._importLogger(`Error importing weapon: ${JSON.stringify(err)}`); } } } this._importLogger(`Completed Weapon Import`); } async _handleArmor(xmlDoc, zip) { this._importLogger(`Starting Armor Import`); const fa = JXON.xmlToJs(xmlDoc); const armors = xmlDoc.getElementsByTagName("Armor"); if (armors.length > 0) { let totalCount = armors.length; let currentCount = 0; this._importLogger(`Beginning import of ${armors.length} armor`); $(".import-progress.armor").toggleClass("import-hidden"); let pack = await this._getCompendiumPack("Item", `oggdude.Armor`); for (let i = 0; i < armors.length; i += 1) { try { const armor = armors[i]; const importkey = armor.getElementsByTagName("Key")[0]?.textContent; const name = armor.getElementsByTagName("Name")[0]?.textContent; const description = armor.getElementsByTagName("Description")[0]?.textContent; const price = armor.getElementsByTagName("Price")[0]?.textContent; const rarity = armor.getElementsByTagName("Rarity")[0]?.textContent; const restricted = armor.getElementsByTagName("Restricted")[0]?.textContent === "true" ? true : false; const encumbrance = armor.getElementsByTagName("Encumbrance")[0]?.textContent; const defense = armor.getElementsByTagName("Defense")[0]?.textContent; const soak = armor.getElementsByTagName("Soak")[0]?.textContent; const hardpoints = armor.getElementsByTagName("HP")[0]?.textContent; this._importLogger(`Start importing armor ${name}`); let newItem = { name, type: "armour", flags: { ffgimportid: importkey, }, data: { attributes: {}, description, encumbrance: { value: encumbrance, }, price: { value: price, }, rarity: { value: rarity, isrestricted: restricted, }, defence: { value: defense, }, soak: { value: soak, }, hardpoints: { value: hardpoints, }, }, }; const d = JXON.xmlToJs(armor); newItem.data.description += ImportHelpers.getSources(d?.Sources ?? d?.Source); const baseMods = armor.getElementsByTagName("BaseMods")[0]; if (baseMods) { const mods = await ImportHelpers.getBaseModObject(baseMods); if (mods) { newItem.data.attributes = mods; } } // does an image exist? let imgPath = await ImportHelpers.getImageFilename(zip, "Equipment", "Armor", newItem.flags.ffgimportid); if (imgPath) { newItem.img = await ImportHelpers.importImage(imgPath.name, zip, pack); } let compendiumItem; await pack.getIndex(); let entry = pack.index.find((e) => e.name === newItem.name); if (!entry) { CONFIG.logger.debug(`Importing Armor - Item`); compendiumItem = new Item(newItem, { temporary: true }); this._importLogger(`New armor ${name} : ${JSON.stringify(compendiumItem)}`); pack.importEntity(compendiumItem); } else { CONFIG.logger.debug(`Updating Armor - Item`); //let updateData = ImportHelpers.buildUpdateData(newItem); let updateData = newItem; updateData["_id"] = entry._id; this._importLogger(`Updating armor ${name} : ${JSON.stringify(updateData)}`); pack.updateEntity(updateData); } currentCount += 1; $(".armor .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing armor ${name}`); } catch (err) { CONFIG.logger.error(`Error importing record : `, err); this._importLogger(`Error importing armor: ${JSON.stringify(err)}`); } } } this._importLogger(`Completed Armor Import`); } async _handleSpecializations(zip) { this._importLogger(`Starting Specialization Import`); const specializationFiles = Object.values(zip.files).filter((file) => { return !file.dir && file.name.split(".").pop() === "xml" && file.name.includes("/Specializations/"); }); let totalCount = specializationFiles.length; let currentCount = 0; if (specializationFiles.length > 0) { $(".import-progress.specializations").toggleClass("import-hidden"); let pack = await this._getCompendiumPack("Item", `oggdude.Specializations`); await this.asyncForEach(specializationFiles, async (file) => { try { const data = await zip.file(file.name).async("text"); const xmlDoc = ImportHelpers.stringToXml(data); const specData = JXON.xmlToJs(xmlDoc); let specialization = { name: specData.Specialization.Name, type: "specialization", flags: { ffgimportid: specData.Specialization.Key, }, data: { attributes: {}, description: specData.Specialization.Description, talents: {}, careerskills: {}, isReadOnly: true, }, }; specialization.data.description += ImportHelpers.getSources(specData?.Specialization?.Sources ?? specData?.Specialization?.Source); this._importLogger(`Start importing Specialization ${specialization.name}`); // assign career skills try { specData.Specialization.CareerSkills.Key.forEach((skillKey) => { let skill = CONFIG.temporary.skills[skillKey]; if (skill) { // add career skill const careerKey = Object.keys(specialization.data.attributes).length + 1; specialization.data.attributes[`attr${careerKey}`] = { mod: skill, modtype: "Career Skill", value: true, }; // most specialization give players choice were to put points, create modifier but put value of 0 const skillKey = Object.keys(specialization.data.attributes).length + 1; specialization.data.attributes[`attr${skillKey}`] = { mod: skill, modtype: "Skill Rank", value: "0", }; } }); } catch (err) { // skipping career skills } if (specData.Specialization?.Attributes?.ForceRating) { specialization.data.attributes[`attrForceRating`] = { mod: "ForcePool", modtype: "Stat", value: 1, }; } for (let i = 0; i < specData.Specialization.TalentRows.TalentRow.length; i += 1) { const row = specData.Specialization.TalentRows.TalentRow[i]; await this.asyncForEach(row.Talents.Key, async (keyName, index) => { let rowTalent = {}; let talentItem = ImportHelpers.findEntityByImportId("items", keyName); if (!talentItem) { talentItem = await ImportHelpers.findCompendiumEntityByImportId("Item", keyName); } if (talentItem) { rowTalent.name = talentItem.data.name; rowTalent.description = talentItem.data.data.description; rowTalent.activation = talentItem.data.data.activation.value; rowTalent.activationLabel = talentItem.data.data.activation.label; rowTalent.isForceTalent = talentItem.data.data.isForceTalent === "true" ? true : false; rowTalent.isConflictTalent = talentItem.data.data.isConflictTalent === "true" ? true : false; rowTalent.isRanked = talentItem.data.data.ranks.ranked === "true" ? true : false; rowTalent.size = "single"; rowTalent.canLinkTop = true; rowTalent.canLinkRight = true; rowTalent.itemId = talentItem.data._id; rowTalent.attributes = talentItem.data.data.attributes; if (row.Directions.Direction[index].Up && row.Directions.Direction[index].Up === "true") { rowTalent["links-top-1"] = true; } if (row.Directions.Direction[index].Right && row.Directions.Direction[index].Right === "true") { rowTalent["links-right"] = true; } if (talentItem.compendium) { rowTalent.pack = `${talentItem.compendium.metadata.package}.${talentItem.compendium.metadata.name}`; } const talentKey = `talent${i * 4 + index}`; specialization.data.talents[talentKey] = rowTalent; } }); } // does an image exist? let imgPath = await ImportHelpers.getImageFilename(zip, "Specialization", "", specialization.flags.ffgimportid); if (imgPath) { specialization.img = await ImportHelpers.importImage(imgPath.name, zip, pack); } let compendiumItem; await pack.getIndex(); let entry = pack.index.find((e) => e.name === specialization.name); if (!entry) { CONFIG.logger.debug(`Importing Specialization - Item`); compendiumItem = new Item(specialization, { temporary: true }); this._importLogger(`New Specialization ${specialization.name} : ${JSON.stringify(compendiumItem)}`); pack.importEntity(compendiumItem); } else { CONFIG.logger.debug(`Updating Specialization - Item`); //let updateData = ImportHelpers.buildUpdateData(specialization); let updateData = specialization; updateData["_id"] = entry._id; this._importLogger(`Updating Specialization ${specialization.name} : ${JSON.stringify(updateData)}`); pack.updateEntity(updateData); } currentCount += 1; $(".specializations .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing Specialization ${specialization.name}`); } catch (err) { CONFIG.logger.error(`Error importing record : `, err); } }); } this._importLogger(`Completed Specialization Import`); } async _handleCareers(zip) { this._importLogger(`Starting Career Import`); const careerFiles = Object.values(zip.files).filter((file) => { return !file.dir && file.name.split(".").pop() === "xml" && file.name.includes("/Careers/"); }); let totalCount = careerFiles.length; let currentCount = 0; if (careerFiles.length > 0) { $(".import-progress.careers").toggleClass("import-hidden"); let pack = await this._getCompendiumPack("Item", `oggdude.Careers`); await this.asyncForEach(careerFiles, async (file) => { try { const data = await zip.file(file.name).async("text"); const xmlDoc = ImportHelpers.stringToXml(data); const careerData = JXON.xmlToJs(xmlDoc); let career = { name: careerData.Career.Name, type: "career", flags: { ffgimportid: careerData.Career.Key, }, data: { attributes: {}, description: careerData.Career.Description, }, }; career.data.description += ImportHelpers.getSources(careerData?.Career?.Sources ?? careerData?.Career?.Source); this._importLogger(`Start importing Career ${career.name}`); careerData.Career.CareerSkills.Key.forEach((skillKey) => { let skill = CONFIG.temporary.skills[skillKey]; if (skill) { const careerKey = Object.keys(career.data.attributes).length + 1; career.data.attributes[`attr${careerKey}`] = { mod: skill, modtype: "Career Skill", value: true, }; const skillKey = Object.keys(career.data.attributes).length + 1; career.data.attributes[`attr${skillKey}`] = { mod: skill, modtype: "Skill Rank", value: "0", }; } }); // does an image exist? let imgPath = await ImportHelpers.getImageFilename(zip, "Career", "", career.flags.ffgimportid); if (imgPath) { career.img = await ImportHelpers.importImage(imgPath.name, zip, pack); } let compendiumItem; await pack.getIndex(); let entry = pack.index.find((e) => e.name === career.name); if (!entry) { CONFIG.logger.debug(`Importing Career - Item`); compendiumItem = new Item(career, { temporary: true }); this._importLogger(`New Career ${career.name} : ${JSON.stringify(compendiumItem)}`); pack.importEntity(compendiumItem); } else { CONFIG.logger.debug(`Updating Career - Item`); //let updateData = ImportHelpers.buildUpdateData(career); let updateData = career; updateData["_id"] = entry._id; this._importLogger(`Updating Career ${career.name} : ${JSON.stringify(updateData)}`); pack.updateEntity(updateData); } currentCount += 1; $(".careers .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing Career ${career.name}`); } catch (err) { this._importLogger(`Error importing record : `, err); CONFIG.logger.error(`Error importing record : `, err); } }); } } async _handleSpecies(zip) { this._importLogger(`Starting Species Import`); const speciesFiles = Object.values(zip.files).filter((file) => { return !file.dir && file.name.split(".").pop() === "xml" && file.name.includes("/Species/"); }); let totalCount = speciesFiles.length; let currentCount = 0; if (speciesFiles.length > 0) { $(".import-progress.species").toggleClass("import-hidden"); let pack = await this._getCompendiumPack("Item", `oggdude.Species`); await this.asyncForEach(speciesFiles, async (file) => { try { const data = await zip.file(file.name).async("text"); const xmlDoc = ImportHelpers.stringToXml(data); const speciesData = JXON.xmlToJs(xmlDoc); let species = { name: speciesData.Species.Name, type: "species", flags: { ffgimportid: speciesData.Species.Key, }, data: { attributes: {}, description: speciesData.Species.Description, }, }; species.data.description += ImportHelpers.getSources(speciesData?.Species?.Sources ?? speciesData?.Species?.Source); const funcAddAttribute = (modtype, mod, value, hidden) => { const charKey = Object.keys(species.data.attributes).length + 1; species.data.attributes[mod] = { mod, modtype, value: parseInt(value, 10), exclude: hidden, }; }; funcAddAttribute("Characteristic", "Brawn", speciesData.Species.StartingChars.Brawn, true); funcAddAttribute("Characteristic", "Agility", speciesData.Species.StartingChars.Agility, true); funcAddAttribute("Characteristic", "Intellect", speciesData.Species.StartingChars.Intellect, true); funcAddAttribute("Characteristic", "Cunning", speciesData.Species.StartingChars.Cunning, true); funcAddAttribute("Characteristic", "Willpower", speciesData.Species.StartingChars.Willpower, true); funcAddAttribute("Characteristic", "Presence", speciesData.Species.StartingChars.Presence, true); funcAddAttribute("Stat", "Wounds", speciesData.Species.StartingAttrs.WoundThreshold, true); funcAddAttribute("Stat", "Strain", speciesData.Species.StartingAttrs.StrainThreshold, true); if (speciesData?.Species?.SkillModifiers?.SkillModifier) { if (Array.isArray(speciesData.Species.SkillModifiers.SkillModifier)) { speciesData.Species.SkillModifiers.SkillModifier.forEach((s) => { let skill = CONFIG.temporary.skills[s.Key]; if (skill) { funcAddAttribute("Skill Rank", skill, s.RankStart, false); } }); } else { let skill = CONFIG.temporary.skills[speciesData.Species.SkillModifiers.SkillModifier.Key]; if (skill) { funcAddAttribute("Skill Rank", skill, speciesData.Species.SkillModifiers.SkillModifier.RankStart, false); } } } let abilities = []; if (speciesData?.Species?.OptionChoices?.OptionChoice) { let options = speciesData.Species.OptionChoices.OptionChoice; if (!Array.isArray(speciesData.Species.OptionChoices.OptionChoice)) { options = [speciesData.Species.OptionChoices.OptionChoice]; } options.forEach((o) => { let option = o.Options.Option; if (!Array.isArray(o.Options.Option)) { option = [o.Options.Option]; } abilities.push(`<p>${option[0].Name} : ${option[0].Description}</p>`); }); } species.data.description = `<h4>Abilities</h4>` + abilities.join("") + "<p></p>" + species.data.description; // does an image exist? let imgPath = await ImportHelpers.getImageFilename(zip, "Species", "", species.flags.ffgimportid); if (imgPath) { species.img = await ImportHelpers.importImage(imgPath.name, zip, pack); } let compendiumItem; await pack.getIndex(); let entry = pack.index.find((e) => e.name === species.name); if (!entry) { CONFIG.logger.debug(`Importing Species - Item`); compendiumItem = new Item(species, { temporary: true }); this._importLogger(`New Species ${species.name} : ${JSON.stringify(compendiumItem)}`); pack.importEntity(compendiumItem); } else { CONFIG.logger.debug(`Updating Species - Item`); //let updateData = ImportHelpers.buildUpdateData(species); let updateData = species; updateData["_id"] = entry._id; this._importLogger(`Updating Species ${species.name} : ${JSON.stringify(updateData)}`); pack.updateEntity(updateData); } currentCount += 1; $(".species .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing Species ${species.name}`); } catch (err) { this._importLogger(`Error importing record : `, err); CONFIG.logger.error(`Error importing record : `, err); } }); } } async _handleVehicles(zip) { this._importLogger(`Starting Vehicles Import`); const vehicleFiles = Object.values(zip.files).filter((file) => { return !file.dir && file.name.split(".").pop() === "xml" && file.name.includes("/Vehicles/"); }); let totalCount = vehicleFiles.length; let currentCount = 0; if (vehicleFiles.length > 0) { $(".import-progress.vehicles").toggleClass("import-hidden"); let packSpace = await this._getCompendiumPack("Actor", `oggdude.Vehicles.Space`); let packPlanetary = await this._getCompendiumPack("Actor", `oggdude.Vehicles.Planetary`); const isSpace = (vehicle) => { let result = false; const spacecategories = ["Starship", "Non-Fighter Starship", "Capital Ship", "Bulk Transport", "Station", "Medium Transport"]; const spacetypes = ["Space-dwelling Creature", "Hyperdrive Sled", "Hyperdrive Docking Ring"]; if (vehicle?.Vehicle?.Categories?.Category) { if (Array.isArray(vehicle.Vehicle.Categories.Category)) { vehicle.Vehicle.Categories.Category.forEach((cat) => { if (spacecategories.includes(cat)) { result = true; } }); } else { if (spacecategories.includes(vehicle.Vehicle.Categories.Category)) { result = true; } } } else { if (vehicle.Vehicle.Type) { if (spacetypes.includes(vehicle.Vehicle.Type)) { result = true; } } } return result; }; await this.asyncForEach(vehicleFiles, async (file) => { try { const data = await zip.file(file.name).async("text"); const xmlDoc = ImportHelpers.stringToXml(data); const vehicleData = JXON.xmlToJs(xmlDoc); let sensorRange; switch (vehicleData.Vehicle.SensorRangeValue) { case "srClose": sensorRange = "Close"; break; case "srShort": sensorRange = "Short"; break; case "srMedium": sensorRange = "Medium"; break; case "srLong": sensorRange = "Long"; break; case "srExtreme": sensorRange = "Extreme"; break; default: sensorRange = "None"; } let vehicle = { name: vehicleData.Vehicle.Name, type: "vehicle", flags: { ffgimportid: vehicleData.Vehicle.Key, }, data: { biography: vehicleData.Vehicle.Description, stats: { silhouette: { value: parseInt(vehicleData.Vehicle.Silhouette, 10), }, speed: { max: parseInt(vehicleData.Vehicle.Speed, 10), }, handling: { value: parseInt(vehicleData.Vehicle.Handling, 10), }, hullTrauma: { max: parseInt(vehicleData.Vehicle.HullTrauma, 10), }, systemStrain: { max: parseInt(vehicleData.Vehicle.SystemStrain, 10), }, shields: { fore: parseInt(vehicleData.Vehicle.DefFore, 10), port: parseInt(vehicleData.Vehicle.DefPort, 10), starboard: parseInt(vehicleData.Vehicle.DefStarboard, 10), aft: parseInt(vehicleData.Vehicle.DefAft, 10), }, armour: { value: parseInt(vehicleData.Vehicle.Armor, 10), }, sensorRange: { value: sensorRange, }, crew: {}, passengerCapacity: { value: parseInt(vehicleData.Vehicle.Passengers, 10), }, encumbrance: { max: parseInt(vehicleData.Vehicle.Encumbrance, 10), }, cost: { value: parseInt(vehicleData.Vehicle.Price, 10), }, rarity: { value: parseInt(vehicleData.Vehicle.Rarity, 10), }, customizationHardPoints: { value: parseInt(vehicleData.Vehicle.HP, 10), }, hyperdrive: { value: parseInt(vehicleData.Vehicle.HyperdrivePrimary, 10), }, consumables: { value: 1, duration: "months", }, }, }, items: [], }; vehicle.data.biography += ImportHelpers.getSources(vehicleData?.Vehicle?.Sources ?? vehicleData?.Vehicle?.Source); const funcAddWeapon = async (weapon) => { try { let weaponData = JSON.parse(JSON.stringify(await ImportHelpers.findCompendiumEntityByImportId("Item", weapon.Key))); let weapons = 1; if (weapon.Count) { weapons = weapon.Count; } for (let i = 0; i < weapons; i += 1) { if (!weaponData.data.firingarc) { weaponData.data.firingarc = {}; } weaponData.data.firingarc.fore = weapon.FiringArcs.Fore === "true" ? true : false; weaponData.data.firingarc.aft = weapon.FiringArcs.Aft === "true" ? true : false; weaponData.data.firingarc.port = weapon.FiringArcs.Port === "true" ? true : false; weaponData.data.firingarc.starboard = weapon.FiringArcs.Starboard === "true" ? true : false; weaponData.data.firingarc.dorsal = weapon.FiringArcs.Dorsal === "true" ? true : false; weaponData.data.firingarc.ventral = weapon.FiringArcs.Ventral === "true" ? true : false; if (weapon?.Qualities?.Quality) { const qualities = await ImportHelpers.getQualities(weapon.Qualities.Quality); weaponData.data.special.value = qualities.qualities.join(", "); weaponData.data.attributes = qualities.attributes; } vehicle.items.push(weaponData); } } catch (err) { CONFIG.logger.warn(`Unable to locate weapon ${weapon.Key} while import ${vehicle.name}`); this._importLogger(`Unable to locate weapon ${weapon.Key} for ${vehicle.name}`); } }; if (vehicleData.Vehicle.VehicleWeapons?.VehicleWeapon) { const temp = new Actor(vehicle, { temporary: true }); if (!Array.isArray(vehicleData.Vehicle.VehicleWeapons.VehicleWeapon)) { vehicleData.Vehicle.VehicleWeapons.VehicleWeapon = [vehicleData.Vehicle.VehicleWeapons.VehicleWeapon]; } await this.asyncForEach(vehicleData.Vehicle.VehicleWeapons.VehicleWeapon, async (weapon) => { await funcAddWeapon(weapon); }); } let pack; if (isSpace(vehicleData)) { pack = packSpace; } else { pack = packPlanetary; } let compendiumItem; let actor; await pack.getIndex(); let entry = pack.index.find((e) => e.name === vehicle.name); if (!entry) { CONFIG.logger.debug(`Importing Vehicles - Actor`); compendiumItem = new Actor(vehicle, { temporary: true }); this._importLogger(`New Vehicles ${vehicle.name} : ${JSON.stringify(compendiumItem)}`); actor = await pack.importEntity(compendiumItem); } else { CONFIG.logger.debug(`Updating Vehicles - Actor`); //let updateData = ImportHelpers.buildUpdateData(vehicle); let updateData = vehicle; updateData["_id"] = entry._id; this._importLogger(`Updating Vehicles ${vehicle.name} : ${JSON.stringify(updateData)}`); await pack.updateEntity(updateData); actor = await game.actors.get(entry._id); } currentCount += 1; $(".vehicles .import-progress-bar") .width(`${Math.trunc((currentCount / totalCount) * 100)}%`) .html(`<span>${Math.trunc((currentCount / totalCount) * 100)}%</span>`); this._importLogger(`End importing Vehicles ${vehicle.name}`); } catch (err) { this._importLogger(`Error importing record : `, err); CONFIG.logger.error(`Error importing record : `, err); } }); } } async _getCompendiumPack(type, name) { this._importLogger(`Checking for existing compendium pack ${name}`); let pack = game.packs.find((p) => { return p.metadata.label === name; }); if (!pack) { this._importLogger(`Compendium pack ${name} not found, creating new`); pack = await Compendium.create({ entity: type, label: name }); } else { this._importLogger(`Existing compendium pack ${name} found`); } return pack; } _enableImportSelection(files, name, isDirectory, returnFilename) { this._importLogger(`Checking zip file for ${name}`); let fileName; Object.values(files).findIndex((file) => { if (file.name.includes(`/${name}.xml`) || (isDirectory && file.name.includes(`/${name}`))) { this._importLogger(`Found file ${file.name}`); let filename = file.name; if (file.name.includes(`.xml`) && isDirectory) { filename = `${file.name.substring(0, file.name.lastIndexOf("/"))}/`; } $(`#import${name.replace(" ", "")}`) .removeAttr("disabled") .val(filename); if (returnFilename) { fileName = file.name; } return true; } return false; }) > -1; return fileName; } asyncForEach = async (array, callback) => { for (let index = 0; index < array.length; index += 1) { await callback(array[index], index, array); } }; }
JavaScript
class MatClockView { /** * @param {?} _changeDetectorRef * @param {?} _element * @param {?} _dateAdapter * @param {?} _dateFormats */ constructor(_changeDetectorRef, _element, _dateAdapter, _dateFormats) { this._changeDetectorRef = _changeDetectorRef; this._element = _element; this._dateAdapter = _dateAdapter; this._dateFormats = _dateFormats; this.clockStep = 1; this.twelveHour = false; // Whether the clock is in hour view. this.hourView = true; // Emits when the final time was selected. this.selectedTime = new EventEmitter(); // Emits when the currently selected date changes. this.selectedChange = new EventEmitter(); // Emits when the currently selected date changes. this.changeView = new EventEmitter(); // Hours and Minutes representing the clock view. this._hours = []; this._minutes = []; if (!this._dateAdapter) { throw createMissingDateImplError('DateAdapter'); } if (!this._dateFormats) { throw createMissingDateImplError('MAT_DATE_FORMATS'); } this.mouseMoveListener = (/** * @param {?} event * @return {?} */ (event) => { this._handleMousemove(event); }); this.mouseUpListener = (/** * @return {?} */ () => { this._handleMouseup(); }); } /** * The time to display in this clock view. (the rest is ignored) * @return {?} */ get activeDate() { return this._activeDate; } /** * @param {?} value * @return {?} */ set activeDate(value) { /** @type {?} */ const oldActiveDate = this._activeDate; /** @type {?} */ const validDate = this._getValidDateOrNull(this._dateAdapter.deserialize(value)) || this._dateAdapter.today(); this._activeDate = this._dateAdapter.clampDate(validDate, this.minDate, this.maxDate); if (oldActiveDate && this._dateAdapter.compareDate(oldActiveDate, this._activeDate, 'minute')) { this._init(); } } // The currently selected date. /** * @return {?} */ get selected() { return this._selected; } /** * @param {?} value * @return {?} */ set selected(value) { this._selected = this._getValidDateOrNull(this._dateAdapter.deserialize(value)); } /** * The minimum selectable date. * @return {?} */ get minDate() { return this._minDate; } /** * @param {?} value * @return {?} */ set minDate(value) { this._minDate = this._getValidDateOrNull(this._dateAdapter.deserialize(value)); } /** * The maximum selectable date. * @return {?} */ get maxDate() { return this._maxDate; } /** * @param {?} value * @return {?} */ set maxDate(value) { this._maxDate = this._getValidDateOrNull(this._dateAdapter.deserialize(value)); } /** * @return {?} */ get _hand() { this._selectedHour = this._dateAdapter.getHours(this.activeDate); this._selectedMinute = this._dateAdapter.getMinutes(this.activeDate); /** @type {?} */ let radius = CLOCK_OUTER_RADIUS; /** @type {?} */ let deg = 0; if (this.twelveHour) { this._selectedHour = this._selectedHour < 12 ? this._selectedHour : this._selectedHour - 12; this._selectedHour = this._selectedHour === 0 ? 12 : this._selectedHour; } if (this.hourView) { /** @type {?} */ const outer = this._selectedHour > 0 && this._selectedHour < 13; radius = outer ? CLOCK_OUTER_RADIUS : CLOCK_INNER_RADIUS; if (this.twelveHour) { radius = CLOCK_OUTER_RADIUS; } deg = Math.round(this._selectedHour * (360 / (24 / 2))); } else { deg = Math.round(this._selectedMinute * (360 / 60)); } return { transform: `rotate(${deg}deg)`, height: `${radius}%`, 'margin-top': `${50 - radius}%` }; } /** * @return {?} */ ngAfterContentInit() { this._init(); } // Handles mousedown events on the clock body. /** * @param {?} event * @return {?} */ _handleMousedown(event) { this.setTime(event); document.addEventListener('mousemove', this.mouseMoveListener); document.addEventListener('touchmove', this.mouseMoveListener); document.addEventListener('mouseup', this.mouseUpListener); document.addEventListener('touchend', this.mouseUpListener); } /** * @param {?} event * @return {?} */ _handleMousemove(event) { event.preventDefault(); this.setTime(event); } /** * @return {?} */ _handleMouseup() { document.removeEventListener('mousemove', this.mouseMoveListener); document.removeEventListener('touchmove', this.mouseMoveListener); document.removeEventListener('mouseup', this.mouseUpListener); document.removeEventListener('touchend', this.mouseUpListener); } // Initializes this clock view. /** * @return {?} */ _init() { this._hours.length = 0; this._minutes.length = 0; /** @type {?} */ const hourNames = this._dateAdapter.getHourNames(); /** @type {?} */ const minuteNames = this._dateAdapter.getMinuteNames(); if (this.twelveHour) { this._anteMeridian = this._dateAdapter.getHours(this.activeDate) < 12; for (let i = 0; i < hourNames.length / 2; i++) { /** @type {?} */ const radian = i / 6 * Math.PI; /** @type {?} */ const radius = CLOCK_OUTER_RADIUS; /** @type {?} */ const date = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), this._dateAdapter.getMonth(this.activeDate), this._dateAdapter.getDate(this.activeDate), this._anteMeridian ? i : i + 12); this._hours.push({ value: i, displayValue: i === 0 ? '12' : hourNames[i], enabled: !this.dateFilter || this.dateFilter(date, 'hour'), top: CLOCK_RADIUS - Math.cos(radian) * radius - CLOCK_TICK_RADIUS, left: CLOCK_RADIUS + Math.sin(radian) * radius - CLOCK_TICK_RADIUS }); } } else { for (let i = 0; i < hourNames.length; i++) { /** @type {?} */ const radian = i / 6 * Math.PI; /** @type {?} */ const outer = i > 0 && i < 13; /** @type {?} */ const radius = outer ? CLOCK_OUTER_RADIUS : CLOCK_INNER_RADIUS; /** @type {?} */ const date = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), this._dateAdapter.getMonth(this.activeDate), this._dateAdapter.getDate(this.activeDate), i); this._hours.push({ value: i, displayValue: i === 0 ? '12' : hourNames[i], enabled: !this.dateFilter || this.dateFilter(date, 'hour'), top: CLOCK_RADIUS - Math.cos(radian) * radius - CLOCK_TICK_RADIUS, left: CLOCK_RADIUS + Math.sin(radian) * radius - CLOCK_TICK_RADIUS, fontSize: i > 0 && i < 13 ? '' : '80%' }); } } for (let i = 0; i < minuteNames.length; i += 5) { /** @type {?} */ const radian = i / 30 * Math.PI; /** @type {?} */ const date = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), this._dateAdapter.getMonth(this.activeDate), this._dateAdapter.getDate(this.activeDate), this._dateAdapter.getHours(this.activeDate), i); this._minutes.push({ value: i, displayValue: i === 0 ? '00' : minuteNames[i], enabled: !this.dateFilter || this.dateFilter(date, 'minute'), top: CLOCK_RADIUS - Math.cos(radian) * CLOCK_OUTER_RADIUS - CLOCK_TICK_RADIUS, left: CLOCK_RADIUS + Math.sin(radian) * CLOCK_OUTER_RADIUS - CLOCK_TICK_RADIUS }); } this._changeDetectorRef.markForCheck(); } // Set Time /** * @private * @param {?} event * @return {?} */ setTime(event) { /** @type {?} */ const trigger = this._element.nativeElement; /** @type {?} */ const triggerRect = trigger.getBoundingClientRect(); /** @type {?} */ const width = trigger.offsetWidth; /** @type {?} */ const height = trigger.offsetHeight; /** @type {?} */ const pageX = event.pageX !== undefined ? event.pageX : event.touches[0].pageX; /** @type {?} */ const pageY = event.pageY !== undefined ? event.pageY : event.touches[0].pageY; /** @type {?} */ const x = width / 2 - (pageX - triggerRect.left - window.pageXOffset); /** @type {?} */ const y = height / 2 - (pageY - triggerRect.top - window.pageYOffset); /** @type {?} */ const unit = Math.PI / (this.hourView ? 6 : this.clockStep ? 30 / this.clockStep : 30); /** @type {?} */ const z = Math.sqrt(x * x + y * y); /** @type {?} */ const outer = this.hourView && z > (width * (CLOCK_OUTER_RADIUS / 100) + width * (CLOCK_INNER_RADIUS / 100)) / 2; /** @type {?} */ let radian = Math.atan2(-x, y); if (radian < 0) { radian = Math.PI * 2 + radian; } /** @type {?} */ let value = Math.round(radian / unit); /** @type {?} */ const date = this._dateAdapter.clone(this.activeDate); if (this.hourView) { if (value === 12) { value = 0; } value = this.twelveHour ? this._anteMeridian ? value : value + 12 : outer ? (value === 0 ? 12 : value) : value === 0 ? 0 : value + 12; this._dateAdapter.setHours(date, value); } else { if (this.clockStep) { value *= this.clockStep; } if (value === 60) { value = 0; } this._dateAdapter.setMinutes(date, value); } // validate if the resulting value is disabled and do not take action if (this.dateFilter && !this.dateFilter(date, this.hourView ? 'hour' : 'minute')) { return; } this.activeDate = date; if (this.hourView) { this.changeView.emit(); this.selectedChange.emit(this.activeDate); } else { this.selectedTime.emit(this.activeDate); } } /** * @return {?} */ _focusActiveCell() { } /** * @private * @param {?} obj The object to check. * @return {?} The given object if it is both a date instance and valid, otherwise null. */ _getValidDateOrNull(obj) { return this._dateAdapter.isDateInstance(obj) && this._dateAdapter.isValid(obj) ? obj : null; } }
JavaScript
class InitiateRequestRedemption extends ServiceBase { /** * Constructor to request redemption for user. * * @param {object} params * @param {object} params.current_user * @param {number} params.product_id * @param {number} params.dollar_amount * * @augments ServiceBase * * @constructor */ constructor(params) { super(); const oThis = this; oThis.currentUser = params.current_user; oThis.productId = params.product_id; oThis.dollarAmount = params.dollar_amount; oThis.currentUserId = oThis.currentUser.id; oThis.currentUserTwitterHandle = ''; } /** * Async perform. * * @sets oThis.redemptionId * * @returns {Promise<any>} * @private */ async _asyncPerform() { const oThis = this; await oThis._validateAndSetUserDetails(); await oThis._validateAndSanitize(); const promisesArray = [oThis._getTokenUserDetails(), oThis._getCurrentUserTwitterHandle()]; await Promise.all(promisesArray); oThis.redemptionId = uuidV4(); oThis._prepareSendMailParams(); await oThis._debitPepocornBalance(); await oThis._insertPepocornTransactions(); await oThis._enqueueAfterRedemptionJob(); return responseHelper.successWithData({ redemption: { id: oThis.redemptionId, userId: oThis.currentUserId, productId: oThis.productId, uts: parseInt(Date.now() / 1000) } }); } /** * Validate and set user details. * * @sets oThis.currentUserEmailAddress, oThis.currentUserUserName, oThis.redemptionReceiverUsername * * @returns {Promise<never>} * @private */ async _validateAndSetUserDetails() { const oThis = this; const userDetailsCacheRsp = await new UserMultiCache({ ids: [oThis.currentUserId, coreConstants.PEPO_REDEMPTION_USER_ID] }).fetch(); if (userDetailsCacheRsp.isFailure()) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'a_s_r_ir_1', api_error_identifier: 'something_went_wrong_bad_request', debug_options: { error: userDetailsCacheRsp } }) ); } const currentUserDetails = userDetailsCacheRsp.data[oThis.currentUserId]; logger.log('currentUserDetails', currentUserDetails); if (!currentUserDetails || !UserModel.isUserApprovedCreator(currentUserDetails)) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'a_s_r_ir_2', api_error_identifier: 'redemption_user_not_approved_creator', debug_options: {} }) ); } const redemptionUserDetails = userDetailsCacheRsp.data[coreConstants.PEPO_REDEMPTION_USER_ID]; oThis.currentUserEmailAddress = currentUserDetails.email || ''; oThis.currentUserUserName = currentUserDetails.userName; oThis.redemptionReceiverUsername = redemptionUserDetails.userName; } /** * Validate if user has a video. * * @returns {Promise<boolean>} * @private */ async _validateUserEligibility() { const oThis = this; const videoDetailCacheResponse = await new VideoDetailsByUserIdCache({ userId: oThis.currentUserId, limit: paginationConstants.defaultVideoListPageSize, paginationTimestamp: null }).fetch(); if (videoDetailCacheResponse.isFailure()) { return Promise.reject(videoDetailCacheResponse); } if (videoDetailCacheResponse.data.videoIds.length === 0) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'a_s_r_ir_vue_2', api_error_identifier: 'redemption_user_without_video', debug_options: {} }) ); } } /** * Validate and sanitize params. * * @returns {Promise<never>} * @private */ async _validateAndSanitize() { const oThis = this; await oThis._validateUserEligibility(); await oThis._validateProductId(); await oThis._validateDollarAmount(); oThis._getPepocornAmount(); await oThis._validatePepocornBalance(); } /** * Get redemption product details and validate product id. * * @sets oThis.productLink, oThis.productDollarValue, oThis.productKind, oThis.productMinDollarValue, oThis.productDollarStep * * @returns {Promise<boolean>} * @private */ async _validateProductId() { const oThis = this; const redemptionProductsCacheResponse = await new RedemptionProductsCache().fetch(); if (redemptionProductsCacheResponse.isFailure()) { return Promise.reject(redemptionProductsCacheResponse); } const redemptionProducts = redemptionProductsCacheResponse.data.products; let validationResult = false; for (let index = 0; index < redemptionProducts.length; index++) { const redemptionProduct = redemptionProducts[index]; if (+redemptionProduct.id === +oThis.productId && redemptionProduct.status === redemptionConstants.activeStatus) { validationResult = true; logger.log('redemptionProduct ======', redemptionProduct); oThis.productLink = redemptionProduct.images.landscape; oThis.productDollarValue = redemptionProduct.dollarValue; oThis.productKind = redemptionProduct.kind; oThis.productMinDollarValue = redemptionProduct.minDollarValue; oThis.productMaxDollarValue = redemptionProduct.maxDollarValue; oThis.productDollarStep = redemptionProduct.dollarStep; } } if (!validationResult) { return Promise.reject( responseHelper.paramValidationError({ internal_error_identifier: 'a_s_r_ir_3', api_error_identifier: 'invalid_api_params', params_error_identifiers: ['invalid_product_id'], debug_options: {} }) ); } } /** * Validate dollar amount. * * @returns {Promise<never>} * @private */ async _validateDollarAmount() { const oThis = this; logger.log('oThis.dollarAmount =========', oThis.dollarAmount); logger.log('oThis.productMinDollarValue ======', oThis.productMinDollarValue); const dollarAmountBN = new BigNumber(oThis.dollarAmount), productMinDollarValueBN = new BigNumber(oThis.productMinDollarValue), productDollarStepBN = new BigNumber(oThis.productDollarStep); let productMaxDollarValueBN; if (oThis.productMaxDollarValue) { productMaxDollarValueBN = new BigNumber(oThis.productMaxDollarValue); } if (dollarAmountBN.lt(productMinDollarValueBN)) { let apiErrorIdentifier = null; switch (Number(oThis.productMinDollarValue)) { case 5: apiErrorIdentifier = 'min_redemption_amount_5'; break; case 10: apiErrorIdentifier = 'min_redemption_amount_10'; break; case 15: apiErrorIdentifier = 'min_redemption_amount_15'; break; case 25: apiErrorIdentifier = 'min_redemption_amount_25'; break; default: throw new Error('Invalid Min Dollar Amount for Product.'); } return Promise.reject( responseHelper.error({ internal_error_identifier: 'a_s_r_ir_4', api_error_identifier: apiErrorIdentifier, debug_options: { dollarAmountBN: dollarAmountBN, productMinDollarValueBN: productMinDollarValueBN } }) ); } if (productMaxDollarValueBN && dollarAmountBN.gt(productMaxDollarValueBN)) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'a_s_r_ir_7', api_error_identifier: 'max_redemption_amount_crossed', debug_options: { dollarAmountBN: dollarAmountBN, productMaxDollarValueBN: productMaxDollarValueBN } }) ); } if (!dollarAmountBN.mod(productDollarStepBN).eq(new BigNumber(0))) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'a_s_r_ir_5', api_error_identifier: 'invalid_dollar_step', debug_options: { dollarAmountBN: dollarAmountBN, productDollarStepBN: productDollarStepBN } }) ); } } /** * Get pepocorn amount. * * @private */ _getPepocornAmount() { const oThis = this; oThis.pepocornAmount = oThis.dollarAmount * redemptionConstants.pepocornPerDollar; logger.log('oThis.pepocornAmount ====', oThis.pepocornAmount); } /** * Get pepocorn balance. * * @returns {Promise<void>} * @private */ async _validatePepocornBalance() { const oThis = this, pepoCornBalanceResponse = await new GetPepocornBalance({ userIds: [oThis.currentUserId] }).perform(); const pepocornBalance = pepoCornBalanceResponse[oThis.currentUserId].balance; logger.log('pepocornBalance ====', pepocornBalance); logger.log('oThis.pepocornAmount ====', oThis.pepocornAmount); const pepocornAmountBN = new BigNumber(oThis.pepocornAmount), pepocornBalanceBN = new BigNumber(pepocornBalance); if (pepocornAmountBN.gt(pepocornBalanceBN)) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'a_s_r_ir_6', api_error_identifier: 'insufficient_pepocorn_balance', debug_options: { pepocornAmountBN: pepocornAmountBN.toString(10), pepocornBalanceBN: pepocornBalanceBN.toString(10) } }) ); } } /** * Get token user details. * * @sets oThis.currentUserTokenHolderAddress, oThis.redemptionReceiverTokenHolderAddress * * @returns {Promise<never>} * @private */ async _getTokenUserDetails() { const oThis = this; const tokenUserCacheResponse = await new TokenUserByUserIdCache({ userIds: [oThis.currentUserId, coreConstants.PEPO_REDEMPTION_USER_ID] }).fetch(); if (tokenUserCacheResponse.isFailure()) { return Promise.reject(tokenUserCacheResponse); } oThis.currentUserTokenHolderAddress = tokenUserCacheResponse.data[oThis.currentUserId].ostTokenHolderAddress; oThis.redemptionReceiverTokenHolderAddress = tokenUserCacheResponse.data[coreConstants.PEPO_REDEMPTION_USER_ID].ostTokenHolderAddress; } /** * Get current user twitter handle. * * @sets oThis.currentUserTwitterHandle * * @returns {Promise<never>} * @private */ async _getCurrentUserTwitterHandle() { const oThis = this; const twitterUserByUserIdsCacheResponse = await new TwitterUserByUserIdsCache({ userIds: [oThis.currentUserId] }).fetch(); if (twitterUserByUserIdsCacheResponse.isFailure()) { return Promise.reject(twitterUserByUserIdsCacheResponse); } const currentUserTwitterId = twitterUserByUserIdsCacheResponse.data[oThis.currentUserId].id; if (currentUserTwitterId) { const twitterUserByUserIdCacheResponse = await new TwitterUserByIdsCache({ ids: [currentUserTwitterId] }).fetch(); if (twitterUserByUserIdCacheResponse.isFailure()) { return Promise.reject(twitterUserByUserIdCacheResponse); } oThis.currentUserTwitterHandle = twitterUserByUserIdCacheResponse.data[currentUserTwitterId].handle || ''; } } /** * Debit pepocorn balance. * * @returns {Promise<void>} * @private */ async _debitPepocornBalance() { const oThis = this; const updatePepocornBalanceResp = await new PepocornBalanceModel({}) .update(['balance = balance - ?', oThis.pepocornAmount]) .where({ user_id: oThis.currentUserId }) .where(['balance >= ?', oThis.pepocornAmount]) .fire(); if (updatePepocornBalanceResp.affectedRows === 0) { return Promise.reject( responseHelper.error({ internal_error_identifier: 'a_s_r_ir_6', api_error_identifier: 'insufficient_pepocorn_balance', debug_options: { pepocornAmount: oThis.pepocornAmount } }) ); } await PepocornBalanceModel.flushCache({ userIds: [oThis.currentUserId] }); } /** * Insert into pepocorn transactions. * * @returns {Promise<void>} * @private */ async _insertPepocornTransactions() { const oThis = this; await new PepocornTransactionModel({}) .insert({ user_id: oThis.currentUserId, kind: pepocornTransactionConstants.invertedKinds[pepocornTransactionConstants.debitKind], pepocorn_amount: oThis.pepocornAmount, redemption_id: oThis.redemptionId, status: pepocornTransactionConstants.invertedStatuses[pepocornTransactionConstants.processedStatus] }) .fire(); } /** * Prepare send mail params. * * @sets oThis.transactionalMailParams * * @private */ _prepareSendMailParams() { const oThis = this; oThis.transactionalMailParams = { receiverEntityId: 0, receiverEntityKind: emailServiceApiCallHookConstants.hookParamsInternalEmailEntityKind, templateName: emailServiceApiCallHookConstants.userRedemptionRequestTemplateName, templateVars: { // User details. username: oThis.currentUserUserName, user_id: oThis.currentUserId, user_token_holder_address: oThis.currentUserTokenHolderAddress, user_twitter_handle: oThis.currentUserTwitterHandle, user_email: oThis.currentUserEmailAddress, user_admin_url_prefix: basicHelper.userProfilePrefixUrl(), // Product details. product_id: oThis.productId, product_kind: oThis.productKind, product_link: oThis.productLink, product_dollar_value: oThis.productDollarValue, // Redemption details. redemption_id: oThis.redemptionId, dollar_amount: oThis.dollarAmount, redemption_receiver_username: oThis.redemptionReceiverUsername, redemption_receiver_token_holder_address: oThis.redemptionReceiverTokenHolderAddress, pepo_api_domain: 1, pepocorn_amount: oThis.pepocornAmount, receiverEmail: emailConstants.redemptionRequest } }; } /** * Enqueue after sign-up job. * * @returns {Promise<void>} * @private */ async _enqueueAfterRedemptionJob() { const oThis = this; const messagePayload = { transactionalMailParams: oThis.transactionalMailParams, currentUserId: oThis.currentUserId, productKind: oThis.productKind, newRequest: 1 }; await bgJob.enqueue(bgJobConstants.afterRedemptionJobTopic, messagePayload); } }
JavaScript
class MiddlewareView extends core_1.ContextView { constructor(ctx, options) { var _a; // Find extensions for the given extension point binding const filter = (0, core_1.extensionFilter)((_a = options === null || options === void 0 ? void 0 : options.chain) !== null && _a !== void 0 ? _a : types_1.DEFAULT_MIDDLEWARE_CHAIN); super(ctx, filter); this.options = { chain: types_1.DEFAULT_MIDDLEWARE_CHAIN, orderedGroups: [], ...options, }; this.buildMiddlewareKeys(); this.open(); } refresh() { super.refresh(); this.buildMiddlewareKeys(); } /** * A list of binding keys sorted by group for registered middleware */ get middlewareBindingKeys() { return this.keys; } buildMiddlewareKeys() { var _a; const middlewareBindings = this.bindings; if (debug.enabled) { debug('Middleware for extension point "%s":', this.options.chain, middlewareBindings.map(b => b.key)); } // Calculate orders from middleware dependencies const ordersFromDependencies = []; middlewareBindings.forEach(b => { var _a, _b, _c; const group = (_a = b.tagMap.group) !== null && _a !== void 0 ? _a : keys_1.DEFAULT_MIDDLEWARE_GROUP; const groupsBefore = (_b = b.tagMap.upstreamGroups) !== null && _b !== void 0 ? _b : []; groupsBefore.forEach(d => ordersFromDependencies.push([d, group])); const groupsAfter = (_c = b.tagMap.downstreamGroups) !== null && _c !== void 0 ? _c : []; groupsAfter.forEach(d => ordersFromDependencies.push([group, d])); }); const order = (0, group_sorter_1.sortListOfGroups)(...ordersFromDependencies, this.options.orderedGroups); /** * Validate sorted groups */ if (typeof ((_a = this.options) === null || _a === void 0 ? void 0 : _a.validate) === 'function') { this.options.validate(order); } this.keys = middlewareBindings .sort((0, core_1.compareBindingsByTag)('group', order)) .map(b => b.key); } }
JavaScript
class StubAWSElasticTranscoder { /** * @param {boolean} operational */ constructor(operational = true, attempts = 1) { this.operational = operational; this.attempts = attempts; } createJob(params) { assert.equal(params.Input.Key, 'input'); assert.equal(params.Output.Key, 'output'); if (this.operational) { return { promise() { return new Promise((resolve) => { resolve({ Job: { Id: 'id' } }); }); } }; } else { // eslint-disable-line no-else-return return { promise() { return Promise.reject(); } }; } } readJob(params) { this.attempts -= 1; const status = (this.attempts === 0) ? 'Complete' : 'Progressing'; assert.equal(params.Id, 'id'); return this.operational ? { promise() { return new Promise((resolve) => { resolve({ Job: { Status: status } }); }); } } : { promise() { return Promise.reject(); } }; } }
JavaScript
class NavSubmenu { /** * Initialize submenu. * * @param {JQuery} $root Submenu root element */ constructor($root) { this.elements = { $root, $parentLink: $root.prev(SELECTORS.LINK), $parentItem: $root.closest(SELECTORS.ITEM), $scrollpane: $(SELECTORS.SCROLLPANE, $root).first(), $backLink: $(SELECTORS.LINK_BACK, $root).first(), $firstLink: $(SELECTORS.LINK, $root) .not(SELECTORS.LINK_BACK).first(), }; this.drilldownStrategy = new DrilldownStrategy({ $trigger: this.elements.$parentLink, $drawer: this.elements.$root, $initialFocus: this.elements.$firstLink, onCollapse: this.collapse.bind(this), onExpand: this.expand.bind(this), }); this.dropdownStrategy = new DropdownStrategy({ $root: this.elements.$parentItem, $trigger: this.elements.$parentLink, $drawer: this.elements.$root, onCollapse: this.collapse.bind(this), onExpand: this.expand.bind(this), }); // Mobile by default this.drilldownStrategy.activate(); this.elements.$backLink.click(() => this.drilldownStrategy.collapse()); } /** * Collapse the submenu */ collapse() { this.elements.$root.removeClass(CLASSES.SUBMENU_VISIBLE); } /** * Expand the submenu */ expand() { const { $root, $scrollpane } = this.elements; $scrollpane.scrollTop(0); // Reset submenu scroll position $root.addClass(CLASSES.SUBMENU_VISIBLE); } }
JavaScript
class Service { constructor(route) { this.axios = axios; const host = 'http://localhost'; // process.env.API_URL; const basePath = '/api/v1'; // process.env.API_PATH; const port = 5000; // process.env.API_PORT; this.initialParams = { withCredentials: true, credentials: 'include', }; this.url = `${host}:${port}${basePath}/${route}`; } async create(object) { const response = await this.axios.post(this.url, object, this.initialParams); if (!response || response.status != 200) { console.error(response); AlertUtil.error('Ha ocurrido un error.'); } return response.data; } async update(id, object) { let response = await this.axios.put(`${this.url}/${id}`, object, this.initialParams) if(!response || response.status != 200) { console.error(response) //AlertUtil.error('Ha ocurrido un error.') } return response.data } async find(filters) { let params = new URLSearchParams(filters).toString() const response = await this.axios.get(`${this.url}?${params}`, this.initialParams); if (!response || response.status != 200) { console.error(response); AlertUtil.error('Ha ocurrido un error.'); } return response.data; } async findById(id) { let response = await this.axios.get(`${this.url}/${id}`, this.initialParams) if(!response || response.status != 200) { console.error(response) //AlertUtil.error('Ha ocurrido un error.') } return response.data } async delete(id) { const response = await this.axios.delete(`${this.url}/${id}`, this.initialParams); if (!response || response.status != 200) { console.error(response); AlertUtil.error('Ha ocurrido un error.'); } return response.data; } }
JavaScript
class PickerMenuOption extends FoundationElement { contentsTemplateChanged() { if (this.$fastController.isConnected) { this.updateView(); } } /** * @internal */ connectedCallback() { super.connectedCallback(); this.updateView(); } /** * @internal */ disconnectedCallback() { super.disconnectedCallback(); this.disconnectView(); } handleClick(e) { if (e.defaultPrevented) { return false; } this.handleInvoked(); return false; } handleInvoked() { this.$emit("pickeroptioninvoked"); } updateView() { var _a, _b; this.disconnectView(); this.customView = (_b = (_a = this.contentsTemplate) === null || _a === void 0 ? void 0 : _a.render(this, this)) !== null && _b !== void 0 ? _b : defaultContentsTemplate.render(this, this); } disconnectView() { var _a; (_a = this.customView) === null || _a === void 0 ? void 0 : _a.dispose(); this.customView = undefined; } }
JavaScript
class ScrollSpy extends BaseComponent { /** * @param {HTMLElement | Element | string} target the target element * @param {BSN.Options.ScrollSpy=} config the instance options */ constructor(target, config) { super(target, config); // bind const self = this; // initialization element & options const { element, options } = self; // additional properties /** @type {(HTMLElement | Element)?} */ self.target = querySelector(options.target, getDocument(element)); // invalidate if (!self.target) return; const win = getWindow(element); // set initial state /** @type {HTMLElement | Element | Window | globalThis} */ self.scrollTarget = element.clientHeight < element.scrollHeight ? element : win; /** @type {number} */ self.scrollTop = 0; /** @type {number} */ self.maxScroll = 0; /** @type {number} */ self.scrollHeight = 0; /** @type {(HTMLElement | Element)?} */ self.activeItem = null; /** @type {(HTMLElement | Element)[]} */ self.items = []; /** @type {number} */ self.itemsLength = 0; /** @type {number[]} */ self.offsets = []; // bind events self.refresh = self.refresh.bind(self); // add event handlers toggleSpyHandlers(self, true); self.refresh(); } /* eslint-disable */ /** * Returns component name string. * @readonly @static */ get name() { return scrollspyComponent; } /** * Returns component default options. * @readonly @static */ get defaults() { return scrollspyDefaults; } /* eslint-enable */ // SCROLLSPY PUBLIC METHODS // ======================== /** Updates all items. */ refresh() { const self = this; const { target } = self; // check if target is visible and invalidate // @ts-ignore if (target.offsetHeight === 0) return; updateSpyTargets(self); const { scrollTop, maxScroll, itemsLength, items, activeItem, } = self; if (scrollTop >= maxScroll) { const newActiveItem = items[itemsLength - 1]; if (activeItem !== newActiveItem) { activate(self, newActiveItem); } return; } const { offsets } = self; if (activeItem && scrollTop < offsets[0] && offsets[0] > 0) { self.activeItem = null; // @ts-ignore clear(target); return; } items.forEach((item, i) => { if (activeItem !== item && scrollTop >= offsets[i] && (typeof offsets[i + 1] === 'undefined' || scrollTop < offsets[i + 1])) { activate(self, item); } }); } /** Removes `ScrollSpy` from the target element. */ dispose() { toggleSpyHandlers(this); super.dispose(); } }
JavaScript
class MarkerRegistry { constructor() { this._s = new Set(); } get state() { return [...this._s]; } set state(value) { this._s = new Set(value); } /** * Marks this position * @param x {number} * @param y {number} */ mark(x, y) { this._s.add(x << 16 | y); } /** * Unmarks this position * @param x {number} * @param y {number} */ unmark(x, y) { this._s.delete(x << 16 | y); } /** * Clears all marks */ clear() { this._s.clear(); } /** * returns true if this position has previously been marked, false otherwise * @param x {number} * @param y {number} * @return {boolean} */ isMarked(x, y) { return this._s.has(x << 16 | y); } /** * iterates through all markers and call a function back for each marked position * @param f {function} */ iterate(f) { this._s.forEach(n => { const y = n & 0xFFFF; const x = n >> 16; f(x, y); }); } /** * Merges the specified marker registry into this one. * This operation mutates this registry * @param mr {MarkerRegistry} */ merge(mr) { mr._s.forEach(v => this._s.add(v)); } /** * Returns an array of {x, y} for each marked cell */ toArray() { const a = []; this.iterate((x, y) => { a.push({x, y}); }); return a; } }
JavaScript
class App extends React.Component { constructor(props) { super(props); this.state = { data: [], } this.setup() } async setup() { try { const res = await get('') const { data } = res this.setState({ data }) } catch (error) { console.log("Can't fetch data network, Error:", error) } setTimeout(() => this.setup(), 10000) } render() { return ( <div className="main"> {this.state.data.map((el, id) => <Graph key={id} data={el} /> )} </div> ) } }
JavaScript
class CampSite extends React.Component { constructor(props) { super(props); } render() { return ( <div> <Camper /> </div> ); } }
JavaScript
class Invisible extends Phaser.GameObjects.Sprite { /** * Constructor de la Plataforma * @param {Phaser.Scene} scene Escena a la que pertenece la plataforma * @param {Player} player Jugador del juego * @param {Phaser.GameObjects.Group} baseGroup Grupo en el que se incluirá la base creada por la plataforma * @param {number} x Coordenada x * @param {number} y Coordenada y */ constructor(scene, x, y, w, h){ super(scene, x, y, 'invisible'); this.setScale(1, 1); this.alpha = 0; this.scene.add.existing(this); this.scene.physics.add.existing(this, true); this.body.setSize(w,h); this.scene.physics.add.collider(this, this.scene.player); } }
JavaScript
class HttpsProxyAgent extends agent_base_1.Agent { constructor(_opts) { let opts; if (typeof _opts === 'string') { opts = url_1.default.parse(_opts); } else { opts = _opts; } if (!opts) { throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); } debug('creating new HttpsProxyAgent instance: %o', opts); super(opts); const proxy = Object.assign({}, opts); // If `true`, then connect to the proxy server over TLS. // Defaults to `false`. this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); // Prefer `hostname` over `host`, and set the `port` if needed. proxy.host = proxy.hostname || proxy.host; if (typeof proxy.port === 'string') { proxy.port = parseInt(proxy.port, 10); } if (!proxy.port && proxy.host) { proxy.port = this.secureProxy ? 443 : 80; } // ALPN is supported by Node.js >= v5. // attempt to negotiate http/1.1 for proxy servers that support http/2 if (this.secureProxy && !('ALPNProtocols' in proxy)) { proxy.ALPNProtocols = ['http 1.1']; } if (proxy.host && proxy.path) { // If both a `host` and `path` are specified then it's most likely // the result of a `url.parse()` call... we need to remove the // `path` portion so that `net.connect()` doesn't attempt to open // that as a Unix socket file. delete proxy.path; delete proxy.pathname; } this.proxy = proxy; } /** * Called when the node-core HTTP client library is creating a * new HTTP request. * * @api protected */ callback(req, opts) { return __awaiter(this, void 0, void 0, function* () { const { proxy, secureProxy } = this; // Create a socket connection to the proxy server. let socket; if (secureProxy) { debug('Creating `tls.Socket`: %o', proxy); socket = tls_1.default.connect(proxy); } else { debug('Creating `net.Socket`: %o', proxy); socket = net_1.default.connect(proxy); } const headers = Object.assign({}, proxy.headers); const hostname = `${opts.host}:${opts.port}`; let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; // Inject the `Proxy-Authorization` header if necessary. if (proxy.auth) { headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; } // The `Host` header should only include the port // number when it is not the default port. let { host, port, secureEndpoint } = opts; if (!isDefaultPort(port, secureEndpoint)) { host += `:${port}`; } headers.Host = host; headers.Connection = 'close'; for (const name of Object.keys(headers)) { payload += `${name}: ${headers[name]}\r\n`; } const proxyResponsePromise = parse_proxy_response_1.default(socket); socket.write(`${payload}\r\n`); const { statusCode, buffered } = yield proxyResponsePromise; if (statusCode === 200) { req.once('socket', resume); if (opts.secureEndpoint) { const servername = opts.servername || opts.host; if (!servername) { throw new Error('Could not determine "servername"'); } // The proxy is connecting to a TLS server, so upgrade // this socket connection to a TLS connection. debug('Upgrading socket connection to TLS'); return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, servername })); } return socket; } // Some other status code that's not 200... need to re-play the HTTP // header "data" events onto the socket once the HTTP machinery is // attached so that the node core `http` can parse and handle the // error status code. // Close the original socket, and a new "fake" socket is returned // instead, so that the proxy doesn't get the HTTP request // written to it (which may contain `Authorization` headers or other // sensitive data). // // See: https://hackerone.com/reports/541502 socket.destroy(); const fakeSocket = new net_1.default.Socket(); fakeSocket.readable = true; // Need to wait for the "socket" event to re-play the "data" events. req.once('socket', (s) => { debug('replaying proxy buffer for failed request'); assert_1.default(s.listenerCount('data') > 0); // Replay the "buffered" Buffer onto the fake `socket`, since at // this point the HTTP module machinery has been hooked up for // the user. s.push(buffered); s.push(null); }); return fakeSocket; }); } }
JavaScript
class Agent extends events_1.EventEmitter { constructor(callback, _opts) { super(); let opts = _opts; if (typeof callback === 'function') { this.callback = callback; } else if (callback) { opts = callback; } // Timeout for the socket to be returned from the callback this.timeout = null; if (opts && typeof opts.timeout === 'number') { this.timeout = opts.timeout; } // These aren't actually used by `agent-base`, but are required // for the TypeScript definition files in `@types/node` :/ this.maxFreeSockets = 1; this.maxSockets = 1; this.sockets = {}; this.requests = {}; this.options = {}; } get defaultPort() { if (typeof this.explicitDefaultPort === 'number') { return this.explicitDefaultPort; } return isSecureEndpoint() ? 443 : 80; } set defaultPort(v) { this.explicitDefaultPort = v; } get protocol() { if (typeof this.explicitProtocol === 'string') { return this.explicitProtocol; } return isSecureEndpoint() ? 'https:' : 'http:'; } set protocol(v) { this.explicitProtocol = v; } callback(req, opts, fn) { throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); } /** * Called by node-core's "_http_client.js" module when creating * a new HTTP request with this Agent instance. * * @api public */ addRequest(req, _opts) { const opts = Object.assign({}, _opts); if (typeof opts.secureEndpoint !== 'boolean') { opts.secureEndpoint = isSecureEndpoint(); } if (opts.host == null) { opts.host = 'localhost'; } if (opts.port == null) { opts.port = opts.secureEndpoint ? 443 : 80; } if (opts.protocol == null) { opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; } if (opts.host && opts.path) { // If both a `host` and `path` are specified then it's most // likely the result of a `url.parse()` call... we need to // remove the `path` portion so that `net.connect()` doesn't // attempt to open that as a unix socket file. delete opts.path; } delete opts.agent; delete opts.hostname; delete opts._defaultAgent; delete opts.defaultPort; delete opts.createConnection; // Hint to use "Connection: close" // XXX: non-documented `http` module API :( req._last = true; req.shouldKeepAlive = false; let timedOut = false; let timeoutId = null; const timeoutMs = opts.timeout || this.timeout; const onerror = (err) => { if (req._hadError) return; req.emit('error', err); // For Safety. Some additional errors might fire later on // and we need to make sure we don't double-fire the error event. req._hadError = true; }; const ontimeout = () => { timeoutId = null; timedOut = true; const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); err.code = 'ETIMEOUT'; onerror(err); }; const callbackError = (err) => { if (timedOut) return; if (timeoutId !== null) { clearTimeout(timeoutId); timeoutId = null; } onerror(err); }; const onsocket = (socket) => { if (timedOut) return; if (timeoutId != null) { clearTimeout(timeoutId); timeoutId = null; } if (isAgent(socket)) { // `socket` is actually an `http.Agent` instance, so // relinquish responsibility for this `req` to the Agent // from here on debug('Callback returned another Agent instance %o', socket.constructor.name); socket.addRequest(req, opts); return; } if (socket) { socket.once('free', () => { this.freeSocket(socket, opts); }); req.onSocket(socket); return; } const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); onerror(err); }; if (typeof this.callback !== 'function') { onerror(new Error('`callback` is not defined')); return; } if (!this.promisifiedCallback) { if (this.callback.length >= 3) { debug('Converting legacy callback function to promise'); this.promisifiedCallback = promisify_1.default(this.callback); } else { this.promisifiedCallback = this.callback; } } if (typeof timeoutMs === 'number' && timeoutMs > 0) { timeoutId = setTimeout(ontimeout, timeoutMs); } if ('port' in opts && typeof opts.port !== 'number') { opts.port = Number(opts.port); } try { debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); } catch (err) { Promise.reject(err).catch(callbackError); } } freeSocket(socket, opts) { debug('Freeing socket %o %o', socket.constructor.name, opts); socket.destroy(); } destroy() { debug('Destroying agent %o', this.constructor.name); } }
JavaScript
class RectangleShape extends CollisionShape { /** * Create the collision shape. * @param {Rectangle} rectangle the rectangle shape. */ constructor(rectangle) { super(); this.setShape(rectangle); } /** * Set this collision shape from rectangle. * @param {Rectangle} rectangle Rectangle shape. */ setShape(rectangle) { this._rect = rectangle; this._center = rectangle.getCenter(); this._radius = this._rect.getBoundingCircle().radius; this._shapeChanged(); } /** * @inheritdoc */ _getRadius() { return this._radius; } /** * @inheritdoc */ _getBoundingBox() { return this._rect; } /** * @inheritdoc */ getCenter() { return this._center.clone(); } /** * Debug draw this shape. * @param {Number} opacity Shape opacity factor. */ debugDraw(opacity) { if (opacity === undefined) opacity = 1; let color = this._getDebugColor(); color.a *= opacity; gfx.outlineRect(this._rect, color, gfx.BlendModes.AlphaBlend); color.a *= 0.25; gfx.fillRect(this._rect, color, gfx.BlendModes.AlphaBlend); } }
JavaScript
class Confirm extends PureComponent { static navigationOptions = ({ navigation }) => getSendFlowTitle('send.confirm', navigation); static propTypes = { /** * Object that represents the navigator */ navigation: PropTypes.object, /** * Map of accounts to information objects including balances */ accounts: PropTypes.object, /** * Object containing token balances in the format address => balance */ contractBalances: PropTypes.object, /** * Current provider ticker */ ticker: PropTypes.string, /** * Current transaction state */ transactionState: PropTypes.object, /** * ETH to current currency conversion rate */ conversionRate: PropTypes.number, /** * Currency code of the currently-active currency */ currentCurrency: PropTypes.string, /** * Object containing token exchange rates in the format address => exchangeRate */ contractExchangeRates: PropTypes.object, /** * Set transaction object to be sent */ prepareTransaction: PropTypes.func, /** * Network id */ network: PropTypes.string, /** * Indicates whether hex data should be shown in transaction editor */ showHexData: PropTypes.bool }; state = { customGasModalVisible: false, currentCustomGasSelected: 'average', customGasSelected: 'average', gasEstimationReady: false, customGas: undefined, customGasPrice: undefined, fromAccountBalance: undefined, hexDataModalVisible: false, gasError: undefined, transactionValue: undefined, transactionValueFiat: undefined, transactionFee: undefined, transactionTotalAmount: undefined, transactionTotalAmountFiat: undefined, errorMessage: undefined }; componentDidMount = async () => { this.parseTransactionData(); this.prepareTransaction(); }; parseTransactionData = () => { const { accounts, contractBalances, contractExchangeRates, conversionRate, currentCurrency, transactionState: { selectedAsset, transactionTo: to, transaction: { from, value, gas, gasPrice, data } }, ticker } = this.props; let fromAccountBalance, transactionValue, transactionValueFiat, transactionTo, transactionTotalAmount, transactionTotalAmountFiat; const weiTransactionFee = gas && gas.mul(gasPrice); const valueBN = hexToBN(value); const transactionFeeFiat = weiToFiat(weiTransactionFee, conversionRate, currentCurrency); const parsedTicker = getTicker(ticker); if (selectedAsset.isETH) { fromAccountBalance = `${renderFromWei(accounts[from].balance)} ${parsedTicker}`; transactionValue = `${renderFromWei(value)} ${parsedTicker}`; transactionValueFiat = weiToFiat(valueBN, conversionRate, currentCurrency); const transactionTotalAmountBN = weiTransactionFee && weiTransactionFee.add(valueBN); transactionTotalAmount = `${renderFromWei(transactionTotalAmountBN)} ${parsedTicker}`; transactionTotalAmountFiat = weiToFiat(transactionTotalAmountBN, conversionRate, currentCurrency); transactionTo = to; } else if (selectedAsset.tokenId) { fromAccountBalance = `${renderFromWei(accounts[from].balance)} ${parsedTicker}`; const collectibleTransferInformation = selectedAsset.address.toLowerCase() in collectiblesTransferInformation && collectiblesTransferInformation[selectedAsset.address.toLowerCase()]; if ( !collectibleTransferInformation || (collectibleTransferInformation.tradable && collectibleTransferInformation.method === 'transferFrom') ) { [, transactionTo] = decodeTransferData('transferFrom', data); } else if ( collectibleTransferInformation.tradable && collectibleTransferInformation.method === 'transfer' ) { [transactionTo, ,] = decodeTransferData('transfer', data); } transactionValueFiat = weiToFiat(valueBN, conversionRate, currentCurrency); const transactionTotalAmountBN = weiTransactionFee && weiTransactionFee.add(valueBN); transactionTotalAmount = `${renderFromWei(weiTransactionFee)} ${parsedTicker}`; transactionTotalAmountFiat = weiToFiat(transactionTotalAmountBN, conversionRate, currentCurrency); } else { let amount; const { address, symbol = 'ERC20', decimals } = selectedAsset; fromAccountBalance = `${renderFromTokenMinimalUnit(contractBalances[address], decimals)} ${symbol}`; [transactionTo, , amount] = decodeTransferData('transfer', data); const transferValue = renderFromTokenMinimalUnit(amount, decimals); transactionValue = `${transferValue} ${symbol}`; const exchangeRate = contractExchangeRates[address]; const transactionFeeFiatNumber = weiToFiatNumber(weiTransactionFee, conversionRate); transactionValueFiat = balanceToFiat(transferValue, conversionRate, exchangeRate, currentCurrency) || `0 ${currentCurrency}`; const transactionValueFiatNumber = balanceToFiatNumber(transferValue, conversionRate, exchangeRate); transactionTotalAmount = `${transactionValue} + ${renderFromWei(weiTransactionFee)} ${parsedTicker}`; transactionTotalAmountFiat = renderFiatAddition( transactionValueFiatNumber, transactionFeeFiatNumber, currentCurrency ); } this.setState({ fromAccountBalance, transactionValue, transactionValueFiat, transactionFeeFiat, transactionTo, transactionTotalAmount, transactionTotalAmountFiat }); }; prepareTransaction = async () => { const { prepareTransaction, transactionState: { transaction } } = this.props; const estimation = await this.estimateGas(transaction); prepareTransaction({ ...transaction, ...estimation }); this.parseTransactionData(); this.setState({ gasEstimationReady: true }); }; estimateGas = async transaction => { const { TransactionController } = Engine.context; const { value, data, to, from } = transaction; let estimation; try { estimation = await TransactionController.estimateGas({ value, from, data, to }); } catch (e) { estimation = { gas: TransactionTypes.CUSTOM_GAS.DEFAULT_GAS_LIMIT }; } let basicGasEstimates; try { basicGasEstimates = await fetchBasicGasEstimates(); } catch (error) { Logger.log('Error while trying to get gas limit estimates', error); basicGasEstimates = { average: AVERAGE_GAS, safeLow: LOW_GAS, fast: FAST_GAS }; } return { gas: hexToBN(estimation.gas), gasPrice: toWei(convertApiValueToGWEI(basicGasEstimates.average), 'gwei') }; }; handleGasFeeSelection = ({ gas, gasPrice, customGasSelected, error }) => { this.setState({ customGas: gas, customGasPrice: gasPrice, customGasSelected, gasError: error }); }; handleSetGasFee = () => { const { customGas, customGasPrice, customGasSelected } = this.state; if (!customGas || !customGasPrice) { this.toggleCustomGasModal(); return; } this.setState({ gasEstimationReady: false }); const { prepareTransaction, transactionState } = this.props; let transaction = transactionState.transaction; transaction = { ...transaction, gas: customGas, gasPrice: customGasPrice }; prepareTransaction(transaction); setTimeout(() => { this.parseTransactionData(); this.setState({ customGas: undefined, customGasPrice: undefined, gasEstimationReady: true, currentCustomGasSelected: customGasSelected, errorMessage: undefined }); }, 100); this.toggleCustomGasModal(); }; toggleCustomGasModal = () => { const { customGasModalVisible } = this.state; this.setState({ customGasModalVisible: !customGasModalVisible }); }; toggleHexDataModal = () => { const { hexDataModalVisible } = this.state; this.setState({ hexDataModalVisible: !hexDataModalVisible }); }; renderCustomGasModal = () => { const { customGasModalVisible, currentCustomGasSelected, gasError } = this.state; const { gas, gasPrice } = this.props.transactionState.transaction; return ( <ActionModal modalVisible={customGasModalVisible} confirmText={strings('transaction.set_gas')} cancelText={strings('transaction.cancel_gas')} onCancelPress={this.toggleCustomGasModal} onRequestClose={this.toggleCustomGasModal} onConfirmPress={this.handleSetGasFee} confirmDisabled={!!gasError} cancelButtonMode={'neutral'} confirmButtonMode={'confirm'} > <View style={baseStyles.flexGrow}> <View style={styles.customGasModalTitle}> <Text style={styles.customGasModalTitleText}>{strings('transaction.transaction_fee')}</Text> </View> <CustomGas selected={currentCustomGasSelected} handleGasFeeSelection={this.handleGasFeeSelection} gas={gas} gasPrice={gasPrice} /> </View> </ActionModal> ); }; renderHexDataModal = () => { const { hexDataModalVisible } = this.state; const { data } = this.props.transactionState.transaction; return ( <Modal isVisible={hexDataModalVisible} onBackdropPress={this.toggleHexDataModal} onBackButtonPress={this.toggleHexDataModal} onSwipeComplete={this.toggleHexDataModal} swipeDirection={'down'} propagateSwipe > <View style={styles.hexDataWrapper}> <TouchableOpacity style={styles.hexDataClose} onPress={this.toggleHexDataModal}> <IonicIcon name={'ios-close'} size={28} color={colors.black} /> </TouchableOpacity> <View style={styles.qrCode}> <Text style={styles.addressTitle}>{strings('transaction.hex_data')}</Text> <Text style={styles.hexDataText}>{data || strings('unit.empty_data')}</Text> </View> </View> </Modal> ); }; validateGas = () => { const { accounts } = this.props; const { gas, gasPrice, value, from } = this.props.transactionState.transaction; let errorMessage; const totalGas = gas.mul(gasPrice); const valueBN = hexToBN(value); const balanceBN = hexToBN(accounts[from].balance); if (valueBN.add(totalGas).gt(balanceBN)) { errorMessage = strings('transaction.insufficient'); this.setState({ errorMessage }); } return errorMessage; }; prepareTransactionToSend = () => { const { transactionState: { transaction } } = this.props; transaction.gas = BNToHex(transaction.gas); transaction.gasPrice = BNToHex(transaction.gasPrice); return transaction; }; /** * Removes collectible in case an ERC721 asset is being sent, when not in mainnet */ checkRemoveCollectible = () => { const { transactionState: { selectedAsset, assetType }, network } = this.props; if (assetType === 'ERC721' && network !== 1) { const { AssetsController } = Engine.context; AssetsController.removeCollectible(selectedAsset.address, selectedAsset.tokenId); } }; onNext = async () => { const { TransactionController } = Engine.context; const { transactionState: { assetType }, navigation } = this.props; this.setState({ transactionConfirmed: true }); if (this.validateGas()) { this.setState({ transactionConfirmed: false }); return; } try { const transaction = this.prepareTransactionToSend(); const { result, transactionMeta } = await TransactionController.addTransaction( transaction, TransactionTypes.MMM ); await TransactionController.approveTransaction(transactionMeta.id); await new Promise(resolve => resolve(result)); if (transactionMeta.error) { throw transactionMeta.error; } InteractionManager.runAfterInteractions(() => { TransactionsNotificationManager.watchSubmittedTransaction({ ...transactionMeta, assetType }); this.checkRemoveCollectible(); navigation && navigation.dismiss(); }); } catch (error) { Alert.alert(strings('transactions.transaction_error'), error && error.message, [ { text: strings('navigation.ok') } ]); } this.setState({ transactionConfirmed: false }); }; renderIfGastEstimationReady = children => { const { gasEstimationReady } = this.state; return !gasEstimationReady ? ( <View style={styles.loader}> <ActivityIndicator size="small" /> </View> ) : ( children ); }; render = () => { const { transaction: { from }, transactionToName, transactionFromName, selectedAsset } = this.props.transactionState; const { showHexData } = this.props; const { gasEstimationReady, fromAccountBalance, transactionValue, transactionValueFiat, transactionFeeFiat, transactionTo, transactionTotalAmount, transactionTotalAmountFiat, errorMessage, transactionConfirmed } = this.state; return ( <SafeAreaView style={styles.wrapper}> <View style={styles.inputWrapper}> <AddressFrom onPressIcon={this.toggleFromAccountModal} fromAccountAddress={from} fromAccountName={transactionFromName} fromAccountBalance={fromAccountBalance} /> <AddressTo addressToReady toSelectedAddress={transactionTo} toAddressName={transactionToName} onToSelectedAddressChange={this.onToSelectedAddressChange} /> </View> <ScrollView style={baseStyles.flexGrow}> {!selectedAsset.tokenId ? ( <View style={styles.amountWrapper}> <Text style={styles.textAmountLabel}>{strings('transaction.amount')}</Text> <Text style={styles.textAmount}>{transactionValue}</Text> <Text style={styles.textAmountLabel}>{transactionValueFiat}</Text> </View> ) : ( <View style={styles.amountWrapper}> <Text style={styles.textAmountLabel}>{strings('transaction.asset')}</Text> <View style={styles.collectibleImageWrapper}> <CollectibleImage iconStyle={styles.collectibleImage} containerStyle={styles.collectibleImage} collectible={selectedAsset} /> </View> <View> <Text style={styles.collectibleName}>{selectedAsset.name}</Text> <Text style={styles.collectibleTokenId}>{`#${selectedAsset.tokenId}`}</Text> </View> </View> )} <View style={styles.summaryWrapper}> <View style={styles.summaryRow}> <Text style={styles.textSummary}>{strings('transaction.amount')}</Text> <Text style={[styles.textSummary, styles.textSummaryAmount]}>{transactionValueFiat}</Text> </View> <View style={styles.summaryRow}> <Text style={styles.textSummary}>{strings('transaction.transaction_fee')}</Text> {this.renderIfGastEstimationReady( <Text style={[styles.textSummary, styles.textSummaryAmount]}>{transactionFeeFiat}</Text> )} </View> <View style={styles.separator} /> <View style={styles.summaryRow}> <Text style={[styles.textSummary, styles.textBold]}> {strings('transaction.total_amount')} </Text> {this.renderIfGastEstimationReady( <Text style={[styles.textSummary, styles.textSummaryAmount, styles.textBold]}> {transactionTotalAmountFiat} </Text> )} </View> <View style={styles.totalCryptoRow}> {this.renderIfGastEstimationReady( <Text style={[styles.textSummary, styles.textCrypto]}>{transactionTotalAmount}</Text> )} </View> </View> {errorMessage && ( <View style={styles.errorMessageWrapper}> <ErrorMessage errorMessage={errorMessage} /> </View> )} <View style={styles.actionsWrapper}> <TouchableOpacity style={styles.actionTouchable} disabled={!gasEstimationReady} onPress={this.toggleCustomGasModal} > <Text style={styles.actionText}>{strings('transaction.adjust_transaction_fee')}</Text> </TouchableOpacity> {showHexData && ( <TouchableOpacity style={styles.actionTouchable} onPress={this.toggleHexDataModal}> <Text style={styles.actionText}>{strings('transaction.hex_data')}</Text> </TouchableOpacity> )} </View> </ScrollView> <View style={styles.buttonNextWrapper}> <StyledButton type={'confirm'} disabled={!gasEstimationReady} containerStyle={styles.buttonNext} onPress={this.onNext} > {transactionConfirmed ? <ActivityIndicator size="small" color="white" /> : 'Send'} </StyledButton> </View> {this.renderCustomGasModal()} {this.renderHexDataModal()} </SafeAreaView> ); }; }
JavaScript
class ErrorResponse extends AbstractLambdaPlugin { /** * ErrorResponse constructor. * * @param {errorMapperCallback=} defaultErrorResponse default error response fn */ constructor (defaultErrorResponse = null) { super('errorResponse', LambdaType.API_GATEWAY) this._defaultErrorResponse = defaultErrorResponse this.addHook(PluginHook.ON_ERROR, this.mapErrorResponse.bind(this)) } /** * Map error to a custom body * * @param {errorMapperCallback=} errorResponseFn error response fn */ mapErrorResponse (errorResponseFn = null) { const fn = errorResponseFn || this._defaultErrorResponse || null return (req, res, error, context, done) => { let errorBody if (fn !== null) { errorBody = fn(error) } else { const errorObj = error const errorType = error && error.constructor && error.constructor.name errorBody = { error: { message: error.message || 'Unknown error. No error specified', name: errorType !== 'Object' ? errorType : 'Unknown', ...errorObj, _stackTrace: (error.stack || '').split('\n').map(x => x.trim()) } } } res.body = CircularJSON.stringify(errorBody) done() } } }
JavaScript
class NativeStorage { constructor(storage) { this.storage = storage } /** * Retrieve the keys list from storage * @returns {Array<String>} List of keys contained into the a storage * */ get keys() { return this.storage.getAllKeys() } /** * Get the storage size * @returns {Number} How many keys are contained into the storage */ get length() { return this.keys.length } /** * * @param {Number} index Array index * @returns {String} Keys at index */ key(index) { return this.keys[index] } /** * * @param {*} key Key to associate to the data * @param {*} data Data to be saved into the storage */ setItem(key, data) { this.storage.setString(key, data) } /** * Retrieve a value from the store saved associated to the key * @param {*} key Key used to select the value */ getItem(key) { return this.storage.getString(key) } /** * Remove one key from the storage * @param {*} key Key to be removed */ removeItem(key) { this.storage.remove(key) } /** * Remove all keys from the storage */ clear() { this.storage.clear() } }
JavaScript
class PeerBaseController { constructor () { this.peer = new Peer() this.peer.on('open', this.onPeerOpen.bind(this)) this.peer.on('close', this.onPeerClose.bind(this)) this.peer.on('connection', this.onPeerConnect.bind(this)) this.peer.on('disconnected', this.onPeerDisconnect.bind(this)) this.peer.on('error', this.onPeerError.bind(this)) } connectToHost (hostId) { this.hostId = hostId this.connection = this.peer.connect(this.hostId) this.connection.on('open', this.onFriendToHostConnectionOpen.bind(this)) this.connection.on('data', this.onFriendToHostConnectionData.bind(this)) this.connection.on('close', this.onFriendToHostConnectionClose.bind(this)) this.connection.on('error', this.onFriendToHostConnectionError.bind(this)) } onPeerOpen (peerId) { console.debug(`Connected with peer server and got the ID: ${peerId}`) this.peerId = peerId this.trigger('open') } onPeerClose () { console.debug('Peer closed') } onPeerConnect (connection) { if (this.connection) { console.debug('User is already connected') return } // This is from the host perspective this.connection = connection this.connection.on('open', this.onHostToFriendConnectionOpen.bind(this)) this.connection.on('data', this.onHostToFriendConnectionData.bind(this)) this.connection.on('close', this.onHostToFriendConnectionClose.bind(this)) this.connection.on('error', this.onHostToFriendConnectionError.bind(this)) } onPeerDisconnect () { console.debug('Peer disconnected') } onPeerError (error) { console.error('Error from peerjs', error) this.trigger('error', error) } onFriendToHostConnectionOpen () { console.debug('Connected to host') this.trigger('connected') } onFriendToHostConnectionData (data) { console.debug('Received data from host', data) } onFriendToHostConnectionClose () { console.debug('Connected to host closed') } onFriendToHostConnectionError (error) { console.error('Connect to host error', error) this.trigger('error', error) } onHostToFriendConnectionOpen () { console.debug('Connected to friend') this.trigger('connected') } onHostToFriendConnectionData (data) { console.debug('Received data from friend', data) } onHostToFriendConnectionClose () { console.debug('Connected to friend closed') } onHostToFriendConnectionError (error) { console.error('Connect to friend error', error) this.trigger('error', error) } }
JavaScript
class AJAX { // Attributes queue; // Constructors constructor() { this.queue = []; } // Methods /** * Send a query with AJAX. * * This function send a query to a * given url and return a Promise. * Use this function followed by * .then to get result. * * Example: * const ajax = new AJAX(); * ajax.call("./some/file/or/url", "POST", [name, id]) * .then(successCallback, errorCallback); * * @function call * @access public * @param {string} url Url to file or resource * @param {string} type (default = POST) Method type of the query (POST, GET, PUT, etc...) * @param {Array} data (optional) Data array sent * @returns {Promise<XMLHttpRequest>} */ call(url, type, data) { // Init optional parameters type = type || "POST"; data = data || []; const that = this; return new Promise(function (resolve, reject) { // XMLHttp object const xHttp = new XMLHttpRequest(); xHttp.open(type, url, true); that.add(xHttp); xHttp.send(JSON.stringify(data)); // Status event xHttp.onreadystatechange = function () { if (xHttp.readyState === XMLHttpRequest.DONE) { if (xHttp.status === 200) { //const JSONresp = JSON.parse(xHttp.responseText); that.del(xHttp); resolve(xHttp.responseText); } else { reject(xHttp.status) } } } }); } /** * Send multiples queries with AJAX. * * This function will send multiples * queries using a {QueriesList}. The * promise returned start the callback * when every promises contained are * finished. * * Example: * const ajax = new AJAX(); * ajax.multipleCalls([ * {url: "/path/to/file/1", type: "POST", data: [1, 2, 3]}, * {url: "/path/to/file/2", type: "GET"}, * {url: "/path/to/file/3"}]) * .then(successCallback, errorCallback); * * @function multipleCalls * @access public * @param {QueriesList} queries List of queries. * @return {Promise<Array<Promise<XMLHttpRequest>>>} */ multipleCalls(queries) { const that = this; let promises = []; // Start every promises queries.forEach(function (query) { let type = query.type || "POST"; let data = query.data || []; promises.push(that.call(query.url, type, data)); }); return Promise.all(promises); } isQueueEmpty() { return !Boolean(this.queue.length); } /** * Add a running XMLHttpRequest to * the queue. * * AJAX() has a queue with every * queries running. This function * add a newly created query to * this queue. This method shouldn't * be called outside of AJAX.call(); * * @function add * @access public * @param {XMLHttpRequest} xHttp Running XMLHttpRequest object * @return {void} */ add(xHttp) { this.queue.push(xHttp); } /** * Delete an ended XMLHttpRequest * of the queue. * * This method will remove an * ended XMLHttpRequest from the * queue. It shouldn't not be called * outside of AJAX.call(); * * @function del * @access public * @param {XMLHttpRequest} xHttp Ended XMLHttpRequest object * @return {void} */ del(xHttp) { const index = this.queue.indexOf(xHttp); if (index > -1) this.queue.splice(index, 1); } /** * Stop all running queries. * * It can be useful when you need * to stop every queries or when * some queries takes to much time. * * @function abortAll * @access public * @return {void} */ abortAll() { // Abort all AJAX queries this.queue.forEach(function (xHttp) { xHttp.abort(); }); // Clean the queue this.queue = []; } /** * Show a query error. It's can * be used by every ajax.call.then * to handle errors easily. * * @function error * @access public * @param {string} status Error's status * @return {void} */ error(status) { alert(status); } }
JavaScript
class ParticleSystem extends Component { constructor(props) { super(props); } render() { return ( <View> {this.props.particles.map((p, i) => ( <Particle key={i} position={p.position} color={p.color} size={p.size} /> ))} </View> ); } }
JavaScript
class ParticleSystemReactNativeSvg extends Component { constructor(props) { super(props); } render() { const data = this.props.particles.map( p => `M${p.position[0]},${p.position[1]}a5,5 0 1,0 10,0a5,5 0 1,0 -10,0` ); return ( <Svg height={HEIGHT} width={WIDTH}> <Path d={data.join(" ")} fill="#FF7373" /> </Svg> ); } }
JavaScript
class VirtualWorldBlock { constructor(manager, begin, end) { this.manager_ = manager; this.begin_ = begin; this.end_ = end; this.released_ = []; this.next_ = begin; } // Gets the first Virtual World that's part of this block. get begin() { return this.begin_; } // Gets the final Virtual World that's part of this block. get end() { return this.end_ - 1; } // Gets the size of this block in total number of virtual worlds. get size() { return this.end_ - this.begin_; } // Returns whether the |virtualWorld| is part of this range. isValid(virtualWorld) { return virtualWorld >= this.begin_ && virtualWorld < this.end_; } // Acquires a unique Virtual World. It will not be handed out again until the world either gets // released, or the entire block gets disposed of. allocate() { if (this.released_.length) return this.released_.shift(); if (this.next_ === this.end_) throw new Error('The block of virtual worlds has been entirely consumed.'); return this.next_++; } // Releases the |virtualWorld| for future usage. Will throw an exception if the |virtualWorld| // is not valid for the range owned by this block. release(virtualWorld) { if (virtualWorld < this.begin_ || virtualWorld >= this.end_) throw new Error('The virtual world #' + virtualWorld + ' is out of bounds.'); this.released_.push(virtualWorld); } // Disposes the entire block of virtual worlds. dispose() { this.manager_.didDisposeBlock(); this.manager_ = null; } }
JavaScript
class Awesomplete { /** @param {!Element} input */ constructor(input) { /** @type {!Array.<string>} */ this.list; /** @type {number} */ this.minChars; } evaluate() {} }
JavaScript
class Font extends EventManager { constructor(name, options={}) { super(); this.name = name; this.options = options; this.metrics = false; } get src() { return this.__src; } /** * Just like Image and Audio, we kick everything off when * our `src` gets assigned. * * @param {string} url */ set src(url) { this.__src = url; this.defineFontFace(this.name, url, this.options); this.loadFont(url); } /** * This is a blocking operation. */ defineFontFace(name, url, options) { let format = getFontCSSFormat(url); if (!format) return; let style = document.createElement(`style`); style.className = `injected by Font.js`; let rules = Object.keys(options).map(r => `${r}: ${options[r]};`).join(`\n\t`); style.textContent = ` @font-face { font-family: "${name}"; ${rules} src: url("${url}") format("${format}"); }`; this.styleElement = style; document.head.appendChild(style); } /** * This is a non-blocking operation. * * @param {String} url The URL for the font in question */ async loadFont(url) { const type = getFontCSSFormat(url); fetch(url) .then(response => checkFetchResponseStatus(response) && response.arrayBuffer()) .then(buffer => this.fromDataBuffer(buffer, type)) .catch(err => { const evt = new Event(`error`, err, `Failed to load font at ${url}`); this.dispatch(evt); if (this.onerror) this.onerror(evt); }); } /** * This is a non-blocking operation. * * @param {Buffer} buffer The binary data associated with this font. */ async fromDataBuffer(buffer, type) { this.fontData = new DataView(buffer); // Because we want to enforce Big Endian everywhere await this.parseBasicData(type); const evt = new Event("load", { font: this }); this.dispatch(evt); if (this.onload) this.onload(evt); } /** * This is a non-blocking operation IF called from an async function */ async parseBasicData(type) { return loadTableClasses().then(createTable => { if (type === `truetype` || type === `opentype`) { this.opentype = new SFNT(this.fontData, createTable); } if (type === `woff`) { this.opentype = new WOFF(this.fontData, createTable); } if (type === `woff2`) { this.opentype = new WOFF2(this.fontData, createTable); } return this.opentype; }); } /** * Does this font support the specified character? * @param {*} char */ supports(char) { return this.opentype.tables.cmap.supports(char) !== false; } /** * Does this font support the specified unicode variation? * @param {*} variation */ supportsVariation(variation) { return this.opentype.tables.cmap.supportsVariation(variation) !== false; } /** * Effectively, be https://html.spec.whatwg.org/multipage/canvas.html#textmetrics * @param {*} text * @param {*} size */ measureText(text, size=16) { if (this.__unloaded) throw new Error("Cannot measure text: font was unloaded. Please reload before calling measureText()"); let d = document.createElement('div'); d.textContent = text; d.style.fontFamily = this.name; d.style.fontSize = `${size}px`; d.style.color = `transparent`; d.style.background = `transparent`; d.style.top = `0`; d.style.left = `0`; d.style.position = `absolute`; document.body.appendChild(d); let bbox = d.getBoundingClientRect(); document.body.removeChild(d); const OS2 = this.opentype.tables["OS/2"]; bbox.fontSize = size; bbox.ascender = OS2.sTypoAscender; bbox.descender = OS2.sTypoDescender; return bbox; } /** * unload this font from the DOM context, making it no longer available for CSS purposes */ unload() { if (this.styleElement.parentNode) { this.styleElement.parentNode.removeElement(this.styleElement); const evt = new Event("unload", { font: this }); this.dispatch(evt); if (this.onunload) this.onunload(evt); } this._unloaded = true; } /** * load this font back into the DOM context after being unload()'d earlier. */ unload() { if (this.__unloaded) { delete this.__unloaded; document.head.appendChild(this.styleElement); const evt = new Event("load", { font: this }); this.dispatch(evt); if (this.onload) this.onload(evt); } } }
JavaScript
class DubboDirectlyInvoker { constructor(props) { //===================socket event=================== this.handleTransportConnect = () => { this.status = 'CONNECTED' /* CONNECTED */ for (let ctx of this.queue.values()) { //如果还没有被处理 if (!ctx.wasInvoked) { ctx.invokedByHost = this.props.dubboHost this.transport.write(ctx) } } } this.handleTransportData = ({ requestId, res, err }) => { log(`receive transport data %d - res: %O - err: %s`, requestId, res, err) this.consume({ requestId, err, res }) } this.handleTransportClose = () => { log('socket-worker was closed') this.status = 'CLOSED' /* CLOSED */ //failed all for (let ctx of this.queue.values()) { ctx.reject(new Error('socket-worker was closed.')) ctx.cleanTimeout() } this.queue.clear() } log('bootstrap....%O', this.props) this.props = props this.queue = new Map() this.status = 'PADDING' /* PADDING */ this.transport = dubbo_tcp_transport_1.default .from(this.props.dubboHost) .subscribe({ onConnect: this.handleTransportConnect, onData: this.handleTransportData, onClose: this.handleTransportClose }) } static from(props) { return new DubboDirectlyInvoker(props) } close() { this.transport.close() } proxyService(invokeParam) { const { dubboInterface, path, methods, timeout, group = '', version = '0.0.0', attachments = {}, isSupportedDubbox = false } = invokeParam const proxy = Object.create(null) for (let methodName of Object.keys(methods)) { proxy[methodName] = (...args) => { return (0, apache_dubbo_common_1.go)( new Promise((resolve, reject) => { const ctx = context_1.default.init() ctx.resolve = resolve ctx.reject = reject ctx.methodName = methodName const method = methods[methodName] ctx.methodArgs = method.call(invokeParam, ...args) || [] ctx.dubboVersion = this.props.dubboVersion ctx.dubboInterface = dubboInterface ctx.path = path || dubboInterface ctx.group = group ctx.timeout = timeout ctx.version = version ctx.attachments = attachments ctx.isSupportedDubbox = isSupportedDubbox //check param //param should be hessian data type if (!ctx.isRequestMethodArgsHessianType) { log( `${dubboInterface} method: ${methodName} not all arguments are valid hessian type` ) log(`arguments->%O`, ctx.request.methodArgs) reject(new Error('not all arguments are valid hessian type')) return } //超时检测 ctx.timeout = this.props.dubboInvokeTimeout ctx.setMaxTimeout(() => { this.queue.delete(ctx.requestId) }) //add task to queue this.addQueue(ctx) }) ) } } return proxy } // ~~~~~~~~~~~~~~~~private~~~~~~~~~~~~~~~~~~~~~~~~ /** * Successfully process the task of the queue * * @param requestId * @param err * @param res */ consume({ requestId, err, res }) { const ctx = this.queue.get(requestId) if (!ctx) { return } if (err) { ctx.reject(err) } else { ctx.resolve(res) } ctx.cleanTimeout() this.queue.delete(requestId) } /** * add task's context to queue * * @param ctx */ addQueue(ctx) { const { requestId } = ctx this.queue.set(requestId, ctx) log(`current dubbo transport => ${this.status}`) //根据当前socket的worker的状态,来对任务进行处理 switch (this.status) { case 'PADDING' /* PADDING */: break case 'CONNECTED' /* CONNECTED */: this.transport.write(ctx) break case 'CLOSED' /* CLOSED */: this.consume({ requestId, err: new Error(`dubbo transport was closed.`) }) break } } }
JavaScript
class UpdateTerminationProtectionCommand extends smithy_client_1.Command { // Start section: command_properties // End section: command_properties constructor(input) { // Start section: command_constructor super(); this.input = input; // End section: command_constructor } /** * @internal */ resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "CloudFormationClient"; const commandName = "UpdateTerminationProtectionCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.UpdateTerminationProtectionInput.filterSensitiveLog, outputFilterSensitiveLog: models_0_1.UpdateTerminationProtectionOutput.filterSensitiveLog, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return Aws_query_1.serializeAws_queryUpdateTerminationProtectionCommand(input, context); } deserialize(output, context) { return Aws_query_1.deserializeAws_queryUpdateTerminationProtectionCommand(output, context); } }
JavaScript
class MeetingByIds extends CacheMultiBase { /** * Init params in oThis. * * @param {object} params * @param {array<number>} params.ids * * @private */ _initParams(params) { const oThis = this; oThis.ids = params.ids; } /** * Set cache type. * * @sets oThis.cacheType * * @private */ _setCacheType() { const oThis = this; oThis.cacheType = cacheManagementConstants.memcached; } /** * Set cache keys. * * @sets oThis.cacheKeys * * @private */ _setCacheKeys() { const oThis = this; for (let index = 0; index < oThis.ids.length; index++) { oThis.cacheKeys[oThis._cacheKeyPrefix() + '_cmm_m_ids_' + oThis.ids[index]] = oThis.ids[index]; } } /** * Set cache expiry. * * @sets oThis.cacheExpiry * * @private */ _setCacheExpiry() { const oThis = this; oThis.cacheExpiry = cacheManagementConstants.mediumExpiryTimeInterval; // 60 minutes } /** * Fetch data from source for cache miss ids. * * @param cacheMissIds * * @return {Promise<*>} */ async fetchDataFromSource(cacheMissIds) { const fetchByIdsRsp = await new MeetingsModel().fetchByIds(cacheMissIds); return responseHelper.successWithData(fetchByIdsRsp); } }
JavaScript
class ContextEntityCollector extends Decorator { constructor() { super(); this.title = this.name = 'ContextEntityCollector'; this.contextNode = true; // this node has the context data this.description = 'Holds a context manager for its single child context'; this.contextManager = new ContextManager(this); /** * Node parameters * @property parameters * @type {Object} * @property {Array<EntitiesToContextMapItem>} parameters.entities - entities map. Each item carries an additional member - mandatory boolean field * @property {boolean} parameters.returnWhenAllEntitiesCollected - return success when all entities collected, regardless of the child status * */ this.parameters = _.extend(this.parameters, { returnWhenAllEntitiesCollected: false, entities: [{ 'contextFieldName': '', 'entityName': '', 'entityIndex': 0, "mandatory": true }] }); } /** * * @param {Tick} tick */ open(tick) { this.contextManager.open(tick); } currentChildIndex() { // we always switch to this 0 context! return 0; } setContextChild(tick, selectedConvoIndex) { dblogger.assert(selectedConvoIndex == 0, 'cant have more than one convo index in ContextEntityCollector'); // do nothing, one index } /** * close this node and context * @param {Tick} tick */ close(tick, status) { // move to the first context up this.contextManager.close(tick, status); } currentContextIndex(tick) { return 0; } currentContextChild(tick) { return this.child; } contextChildren() { return [this.currentContextChild()]; } allEntitiesCollected(tick) { for (let prop of this.contextProperties()[0].entities) { let contextField = this.context(tick, prop.contextFieldName); if (prop.mandatory && Utils.isEmpty(contextField)) { return false; } } return true; } tick(tick) { if (!this.child) { return b3.ERROR(); } var status = this.child._execute(tick); if (status === b3.RUNNING()) { if (this.properties.returnWhenAllEntitiesCollected && this.allEntitiesCollected(tick)) { status = b3.SUCCESS(); } } return status; } contextProperties() { return [{ entities: this.properties.entities }]; } nonContextChild() { return true; } }
JavaScript
class Option extends UI5Element { static get metadata() { return metadata; } get stableDomRef() { return `${this._id}-stable-dom-ref`; } }
JavaScript
class Layer { constructor(base, options) { this._base = base; this._handlers = {}; this._lifecycleRe = /^(enter|update|merge|exit)(:transition)?$/; if (options) { // Set layer methods (required) this.dataBind = options.dataBind; this.insert = options.insert; // Bind events (optional) if ('events' in options) { for (var eventName in options.events) { this.on(eventName, options.events[eventName]); } } } } /** * Invoked by {@link Layer#draw} to join data with this layer's DOM nodes. This * implementation is "virtual"--it *must* be overridden by Layer instances. * * @param {Array} data Value passed to {@link Layer#draw} * @param {Object} [context] the instance of this layers */ dataBind() { kotoAssert(false, 'Layers must specify a dataBind method.'); } /** * Invoked by {@link Layer#draw} in order to insert new DOM nodes into this * layer's `base`. This implementation is "virtual"--it *must* be overridden by * Layer instances. */ insert() { kotoAssert(false, 'Layers must specify an `insert` method.'); } /** * Subscribe a handler to a lifecycle event. These events (and only these * events) are triggered when {@link Layer#draw} is invoked--see that method * for more details on lifecycle events. * * @param {String} eventName Identifier for the lifecycle event for which to * subscribe. * @param {Function} handler Callback function * * @returns {Chart} Reference to the layer instance (for chaining). */ on(eventName, handler, options) { options = options || {}; kotoAssert(this._lifecycleRe.test(eventName), `Unrecognized lifecycle event name specified to 'Layer#on': '${eventName}'.`); if (!(eventName in this._handlers)) { this._handlers[eventName] = []; } this._handlers[eventName].push({ callback: handler, chart: options.chart || null }); return this; } /** * Unsubscribe the specified handler from the specified event. If no handler is * supplied, remove *all* handlers from the event. * * @param {String} eventName Identifier for event from which to remove * unsubscribe * @param {Function} handler Callback to remove from the specified event * * @returns {Chart} Reference to the layer instance (for chaining). */ off(eventName, handler) { var handlers = this._handlers[eventName]; var idx; kotoAssert(this._lifecycleRe.test(eventName), `Unrecognized lifecycle event name specified to 'Layer#on': '${eventName}'.`); if (!handlers) { return this; } if (arguments.length === 1) { handlers.length = 0; return this; } for (idx = handlers.length - 1; idx > -1; --idx) { if (handlers[idx].callback === handler) { handlers.splice(idx, 1); } } return this; } /** * Render the layer according to the input data. Bind the data to the layer * (according to {@link Layer#dataBind}, insert new elements (according to * {@link Layer#insert}, make lifecycle selections, and invoke all relevant * handlers (as attached via {@link Layer#on}) with the lifecycle selections. * * - update * - update:transition * - enter * - enter:transition * - exit * - exit:transition * * @param {Array} data Data to drive the rendering. */ draw(data) { var bound, entering, events, selection, method, handlers, eventName, idx, len, tidx, tlen, promises = []; function endAll(transition, callback) { let n = 0; transition .each(function inc () { ++n; }) .on('end', function done (...args) { if (!--n) { callback.apply(this, args); } }); } function promiseCallback (resolve) { selection.call(endAll, function allDone () { return resolve(true); }); } bound = this.dataBind.call(this._base, data, this); kotoAssert(bound instanceof d3.selection, 'Invalid selection defined by `Layer#dataBind` method.'); kotoAssert(bound.enter, 'Layer selection not properly bound.'); entering = bound.enter(); entering._chart = this._base._chart; events = [ { name: 'update', selection: bound }, { name: 'enter', selection: entering, method: this.insert }, { name: 'merge', // Although the `merge` lifecycle event shares its selection object // with the `update` lifecycle event, the object's contents will be // modified when koto invokes the user-supplied `insert` method // when triggering the `enter` event. selection: bound }, { name: 'exit', // Although the `exit` lifecycle event shares its selection object // with the `update` and `merge` lifecycle events, the object's // contents will be modified when koto invokes // `d3.selection.exit`. selection: bound, method: bound.exit } ]; for (var i = 0, l = events.length; i < l; ++i) { eventName = events[i].name; selection = events[i].selection; method = events[i].method; // Some lifecycle selections modify shared state, so they must be // deferred until just prior to handler invocation. if (typeof method === 'function') { selection = method.call(selection, selection); } if (selection.empty()) { continue; } kotoAssert(selection && selection instanceof d3.selection, `Invalid selection defined for ${eventName} lifecycle event.`); handlers = this._handlers[eventName]; if (handlers) { for (idx = 0, len = handlers.length; idx < len; ++idx) { // Attach a reference to the parent chart so the selection's // `chart` method will function correctly. selection._chart = handlers[idx].chart || this._base._chart; // selection.call(handlers[idx].callback); handlers[idx].callback.call(selection, selection); } } handlers = this._handlers[eventName + ':transition']; if (handlers && handlers.length) { selection = selection.transition(); for (tlen = handlers.length, tidx = 0; tidx < tlen; ++tidx) { selection._chart = handlers[tidx].chart || this._base._chart; // selection.call(handlers[tidx].callback); handlers[tidx].callback.call(selection, selection); promises.push(new Promise(promiseCallback)); } } this.promise = Promise.all(promises); } } }
JavaScript
class ApplicationsContainer extends Component { static propTypes = { application: PropTypes.object.isRequired, getApplications: PropTypes.func.isRequired }; componentDidMount() { this.props.getApplications(); } render() { return ( <ApplicationsView applications={this.props.application.applications} /> ); } }
JavaScript
class ChirpList extends Component { constructor(props){ super(props); this.state = {chirps:[]}; } render() { if(!this.state.chirps) return null; //if no chirps, don't display /* TODO: produce a list of `<ChirpItems>` to render */ let chirpItems = []; //REPLACE THIS with an array of actual values! return ( <div className="container"> {chirpItems} </div>); } }
JavaScript
class ChirpItem extends Component { likeChirp = () => { /* TODO: update the chirp when it is liked */ } render() { let chirp = this.props.chirp; //current chirp (convenience) //counting likes let likeCount = 0; //count likes let userLikes = false; //current user has liked if(chirp.likes){ likeCount = Object.keys(chirp.likes).length; if(chirp.likes[this.props.currentUser.uid]) //if user id is listed userLikes = true; //user liked! } return ( <div className="row py-4 bg-white border"> <div className="col-1"> <img className="avatar" src={chirp.userPhoto} alt={chirp.userName+' avatar'} /> </div> <div className="col pl-4 pl-lg-1"> <span className="handle">{chirp.userName} {/*space*/}</span> <span className="time"><Moment date={chirp.time} fromNow/></span> <div className="chirp">{chirp.text}</div> {/* A section for showing chirp likes */} <div className="likes"> <i className={'fa fa-heart '+(userLikes ? 'user-liked': '')} aria-label="like" onClick={this.likeChirp} ></i> <span>{/*space*/} {likeCount}</span> </div> </div> </div> ); } }
JavaScript
class Login extends ComponentDialog { constructor(dialogId, entityProfileAccessor) { super(dialogId); // validate what was passed in if (!dialogId) throw ('Missing parameter. dialogId is required'); if (!entityProfileAccessor) throw ('Missing parameter. entityProfileAccessor is required'); // Add a water fall dialog with 4 steps. // The order of step function registration is importent // as a water fall dialog executes steps registered in order this.addDialog(new WaterfallDialog(dialogId, [ this.initializeStateStep.bind(this), this.responseForStep.bind(this) ])); // Add choice prompts for name and city this.addDialog(new ChoicePrompt(CONFIRM_PROMPT)); // Save off our state accessor for later use this.entityProfileAccessor = entityProfileAccessor; } /** * Waterfall Dialog step functions. * * Initialize our state. See if the WaterfallDialog has state pass to it * If not, then just new up an empty UserProfile object * * @param {WaterfallStepContext} step contextual information for the current step being executed */ async initializeStateStep(step) { let entityProfile = await this.entityProfileAccessor.get(step.context); if (entityProfile === undefined || (entityProfile && !entityProfile.entity)) { var reply = MessageFactory.suggestedActions( [ 'Invalid userid/password', 'User Id not defined in LDAP', 'Not authorized to access RP due to invalid LOC/DEPT', 'You are currently deactivated in the system', 'Transaction not successfully started' ], 'Ok, glad to help you on that. Please select the appropriate issue from the dropdown ?'); await step.context.sendActivity(reply); return await step.endDialog(); } return await step.next(); } /** * Waterfall Dialog step functions. * * Using a text prompt, prompt the user for their name. * Only prompt if we don't have this information already. * * @param {WaterfallStepContext} step contextual information for the current step being executed */ async responseForStep(step) { let entityProfile = await this.entityProfileAccessor.get(step.context); if (entityProfile && entityProfile.entity.toLowerCase() == login.LDAP) { await step.context.sendActivity("Please follow the below steps."); await step.context.sendActivity("i) Contact your HR to active your profile in LDAP."); await step.context.sendActivity("ii)Contact your business admin to activate in RP."); await step.context.sendActivity("You can refer help tab for business admin contacts."); } else if (entityProfile && entityProfile.entity.toLowerCase() == login.Invalid) { await step.context.sendActivity("Please reset your password .Is still issue persists try login after clearing the browser caches."); } else if (entityProfile && entityProfile.entity.toLowerCase() == login.Transaction) { await step.context.sendActivity("This error occurs when any user/supervisor himself assigned as supervisor in PDM. "); await step.context.sendActivity("Please check your profile and your supervisor profile, and your supervisor's supervisor profile and so on."); await step.context.sendActivity("Then correct the supervisor for the concerned person."); } else if (entityProfile && (entityProfile.entity.toLowerCase() == login.Unauthorized || entityProfile.entity.toLowerCase() ==login.Deactivated)) { await step.context.sendActivity("Please contact your business admin to activate in RP."); await step.context.sendActivity("You can refer help tab for business admin contacts."); } return await step.next(); } }
JavaScript
class BaseRenderer extends DataHandler { /** * Base constructor * * @typedef {Object} options * @property {Boolean} options.appendTo - where the generated html/svg components will be attached to, default body * @property {Function} options.callbackHandler - this handler will be used to invoke actions from the menu, default console.log * @param {Object} context - the context of the application, usually a configuration and a rendering manager instance */ constructor({ appendTo = 'body', callbackHandler }, context = { }) { super(); /** * @typedef {Object} Options * @property {Boolean} appendTo where the generated html/svg components will be attached to, default body * @property {Function} callbackHandler this handler will be used to invoke actions from the menu, default console.log */ this.options = undefined; this.settings({ appendTo: appendTo, callbackHandler: callbackHandler }); this.context = context; } /** * Saves the settings in an internal options object. * * @typedef {Object} options * @property {Boolean} options.appendTo - where the generated html/svg components will be attached to, default body * @property {Function} options.callbackHandler - this handler will be used to invoke actions from the menu, default console.log * @returns {object} this instance * @public */ settings({ appendTo, callbackHandler }) { this.options = this.options || {}; if (!this.options.callbackHandler && !callbackHandler) { throw new Error('A Callback Handler must be provided! This will be used to trigger events from the graphics produced...'); } if (!this.options.appendTo && !appendTo) { throw new Error('Missing an element or id to append the graphics to!'); } if (typeof appendTo === 'string') { appendTo = {element: d3.select(appendTo)}; } this.options.appendTo = appendTo || this.options.appendTo; this.options.callbackHandler = callbackHandler || this.options.callbackHandler; return this; } /** * Returns the parent element of this class * * @return {object} a d3 object * @public */ get parent() { return this.options.appendTo.element; } /** * Returns the parent class of this class * * @return {Renderer} the {Renderer} or {Composite} parent of this class * @public */ get parentClass() { return this.options.appendTo; } /** * Generic error handler. * Will log the error and rethrow if error is unknown. * * @param {Error} error - an error instance * @public */ static handleErrors(error) { if (error instanceof Exception) { // well, most of these are just informative Logger.debug(error.message); return; } Logger.error(error.message); throw error; } /** * Returns the current mouse position. * * @private */ _mousePosition() { var x = ((event.screenX + event.clientX) / 2) - event.pageX + event.offsetX; var y = ((event.screenY + event.clientY) / 2) - event.pageY + event.offsetY; return [x, y]; } /** * Generic Promise handler. * This will show the Loader/Spinner on the application while processing. * * @param {Promise} promise - a promise to execute * @return {Object} the result of the promise * @public */ handlePromise(promise) { let loader = Decorators.Loader.withContext(this).show(); return promise .then(data => data) .catch(error => BaseRenderer.handleErrors(error)) .finally(() => loader.hide()); } }
JavaScript
class CreateTorrentPage extends React.Component { constructor (props) { super(props) const state = this.props.state const info = state.location.current() // First, extract the base folder that the files are all in let pathPrefix = info.folderPath if (!pathPrefix) { pathPrefix = info.files.map((x) => x.path).reduce(findCommonPrefix) if (!pathPrefix.endsWith('/') && !pathPrefix.endsWith('\\')) { pathPrefix = path.dirname(pathPrefix) } } // Then, exclude .DS_Store and other dotfiles const files = info.files .filter((f) => !containsDots(f.path, pathPrefix)) .map((f) => ({name: f.name, path: f.path, size: f.size})) if (files.length === 0) return (<CreateTorrentErrorPage state={state} />) // Then, use the name of the base folder (or sole file, for a single file torrent) // as the default name. Show all files relative to the base folder. let defaultName, basePath if (files.length === 1) { // Single file torrent: /a/b/foo.jpg -> torrent name 'foo.jpg', path '/a/b' defaultName = files[0].name basePath = pathPrefix } else { // Multi file torrent: /a/b/{foo, bar}.jpg -> torrent name 'b', path '/a' defaultName = path.basename(pathPrefix) basePath = path.dirname(pathPrefix) } // Default trackers const trackers = createTorrent.announceList.join('\n') this.state = { comment: '', isPrivate: false, pathPrefix, basePath, defaultName, files, trackers } // Create React event handlers only once this.setIsPrivate = (_, isPrivate) => this.setState({isPrivate}) this.setComment = (_, comment) => this.setState({comment}) this.setTrackers = (_, trackers) => this.setState({trackers}) this.handleSubmit = handleSubmit.bind(this) } render () { const files = this.state.files // Sanity check: show the number of files and total size const numFiles = files.length const totalBytes = files .map((f) => f.size) .reduce((a, b) => a + b, 0) const torrentInfo = `${numFiles} files, ${prettyBytes(totalBytes)}` return ( <div className='create-torrent'> <Heading level={1}>Create torrent {this.state.defaultName}</Heading> <div className='torrent-info'>{torrentInfo}</div> <div className='torrent-attribute'> <label>Path:</label> <div>{this.state.pathPrefix}</div> </div> <ShowMore style={{ marginBottom: 10 }} hideLabel='Hide advanced settings...' showLabel='Show advanced settings...'> {this.renderAdvanced()} </ShowMore> <div className='float-right'> <FlatButton className='control cancel' label='Cancel' style={{ marginRight: 10 }} onClick={dispatcher('cancel')} /> <RaisedButton className='control create-torrent-button' label='Create Torrent' primary onClick={this.handleSubmit} /> </div> </div> ) } // Renders everything after clicking Show Advanced...: // * Is Private? (private torrents, not announced to DHT) // * Announce list (trackers) // * Comment renderAdvanced () { // Create file list const maxFileElems = 100 const files = this.state.files const fileElems = files.slice(0, maxFileElems).map((file, i) => { const relativePath = path.relative(this.state.pathPrefix, file.path) return (<div key={i}>{relativePath}</div>) }) if (files.length > maxFileElems) { fileElems.push(<div key='more'>+ {files.length - maxFileElems} more</div>) } // Align the text fields const textFieldStyle = { width: '' } const textareaStyle = { margin: 0 } return ( <div key='advanced' className='create-torrent-advanced'> <div key='private' className='torrent-attribute'> <label>Private:</label> <Checkbox className='torrent-is-private control' style={{display: ''}} checked={this.state.isPrivate} onCheck={this.setIsPrivate} /> </div> <div key='trackers' className='torrent-attribute'> <label>Trackers:</label> <TextField className='torrent-trackers control' style={textFieldStyle} textareaStyle={textareaStyle} multiLine rows={2} rowsMax={10} value={this.state.trackers} onChange={this.setTrackers} /> </div> <div key='comment' className='torrent-attribute'> <label>Comment:</label> <TextField className='torrent-comment control' style={textFieldStyle} textareaStyle={textareaStyle} hintText='Optionally describe your torrent...' multiLine rows={2} rowsMax={10} value={this.state.comment} onChange={this.setComment} /> </div> <div key='files' className='torrent-attribute'> <label>Files:</label> <div>{fileElems}</div> </div> </div> ) } }
JavaScript
class Admin { constructor() { this.configService = null; this.client = null; this.authorizedUsers = []; this.ignoredUsers = []; } load(client, configService, _env) { this.client = client; this.configService = configService; this.authorizedUsers = this.loadAuthorizedUsers(); this.ignoredUsers = JSON.parse(fs.readFileSync(configService.pathToIgnoredUsers, 'utf8')); this.client.addListener('message', (from, to, text, message) => { // .trust / .untrust if (text.startsWith(`.trust `) && this.isAuthorized(message)) { const nick = text .slice() .replace(`.trust `, '') .trim(); return this.addUser(nick).then(() => this.client.say(to === this.client.nick ? from : to, `${nick}: your wish is my command.`)); } if (text.startsWith(`.untrust `) && this.isAuthorized(message)) { const nick = text .slice() .replace(`.untrust `, '') .trim(); return this.removeUser(nick).then(() => this.client.say(to === this.client.nick ? from : to, `${nick}: bye felicia.`)); } // .join / .part if (text.startsWith(`.join `) && this.isAuthorized(message)) { return this.joinChannel(text.replace(`.join `, '')); } if (text.startsWith(`.part `) && this.isAuthorized(message)) { return this.partChannel(text.replace(`.part `, '')); } // .ignore / .unignore if (text.startsWith(`.ignore `) && this.isAuthorized(message)) { const nick = text .slice() .replace(`.ignore `, '') .trim(); return this.ignoreUser(nick) .then(() => this.client.say(to === this.client.nick ? from : to, `${nick} who? :)`)) .catch(() => { }); } if (text.startsWith(`.unignore `) && this.isAuthorized(message)) { const nick = text .slice() .replace(`.unignore `, '') .trim(); return this.unignoreUser(nick) .then(() => this.client.say(to === this.client.nick ? from : to, `Oh there's ${nick}!`)) .catch(() => { }); } // .say let matches = text.match(/^\.say to (.+?) (.+)/); if (matches && this.isAuthorized(message)) { const [, destination, message] = matches; return this.client.say(destination, message); } // .emote matches = text.match(/^\.emote to (.+?) (.+)/); if (matches && this.isAuthorized(message)) { const [, destination, message] = matches; return this.client.action(destination, message); } // .nick if (text.startsWith('.nick ') && this.isAuthorized(message)) { // Update nick const newNick = text.replace(`.nick `, '').trim(); this.client.send('NICK', newNick); // Update config file const config = this.configService.getConfig(); config.nickname = newNick; this.configService.updateConfig(config); } }); return true; } ignoreUser(user) { return this._whoisUser(user).then(userObject => this._addToIgnoreList(userObject)); } unignoreUser(user) { return this._whoisUser(user).then(userObject => this._removeFromIgnoreList(userObject)); } isAuthorized(user) { return this.authorizedUsers.findIndex(u => u.nick === user.nick && u.user === user.user && u.host === user.host) !== -1; } loadAuthorizedUsers() { if (!fs.existsSync(pathToAuthorizedUsers)) { fs.writeFileSync(pathToAuthorizedUsers, JSON.stringify([], null, 2)); return []; } return JSON.parse(fs.readFileSync(pathToAuthorizedUsers, 'utf8')); } addUser(user) { return new Promise((resolve, _reject) => { this._whoisUser(user).then(userObject => { this.authorizedUsers.push({ nick: userObject.nick, user: userObject.user, host: userObject.host, }); fs.writeFileSync(pathToAuthorizedUsers, JSON.stringify(this.authorizedUsers, null, 2)); resolve(); }); }); } removeUser(user) { return new Promise((resolve, _reject) => { this._whoisUser(user).then(_userObject => { this.authorizedUsers = this.authorizedUsers.filter(u => u.nick !== user); fs.writeFileSync(pathToAuthorizedUsers, JSON.stringify(this.authorizedUsers, null, 2)); resolve(); }); }); } joinChannel(channel) { this.client.join(channel); const config = this.configService.getConfig(); config.channels.push(channel); this.configService.updateConfig(config); } partChannel(channel) { this.client.part(channel); const config = this.configService.getConfig(); if (config.channels.includes(channel)) { config.channels = config.channels.filter(c => c !== channel); this.configService.updateConfig(config); } } _whoisUser(user) { return new Promise((resolve, reject) => { this.client.whois(user, whois => { // If the user exists, we'll have all data. Otherwise, we will only have 'nick'. if (!whois.host) { return reject(whois); } const userObject = { nick: whois.nick, user: whois.user, host: whois.host, realname: whois.realname, account: whois.account, }; resolve(userObject); }); }); } _addToIgnoreList(ignored) { this.ignoredUsers.push(ignored); fs.writeFileSync(path.join(this.configService.pathToIgnoredUsers), JSON.stringify(this.ignoredUsers)); this.configService.reloadIgnoredUsers(); } _removeFromIgnoreList(ignored) { const originalLength = this.ignoredUsers.length; this.ignoredUsers = this.ignoredUsers.filter(u => JSON.stringify(u) !== JSON.stringify(ignored)); if (this.ignoredUsers.length === originalLength) { // No change. return false; } fs.writeFileSync(path.join(this.configService.pathToIgnoredUsers), JSON.stringify(this.ignoredUsers)); this.configService.reloadIgnoredUsers(); return true; } }
JavaScript
class Application extends View { static title = document.title; static events = { 'click a[href]': 'pushState' }; /** * this is constructor description. * @param {number} arg1 this is arg1 description. * @param {string[]} arg2 this is arg2 description. */ constructor(options = {}) { super(options); const result = this.render(); if (result instanceof Promise) { result.then(() => this.router?.start()); } else { this.router?.start(); } } setup() { if (this.constructor.router) { this.router = new this.constructor.router(this); } if (this.constructor.initializers) { this.constructor.initializers.forEach((i) => i(this)); } } async display(view, options) { const oldView = this.view; this.view = new view(options); await this.view.render(); if (oldView) { replace(oldView.el, this.view.el) oldView.remove(); } else { this.appendView(this.view) } let title = (result(this.view, 'title') || this.title); if (title !== undefined) { document.title = title; } return this.view; } appendView (view) { this.el.appendChild(view.el) } navigateTo(path) { this.router.navigateTo(path); } pushState (e) { if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) { return; } const destination = e.delegateTarget; if (destination.origin !== location.origin) { return; } if (this.router.handlerForPath(destination.pathname)) { e.preventDefault(); this.navigateTo(destination.pathname); } } }
JavaScript
class AgoraView extends react_1.default.Component { /** * render * * It would render view for VideoStream */ render() { return (react_1.default.createElement(RCTAgoraView, Object.assign({}, this.getHTMLProps()))); } /** * getHTMLProps * * get agora view props */ getHTMLProps() { let htmlProps = {}; for (let key in this.props) { htmlProps[key] = this.props[key]; } return htmlProps; } }
JavaScript
class ModelInputs { constructor() { this.age = 45; this.sex = "Female"; this.country = "United States"; this.state = "California"; this.flatteningDate = moment("2020-03-19").toDate(); this.scenario = "current"; // @TODO get rid of this this.rBefore = 2.2; this.rAfter = 0.5; } }
JavaScript
class ModelManager { /** * @todo the query runs right now in index.js, which is inconvenient. figure out a better way * * @param {Object} queryData Result of running the model query */ static initWithData(queryData) { this.modelInputs = new ModelInputs(); this.scenarios = {}; this.historicalData = queryData; this.presetScenarios = this.generatePresetScenarios(); this.presetDisplayData = {}; for(let key in this.presetScenarios) { this.presetDisplayData[key] = this.presetScenarios[key].getDisplayData(); } this.updateModelInputs(this.modelInputs); } static getDailyData(country, state) { const dailyData = this.historicalData.allDailyDataCsv.nodes.filter(x => { return x.country === country && x.state === state; }).map(x => { return { date: x.date, confirmedCases: parseFloat(x.confirmedCases), confirmedDeaths: parseFloat(x.confirmedDeaths) } }); if(dailyData.length === 0) { alert("Unable to find data for country ", country, " and state/province ", state); return []; } return dailyData; } /** Runs the preset scenarios once. These are not affected by model parameter changes */ static generatePresetScenarios() { var result = {}; for(let [key, presetData] of PresetScenarios.entries()) { const scenarioData = {...BASE_SCENARIO}; // Make modifications Object.assign(scenarioData, presetData); // Special case to pull in Wuhan data for now const { country, state } = scenarioData; const dailyData = this.getDailyData(country, state); const population = LocationManager.lookupLocation(country, state).population; // Run the scenario // console.log("Running preset scenario ", JSON.stringify(scenarioData)); result[key] = new BasicDiseaseModelScenario( scenarioData.category, scenarioData.name, dailyData, population, scenarioData.rBefore, scenarioData.cfrBefore, scenarioData.rAfter, scenarioData.cfrAfter, scenarioData.thresholdDate ); } return result; } static updateModelInputs(newModelInputs) { this.modelInputs = newModelInputs; console.log("New modelInputs", this.modelInputs); // console.log("model.updateModelInputs", newModelInputs); const { country, state, rAfter, rBefore, flatteningDate } = newModelInputs; // Load daily data and location data const { rInitial, cfrInitial, population } = LocationManager.lookupLocation(country, state); const dailyData = this.getDailyData(country, state); // Create and run the preset scenarios // Base scenario. Construct additional scenarios from this const locationScenario = {...BASE_SCENARIO}; if(rAfter) locationScenario.rAfter = rAfter; if(rBefore) locationScenario.rBefore = rBefore; if(rInitial) locationScenario.rBefore = rInitial; if(cfrInitial) locationScenario.cfrBefore = cfrInitial; if(flatteningDate) locationScenario.thresholdDate = flatteningDate; console.log("Running current scenario ", JSON.stringify(locationScenario)); const diseaseModel = new BasicDiseaseModelScenario( locationScenario.category, locationScenario.name, dailyData, population, locationScenario.rBefore, locationScenario.cfrBefore, locationScenario.rAfter, locationScenario.cfrAfter, locationScenario.thresholdDate ); this.scenarios = { current: diseaseModel }; return this.scenarios; } /** Get display data for all scenarios and preset scenarios */ static getDisplayData() { var result = {} for(let key in this.scenarios) { result[key] = this.scenarios[key].getDisplayData(); } for(let key in this.presetScenarios) { result[key] = this.presetDisplayData[key]; } return result; } }
JavaScript
class PKGMetadata { constructor (opts) { const { icon, keepTMP, metaData, pkg, pkgCachePath, rcData, rcFilePath, resFilePath, rhPath, targets } = opts this.uiid = uuidv4() this.tmpPath = path.join(__dirname, '.tmp', this.uiid) this.binTMPPath = path.join(this.tmpPath, 'bin') this.cachePath = path.join(__dirname, '.cache') this.resPath = path.join(__dirname, 'res') this.pkgCachePath = pkgCachePath || path.join(this.cachePath, 'pkg-cache') process.env.PKG_CACHE_PATH = this.pkgCachePath this.keepTMP = keepTMP this.unparsedTargets = targets || ['host'] this.pkg = pkg this.rhPath = rhPath this.metaData = metaData || {} this.icon = icon ? path.resolve(icon) : null this.rcData = rcData || {} this.rcFilePath = rcFilePath this.resFilePath = resFilePath } async run () { console.log('Start...') await ensureDir([ this.cachePath, this.tmpPath, this.binTMPPath, this.pkgCachePath ]) // scuffed hack bc env gets used too early otherwise pkgFetch = require('pkg-fetch') this.parseTargets() await this.fetchResourceHacker() await this.fetchBinaries() await this.generateRES() await this.editMetaData() if (this.pkg) { await this.runPKG() await this.cleanup() } } async fetchResourceHacker () { console.log('fetch ResourceHacker..') if (this.rhPath) { this.rhPath = path.resolve(this.rhPath) return } const rhPathDir = path.join(this.cachePath, 'rh') const rhPathZip = rhPathDir + '.zip' this.rhPath = path.join(rhPathDir, 'ResourceHacker.exe') if (!fs.existsSync(rhPathZip)) { const res = await fetch(RH_URL) const zipOut = fs.createWriteStream(rhPathZip) res.body.pipe(zipOut) await waitOnStreamEnd(zipOut) } if (!fs.existsSync(this.rhPath)) { const zipIn = fs.createReadStream(rhPathZip) const exeOut = unzipper.Extract({ path: rhPathDir }) zipIn.pipe(exeOut) await waitOnStreamEnd(exeOut) } } async fetchBinaries () { console.log('Fetch base binaries...') console.log('targets: ') console.log(this.targets) for (const target of this.targets) { target.fullPath = await pkgFetch.need(target.target) target.fileName = path.basename(target.fullPath) } } generateRCData () { console.log('Generate RC data...') const exeName = this.metaData.name + '.exe' const customData = { FileDescription: this.metaData.descriptios, FileVersion: this.metaData.version, InternalName: exeName, LegalCopyright: this.metaData.legal, OriginalFilename: exeName, ProductName: this.metaData.name, ProductVersion: this.metaData.version } return { ...removeNullProperties(customData), ...removeNullProperties(this.rcData) } } async generateRES () { if (this.resFilePath) { return } console.log('generate res file...') this.resFilePath = path.join(this.tmpPath, 'bin.res') if (!this.rcFilePath) { this.rcFilePath = path.join(this.tmpPath, 'bin.rc') const finalRCDAta = this.generateRCData() console.log(finalRCDAta) let rcSample = await fs.readFile(path.join(this.resPath, 'q_sample.rc')) rcSample = rcSample.toString() let rc = rcSample.replace('#fileVersion#', toCommaVersion(finalRCDAta.FileVersion)) rc = rc.replace('#productVersion#', toCommaVersion(finalRCDAta.ProductVersion)) let block = '' for (const [key, value] of Object.entries(finalRCDAta)) { block += `\t\tVALUE "${key}", "${value}"\n` } rc = rc.replace('#fileInfoBlock#', block) await fs.writeFile(this.rcFilePath, rc) } await this.execRHInternal({ open: this.rcFilePath, save: this.resFilePath, action: 'compile' }) } async editMetaData () { console.log('Edit metadata...') this.changePKGEnv(this.binTMPPath) if (this.icon) { console.log('Prepare icon...') const iconType = this.icon.split('.').pop() if (iconType === 'ico') { this.finalIcon = this.icon } else { this.finalIcon = await this.prepareIcon() } } for (const target of this.targets) { if (target.target.platform !== 'win') { continue } console.log('Edit base binary of target: ' + target.name) const pkgTMPPath = path.join(this.binTMPPath, 'v2.6') fs.ensureDir(pkgTMPPath) target.tmpPath = path.join(pkgTMPPath, target.fileName) await fs.copyFile(target.fullPath, target.tmpPath) await this.execRHInternal({ open: target.tmpPath, save: target.tmpPath, action: 'addoverwrite', resource: this.resFilePath }) if (this.icon) { await this.execRHInternal({ open: target.tmpPath, save: target.tmpPath, action: 'addoverwrite', resource: this.finalIcon, mask: 'ICONGROUP,1,' }) } } } async prepareIcon () { console.log('Generate icon...') if (!this.icon) { return } const stat = await fs.lstat(this.icon) const icons = { 16: null, 24: null, 32: null, 48: null, 64: null, 128: null, 256: null } const tmpIcons = {} let biggestIcon = 0 if (stat.isFile()) { const dimensions = sizeOf(this.icon) tmpIcons[dimensions.width] = this.icon biggestIcon = dimensions.width } else { const iconPaths = await fs.readdir(this.icon) iconPaths.forEach(i => { const name = i.split('.')[0] const size = parseInt(name) biggestIcon = size > biggestIcon ? size : biggestIcon tmpIcons[name] = path.join(this.icon, i) }) } Object.keys(tmpIcons).filter(key => key in icons).forEach(key => { icons[key] = tmpIcons[key] }) const biggestIconBuffer = await fs.readFile(icons[biggestIcon]) const tmpIconPath = path.join(this.tmpPath, 'icon') const tmpIconRawPath = path.join(tmpIconPath, 'raw') await fs.ensureDir(tmpIconRawPath) await Promise.all(Object.entries(icons).map(async ([size, i]) => { size = parseInt(size) const iIconPath = path.join(tmpIconRawPath, size + '.png') if (i === null) { await sharp(biggestIconBuffer) .png() .resize(size, size) .toFile(iIconPath) } else { await fs.copyFile(i, iIconPath) } })) const tmpIconFinalPath = path.join(tmpIconPath, 'final') await fs.ensureDir(tmpIconFinalPath) await icongen(tmpIconRawPath, tmpIconFinalPath, { report: true, ico: { name: 'icon' } }) return path.join(tmpIconFinalPath, 'icon.ico') } async runPKG () { console.log('Run pkg...') let args = this.pkg.args if (!args) { args = [ this.pkg.src, '--target', this.unparsedTargets.join(','), '--out-path', this.pkg.out ] } await pkgExec(args) } async cleanup () { console.log('cleanup') if (!this.keepTMP) { await fs.remove(this.tmpPath) } } execRHInternal (opts) { return PKGMetadata.execRH(this.rhPath, opts) } async compareExeWithRC (exe, rc) { console.log(exe) console.log(rc) const tmpRCFile = path.join(this.tmpPath, 'exeRc.rc') await this.execRHInternal({ open: exe, save: tmpRCFile, action: 'extract', mask: 'VERSIONINFO,,' }) // rh.exe -open source.exe -save .\icons -action extract -mask ICONGROUP,, -log CON const file1 = (await fs.readFile(tmpRCFile)).toString('utf-8').trim() const rcContent = (await fs.readFile(rc)).toString('utf-8').trim() // console.log(file1) // console.log(rcContent) const diff = JsDiff.diffTrimmedLines(file1, rcContent) console.log(JSON.stringify(diff, null, 3)) } parseTargets () { // [ 'node6-macos-x64', 'node6-linux-x64' ] const { hostArch, hostPlatform, isValidNodeRange, knownArchs, knownPlatforms, toFancyArch, toFancyPlatform } = pkgFetch.system const hostNodeRange = 'node' + process.version.match(/^v(\d+)/)[1] const targets = [] for (const item of this.unparsedTargets) { const target = { nodeRange: hostNodeRange, platform: hostPlatform, arch: hostArch, name: item } if (item !== 'host') { for (const token of item.split('-')) { if (!token) continue if (isValidNodeRange(token)) { target.nodeRange = token continue } const p = toFancyPlatform(token) if (knownPlatforms.indexOf(p) >= 0) { target.platform = p continue } const a = toFancyArch(token) if (knownArchs.indexOf(a) >= 0) { target.arch = a continue } throw new Error('invalid target: ' + item) } } targets.push({ name: item, target }) } this.targets = targets } changePKGEnv (p) { decache('pkg-fetch') process.env.PKG_CACHE_PATH = p pkgExec = require('pkg').exec } static async execRH (path, opts) { const possibleOpts = [ 'open', 'action', 'save', 'resource', 'mask' ] const args = [] possibleOpts.forEach(o => { if (opts[o]) { args.push('-' + o) args.push(opts[o]) } }) return execFileP(path, args) } }
JavaScript
class WizardTab extends UI5Element { static get metadata() { return metadata; } static get render() { return litRender; } static get styles() { return WizardTabCss; } static get template() { return WizardTabTemplate; } static get dependencies() { return [Icon]; } _onclick() { if (!this.disabled) { this.fireEvent("selection-change-requested"); } } _onkeydown(event) { if (this.disabled) { return; } if (isSpace(event) || isEnter(event)) { event.preventDefault(); this.fireEvent("selection-change-requested"); } } _onkeyup(event) { if (this.disabled) { return; } if (isSpace(event)) { this.fireEvent("selection-change-requested"); } } _onfocusin() { if (this.disabled) { return; } this.fireEvent("focused"); } get tabIndex() { return this.disabled ? undefined : this._tabIndex; } get hasTexts() { return this.titleText || this.subtitleText; } get accInfo() { return { "ariaSetsize": this._wizardTabAccInfo && this._wizardTabAccInfo.ariaSetsize, "ariaPosinset": this._wizardTabAccInfo && this._wizardTabAccInfo.ariaPosinset, "ariaLabel": this._wizardTabAccInfo && this._wizardTabAccInfo.ariaLabel, "ariaCurrent": this.selected ? "true" : undefined, "ariaDisabled": this.disabled ? "true" : undefined, }; } }
JavaScript
class IndexPage extends React.Component { componentDidMount() { Router.push(linkPrefix + '/configuration'); } render() { return <div />; } }
JavaScript
class Calender extends Component { constructor() { super(...arguments); this.data = extend([], /*,scheduleData,*/ null, true); } onPopupOpen(args) { args.cancel = true; } render() { return ( <div className="container-fluid"> <ScheduleComponent width="100%" height="550px" selectedDate={new Date(2018, 1, 15)} ref={(schedule) => (this.scheduleObj = schedule)} eventSettings={{ dataSource: this.data }} popupOpen={this.onPopupOpen.bind(this)} > <ViewsDirective> <ViewDirective option="Day" /> <ViewDirective option="Week" /> <ViewDirective option="WorkWeek" /> <ViewDirective option="Month" /> </ViewsDirective> <Inject services={[Day, Week, WorkWeek, Month]} /> </ScheduleComponent> </div> ); } }
JavaScript
class NeedParams extends NeedParams_1.default { constructor(values) { super(NeedParams._protocol, NeedParams._type, values); if (!!values) { this.startAt = values.startAt; this.startLocation = { lat: values.startLocation.lat, long: values.startLocation.long, }; this.endLocation = { lat: values.endLocation.lat, long: values.endLocation.long, }; this.vehicleType = values.vehicleType; this.maxAltitude = values.maxAltitude; } } static getMessageType() { return NeedParams._type; } static getMessageProtocol() { return NeedParams._protocol; } serialize() { const formattedParams = super.serialize(); Object.assign(formattedParams, { startLocation: this.startLocation, endLocation: this.endLocation, vehicleType: this.vehicleType, maxAltitude: this.maxAltitude, }); return formattedParams; } deserialize(json) { super.deserialize(json); this.startLocation = json.startLocation; this.endLocation = json.endLocation; this.vehicleType = json.vehicleType; this.maxAltitude = json.maxAltitude; } }
JavaScript
class KnobInput { constructor(containerElement, options = {}) { if (!isHtmlElement(containerElement)) { throw new Error('KnobInput constructor must receive a valid container element'); } // settings const step = options.step || 'any'; const min = typeof options.min === 'number' ? options.min : 0; const max = typeof options.max === 'number' ? options.max : 1; this.initial = typeof options.initial === 'number' ? options.initial : 0.5 * (min + max); this.dragResistance = typeof options.dragResistance === 'number' ? options.dragResistance : 100; this.dragResistance *= 3 / (max - min); this.wheelResistance = typeof options.wheelResistance === 'number' ? options.wheelResistance : 100; this.wheelResistance *= 40 / (max - min); // setup elements this._input = crel('input', { class: styles.knobInputBase, type: 'range', step, min, max, value: this.initial }); containerElement.appendChild(this._input); this._container = containerElement; this._container.classList.add(styles.knobInputContainer); // misc variables this.transformProperty = getTransformProperty(); this.focusActiveClass = typeof options.focusActiveClass === 'string' ? options.focusActiveClass : null; this.dragActiveClass = typeof options.dragActiveClass === 'string' ? options.dragActiveClass : null; this._activeDrag = false; // event listeners this.handleInputChange = this.handleInputChange.bind(this); this.handleTouchStart = this.handleTouchStart.bind(this); this.handleTouchMove = this.handleTouchMove.bind(this); this.handleTouchEnd = this.handleTouchEnd.bind(this); this.handleTouchCancel = this.handleTouchCancel.bind(this); this.handleMouseDown = this.handleMouseDown.bind(this); this.handleMouseMove = this.handleMouseMove.bind(this); this.handleMouseUp = this.handleMouseUp.bind(this); this.handleMouseWheel = this.handleMouseWheel.bind(this); this.handleMiddleClick = this.handleMiddleClick.bind(this); this.handleDoubleClick = this.handleDoubleClick.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); this._input.addEventListener('change', this.handleInputChange); this._input.addEventListener('touchstart', this.handleTouchStart); this._input.addEventListener('mousedown', this.handleMouseDown); this._input.addEventListener('wheel', this.handleMouseWheel); this._input.addEventListener('auxclick', this.handleMiddleClick); this._input.addEventListener('dblclick', this.handleDoubleClick); this._input.addEventListener('focus', this.handleFocus); this._input.addEventListener('blur', this.handleBlur); } setupVisuals = (updateCallback, visualElement) => { if (typeof updateCallback === 'function') { this.updateVisuals = updateCallback; } else { throw new Error('KnobInput setupVisuals must receive a valid updateCallback function'); } if (!isHtmlElement(visualElement)) { visualElement.classList.add(styles.knobInputVisual); } this.updateToInputValue(); }; // handlers handleInputChange() { this.updateToInputValue(); } handleTouchStart(evt) { this.clearDrag(); evt.preventDefault(); const touch = evt.changedTouches.item(evt.changedTouches.length - 1); this._activeDrag = touch.identifier; this.startDrag(touch.clientY); // drag update/end listeners document.body.addEventListener('touchmove', this.handleTouchMove); document.body.addEventListener('touchend', this.handleTouchEnd); document.body.addEventListener('touchcancel', this.handleTouchCancel); } handleTouchMove(evt) { const activeTouch = this.findActiveTouch(evt.changedTouches); if (activeTouch) { this.updateDrag(activeTouch.clientY); } else if (!this.findActiveTouch(evt.touches)) { this.clearDrag(); } } handleTouchEnd(evt) { const activeTouch = this.findActiveTouch(evt.changedTouches); if (activeTouch) { this.finalizeDrag(activeTouch.clientY); } } handleTouchCancel(evt) { if (this.findActiveTouch(evt.changedTouches)) { this.clearDrag(); } } handleMouseDown(evt) { if (evt.buttons & 0b1) { // left mouse button this.clearDrag(); evt.preventDefault(); this._activeDrag = true; this.startDrag(evt.clientY); // drag update/end listeners document.body.addEventListener('mousemove', this.handleMouseMove); document.body.addEventListener('mouseup', this.handleMouseUp); } } handleMouseMove(evt) { if (evt.buttons & 0b1) { // left mouse button held this.updateDrag(evt.clientY); } else { this.finalizeDrag(evt.clientY); } } handleMouseUp(evt) { this.finalizeDrag(evt.clientY); } handleMouseWheel(evt) { evt.preventDefault(); this._input.focus(); this.clearDrag(); this._prevValue = parseFloat(this._input.value); this.updateFromDrag(evt.deltaY, this.wheelResistance); } handleMiddleClick(evt) { if (evt.button === 1) { // middle click; for some reason `buttons` doesn't work with auxclick event this.clearDrag(); this._input.value = this.initial; this.updateToInputValue(); } } handleDoubleClick() { this.clearDrag(); this._input.value = this.initial; this.updateToInputValue(); } handleFocus() { if (this.focusActiveClass) { this._container.classList.add(this.focusActiveClass); } } handleBlur() { if (this.focusActiveClass) { this._container.classList.remove(this.focusActiveClass); } } // dragging startDrag(yPosition) { this._dragStartPosition = yPosition; this._prevValue = parseFloat(this._input.value); this._input.focus(); document.body.classList.add(styles.knobInputDragActive); if (this.dragActiveClass) { this._container.classList.add(this.dragActiveClass); } this._input.dispatchEvent(new InputEvent('knobdragstart')); } updateDrag(yPosition) { const diff = yPosition - this._dragStartPosition; this.updateFromDrag(diff, this.dragResistance); this._input.dispatchEvent(new InputEvent('change')); } finalizeDrag(yPosition) { const diff = yPosition - this._dragStartPosition; this.updateFromDrag(diff, this.dragResistance); this.clearDrag(); this._input.dispatchEvent(new InputEvent('change')); this._input.dispatchEvent(new InputEvent('knobdragend')); } clearDrag() { document.body.classList.remove(styles.knobInputDragActive); if (this.dragActiveClass) { this._container.classList.remove(this.dragActiveClass); } this._activeDrag = false; this._input.dispatchEvent(new InputEvent('change')); // clean up event listeners document.body.removeEventListener('mousemove', this.handleMouseMove); document.body.removeEventListener('mouseup', this.handleMouseUp); document.body.removeEventListener('touchmove', this.handleTouchMove); document.body.removeEventListener('touchend', this.handleTouchEnd); document.body.removeEventListener('touchcancel', this.handleTouchCancel); } updateToInputValue() { if (typeof this.updateVisuals === 'function') { const newVal = parseFloat(this._input.value); this.updateVisuals(this.normalizeValue(newVal), newVal); } } updateFromDrag(dragAmount, resistance) { const newVal = this.clampValue(this._prevValue - (dragAmount/resistance)); this._input.value = newVal; if (typeof this.updateVisuals === 'function') { this.updateVisuals(this.normalizeValue(newVal), newVal); } } // utils clampValue(val) { return Math.min(Math.max(val, parseFloat(this._input.min)), parseFloat(this._input.max)); } normalizeValue(val) { const min = parseFloat(this._input.min); const max = parseFloat(this._input.max); return (val - min) / (max - min); } findActiveTouch(touchList) { for (let i = 0, len = touchList.length; i < len; i += 1) if (this._activeDrag === touchList.item(i).identifier) return touchList.item(i); return null; } // public passthrough methods addEventListener() { this._input.addEventListener.apply(this._input, arguments); } removeEventListener() { this._input.removeEventListener.apply(this._input, arguments); } focus() { this._input.focus.apply(this._input, arguments); } blur() { this._input.blur.apply(this._input, arguments); } // getters/setters get value() { return parseFloat(this._input.value); } set value(val) { this._input.value = val; this.updateToInputValue(); this._input.dispatchEvent(new Event('change')); } // TODO: add getters/setters for other properties like min/max? }
JavaScript
class BaseWebAudioPanner extends BaseEmitter { /** * Creates a new spatializer that uses WebAudio's PannerNode. * @param audioContext - the output WebAudio context */ constructor(audioContext, destination) { super(audioContext, destination); this.panner = audioContext.createPanner(); this.panner.panningModel = "HRTF"; this.panner.distanceModel = "inverse"; this.panner.coneInnerAngle = 360; this.panner.coneOuterAngle = 0; this.panner.coneOuterGain = 0; connect(this.output, this.destination); } copyAudioProperties(from) { super.copyAudioProperties(from); this.panner.panningModel = from.panner.panningModel; this.panner.distanceModel = from.panner.distanceModel; this.panner.coneInnerAngle = from.panner.coneInnerAngle; this.panner.coneOuterAngle = from.panner.coneOuterAngle; this.panner.coneOuterGain = from.panner.coneOuterGain; } /** * Sets parameters that alter spatialization. **/ setAudioProperties(minDistance, maxDistance, rolloff, algorithm, transitionTime) { super.setAudioProperties(minDistance, maxDistance, rolloff, algorithm, transitionTime); this.panner.refDistance = this.minDistance; if (this.algorithm === "logarithmic") { algorithm = "inverse"; } this.panner.distanceModel = algorithm; this.panner.rolloffFactor = this.rolloff; } }
JavaScript
class PdfPage { constructor(pdfJsPage) { this.pdfJsPage = pdfJsPage; // This represents general information about page measurements. // We mainly use this to get the page width/height. this.viewport = pdfJsPage.getViewport({scale: 1}); } get asp() { return this.viewport.width / this.viewport.height; } }
JavaScript
class TenhouYaku { /** @override */ check ({ yakus }) { if (yakus.includes('tenhou')) return { key: 'tenhou', hanValue: 0, yakumanValue: 1 } } }
JavaScript
class Component { /** * initalize component * @abstract * @param {Webpack.Compiler} compiler * @returns {void | Promise<void>} */ initalize(compiler) { } /** * called when files change * @param {Webpack.Compiler} compiler * @param {[string, string][]} filesChanged [absolute, relative] * @returns {void | Promise<void>} */ filesChanged(compiler, filesChanged) { } /** * called when emitted * @param {Webpack.Compilation} compilation * @returns {void | Promise<void>} */ afterEmit(compilation) { } }
JavaScript
class RelationIdMetadata { // --------------------------------------------------------------------- // Constructor // --------------------------------------------------------------------- constructor(options) { this.entityMetadata = options.entityMetadata; this.target = options.args.target; this.propertyName = options.args.propertyName; this.relationNameOrFactory = options.args.relation; this.alias = options.args.alias; this.queryBuilderFactory = options.args.queryBuilderFactory; } // --------------------------------------------------------------------- // Public Methods // --------------------------------------------------------------------- /** * Sets relation id value from the given entity. * * todo: make it to work in embeds as well. */ setValue(entity) { const inverseEntity = this.relation.getEntityValue(entity); if (Array.isArray(inverseEntity)) { entity[this.propertyName] = inverseEntity .map((item) => { return this.relation.inverseEntityMetadata.getEntityIdMixedMap(item); }) .filter((item) => item !== null && item !== undefined); } else { const value = this.relation.inverseEntityMetadata.getEntityIdMixedMap(inverseEntity); if (value !== undefined) entity[this.propertyName] = value; } } // --------------------------------------------------------------------- // Public Builder Methods // --------------------------------------------------------------------- /** * Builds some depend relation id properties. * This builder method should be used only after entity metadata, its properties map and all relations are build. */ build() { const propertyPath = typeof this.relationNameOrFactory === "function" ? this.relationNameOrFactory(this.entityMetadata.propertiesMap) : this.relationNameOrFactory; const relation = this.entityMetadata.findRelationWithPropertyPath(propertyPath); if (!relation) throw new error_1.TypeORMError(`Cannot find relation ${propertyPath}. Wrong relation specified for @RelationId decorator.`); this.relation = relation; } }
JavaScript
class NonPartneredSmallParcelDataInput { /** * Constructs a new <code>NonPartneredSmallParcelDataInput</code>. * Information that you provide to Amazon about a Small Parcel shipment shipped by a carrier that has not partnered with Amazon. * @alias module:client/models/NonPartneredSmallParcelDataInput * @class * @param carrierName {String} The carrier that you are using for the inbound shipment. * @param packageList {module:client/models/NonPartneredSmallParcelPackageInputList} */ constructor(carrierName, packageList) { this['CarrierName'] = carrierName; this['PackageList'] = packageList; } /** * Constructs a <code>NonPartneredSmallParcelDataInput</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:client/models/NonPartneredSmallParcelDataInput} obj Optional instance to populate. * @return {module:client/models/NonPartneredSmallParcelDataInput} The populated <code>NonPartneredSmallParcelDataInput</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new NonPartneredSmallParcelDataInput(); if (data.hasOwnProperty('CarrierName')) { obj['CarrierName'] = ApiClient.convertToType(data['CarrierName'], 'String'); } if (data.hasOwnProperty('PackageList')) { obj['PackageList'] = NonPartneredSmallParcelPackageInputList.constructFromObject(data['PackageList']); } } return obj; } /** * The carrier that you are using for the inbound shipment. * @member {String} CarrierName */ 'CarrierName' = undefined; /** * @member {module:client/models/NonPartneredSmallParcelPackageInputList} PackageList */ 'PackageList' = undefined; }
JavaScript
class LogGroupLogDestination { /** * @stability stable */ constructor(logGroup) { this.logGroup = logGroup; } /** * Binds this destination to the CloudWatch Logs. * * @stability stable */ bind(_stage) { return { destinationArn: this.logGroup.logGroupArn, }; } }
JavaScript
class AccessLogField { /** * The API owner's AWS account ID. * * @stability stable */ static contextAccountId() { return '$context.identity.accountId'; } /** * The identifier API Gateway assigns to your API. * * @stability stable */ static contextApiId() { return '$context.apiId'; } /** * A property of the claims returned from the Amazon Cognito user pool after the method caller is successfully authenticated. * * @param property A property key of the claims. * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html * @stability stable */ static contextAuthorizerClaims(property) { return `$context.authorizer.claims.${property}`; } /** * The principal user identification associated with the token sent by the client and returned from an API Gateway Lambda authorizer (formerly known as a custom authorizer). * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html * @stability stable */ static contextAuthorizerPrincipalId() { return '$context.authorizer.principalId'; } /** * The stringified value of the specified key-value pair of the `context` map returned from an API Gateway Lambda authorizer function. * * @param property key of the context map. * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html * @stability stable */ static contextAuthorizer(property) { return `$context.authorizer.${property}`; } /** * The AWS endpoint's request ID. * * @stability stable */ static contextAwsEndpointRequestId() { return '$context.awsEndpointRequestId'; } /** * The full domain name used to invoke the API. * * This should be the same as the incoming `Host` header. * * @stability stable */ static contextDomainName() { return '$context.domainName'; } /** * The first label of the `$context.domainName`. This is often used as a caller/customer identifier. * * @stability stable */ static contextDomainPrefix() { return '$context.domainPrefix'; } /** * A string containing an API Gateway error message. * * @stability stable */ static contextErrorMessage() { return '$context.error.message'; } /** * The quoted value of $context.error.message, namely "$context.error.message". * * @stability stable */ static contextErrorMessageString() { return '$context.error.messageString'; } /** * A type of GatewayResponse. * * This variable can only be used for simple variable substitution in a GatewayResponse body-mapping template, * which is not processed by the Velocity Template Language engine, and in access logging. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/customize-gateway-responses.html * @stability stable */ static contextErrorResponseType() { return '$context.error.responseType'; } /** * A string containing a detailed validation error message. * * @stability stable */ static contextErrorValidationErrorString() { return '$context.error.validationErrorString'; } /** * The extended ID that API Gateway assigns to the API request, which contains more useful information for debugging/troubleshooting. * * @stability stable */ static contextExtendedRequestId() { return '$context.extendedRequestId'; } /** * The HTTP method used. * * Valid values include: `DELETE`, `GET`, `HEAD`, `OPTIONS`, `PATCH`, `POST`, and `PUT`. * * @stability stable */ static contextHttpMethod() { return '$context.httpMethod'; } /** * The AWS account ID associated with the request. * * @stability stable */ static contextIdentityAccountId() { return '$context.identity.accountId'; } /** * For API methods that require an API key, this variable is the API key associated with the method request. * * For methods that don't require an API key, this variable is * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html * @stability stable */ static contextIdentityApiKey() { return '$context.identity.apiKey'; } /** * The API key ID associated with an API request that requires an API key. * * @stability stable */ static contextIdentityApiKeyId() { return '$context.identity.apiKeyId'; } /** * The principal identifier of the caller making the request. * * @stability stable */ static contextIdentityCaller() { return '$context.identity.caller'; } /** * The Amazon Cognito authentication provider used by the caller making the request. * * Available only if the request was signed with Amazon Cognito credentials. * * @see https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html * @stability stable */ static contextIdentityCognitoAuthenticationProvider() { return '$context.identity.cognitoAuthenticationProvider'; } /** * The Amazon Cognito authentication type of the caller making the request. * * Available only if the request was signed with Amazon Cognito credentials. * * @stability stable */ static contextIdentityCognitoAuthenticationType() { return '$context.identity.cognitoAuthenticationType'; } /** * The Amazon Cognito identity ID of the caller making the request. * * Available only if the request was signed with Amazon Cognito credentials. * * @stability stable */ static contextIdentityCognitoIdentityId() { return '$context.identity.cognitoIdentityId'; } /** * The Amazon Cognito identity pool ID of the caller making the request. * * Available only if the request was signed with Amazon Cognito credentials. * * @stability stable */ static contextIdentityCognitoIdentityPoolId() { return '$context.identity.cognitoIdentityPoolId'; } /** * The AWS organization ID. * * @stability stable */ static contextIdentityPrincipalOrgId() { return '$context.identity.principalOrgId'; } /** * The source IP address of the TCP connection making the request to API Gateway. * * Warning: You should not trust this value if there is any chance that the `X-Forwarded-For` header could be forged. * * @stability stable */ static contextIdentitySourceIp() { return '$context.identity.sourceIp'; } /** * The principal identifier of the user making the request. * * Used in Lambda authorizers. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html * @stability stable */ static contextIdentityUser() { return '$context.identity.user'; } /** * The User-Agent header of the API caller. * * @stability stable */ static contextIdentityUserAgent() { return '$context.identity.userAgent'; } /** * The Amazon Resource Name (ARN) of the effective user identified after authentication. * * @see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html * @stability stable */ static contextIdentityUserArn() { return '$context.identity.userArn'; } /** * The request path. * * For example, for a non-proxy request URL of https://{rest-api-id.execute-api.{region}.amazonaws.com/{stage}/root/child, * this value is /{stage}/root/child. * * @stability stable */ static contextPath() { return '$context.path'; } /** * The request protocol, for example, HTTP/1.1. * * @stability stable */ static contextProtocol() { return '$context.protocol'; } /** * The ID that API Gateway assigns to the API request. * * @stability stable */ static contextRequestId() { return '$context.requestId'; } /** * The request header override. * * If this parameter is defined, it contains the headers to be used instead of the HTTP Headers that are defined in the Integration Request pane. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-override-request-response-parameters.html * @stability stable */ static contextRequestOverrideHeader(headerName) { return `$context.requestOverride.header.${headerName}`; } /** * The request path override. * * If this parameter is defined, * it contains the request path to be used instead of the URL Path Parameters that are defined in the Integration Request pane. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-override-request-response-parameters.html * @stability stable */ static contextRequestOverridePath(pathName) { return `$context.requestOverride.path.${pathName}`; } /** * The request query string override. * * If this parameter is defined, it contains the request query strings to be used instead * of the URL Query String Parameters that are defined in the Integration Request pane. * * @stability stable */ static contextRequestOverrideQuerystring(querystringName) { return `$context.requestOverride.querystring.${querystringName}`; } /** * The response header override. * * If this parameter is defined, it contains the header to be returned instead of the Response header * that is defined as the Default mapping in the Integration Response pane. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-override-request-response-parameters.html * @stability stable */ static contextResponseOverrideHeader(headerName) { return `$context.responseOverride.header.${headerName}`; } /** * The response status code override. * * If this parameter is defined, it contains the status code to be returned instead of the Method response status * that is defined as the Default mapping in the Integration Response pane. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-override-request-response-parameters.html * @stability stable */ static contextResponseOverrideStatus() { return '$context.responseOverride.status'; } /** * The CLF-formatted request time (dd/MMM/yyyy:HH:mm:ss +-hhmm). * * @stability stable */ static contextRequestTime() { return '$context.requestTime'; } /** * The Epoch-formatted request time. * * @stability stable */ static contextRequestTimeEpoch() { return '$context.requestTimeEpoch'; } /** * The identifier that API Gateway assigns to your resource. * * @stability stable */ static contextResourceId() { return '$context.resourceId'; } /** * The path to your resource. * * For example, for the non-proxy request URI of `https://{rest-api-id.execute-api.{region}.amazonaws.com/{stage}/root/child`, * The $context.resourcePath value is `/root/child`. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-step-by-step.html * @stability stable */ static contextResourcePath() { return '$context.resourcePath'; } /** * The deployment stage of the API request (for example, `Beta` or `Prod`). * * @stability stable */ static contextStage() { return '$context.stage'; } /** * The response received from AWS WAF: `WAF_ALLOW` or `WAF_BLOCK`. * * Will not be set if the stage is not associated with a web ACL. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-aws-waf.html * @stability stable */ static contextWafResponseCode() { return '$context.wafResponseCode'; } /** * The complete ARN of the web ACL that is used to decide whether to allow or block the request. * * Will not be set if the stage is not associated with a web ACL. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-aws-waf.html * @stability stable */ static contextWebaclArn() { return '$context.webaclArn'; } /** * The trace ID for the X-Ray trace. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enabling-xray.html * @stability stable */ static contextXrayTraceId() { return '$context.xrayTraceId'; } /** * The authorizer latency in ms. * * @stability stable */ static contextAuthorizerIntegrationLatency() { return '$context.authorizer.integrationLatency'; } /** * The integration latency in ms. * * @stability stable */ static contextIntegrationLatency() { return '$context.integrationLatency'; } /** * For Lambda proxy integration, this parameter represents the status code returned from AWS Lambda, not from the backend Lambda function. * * @stability stable */ static contextIntegrationStatus() { return '$context.integrationStatus.'; } /** * The response latency in ms. * * @stability stable */ static contextResponseLatency() { return '$context.responseLatency'; } /** * The response payload length. * * @stability stable */ static contextResponseLength() { return '$context.responseLength'; } /** * The method response status. * * @stability stable */ static contextStatus() { return '$context.status'; } }
JavaScript
class AccessLogFormat { constructor(format) { this.format = format; } /** * Custom log format. * * You can create any log format string. You can easily get the $ context variable by using the methods of AccessLogField. * * @stability stable * @example * * custom(JSON.stringify({ * requestId: AccessLogField.contextRequestId(), * sourceIp: AccessLogField.contextIdentitySourceIp(), * method: AccessLogFiled.contextHttpMethod(), * userContext: { * sub: AccessLogField.contextAuthorizerClaims('sub'), * email: AccessLogField.contextAuthorizerClaims('email') * } * })) */ static custom(format) { return new AccessLogFormat(format); } /** * Generate Common Log Format. * * @stability stable */ static clf() { const requester = [AccessLogField.contextIdentitySourceIp(), AccessLogField.contextIdentityCaller(), AccessLogField.contextIdentityUser()].join(' '); const requestTime = AccessLogField.contextRequestTime(); const request = [AccessLogField.contextHttpMethod(), AccessLogField.contextResourcePath(), AccessLogField.contextProtocol()].join(' '); const status = [AccessLogField.contextStatus(), AccessLogField.contextResponseLength(), AccessLogField.contextRequestId()].join(' '); return new AccessLogFormat(`${requester} [${requestTime}] "${request}" ${status}`); } /** * Access log will be produced in the JSON format with a set of fields most useful in the access log. * * All fields are turned on by default with the * option to turn off specific fields. * * @stability stable */ static jsonWithStandardFields(fields = { ip: true, user: true, caller: true, requestTime: true, httpMethod: true, resourcePath: true, status: true, protocol: true, responseLength: true, }) { return this.custom(JSON.stringify({ requestId: AccessLogField.contextRequestId(), ip: fields.ip ? AccessLogField.contextIdentitySourceIp() : undefined, user: fields.user ? AccessLogField.contextIdentityUser() : undefined, caller: fields.caller ? AccessLogField.contextIdentityCaller() : undefined, requestTime: fields.requestTime ? AccessLogField.contextRequestTime() : undefined, httpMethod: fields.httpMethod ? AccessLogField.contextHttpMethod() : undefined, resourcePath: fields.resourcePath ? AccessLogField.contextResourcePath() : undefined, status: fields.status ? AccessLogField.contextStatus() : undefined, protocol: fields.protocol ? AccessLogField.contextProtocol() : undefined, responseLength: fields.responseLength ? AccessLogField.contextResponseLength() : undefined, })); } /** * Output a format string to be used with CloudFormation. * * @stability stable */ toString() { return this.format; } }
JavaScript
class BindingsTest { constructor() {} /** * Evaluates 1+1 and returns the result over the chromium.DevTools.Connection. */ evalOneAddOne() { let connection = new Connection(window.TabSocket); let runtime = new Runtime(connection); runtime.evaluate({'expression': '1+1'}).then(function(message) { connection.sendDevToolsMessage( '__Result', {'result': JSON.stringify(message.result.value)}); }); } /** * Evaluates 1+1 and returns the result over the chromium.DevTools.Connection. */ listenForChildNodeCountUpdated() { let connection = new Connection(window.TabSocket); let dom = new DOM(connection); dom.onChildNodeCountUpdated(function(params) { connection.sendDevToolsMessage('__Result', {'result': JSON.stringify(params)}); }); dom.enable().then(function() { return dom.getDocument({}); }).then(function() { // Create a new div which should trigger the event. let div = document.createElement('div'); document.body.appendChild(div); }); } /** * Uses experimental commands to create an isolated world. */ getIsolatedWorldName() { let connection = new Connection(window.TabSocket); let page = new Page(connection); let runtime = new Runtime(connection); runtime.enable().then(function() { runtime.onExecutionContextCreated(function(params) { if (params.context.auxData['isDefault'] === false) { connection.sendDevToolsMessage( '__Result', {'result': 'Created ' + params.context.name}); } }); page.experimental.getResourceTree().then(function(result) { page.experimental.createIsolatedWorld({ 'frameId': result.frameTree.frame.id, 'worldName': 'Test Isolated World' }); }); }); } }
JavaScript
class GoogleSheetsExtension extends Extension { /** * @param {object} config The config for this extension, as the "googlesheets" * property in awpConfig loaded from src/awp-core.js. */ constructor(config, envVars) { super(); assert(config.connector, 'connector is missing in config.'); assert(config.apiHandler, 'apiHandler is missing in config.'); assert(config.gaAccount, 'gaAccount is missing in config.'); this.envVars = envVars; this.connector = config.connector; this.apiHandler = config.apiHandler; this.userTimeZone = GoogleSheetsHelper.getUserTimeZone(); this.clientEmail = GoogleSheetsHelper.getClientEmail(); this.spreadsheetId = GoogleSheetsHelper.getSpreadsheetId(); this.awpVersion = config.awpVersion || 'awp'; this.gaAccount = config.gaAccount; this.locations = null; this.isSendTrackEvent = config.isSendTrackEvent || false; this.debug = config.debug || false; // Default values mappings. this.defaultResultValues = { 'selected': false, }; } /** * beforeRun - Convert location name to id based on location tab. * @param {object} context */ beforeRun(context, options) { let test = context.test; // Update locations if there's WPT settings. if (test.webpagetest && test.webpagetest.settings) { this.locations = this.locations || this.connector.getList('locationsTab'); this.locations.forEach(location => { if (test.webpagetest.settings.location === location.name) { test.webpagetest.settings.locationId = location.id; } }); } } /** * afterRun - Convert location id to name based on location tab. * @param {object} context Context object that contains Test and Result objects. */ afterRun(context, options) { let test = context.test; let result = context.result; // Update locations if there's WPT settings. if (test.webpagetest && test.webpagetest.settings) { // Replace locationId with location name. this.locations = this.locations || this.connector.getList('locationsTab'); this.locations.forEach(location => { if (test.webpagetest.settings.locationId === location.id) { test.webpagetest.settings.location = location.name; } }); } // Format recurring.nextTrigger with user's timezone. if (test.recurring) { if (test.recurring.nextTriggerTimestamp) { test.recurring.nextTriggerTime = GoogleSheetsHelper.getFormattedDate( new Date(test.recurring.nextTriggerTimestamp), this.userTimeZone); } else { test.recurring.nextTriggerTime = ''; } } if (result) { // Format createdDate if (result.createdTimestamp) { result.createdDate = GoogleSheetsHelper.getFormattedDate( new Date(result.createdTimestamp), this.userTimeZone, 'MM/dd/YYYY HH:mm:ss'); } // Format modifiedDate if (result.modifiedTimestamp) { result.modifiedDate = GoogleSheetsHelper.getFormattedDate( new Date(result.modifiedTimestamp), this.userTimeZone, 'MM/dd/YYYY HH:mm:ss'); } // Send action to Google Analytics let type = result.type === TestType.SINGLE ? TrackingType.SUBMIT_SINGLE_TEST : TrackingType.SUBMIT_RECURRING_TEST; this.trackAction(type, this.spreadsheetId, result); // Send retrieved action to Google Analytics. if (result.status === Status.RETRIEVED) { this.trackAction(TrackingType.RESULT, this.spreadsheetId, result); } // Set default values if there's no value assigned for specific properties. Object.keys(this.defaultResultValues).forEach(key => { if (!result[key]) result[key] = this.defaultResultValues[key]; }); } } /** * afterAllRuns - create a trigger for retrieving results if not exists. * @param {object} context Context object that contains all processed Tests * and Result objects. */ afterAllRuns(context, options) { let tests = context.tests || []; let results = context.results || []; options = options || {}; let pendingResults = results.filter(result => { return result.status === Status.SUBMITTED; }); if (pendingResults.length > 0) { let triggerId = this.connector.getSystemVar(SystemVars.RETRIEVE_TRIGGER_ID); if (options.verbose) console.log(`${SystemVars.RETRIEVE_TRIGGER_ID} = ${triggerId}`); if (!triggerId) { triggerId = GoogleSheetsHelper.createTimeBasedTrigger( RETRIEVE_PENDING_RESULTS_FUNC, 10 /* minutes */); this.connector.setSystemVar(SystemVars.RETRIEVE_TRIGGER_ID, triggerId); if (options.verbose) console.log( `Time-based Trigger created for RETRIEVE_PENDING_RESULTS_FUNC: ${triggerId}`); } } } /** * afterRetrieve - Update modifiedDate for the Result, and send analytics * signals to Google Analytics. * @param {object} context Context object that contains the processed Result. */ afterRetrieve(context, options) { let result = context.result; // Format modifiedDate if (result.modifiedTimestamp) { result.modifiedDate = GoogleSheetsHelper.getFormattedDate( new Date(result.modifiedTimestamp), this.userTimeZone, 'MM/dd/YYYY HH:mm:ss'); } // Send retrieved action to Google Analytics. if (result.status === Status.RETRIEVED) { this.trackAction(TrackingType.RESULT, this.spreadsheetId, result); } } /** * afterAllRetrieves - Collect all latest retrieved Results for each label, * and delete the trigger for retrieving results if all results are done. * @param {object} context Context object that contains all processed Tests * and Result objects. */ afterAllRetrieves(context, options) { let googlesheets = (options || {}).googlesheets || {}; // Skip when there's no newly updated results from the context. if (!context.results || context.results.length === 0) return; // Get all tabIds of results tabs. let resultsTabIds = Object.keys(this.connector.tabConfigs).filter(tabId => { return this.connector.tabConfigs[tabId].tabRole === 'results'; }); let pendingResults = []; // Get results from all Results tab. resultsTabIds.forEach(tabId => { let tabConfig = this.connector.tabConfigs[tabId]; let results = this.connector.getResultList({ googlesheets: {resultsTab: tabId}, filters: [`status==="${Status.SUBMITTED}"`], }); pendingResults = pendingResults.concat(results); }); if (pendingResults.length === 0) { if (options.verbose) { console.log('Deleting Trigger for RETRIEVE_PENDING_RESULTS_FUNC...'); } GoogleSheetsHelper.deleteTriggerByFunction(RETRIEVE_PENDING_RESULTS_FUNC); this.connector.setSystemVar(SystemVars.RETRIEVE_TRIGGER_ID, ''); } } /** * trackAction - Tracking with pageview * * @param {TrackingType} trackingType A TrackingType, e.g. TrackingType.RESULT. * @param {string} sheetId GoogleSheets ID. * @param {object} result Processed Result object. */ trackAction(trackingType, sheetId, result) { let testedUrl = result.url || result.origin || 'No given URL'; let referral = this.awpVersion || 'awp'; let url; // FIXME: Load the list of data sources from awpConfig instead of hardcoded. let dataSources = ['webpagetest', 'psi', 'cruxbigquery', 'cruxapi']; let activeDataSources = []; dataSources.forEach(dataSource => { if (result[dataSource]) { activeDataSources.push(dataSource); } }); if (activeDataSources.length) { referral += '/' + activeDataSources.join('/'); } // Record legacy GA event. if (this.isSendTrackEvent) { url = this.gaEventURL(sheetId, trackingType, testedUrl); this.apiHandler.fetch(url); if (this.debug) console.log(url); } // Record tests with perf budget with Pageview notation. let customValues = this.getCustomValues(trackingType, result) || {}; url = this.gaPageViewURL(referral, sheetId, testedUrl, customValues); let response = this.apiHandler.fetch(url); if (this.debug) console.log('trackAction: ', url); if (this.debug && response.statusCode==200) { console.log('trackAction response: ', response.body); } } /** * trackError - Record an error event to Google Analytics. * @param {string} sheetId GoogleSheets ID. * @param {string} errorStr Error details. */ trackError(sheetId, errorStr) { this.apiHandler.fetch(this.gaEventURL(sheetId, 'Error', errorStr)); } /** * getCustomValues - Return the object of full list of custom metrics and * dimensions used for tracking with GoogleAnalytics. * @param {TrackingType} trackingType A TrackingType, e.g. TrackingType.RESULT. * @param {object} result Processed Result object. */ getCustomValues(trackingType, result) { if (result.budgets) { let hasBudgets = false; let underBudgets = {}; let budgets = result.budgets.budget || {}; let metrics = result.budgets.metrics || {}; Object.keys(budgets).forEach(key => { if (budgets[key] > 0) hasBudgets = true; if (metrics[key] && metrics[key].overRatio >= 0) { underBudgets[key] = true; } }); return { 'cd1': trackingType, // Custom dimensions as booleans 'cd2': hasBudgets || null, 'cd3': underBudgets['SpeedIndex'] || null, 'cd4': underBudgets['TimeToInteractive'] || null, 'cd5': underBudgets['Javascript'] || null, 'cd6': underBudgets['CSS'] || null, 'cd7': underBudgets['Fonts'] || null, 'cd8': underBudgets['Images'] || null, 'cd9': underBudgets['Videos'] || null, 'cd10': underBudgets['FirstContentfulPaint'] || null, // Custom metrics 'cm1': (metrics['SpeedIndex'] || {}).metricsValue || null, 'cm2': budgets['SpeedIndex'] || null, 'cm3': (metrics['TimeToInteractive'] || {}).metricsValue || null, 'cm4': budgets['TimeToInteractive'] || null, 'cm5': (metrics['Javascript'] || {}).metricsValue || null, 'cm6': budgets['Javascript'] || null, 'cm7': (metrics['CSS'] || {}).metricsValue || null, 'cm8': budgets['CSS'] || null, 'cm9': (metrics['Fonts'] || {}).metricsValue || null, 'cm10': budgets['Fonts'] || null, 'cm11': (metrics['Images'] || {}).metricsValue || null, 'cm12': budgets['Images'] || null, 'cm13': (metrics['Videos'] || {}).metricsValue || null, 'cm14': budgets['Videos'] || null, 'cm15': (metrics['FirstContentfulPaint'] || {}).metricsValue || null, 'cm16': budgets['FirstContentfulPaint'] || null, }; } else { return {}; } } /** * Get tracking URL with pageview to Google Analytics * @param {string} referral * @param {string} sheetId * @param {string} testedUrl * @param {string} customValues Custom dimensions and metrics in 'cd1' or 'cm1' format. * @return {string} */ gaPageViewURL(referral, sheetId, testedUrl, customValues) { assert(referral, 'referral is missing in gaPageViewURL'); assert(sheetId, 'sheetId is missing in gaPageViewURL'); assert(testedUrl, 'testedUrl is missing in gaPageViewURL'); let customs = customValues ? Object.keys(customValues).map(x => x + '=' + customValues[x]) : []; // Random ID to prevent browser caching. let cacheBuster = Math.round(Date.now() / 1000).toString(); let urlParams = [ 'v=1', 't=pageview', 'dl=' + sheetId, // Tested URL as active Page 'dr=https://' + encodeURI(referral), // Referral Source 'ul=en-us', 'de=UTF-8', 'dt=' + testedUrl, // Page Title 'cid=' + this.clientEmail || 'anonymous', 'uid=' + this.clientEmail || 'anonymous', 'tid=' + this.gaAccount, 'z=' + cacheBuster, customs.join('&'), ]; let trackingUrl = 'https://ssl.google-analytics.com/collect?' + urlParams.join('&'); return trackingUrl; } /** * Get tracking URL with event to Google Analytics * @param {type} spreadsheetId description * @param {type} action description * @param {type} label description * @return {type} description */ gaEventURL(spreadsheetId, action, label) { // Random ID to prevent browser caching. var cacheBuster = Math.round(Date.now() / 1000).toString(); let clientEmail = this.clientEmail; // Event Category set to Google Spreadsheets. var eventCategory = encodeURIComponent(spreadsheetId || 'Unknown Google Spreadsheets'); // Set event action as functions, like runTest, amountBatchAutoTests, etc. var eventAction = encodeURIComponent(action || 'Unknown Action'); // Set label as tested URLs var eventLabel = encodeURIComponent(label || 'Unknown Label'); var trackingUrl = [ 'https://ssl.google-analytics.com/collect?', 'v=1', 't=event', 'tid=' + this.gaAccount, 'cid=' + clientEmail, 'uid=' + clientEmail, 'z=' + cacheBuster, 'ec=' + eventCategory, 'ea=' + eventAction, 'el=' + eventLabel ].join('&'); return trackingUrl; } /** * Returns the GoogleSheetsHelper for unit test purpose. * @return {object} */ getGoogleSheetsHelper() { return GoogleSheetsHelper; } }
JavaScript
class Block { constructor(options, count) { this.index = 0; this.thaws = []; this.count = count || 200; this.options = options; } /** * add an item to the end of items * @param item * @returns {Block} */ add(item) { const next = this._next(); next.add(item); return this; } /** * add an Array to the end of items * @param items * @returns {Block} */ addArray(items) { const next = this._next(); next.addArray(items); return this; } /** * insert an item into items @ current position * @param item * @returns {Block} */ insert(item) { const next = this._next(); next.insert(item); return this; } /** * insert and array into items @ current position * @param items * @returns {Block} */ insertArray(items) { const next = this._next(); next.insertArray(items); return this; } /** * Stops all thaws in this block * @returns {Block} */ stop() { for (let i = 0;i < this.thaws.length;i++) { this.thaws[i].stop(); } return this; } /** * Get next available in block * @returns {*} * @private */ _next() { let thaw = null; const thaws = this.thaws; if (thaws.length < this.count) { thaws.push(thaw = new Thaw([], this.options)); } else { thaw = thaws[this.index]; } this.index++; if (this.index >= this.count) { this.index = 0; } return thaw; } }
JavaScript
class Loading extends Component { constructor(props) { super(props); } // addVerses = () => { // verses.push(rand); // alert("Saved successfully!"); // console.log(verses); // } verseScreen = () => { Actions.verses(); } render() { const rand = this.props.rand; return ( <SafeAreaView style={styles.container}> <Image style={{position: "relative", top: 6, width: 200, height: 200}} source={require("/Users/abigaylepeterson/MagnifyWellness2/components/img/logo.png")} /> <Text style={styles.text}>You are loved. Click me to load!</Text> </SafeAreaView> ); } }
JavaScript
class LocalStorageAdapter extends StorageAdapter { /** * @method * @return {LocalStorageAdapter} */ static fromGlobals() { const {localStorage} = window; return new LocalStorageAdapter(localStorage); } /** * @param {Storage} localStorage see {@link https://developer.mozilla.org/en-US/docs/Web/API/Storage} */ constructor (localStorage) { super(); this.props = { localStorage }; } /** * @method * @param {Promise.<AppEventEmitter, Error>} dispatchPromise a promise which resolve with an event dispatcher * @param {Array<{name:String, value:*}>} nameValuePairsList * @param {String} entityId the id of the entity to link the values to * @return {Promise<Array<{name:String, value:*}>, Error>} */ async handleSetBatchStorage (dispatchPromise, nameValuePairsList, entityId) { const { localStorage } = this.props; return dispatchPromise.then((props) => { nameValuePairsList .map((nameAndValue) => { const [name, value] = nameAndValue; return [`apps/${props.instanceId}/state/${entityId}/${name}`, value] }) .forEach((keyAndValue) => { const [key, value] = keyAndValue; localStorage.setItem(key, JSON.stringify(value)); }) ; return nameValuePairsList; }); }; /** * @method * @param {Promise<AppEventEmitter, Error>} dispatchPromise a promise which resolve with an event dispatcher * @param {String} name the name under which to store the value * @param {*} value the value to store, will be `JSON serialized` * @param {String} entityId the id of the entity to link the values to * @return {Promise<*, Error>} */ async handleSetStorage (dispatchPromise, name, value, entityId) { const { localStorage } = this.props; return dispatchPromise.then((props) => { const key = `apps/${props.instanceId}/state/${entityId}/${name}`; if (! value) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(value)); } return value; }); }; /** * @method * @param {Promise<AppEventEmitter, Error>} dispatchPromise a promise which resolve with an event dispatcher * @param {String} name the name under which to store the value * @param {String} entityId the id of the entity to link the values to * @param {*} [defaultValue=null] the value to return if one the the storage items was not found * @return {Promise<*, Error>} */ async handleGetStorage (dispatchPromise, name, entityId, defaultValue = null) { const { localStorage } = this.props; return dispatchPromise.then((props) => { const key = `apps/${props.instanceId}/state/${entityId}/${name}`; const value = localStorage.getItem(key); if (value) { return JSON.parse(value); } return defaultValue; }); }; /** * @method * @param {Promise<AppEventEmitter, Error>} dispatchPromise a promise which resolve with an event dispatcher * @param {Array<String>} nameList the list of value names to retrieve * @param {String} entityId the id of the entity which the values are linked to * @param {*} [defaultValue=null] the value to return if one the the storage items was not found * @return {Promise.<Array<*>, Error>} */ async handleGetBatchStorage(dispatchPromise, nameList, entityId, defaultValue = null) { const { localStorage } = this.props; return dispatchPromise.then((props) => { return nameList .map((name) => [name, `apps/${props.instanceId}/state/${entityId}/${name}`]) .reduce( (values, nameAndKey) => { const [name, key] = nameAndKey; const value = localStorage.getItem(key); if (value) { values[name] = JSON.parse(value) } return values; }, {} ); }); }; }
JavaScript
class SearchBar extends Component { constructor(props) { // Component has it's own constructor method. // We call the parent's constructor method, by calling super(props); super(props); this.state = { term: '' }; } render() { // added an evetHandler, which watches for change when an input occurs. return ( <div className="search-bar"> <input value={this.state.term} onChange={event => this.onInputChange(event.target.value)}/> </div> ); } onInputChange(term) { // equivalent to this.setState({term: term}) this.setState({term}); this.props.onSearchTermChange(term); } }
JavaScript
class PersonalPreferencesOperationsPayload { /** * Create a PersonalPreferencesOperationsPayload. * @property {string} [labAccountResourceId] Resource Id of the lab account * @property {string} [addRemove] Enum indicating if user is adding or * removing a favorite lab. Possible values include: 'Add', 'Remove' * @property {string} [labResourceId] Resource Id of the lab to add/remove * from the favorites list */ constructor() { } /** * Defines the metadata of PersonalPreferencesOperationsPayload * * @returns {object} metadata of PersonalPreferencesOperationsPayload * */ mapper() { return { required: false, serializedName: 'PersonalPreferencesOperationsPayload', type: { name: 'Composite', className: 'PersonalPreferencesOperationsPayload', modelProperties: { labAccountResourceId: { required: false, serializedName: 'labAccountResourceId', type: { name: 'String' } }, addRemove: { required: false, serializedName: 'addRemove', type: { name: 'String' } }, labResourceId: { required: false, serializedName: 'labResourceId', type: { name: 'String' } } } } }; } }