language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Gestures { /** @see [[BrowserTests.Gestures.create]] */ create(page, options) { return page.evaluateHandle((options) => new globalThis._Gestures(options), options); } }
JavaScript
class Doc { constructor(list, from, world) { this.list = list //quiet these properties in console.logs Object.defineProperty(this, 'from', { enumerable: false, value: from, writable: true, }) //borrow some missing data from parent if (world === undefined && from !== undefined) { world = from.world } //'world' getter Object.defineProperty(this, 'world', { enumerable: false, value: world, writable: true, }) //fast-scans for our data //'found' getter Object.defineProperty(this, 'found', { get: () => this.list.length > 0, }) //'length' getter Object.defineProperty(this, 'length', { get: () => this.list.length, }) // this is way easier than .constructor.name... Object.defineProperty(this, 'isA', { get: () => 'Doc', }) } /** run part-of-speech tagger on all results*/ tagger() { return tagger(this) } /** pool is stored on phrase objects */ pool() { if (this.list.length > 0) { return this.list[0].pool } return this.all().list[0].pool } }
JavaScript
class OptionalChainingNullishTransformer extends _Transformer2.default { constructor( tokens, nameManager) { super();this.tokens = tokens;this.nameManager = nameManager;; } process() { if (this.tokens.matches1(_types.TokenType.nullishCoalescing)) { const token = this.tokens.currentToken(); if (this.tokens.tokens[token.nullishStartIndex].isAsyncOperation) { this.tokens.replaceTokenTrimmingLeftWhitespace(", async () =>"); } else { this.tokens.replaceTokenTrimmingLeftWhitespace(", () =>"); } return true; } if (this.tokens.matches1(_types.TokenType._delete)) { const nextToken = this.tokens.tokenAtRelativeIndex(1); if (nextToken.isOptionalChainStart) { this.tokens.removeInitialToken(); return true; } } const token = this.tokens.currentToken(); const chainStart = token.subscriptStartIndex; if ( chainStart != null && this.tokens.tokens[chainStart].isOptionalChainStart && // Super subscripts can't be optional (since super is never null/undefined), and the syntax // relies on the subscript being intact, so leave this token alone. this.tokens.tokenAtRelativeIndex(-1).type !== _types.TokenType._super ) { const param = this.nameManager.claimFreeName("_"); let arrowStartSnippet; if ( chainStart > 0 && this.tokens.matches1AtIndex(chainStart - 1, _types.TokenType._delete) && this.isLastSubscriptInChain() ) { // Delete operations are special: we already removed the delete keyword, and to still // perform a delete, we need to insert a delete in the very last part of the chain, which // in correct code will always be a property access. arrowStartSnippet = `${param} => delete ${param}`; } else { arrowStartSnippet = `${param} => ${param}`; } if (this.tokens.tokens[chainStart].isAsyncOperation) { arrowStartSnippet = `async ${arrowStartSnippet}`; } if ( this.tokens.matches2(_types.TokenType.questionDot, _types.TokenType.parenL) || this.tokens.matches2(_types.TokenType.questionDot, _types.TokenType.lessThan) ) { if (this.justSkippedSuper()) { this.tokens.appendCode(".bind(this)"); } this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalCall', ${arrowStartSnippet}`); } else if (this.tokens.matches2(_types.TokenType.questionDot, _types.TokenType.bracketL)) { this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${arrowStartSnippet}`); } else if (this.tokens.matches1(_types.TokenType.questionDot)) { this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'optionalAccess', ${arrowStartSnippet}.`); } else if (this.tokens.matches1(_types.TokenType.dot)) { this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${arrowStartSnippet}.`); } else if (this.tokens.matches1(_types.TokenType.bracketL)) { this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'access', ${arrowStartSnippet}[`); } else if (this.tokens.matches1(_types.TokenType.parenL)) { if (this.justSkippedSuper()) { this.tokens.appendCode(".bind(this)"); } this.tokens.replaceTokenTrimmingLeftWhitespace(`, 'call', ${arrowStartSnippet}(`); } else { throw new Error("Unexpected subscript operator in optional chain."); } return true; } return false; } /** * Determine if the current token is the last of its chain, so that we know whether it's eligible * to have a delete op inserted. * * We can do this by walking forward until we determine one way or another. Each * isOptionalChainStart token must be paired with exactly one isOptionalChainEnd token after it in * a nesting way, so we can track depth and walk to the end of the chain (the point where the * depth goes negative) and see if any other subscript token is after us in the chain. */ isLastSubscriptInChain() { let depth = 0; for (let i = this.tokens.currentIndex() + 1; ; i++) { if (i >= this.tokens.tokens.length) { throw new Error("Reached the end of the code while finding the end of the access chain."); } if (this.tokens.tokens[i].isOptionalChainStart) { depth++; } else if (this.tokens.tokens[i].isOptionalChainEnd) { depth--; } if (depth < 0) { return true; } // This subscript token is a later one in the same chain. if (depth === 0 && this.tokens.tokens[i].subscriptStartIndex != null) { return false; } } } /** * Determine if we are the open-paren in an expression like super.a()?.b. * * We can do this by walking backward to find the previous subscript. If that subscript was * preceded by a super, then we must be the subscript after it, so if this is a call expression, * we'll need to attach the right context. */ justSkippedSuper() { let depth = 0; let index = this.tokens.currentIndex() - 1; while (true) { if (index < 0) { throw new Error( "Reached the start of the code while finding the start of the access chain.", ); } if (this.tokens.tokens[index].isOptionalChainStart) { depth--; } else if (this.tokens.tokens[index].isOptionalChainEnd) { depth++; } if (depth < 0) { return false; } // This subscript token is a later one in the same chain. if (depth === 0 && this.tokens.tokens[index].subscriptStartIndex != null) { return this.tokens.tokens[index - 1].type === _types.TokenType._super; } index--; } } }
JavaScript
class GrowingMethodModel extends BaseModel { /** * GrowingMethodModel Constructor * * @protected */ constructor() { super(); /** * The Growing Method ID * * @type {string} * @public */ this.id = undefined; /** * The Growing Method Code * * @type {string} * @public */ this.code = undefined; /** * The Growing Method Name * * @type {string} * @public */ this.name = undefined; /** * The Growing Method Description * * @type {string} * @public */ this.description = undefined; /** * Whether the Growing Method has been deleted * * @type {boolean} * @public */ this.deleted = undefined; /** * When the Growing Method was last updated * * @type {Date} * @public */ this.updateTimestamp = undefined; } /** * Create a new **GrowingMethodModel** from a JSON Object or JSON String * * @static * @public * @param {Object<string, any>|string} json A JSON Object or JSON String * @return {GrowingMethodModel} */ static fromJSON(json) { let model = new GrowingMethodModel(); /** * The JSON Object * * @type {Object<string, any>} */ let jsonObject = {}; if(typeof json === 'string') { jsonObject = JSON.parse(json); } else if(typeof json === 'object') { jsonObject = json; } if('id' in jsonObject) { model.id = (function(){ if(typeof jsonObject['id'] !== 'string') { return String(jsonObject['id']); } return jsonObject['id']; }()); } if('code' in jsonObject) { model.code = (function(){ if(typeof jsonObject['code'] !== 'string') { return String(jsonObject['code']); } return jsonObject['code']; }()); } if('name' in jsonObject) { model.name = (function(){ if(typeof jsonObject['name'] !== 'string') { return String(jsonObject['name']); } return jsonObject['name']; }()); } if('description' in jsonObject) { model.description = (function(){ if(typeof jsonObject['description'] !== 'string') { return String(jsonObject['description']); } return jsonObject['description']; }()); } if('deleted' in jsonObject) { model.deleted = (function(){ if(typeof jsonObject['deleted'] !== 'boolean') { return Boolean(jsonObject['deleted']); } return jsonObject['deleted']; }()); } if('updateTimestamp' in jsonObject) { model.updateTimestamp = (function(){ if(typeof jsonObject['updateTimestamp'] !== 'string') { return new Date(String(jsonObject['updateTimestamp'])); } return new Date(jsonObject['updateTimestamp']); }()); } return model; } }
JavaScript
class PaymentService { /** * Constructor * @param {Function(Object, XMLHttpRequest)} makeHttpRequest */ constructor(makeHttpRequest) { this.makeHttpRequest = makeHttpRequest; this.getPaymentTypes = this.getPaymentTypes.bind(this); this.getUnallocatedAmount = this.getUnallocatedAmount.bind(this); this.sendPaymentDetails = this.sendPaymentDetails.bind(this); } /** * Get payment types * @param {XMLHttpRequest} req */ getPaymentTypes(req) { return this.makeHttpRequest({ uri: `${barUrl}/payment-types`, method: 'GET' }, req); } getUnallocatedAmount(id, req) { return this.makeHttpRequest({ uri: `${barUrl}/payment-instructions/${id}/unallocated`, method: 'GET' }, req); } /** * sends payment details to API * @param data * @param type */ sendPaymentDetails(body, type, req) { let method = 'POST'; let uri = `${barUrl}/${type}`; delete body.payment_type; if (!isUndefined(body.id)) { uri = `${uri}/${body.id}`; method = 'PUT'; } return this.makeHttpRequest({ uri, method, body }, req); } }
JavaScript
class OneWayExerciseValidator extends ExerciseValidator { getState (exercise, step1, step2) { const state = { exerciseid: exercise.type, prefix: step1.strategyStatus, context: { term: step1.formula, environment: {}, location: [] } } return state } getContext (exercise, step2) { const context = { term: step2.formula, environment: {}, location: [] } return context } }
JavaScript
class CrontabField extends BaseField { /** * Custom method for toInner and toRepresent methods. * @param {object} data */ _getValue(data = {}) { let value = data[this.options.name]; if (!value) { return '* * * * *'; } return value; } /** * Redefinition of base guiField method toInner. * @param {object} data */ toInner(data = {}) { return this._getValue(data); } /** * Redefinition of base guiField method toRepresent. * @param {object} data */ toRepresent(data = {}) { return this._getValue(data); } /** * Redefinition of base guiField static property 'mixins'. */ static get mixins() { return super.mixins.concat(CrontabFieldMixin); } }
JavaScript
class Language { /** * Creates lanuage with a language id. * @param {string} id Language id from languages.json */ constructor(id) { // Check if alias let alias = languages.alias[id]; if (alias) return new Language(alias); /** @private */ this.info = languages.languages[id]; if (!this.info) { ErrorManager.raise(`no such language with id \`${id}\``, InvalidLanguage); } /** @private */ this.id = id; } /** * User-friendly language name * @type {string} */ get displayName() { return (this.info && this.info.display) || (this.id[0].toUpperCase() + this.id.substr(1)); } /** * Returns absolute URL of the answer. */ get url() { return `${Data.shared.envValueForKey('HOST')}/answer/${this.id}` } /** * User-friendly and machine encoding * @return {Encoding} */ encoding() { return Encoding.fromName(languages.encoding[this.id] || 'UTF-8'); } /** * Returns language icon node. * @return {HTMLElement} */ icon() { return <img src={ this.iconURL }/>; } /** * @type {string} */ get iconURL() { return `/lang/logo/${this.id}.svg` } /** * @return {string} */ toString() { return this.id; } /** * TIO language id. `null` if langauge does not support TIO. * @type {?string} */ get tioId() { let tioid = languages.tio[this.id]; if (tioid === 0) return null; return tioid || this.id; } /** * Returns highlight-js id * @type {?string} */ get hljsId() { let hljsId = languages.highlight[this.id]; if (hljsId === 1) return this.id; return hljsId; } /** * CodeMirror-editor lang def file name. * @type {?string} */ get cmName() { let cmName = languages.cm[this.id]; if (!cmName) return null; if (cmName === 1) return this.id; if (cmName === 2) return `text/x-${this.id}`; return cmName; } /** * Byte-counts a JavaScript string (properly encoded) * @param {string} string */ byteCount(string) { // let byteCount = 0; // for (const char of string) { // const codePoint = char.codePointAt(0); // } } /** * Checks if two languages are the same * @param {Language} object other language object. * @return {boolean} representing if they are the same langauge or not. */ equal(object) { return this.id === object.id; } /** * Unwraps from an API JSON object. * @param {Object} json JSON object. * @return {?Language} object if succesful, `null` if unauthorized. * @throws {TypeError} if invalid JSON object */ static fromJSON(json) { try { return new Language(json); } catch(e) { return null; } } /** * Query object for languages * @type {Query} */ static get query() { if (this._query !== null) return this._query; let query = new Query( Language.allLanguages, (lang) => lang.displayName ); return query; } static _langCache = null; /** * Returns every language. * @return {Language[]} */ static get allLanguages() { if (Language._langCache) return Language._langCache; let langs = []; let langIds = Object.keys(languages.languages); let i = langIds.length; while (--i >= 0) { langs.push(new Language(langIds[i])); } return langs; } static _query = null; }
JavaScript
class BusinessRuleDetected extends DomainEvent_1.DomainEvent { constructor(sceneId, details, rule, timestamp) { super(timestamp); this.sceneId = sceneId; this.details = details; this.rule = rule; (0, tiny_types_1.ensure)('sceneId', sceneId, (0, tiny_types_1.isDefined)()); (0, tiny_types_1.ensure)('details', details, (0, tiny_types_1.isDefined)()); (0, tiny_types_1.ensure)('rule', rule, (0, tiny_types_1.isDefined)()); } static fromJSON(o) { return new BusinessRuleDetected(model_1.CorrelationId.fromJSON(o.sceneId), model_1.ScenarioDetails.fromJSON(o.details), model_1.BusinessRule.fromJSON(o.rule), model_1.Timestamp.fromJSON(o.timestamp)); } }
JavaScript
class AutosizeTextarea extends HTMLElement { constructor() { super(); // Attributes this.width = this.getAttribute("autosize-width") || 300; this.minHeight = this.getAttribute("autosize-height") || 20; this.maxHeight = this.getAttribute("autosize-max-height") || 100; // Shadow DOM this.shadow = this.attachShadow({ mode: 'open' }); this.shadow.innerHTML = ` <style> :host textarea { font-size: 14px; /* we have to specify a line height, 'normal' is not the same across browsers (~1.14) */ line-height: 1.14em; resize: none; width: ${this.width}; min-height: ${this.minHeight}; max-height: ${this.maxHeight}; padding: 6px; } </style>`; // Append a native textarea element this.textarea = document.createElement("textarea"); this.textarea.value = this.textContent.trim(); this.innerHTML = ""; this.shadow.appendChild(this.textarea); // event listener this.textarea.oninput = () => { // We can't access the native TextAreaHTMLElement's Shadow DOM :( // Let's just assign the inner scrollHeigth to the element's height let scrollHeight = this.textarea.scrollHeight; // Get computed CSS styles for the textarea element let styles = window.getComputedStyle(this.textarea); /* // Dimensions let height = getValueOf(styles.getPropertyValue("height")); let width = getValueOf(styles.getPropertyValue("width")); // Font & line sizes let fontSize = getValueOf(styles.getPropertyValue("font-size")); let lineHeight = styles.getPropertyValue("line-height"); if (lineHeight === "normal") { lineHeight = fontSize; } else { lineHeight = getValueOf(lineHeight); } */ // Padding let padding = { top: getValueOf(styles.getPropertyValue("padding-top")), bottom: getValueOf(styles.getPropertyValue("padding-bottom")), }; let paddingX = padding.top + padding.bottom; this.textarea.style.height = scrollHeight - paddingX + "px"; /* // console.log("padding-x: ", paddingX); let lineNums = (scrollHeight - paddingX) / lineHeight; console.log(scrollHeight, lineHeight, fontSize, lineNums); // console.log("lineNums: ", lineNums); return { num: lineNums, size: fontSize, };*/ function getValueOf(string) { return parseInt(string.split("px")[0]); } }; } connectedCallback() { // console.log(`%c ${this.constructor.name} mounted `, "background: #555; color: #fff; padding: 2px"); // console.log(`%cwidth:\t\t${this.width} // min-height:\t${this.minHeight} // max-height:\t${this.maxHeight}`, "padding: 1em; border: 2px solid #ccc;"); } handleInput(e) { // calculate the character count // let charCount = this.textarea.value.length; // console.log("character count:", charCount); let newHeight = calculateInnerTextLineCount.bind(this); // console.log(newHeight); this.textarea.style.height = newHeight; } }
JavaScript
class CookieConsent extends Base { constructor(options = {}) { super(options); // const answers = cmpDomainCategories.map((category) => { const answers = COOKIES_CATEGORIES.map(({ name }) => { const cookieName = this.options?.cookie?.name || "gjirafa_"; const answer = getCookie(cookieName + name); return isValidStatus(answer) ? { [name]: answer } : undefined; }).filter((obj) => (obj ? obj[Object.keys(obj)[0]] : false)); // if they have already answered if (answers.length > 0) { setTimeout(() => this.emit("initialized", answers)); } else if (this.options.legal && this.options.legal.countryCode) { this.initializationComplete({ code: this.options.legal.countryCode }); } else if (this.options.location) { new Location(this.options.location).locate(this.initializationComplete.bind(this), this.initializationError.bind(this)); } else { this.initializationComplete({}); } } initializationComplete(result) { if (result.code) { this.options = new Legal(this.options.legal).applyLaw(this.options, result.code); } this.popup = new Popup(this.options); setTimeout(() => this.emit("initialized", this.popup), 0); } initializationError(error) { setTimeout(() => this.emit("error", error, new Popup(this.options)), 0); } getCountryLaws(countryCode) { return new Legal(this.options.legal).get(countryCode); } isOpen() { return this.popup.isOpen(); } close() { return this.popup.close(), this; } revokeChoice() { return this.popup.revokeChoice(), this; } open() { return this.popup.open(), this; } toggleRevokeButton(bool) { return this.popup.toggleRevokeButton(bool), this; } setStatuses(status) { return this.popup.setStatuses(status), this; } clearStatuses() { return this.popup.clearStatuses(), this; } destroy() { return this.popup.destroy(), this; } }
JavaScript
class Table { static EVENT_ONCHANGEDFILTER = 'onChangedFilter'; static getTablePathFromKeyPath(keyPath) { return keyPath.replace(/\./g, '/'); } static getKeyPathFromTablePath(tablePath) { return tablePath.replace(/\//g, '.'); } // takes a json object static from(obj, key) { const table = new Table(); table.key = key; table.filter = obj.filter; // turn json data for a table's entry rows into objects table.entriesWithoutKeys = []; if (obj.valueMacro) { table.valueMacro = obj.valueMacro; table.entries = null; } else if (obj.rows) { table.entries = accumulateEntries(obj.rows, `table '${key}'`, (i) => table.entriesWithoutKeys.push(i)); } table.modifiers = obj.modifiers; table.redirect = obj.redirect; table.entry = obj.entry !== undefined ? Entry.from(obj.entry, -1) : undefined; return table; } constructor() { this.events = new EventTarget(); this.key = undefined; this.filter = undefined; // The macro used to generate a value based on the filter this.valueMacro = undefined; // All the possible options available for randomization (and filtering) this.entries = {}; // Global modifiers that can (and should) be applied to any entry after being rolled. this.modifiers = {}; this.redirect = undefined; } getKey() { return this.key; } getKeyPath() { return Table.getKeyPathFromTablePath(this.getKey()); } hasValueMacro() { return this.valueMacro !== undefined; } length() { return this.entries !== null ? Object.keys(this.entries).length : 1; } getRows() { return this.entries !== null ? Object.values(this.entries) : []; } addRow(entry) { if (this.entries === null) { return; } this.entries.push(entry); this.dispatchOnChangedRowCount(this.entries.length - 1, this.entries.length); } removeRow(entry) { if (this.entries === null) { return; } this.entries.splice(this.entries.indexOf(entry), 1); this.dispatchOnChangedRowCount(this.entries.length, this.entries.length - 1); } dispatchOnChangedRowCount(prev, next) { this.events.dispatchEvent(new CustomEvent('onChangedRowCount', { detail: { prev, next } })); } // TODO: This will never work because Tables are deserialized from the local storage subscribeOnChangedRowCount(callback) { console.error('Changed callbacks will never work on tables'); this.events.addEventListener('onChangedRowCount', callback); } unsubscribeOnChangedRowCount(callback) { this.events.removeEventListener('onChangedRowCount', callback); } // Viewing the table via react getOptions() { return this.getRows().map((entry) => ({ key: entry.getKey(), text: entry.getKey(), value: entry.getKey() })); } hasFilter() { return this.filter === undefined || this.filter !== false; } getFilterType() { return this.hasFilter() && this.filter !== undefined ? this.filter.type : undefined; } getDefaultFilter() { switch (this.getFilterType()) { case 'minMaxRange': return { min: this.filter.min, max: this.filter.max, }; default: return this.getOptions(); } } hasGlobalModifiers() { return this.modifiers !== null && this.modifiers !== undefined && Object.keys(this.modifiers).length > 0; } getGlobalModifiers() { return this.modifiers; } hasRedirector() { return this.redirect !== undefined; } getRedirector() { return this.redirect; } // Performing ops roll(filter, context, ignore) { let result = { value: undefined, modifiers: {} }; if (this.entry !== undefined) { result.value = lodash.cloneDeep(this.entry.value.value); result.modifiers = lodash.cloneDeep(this.entry.value.modifiers); result.entry = this.entry; } else if (this.hasValueMacro()) { const filterContext = { ...context, filter: (filter || this.getDefaultFilter()) }; const macro = createExecutor(this.valueMacro); if (macro === undefined) result.value = inlineEval(this.valueMacro, filterContext); else result.value = macro(filterContext).value; } else if (this.hasRedirector()) { let redirector = this.getRedirector(); const macro = createExecutor(`{roll:${redirector}}`); if (macro) { result = macro({...context, filter: undefined}); } } else { const entry = (() => { const rollable = this.getRows(); if (context.preset !== undefined) { const preset = Array.isArray(context.preset) ? context.preset.shift() : context.preset; const presetEntry = rollable.find((entry) => entry.getKey() === preset); if (presetEntry !== undefined) return presetEntry; else { console.error(`Could not find entry with preset key ${preset} in table ${this.getKey()}`); } } return chooseRandomWithWeight( rollable.filter((entry) => ( (filter === undefined || filter.includes(entry.getKey())) && (ignore === undefined || !ignore.includes(entry.getKey())) )) ); })(); if (entry === null) { console.warn('Received null generated value. Maybe there are missing keys?', this.entriesWithoutKeys, this.getKeyPath()); return result; } result.value = lodash.cloneDeep(entry.value); result.modifiers = lodash.cloneDeep(entry.modifiers); result.entry = entry; } // Modifiers which are determined based on scales or regexs on the generated value if (this.hasGlobalModifiers()) { for (let globalModifierEntry of this.getGlobalModifiers()) { let matched = globalModifierEntry.match === undefined; const macro = globalModifierEntry.match !== undefined ? createExecutor(globalModifierEntry.match) : undefined; if (macro) { let matchResult = macro({ ...context, value: result.value }); matched = matchResult === true; } else { matched = result.value === globalModifierEntry.match; } if (matched) { result.modifiers = appendModifiers(result.modifiers, globalModifierEntry.modifiers); } } } result.modifiers = lodash.mapValues(result.modifiers, (modifierList, targetProperty) => { if (!Array.isArray(modifierList)) modifierList = [modifierList]; return modifierList.map((modifier) => { // Preprocess each modifier to ensure that the modifiers remaining are either numbers or strings if (typeof modifier === 'object') { switch (modifier.type) { case 'curve': switch (modifier.curve) { case 'step': { const keyframes = Object.keys(modifier.values); let currentIndex = undefined; let nextIndex = keyframes.length > 0 ? 0 : undefined; while (nextIndex !== undefined && parseInt(result.value, 10) > parseInt(keyframes[nextIndex], 10)) { currentIndex = nextIndex; nextIndex++; if (nextIndex >= keyframes.length) nextIndex = undefined; } return currentIndex ? modifier.values[keyframes[currentIndex]] : 0; } case 'lerp': { const valueInt = parseInt(result.value, 10); const keyframes = Object.keys(modifier.values); const getInt = (i) => parseInt(keyframes[i], 10); let lowerIndex = undefined; let higherIndex = keyframes.length > 0 ? 0 : undefined; while (higherIndex !== undefined && valueInt > getInt(higherIndex)) { lowerIndex = higherIndex; higherIndex++; if (higherIndex >= keyframes.length) higherIndex = undefined; } if (lowerIndex === undefined) { lowerIndex = higherIndex; } else if (higherIndex === undefined) { higherIndex = lowerIndex; } const lowerInput = getInt(lowerIndex); const higherInput = getInt(higherIndex); const lowerMod = modifier.values[keyframes[lowerIndex]]; const higherMod = modifier.values[keyframes[higherIndex]]; const t = (valueInt - lowerInput) / (higherInput !== lowerInput ? higherInput - lowerInput : higherInput); const lerped = (1 - t) * lowerMod + (t * higherMod); if (modifier.toIntOp === undefined) return lerped; const intOp = Math[modifier.toIntOp]; if (intOp === undefined) { console.warn('Encountered unimplemented curve int cast operator:', modifier.toIntOp); return 0; } else { return intOp(lerped); } } default: break; } break; default: break; } } return modifier; }); }); return result; } }
JavaScript
class Client { /** * @param {string} token - Facebook Page Token * @param {ProxyData} proxyData - Proxy information if behind proxy */ constructor(token, proxyData) { this.requestData = { token }; this.requestData = Utils_1.Utils.getProxyData(this.requestData, proxyData); } /** * Marks latest message from user as seen. * Optional cb, otherwise returns promise * @param {string} id * @param {Function} cb * @return {Promise<any>} */ markSeen(id, cb) { return this.sendAction(id, Client.markSeenPayload, cb); } /** * Toggles typing notification in Messenger to on/off. * Optional cb, otherwise returns promise * @param {string} id * @param {boolean | Function} toggle * @param {string} personaId * @param {Function} cb * @return {any} */ toggleTyping(id, toggle, personaId, cb) { if (arguments.length === 3) { return this.toggleAction(id, toggle, cb, personaId); // tslint:disable-next-line } else { if (Object.prototype.toString.call(toggle) === '[object Function]') { return this.sendAction(id, Client.typingOff, toggle, personaId); // tslint:disable-next-line } else { return this.toggleAction(id, toggle, undefined, personaId); } } } /** * Sends simple text message. * Optional cb, otherwise returns promise * @param {string} id * @param {string} text * @param {string} personaId * @param {Function} cb * @return {Promise<any>} */ sendTextMessage(id, text, personaId, cb) { return this.sendDisplayMessage(id, { text }, cb, personaId); } /** * imageUrlOrId can be either URL to Image or ID of previously uploaded one * Optional cb, otherwise returns promise * @param {string} id * @param {string} imageUrlOrId * @param {string} personaId * @param {Function} cb * @return {Promise<any>} */ sendImageMessage(id, imageUrlOrId, personaId, cb) { return this.sendUrlOrIdBasedMessage(id, enums_1.ATTACHMENT_TYPE.IMAGE, imageUrlOrId, cb, personaId); } /** * audioUrlOrId can be either URL to audio clip or ID of previously uploaded one * Optional cb, otherwise returns promise * @param {string} id * @param {string} audioUrlOrId * @param {Function} cb * @return {Promise<any>} */ sendAudioMessage(id, audioUrlOrId, cb) { return this.sendUrlOrIdBasedMessage(id, enums_1.ATTACHMENT_TYPE.AUDIO, audioUrlOrId, cb); } /** * videoUrlOrId can be either URL to video clip or ID of previously uploaded one * Optional cb, otherwise returns promise * @param {string} id * @param {string} videoUrlOrId * @param {Function} cb * @return {Promise<any>} */ sendVideoMessage(id, videoUrlOrId, cb) { return this.sendUrlOrIdBasedMessage(id, enums_1.ATTACHMENT_TYPE.VIDEO, videoUrlOrId, cb); } /** * fileUrlOrId can be either URL to video clip or ID of previously uploaded one * Optional cb, otherwise returns promise * @param {string} id * @param {string} fileUrlOrId * @param {Function} cb * @return {Promise<any>} */ sendFileMessage(id, fileUrlOrId, cb) { return this.sendUrlOrIdBasedMessage(id, enums_1.ATTACHMENT_TYPE.FILE, fileUrlOrId, cb); } /** * Sends any of the Button message types: https://developers.facebook.com/docs/messenger-platform/send-messages/buttons * Optional cb, otherwise returns promise * @param {string} id * @param {string} text * @param {IButton[]} buttons * @param {Function} cb * @return {Promise<any>} */ sendButtonsMessage(id, text, buttons, cb) { const payload = { type: enums_1.ATTACHMENT_TYPE.TEMPLATE, payload: { text, buttons, template_type: 'button' } }; return this.sendAttachmentMessage(id, payload, cb); } /** * Sends any template message type: https://developers.facebook.com/docs/messenger-platform/send-messages/templates * Optional cb, otherwise returns promise * @param {string} id * @param {IMessageTemplate} templatePayload * @param {Function} cb * @return {Promise<any>} */ sendTemplateMessage(id, templatePayload, cb) { const payload = { type: enums_1.ATTACHMENT_TYPE.TEMPLATE, payload: templatePayload }; return this.sendAttachmentMessage(id, payload, cb); } /** * Sends Quick Reply message: * Optional cb, otherwise returns promise * @param {string} id * @param {string | AttachmentPayload} textOrAttachment * @param {IQuickReply[]} quickReplies * @param {string} personaId * @param {Function} cb * @return {Promise<any>} */ sendQuickReplyMessage(id, textOrAttachment, quickReplies, personaId, cb) { let payload; if (typeof textOrAttachment === 'string') { payload = { text: textOrAttachment, quick_replies: quickReplies }; } else { payload = { attachment: textOrAttachment, quick_replies: quickReplies }; } return this.sendDisplayMessage(id, payload, cb, personaId); } /** * * Optional cb, otherwise returns promise * @param {string} id * @param {string[]} fieldsArray * @param {Function} cb * @return {Promise<any>} */ getUserProfile(id, fieldsArray, cb) { const options = Utils_1.Utils.getRequestOptions(); options.url += id; let fields; if (!Array.isArray(fieldsArray)) { fields = 'first_name'; } else { fields = fieldsArray.join(','); } options.qs.fields = fields; options.method = 'GET'; return Utils_1.Utils.sendMessage(options, this.requestData, cb); } sendUrlOrIdBasedMessage(id, type, urlOrId, cb, personaId) { let payload; if (urlOrId.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g)) { payload = { type, payload: { is_reusable: true, url: urlOrId } }; } else { payload = { type, payload: { attachment_id: urlOrId } }; } return this.sendAttachmentMessage(id, payload, cb, personaId); } sendAttachmentMessage(id, payload, cb, personaId) { return this.sendDisplayMessage(id, { attachment: payload }, cb, personaId); } sendDisplayMessage(id, payload, cb, personaId) { const options = this.generateBasicRequestPayload(id); options.json = Object.assign(Object.assign({}, options.json), { message: payload, persona_id: personaId }); return Utils_1.Utils.sendMessage(options, this.requestData, cb); } sendAction(id, payload, cb, personaId) { const options = this.generateBasicRequestPayload(id); options.json = Object.assign(Object.assign({}, options.json), { sender_action: payload, persona_id: personaId }); return Utils_1.Utils.sendMessage(options, this.requestData, cb); } generateBasicRequestPayload(id) { const options = Utils_1.Utils.getRequestOptions(); options.url += 'me/messages'; options.method = 'POST'; options.json = { recipient: { id } }; return options; } toggleAction(id, toggleValue, cb, personaId) { if (toggleValue) { return this.sendAction(id, Client.typingOn, cb, personaId); // tslint:disable-next-line } else { return this.sendAction(id, Client.typingOff, cb, personaId); } } }
JavaScript
class BabylonianWorker { constructor() { // List of all active editors this._editors = new Set(); // Worker for parsing this._astWorker = new ASTWorkerPromiseWrapper(); // Tracker this.tracker = new Tracker(); // Currently active examples this.activeExamples = new Set([defaultExample()]); } /** * Managing editors */ registerEditor(editor) { if(!this._editors.has(editor)) { this._editors.add(editor); } } unregisterEditor(editor) { this._editors.delete(editor); } updateEditors() { for(let editor of this._editors) { editor.onTrackerChanged(); } } /** * Evaluating */ async evaluateEditor(editor, execute = true) { // Serialize annotations let serializedAnnotations = {}; for(let key of ["probes", "sliders", "replacements", "instances"]) { serializedAnnotations[key] = editor.annotations[key].map((a) => a.serializeForWorker()); } serializedAnnotations.examples = editor.activeExamples.map((a) => a.serializeForWorker()); // Serialize context serializedAnnotations.context = editor.context; // Performance Performance.step("parse_and_transform"); // Generate AST and modified code const { ast, loadableCode, executableCode } = await this._astWorker.process( editor.value, serializedAnnotations, editor.customInstances.map(i => i.serializeForWorker()), editor.url, this._getReplacementUrls() ); if(!ast) { editor.hadParseError = true; editor.loadableWorkspace = null; } else { editor.hadParseError = false; generateLocationMap(ast); editor.ast = ast; editor.loadableCode = loadableCode; editor.executableCode = executableCode; if(!execute) { return; } // Performance Performance.step("execute"); // Reset the tracker to write new results this.tracker.reset(); // Load the loadable version of the module const loadResult = await this._load(editor.loadableCode, editor.url, { tracker: this.tracker, connections: defaultConnections(), }); if(loadResult.isError) { editor.loadableWorkspace = null; } else { editor.loadableWorkspace = loadResult.path; } // Execute all modules that have active examples this.activeExamples = new Set([defaultExample()]); for(let someEditor of this._editors) { if(!someEditor.activeExamples.length) { continue; } someEditor.activeExamples.forEach(e => this.activeExamples.add(e)); console.log(`Executing ${someEditor.url}`); const evalResult = await boundEval(someEditor.executableCode, { tracker: this.tracker, connections: defaultConnections(), }); someEditor.hadEvalError = evalResult.isError; if(someEditor.hadEvalError) { someEditor.lastEvalError = evalResult.value.originalErr.message; } } } // Performance Performance.step("update"); // Tell editors that the tracker has changed this.updateEditors(); // Performance Performance.stop(); } async _load(code, url, thisReference) { // Based on boundEval() const workspaceName = `${url}.babylonian`; const path = `workspacejs:${workspaceName}`; // Unload old version if there is one lively.unloadModule(path); // 'this' reference if (!self.__pluginDoitThisRefs__) { self.__pluginDoitThisRefs__ = {}; } self.__pluginDoitThisRefs__[workspaceName] = thisReference; if (!self.__topLevelVarRecorder_ModuleNames__) { self.__topLevelVarRecorder_ModuleNames__ = {}; } try { setCode(workspaceName, code); return await System.import(path) .then(m => { return ({ value: m.__result__, path: path })}); } catch(err) { return Promise.resolve({ value: err, isError: true }); } } _getReplacementUrls() { const replacementUrls = Array.from(this._editors).reduce((acc, editor) => { if(editor.loadableWorkspace) { acc[editor.url] = editor.loadableWorkspace; } return acc; }, {}) return replacementUrls; } }
JavaScript
class Gestures { /** * @param {PhotoSwipe} pswp */ constructor(pswp) { this.pswp = pswp; /** @type {'x' | 'y'} */ this.dragAxis = undefined; // point objects are defined once and reused // PhotoSwipe keeps track only of two pointers, others are ignored /** @type {Point} */ this.p1 = {}; // the first pressed pointer /** @type {Point} */ this.p2 = {}; // the second pressed pointer /** @type {Point} */ this.prevP1 = {}; /** @type {Point} */ this.prevP2 = {}; /** @type {Point} */ this.startP1 = {}; /** @type {Point} */ this.startP2 = {}; /** @type {Point} */ this.velocity = {}; /** @type {Point} */ this._lastStartP1 = {}; /** @type {Point} */ this._intervalP1 = {}; this._numActivePoints = 0; /** @type {Point[]} */ this._ongoingPointers = []; this._touchEventEnabled = 'ontouchstart' in window; this._pointerEventEnabled = !!(window.PointerEvent); this.supportsTouch = this._touchEventEnabled || (this._pointerEventEnabled && navigator.maxTouchPoints > 1); if (!this.supportsTouch) { // disable pan to next slide for non-touch devices pswp.options.allowPanToNext = false; } this.drag = new DragHandler(this); this.zoomLevels = new ZoomHandler(this); this.tapHandler = new TapHandler(this); pswp.on('bindEvents', () => { pswp.events.add(pswp.scrollWrap, 'click', e => this._onClick(e)); if (this._pointerEventEnabled) { this._bindEvents('pointer', 'down', 'up', 'cancel'); } else if (this._touchEventEnabled) { this._bindEvents('touch', 'start', 'end', 'cancel'); // In previous versions we also bound mouse event here, // in case device supports both touch and mouse events, // but newer versions of browsers now support PointerEvent. // on iOS10 if you bind touchmove/end after touchstart, // and you don't preventDefault touchstart (which PhotoSwipe does), // preventDefault will have no effect on touchmove and touchend. // Unless you bind it previously. pswp.scrollWrap.ontouchmove = () => {}; // eslint-disable-line pswp.scrollWrap.ontouchend = () => {}; // eslint-disable-line } else { this._bindEvents('mouse', 'down', 'up'); } }); } /** * * @param {'mouse' | 'touch' | 'pointer'} pref * @param {'down' | 'start'} down * @param {'up' | 'end'} up * @param {'cancel'} [cancel] */ _bindEvents(pref, down, up, cancel) { const { pswp } = this; const { events } = pswp; const cancelEvent = cancel ? pref + cancel : ''; events.add(pswp.scrollWrap, pref + down, this.onPointerDown.bind(this)); events.add(window, pref + 'move', this.onPointerMove.bind(this)); events.add(window, pref + up, this.onPointerUp.bind(this)); if (cancelEvent) { events.add(pswp.scrollWrap, cancelEvent, this.onPointerUp.bind(this)); } } /** * @param {PointerEvent} e */ onPointerDown(e) { // We do not call preventDefault for touch events // to allow browser to show native dialog on longpress // (the one that allows to save image or open it in new tab). // // Desktop Safari allows to drag images when preventDefault isn't called on mousedown, // even though preventDefault IS called on mousemove. That's why we preventDefault mousedown. let isMousePointer; if (e.type === 'mousedown' || e.pointerType === 'mouse') { isMousePointer = true; } // Allow dragging only via left mouse button. // http://www.quirksmode.org/js/events_properties.html // https://developer.mozilla.org/en-US/docs/Web/API/event.button if (isMousePointer && e.button > 0) { return; } const { pswp } = this; // if PhotoSwipe is opening or closing if (!pswp.opener.isOpen) { e.preventDefault(); return; } if (pswp.dispatch('pointerDown', { originalEvent: e }).defaultPrevented) { return; } if (isMousePointer) { pswp.mouseDetected(); // preventDefault mouse event to prevent // browser image drag feature this._preventPointerEventBehaviour(e); } pswp.animations.stopAll(); this._updatePoints(e, 'down'); this.pointerDown = true; if (this._numActivePoints === 1) { this.dragAxis = null; // we need to store initial point to determine the main axis, // drag is activated only after the axis is determined equalizePoints(this.startP1, this.p1); } if (this._numActivePoints > 1) { // Tap or double tap should not trigger if more than one pointer this._clearTapTimer(); this.isMultitouch = true; } else { this.isMultitouch = false; } } /** * @param {PointerEvent} e */ onPointerMove(e) { e.preventDefault(); // always preventDefault move event if (!this._numActivePoints) { return; } this._updatePoints(e, 'move'); if (this.pswp.dispatch('pointerMove', { originalEvent: e }).defaultPrevented) { return; } if (this._numActivePoints === 1 && !this.isDragging) { if (!this.dragAxis) { this._calculateDragDirection(); } // Drag axis was detected, emit drag.start if (this.dragAxis && !this.isDragging) { if (this.isZooming) { this.isZooming = false; this.zoomLevels.end(); } this.isDragging = true; this._clearTapTimer(); // Tap can not trigger after drag // Adjust starting point this._updateStartPoints(); this._intervalTime = Date.now(); //this._startTime = this._intervalTime; this._velocityCalculated = false; equalizePoints(this._intervalP1, this.p1); this.velocity.x = 0; this.velocity.y = 0; this.drag.start(); this._rafStopLoop(); this._rafRenderLoop(); } } else if (this._numActivePoints > 1 && !this.isZooming) { this._finishDrag(); this.isZooming = true; // Adjust starting points this._updateStartPoints(); this.zoomLevels.start(); this._rafStopLoop(); this._rafRenderLoop(); } } /** * @private */ _finishDrag() { if (this.isDragging) { this.isDragging = false; // Try to calculate velocity, // if it wasn't calculated yet in drag.change if (!this._velocityCalculated) { this._updateVelocity(true); } this.drag.end(); this.dragAxis = null; } } /** * @param {PointerEvent} e */ onPointerUp(e) { if (!this._numActivePoints) { return; } this._updatePoints(e, 'up'); if (this.pswp.dispatch('pointerUp', { originalEvent: e }).defaultPrevented) { return; } if (this._numActivePoints === 0) { this.pointerDown = false; this._rafStopLoop(); if (this.isDragging) { this._finishDrag(); } else if (!this.isZooming && !this.isMultitouch) { //this.zoomLevels.correctZoomPan(); this._finishTap(e); } } if (this._numActivePoints < 2 && this.isZooming) { this.isZooming = false; this.zoomLevels.end(); if (this._numActivePoints === 1) { // Since we have 1 point left, we need to reinitiate drag this.dragAxis = null; this._updateStartPoints(); } } } /** * @private */ _rafRenderLoop() { if (this.isDragging || this.isZooming) { this._updateVelocity(); if (this.isDragging) { // make sure that pointer moved since the last update if (!pointsEqual(this.p1, this.prevP1)) { this.drag.change(); } } else /* if (this.isZooming) */ { if (!pointsEqual(this.p1, this.prevP1) || !pointsEqual(this.p2, this.prevP2)) { this.zoomLevels.change(); } } this._updatePrevPoints(); this.raf = requestAnimationFrame(this._rafRenderLoop.bind(this)); } } /** * Update velocity at 50ms interval * * @param {boolean=} force */ _updateVelocity(force) { const time = Date.now(); const duration = time - this._intervalTime; if (duration < 50 && !force) { return; } this.velocity.x = this._getVelocity('x', duration); this.velocity.y = this._getVelocity('y', duration); this._intervalTime = time; equalizePoints(this._intervalP1, this.p1); this._velocityCalculated = true; } /** * @private * @param {PointerEvent} e */ _finishTap(e) { const { mainScroll } = this.pswp; // Do not trigger tap events if main scroll is shifted if (mainScroll.isShifted()) { // restore main scroll position // (usually happens if stopped in the middle of animation) mainScroll.moveIndexBy(0, true); return; } // Do not trigger tap for touchcancel or pointercancel if (e.type.indexOf('cancel') > 0) { return; } // Trigger click instead of tap for mouse events if (e.type === 'mouseup' || e.pointerType === 'mouse') { this.tapHandler.click(this.startP1, e); return; } // Disable delay if there is no doubleTapAction const tapDelay = this.pswp.options.doubleTapAction ? DOUBLE_TAP_DELAY : 0; // If tapTimer is defined - we tapped recently, // check if the current tap is close to the previous one, // if yes - trigger double tap if (this._tapTimer) { this._clearTapTimer(); // Check if two taps were more or less on the same place if (getDistanceBetween(this._lastStartP1, this.startP1) < MIN_TAP_DISTANCE) { this.tapHandler.doubleTap(this.startP1, e); } } else { equalizePoints(this._lastStartP1, this.startP1); this._tapTimer = setTimeout(() => { this.tapHandler.tap(this.startP1, e); this._clearTapTimer(); }, tapDelay); } } /** * @private */ _clearTapTimer() { if (this._tapTimer) { clearTimeout(this._tapTimer); this._tapTimer = null; } } /** * Get velocity for axis * * @private * @param {'x' | 'y'} axis * @param {number} duration */ _getVelocity(axis, duration) { // displacement is like distance, but can be negative. const displacement = this.p1[axis] - this._intervalP1[axis]; if (Math.abs(displacement) > 1 && duration > 5) { return displacement / duration; } return 0; } /** * @private */ _rafStopLoop() { if (this.raf) { cancelAnimationFrame(this.raf); this.raf = null; } } /** * @private * @param {PointerEvent} e */ _preventPointerEventBehaviour(e) { // TODO find a way to disable e.preventDefault on some elements // via event or some class or something e.preventDefault(); return true; } /** * Parses and normalizes points from the touch, mouse or pointer event. * Updates p1 and p2. * * @private * @param {PointerEvent | TouchEvent} e * @param {'up' | 'down' | 'move'} pointerType Normalized pointer type */ _updatePoints(e, pointerType) { if (this._pointerEventEnabled) { const pointerEvent = /** @type {PointerEvent} */ (e); // Try to find the current pointer in ongoing pointers by its ID const pointerIndex = this._ongoingPointers.findIndex((ongoingPoiner) => { return ongoingPoiner.id === pointerEvent.pointerId; }); if (pointerType === 'up' && pointerIndex > -1) { // release the pointer - remove it from ongoing this._ongoingPointers.splice(pointerIndex, 1); } else if (pointerType === 'down' && pointerIndex === -1) { // add new pointer this._ongoingPointers.push(this._convertEventPosToPoint(pointerEvent, {})); } else if (pointerIndex > -1) { // update existing pointer this._convertEventPosToPoint(pointerEvent, this._ongoingPointers[pointerIndex]); } this._numActivePoints = this._ongoingPointers.length; // update points that PhotoSwipe uses // to calculate position and scale if (this._numActivePoints > 0) { equalizePoints(this.p1, this._ongoingPointers[0]); } if (this._numActivePoints > 1) { equalizePoints(this.p2, this._ongoingPointers[1]); } } else { const touchEvent = /** @type {TouchEvent} */ (e); this._numActivePoints = 0; if (touchEvent.type.indexOf('touch') > -1) { // Touch Event // https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent if (touchEvent.touches && touchEvent.touches.length > 0) { this._convertEventPosToPoint(touchEvent.touches[0], this.p1); this._numActivePoints++; if (touchEvent.touches.length > 1) { this._convertEventPosToPoint(touchEvent.touches[1], this.p2); this._numActivePoints++; } } } else { // Mouse Event this._convertEventPosToPoint(/** @type {PointerEvent} */ (e), this.p1); if (pointerType === 'up') { // clear all points on mouseup this._numActivePoints = 0; } else { this._numActivePoints++; } } } } // update points that were used during previous rAF tick _updatePrevPoints() { equalizePoints(this.prevP1, this.p1); equalizePoints(this.prevP2, this.p2); } // update points at the start of gesture _updateStartPoints() { equalizePoints(this.startP1, this.p1); equalizePoints(this.startP2, this.p2); this._updatePrevPoints(); } _calculateDragDirection() { if (this.pswp.mainScroll.isShifted()) { // if main scroll position is shifted – direction is always horizontal this.dragAxis = 'x'; } else { // calculate delta of the last touchmove tick const diff = Math.abs(this.p1.x - this.startP1.x) - Math.abs(this.p1.y - this.startP1.y); if (diff !== 0) { // check if pointer was shifted horizontally or vertically const axisToCheck = diff > 0 ? 'x' : 'y'; if (Math.abs(this.p1[axisToCheck] - this.startP1[axisToCheck]) >= AXIS_SWIPE_HYSTERISIS) { this.dragAxis = axisToCheck; } } } } /** * Converts touch, pointer or mouse event * to PhotoSwipe point. * * @private * @param {Touch | PointerEvent} e * @param {Point} p */ _convertEventPosToPoint(e, p) { p.x = e.pageX - this.pswp.offset.x; p.y = e.pageY - this.pswp.offset.y; if ('pointerId' in e) { p.id = e.pointerId; } else if (e.identifier !== undefined) { p.id = e.identifier; } return p; } /** * @private * @param {PointerEvent} e */ _onClick(e) { // Do not allow click event to pass through after drag if (this.pswp.mainScroll.isShifted()) { e.preventDefault(); e.stopPropagation(); } } }
JavaScript
class Point { constructor(x,y) { this.x = x this.y = y } add(point) { return new Point( this.x+point.x, this.y+point.y ) } subtract(point) { return new Point( this.x-point.x, this.y-point.y ) } copy(pt) { this.x = pt.x this.y = pt.y return this } toString() { return `point(${this.x},${this.y})` } }
JavaScript
class McTabLink extends McTabLinkMixinBase { constructor(elementRef, focusMonitor, renderer) { super(); this.elementRef = elementRef; this.focusMonitor = focusMonitor; this.renderer = renderer; this.vertical = false; /** Whether the tab link is active or not. */ this.isActive = false; this.focusMonitor.monitor(this.elementRef.nativeElement); } /** Whether the link is active. */ get active() { return this.isActive; } set active(value) { if (value !== this.isActive) { this.isActive = value; } } ngAfterViewInit() { this.addClassModifierForIcons(Array.from(this.elementRef.nativeElement.querySelectorAll('.mc-icon'))); } ngOnDestroy() { this.focusMonitor.stopMonitoring(this.elementRef.nativeElement); } addClassModifierForIcons(icons) { const twoIcons = 2; const [firstIconElement, secondIconElement] = icons; if (icons.length === 1) { const COMMENT_NODE = 8; if (firstIconElement.nextSibling && firstIconElement.nextSibling.nodeType !== COMMENT_NODE) { this.renderer.addClass(firstIconElement, 'mc-icon_left'); } if (firstIconElement.previousSibling && firstIconElement.previousSibling.nodeType !== COMMENT_NODE) { this.renderer.addClass(firstIconElement, 'mc-icon_right'); } } else if (icons.length === twoIcons) { this.renderer.addClass(firstIconElement, 'mc-icon_left'); this.renderer.addClass(secondIconElement, 'mc-icon_right'); } } }
JavaScript
class McTabNav { constructor(vertical) { this.vertical = false; this.vertical = coerceBooleanProperty(vertical); } ngAfterContentInit() { this.links.changes .pipe(delay(0)) .subscribe((links) => links.forEach((link) => link.vertical = this.vertical)); this.links.notifyOnChanges(); } }
JavaScript
class StreamNotLiveError extends common_1.CustomError { /** @private */ constructor() { super('Your stream needs to be live to do this'); } }
JavaScript
class LynnRunner { /** * Constructor for the LynnRunner class * @param {object} request the lynn request details * @param {object} environment the environment data to use for the request * @param {bool} verbose to log additional details */ constructor(request, environment) { this.request = request this.environment = environment this.execute = function(callback) { // create our http options object const path = this.buildPath(this.request.options, environment) const options = { 'protocol': this.envReplace(this.request.options.protocol, environment, 'http:'), 'host': this.envReplace(this.request.options.host, environment, 'localhost'), 'port': this.envReplace(this.request.options.port, environment, '80'), 'method': this.envReplace(this.request.options.method, environment, 'GET'), 'path': path, 'headers': this.envReplaceHeaders(this.request.options.headers, environment), 'auth': this.envReplace(this.request.options.auth, environment, null), 'timeout': this.envReplace(this.request.options.timeout, environment, 30000), } const hrstart = process.hrtime() const protocol = options.protocol == 'http:' ? http : https const req = protocol.request(options, (res) => { res.setEncoding('utf8') let rawData = '' res.on('data', (chunk) => { rawData += chunk }) res.on('end', () => { const hrend = process.hrtime(hrstart) const {statusCode} = res const headers = res.headers try { const parsedData = JSON.parse(rawData) const result = { 'options': options, 'statusCode': statusCode, 'headers': headers, 'data': parsedData, 'error': null, 'responseTime': hrend[1] / 1000000, 'endTime': Date.now(), } callback(result) } catch (e) { const result = { 'options': options, 'statusCode': statusCode, 'headers': headers, 'data': null, 'error': e, 'responseTime': hrend[1] / 1000000, 'endTime': Date.now(), } callback(result) } }) }) req.on('error', (e) => { const result = { 'options': options, 'statusCode': null, 'headers': null, 'data': null, 'error': e, 'responseTime': null, 'endTime': Date.now(), } callback(result) }) // TODO: post a body here if necessary req.end() } this.envReplace = function(template, environment, defaultValue) { if (template == null) { return defaultValue } const replaced = this.replace(template, environment) return replaced } this.replace = function(templateString, templateVars) { return new Function('return `'+templateString +'`;').call(templateVars) } this.buildPath = function(options, environment) { const basePath = this.envReplace(options.path, environment, '/') if (options.queryString != null) { const queryString = queryString.stringify(options.queryString) if (queryString != '') { return basePath + '?' + querystring.stringify(options.queryString) } else { return basePath } } else { return basePath } } this.envReplaceHeaders = function(headers, environment) { const newHeaders = {} for (const key in headers) { if (Object.prototype.hasOwnProperty.call(headers, key)) { const newValue = this.envReplace(headers[key], environment, null) if (newValue != null) { newHeaders[key] = newValue } } } return newHeaders } this.captured = function(result) { if (this.request.capture == null) { return {} } const captured = {} for (const key in this.request.capture) { if (Object.prototype.hasOwnProperty.call(this.request.capture, key)) { let path = this.request.capture[key] let isArrayPath = false if (path.startsWith('[') && path.endsWith(']')) { path = path.slice(1, -1) isArrayPath = true } const found = jp.query(result, path) if (found != null) { if (isArrayPath) { captured[key] = found } else if (found.length > 0) { captured[key] = found[0] } } else { captured[key] = null } } } return captured } } }
JavaScript
class Player extends TObject{ static radius = 35 ; static speed = 500 ; name = ""; x = 0; y = 0; tx = 0 ; ty = 0 ; moving = false; constructor(){ super(); } // Serialize this object to a string serialize(){ let s = {name:this.name, x:this.x, y:this.y, tx:this.tx, ty:this.ty, moving:this.moving}; return JSON.stringify(s); } // Set this object to a serialized string created with serialize. set(serialized){ let s = JSON.parse(serialized); this.name = s.name; this.x = s.x; this.y = s.y ; this.tx = s.tx; this.ty = s.ty ; this.moving = s.moving; } interpolateFrom(last_observed, last_time, this_time){ if(!last_observed){ return this ; } let distance = Math.sqrt((this.x-last_observed.x)*(this.x-last_observed.x)+(this.y-last_observed.y)*(this.y-last_observed.y)); let dt = this_time-last_time ; if(distance/dt < Player.speed *1.1){ return this ; }else{ let ip = new Player(); let b = Player.speed *1.1*dt/distance ; let a = 1-b; ip.x = a*last_observed.x + b* this.x ; ip.y = a*last_observed.y + b* this.y ; ip.tx = a*last_observed.tx + b* this.tx ; ip.ty = a*last_observed.ty + b* this.ty ; return ip ; } } }
JavaScript
class EmitEvent { /** * Creates an instance of AwaitResponseCallAction. */ constructor() { /** * The name of the action. * @type {string} */ this.name = 'Emit Event'; /** * The section of the action. * @type */ this.section = 'Bot Client Control'; /** * The author of the action. * @type {Array<string>} */ this.authors = ['Almeida']; /** * The version of the action. * @type {string} */ this.version = '1.0.0'; // Added in 1.9.6 /** * The Developer Version Number. * @type {string} */ this.DVN = '1.0.0'; /** * The name of the action, displayed on the editor. * @type {string} */ this.displayName = `Emit Event v${this.DVN}`; /** * A short description to be shown on the list of mods. * @type {string} */ this.shortDescription = 'Emits an event.'; /** * The fields used in the actions JSON data and HTML elements. * @type {Array<string>} */ this.fields = ['eventType', 'firstArg', 'secondArg']; } /** * The function that is ran whenever the software/bot starts. * @param {Object<*>} DBM The DBM workspace. * @returns {void} */ mod() {} /** * Generates the subtitle displayed next to the name on the editor. * @param {Object} data The data of the command. * @returns {string} The finalized subtitle. */ subtitle({ eventType }) { let DiscordJS; try { DiscordJS = require('discord.js'); } catch (__) {} const events = Object.values(DiscordJS.Constants.Events).sort(); return events.includes(eventType) ? `Emits a ${eventType} event` : 'Not emitting antyhing'; } /** * Stores the relevant variable info for the editor. * @returns {void} */ variableStorage() {} /** * Is ran when the HTML is loaded. * @returns {void} */ init() { const { execSync } = require('child_process'); const { document } = this; const wrexlinks = document.getElementsByClassName('wrexlink2'); for (let i = 0; i < wrexlinks.length; i++) { const wrexlink = wrexlinks[i]; const url = wrexlink.getAttribute('data-url2'); if (url) { wrexlink.setAttribute('title', url); wrexlink.addEventListener('click', function(e) { e.stopImmediatePropagation(); execSync(`start ${url}`); }); } } } /** * What is ran when the action is called. * @param {Object<*>} cache The cache of the command/event. * @returns {void} */ action(cache) { const data = cache.actions[cache.index]; const WrexMods = this.getWrexMods(); const events = Object.values(WrexMods.require('discord.js').Constants.Events).sort(); const event = this.evalMessage(data.eventType); if (!events.includes(event)) return console.error(`${this.name} (#${cache.index + 1}): Unkown event type.`); const firstArg = this.evalMessage(data.firstArg, cache); const secondArg = this.evalMessage(data.secondArg, cache); const client = this.getDBM().Bot.bot; client.emit(event, firstArg, secondArg); } /** * The HTML document for the action, visible on the editor. * @returns {string} The HTML document. */ html() { let DiscordJS; try { DiscordJS = require('discord.js'); } catch (__) {} const events = DiscordJS && Object.values(DiscordJS.Constants.Events).sort(); const docs = `https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-${(events && events[0]) || 'channelCreate'}`; return ` <div id="wrexdiv" style="width: 550px; height: 350px; overflow-y: scroll;"> <div style="padding-bottom: 100px; padding: 5px 15px 5px 5px"> <div> <div class="ui teal segment" style="background: inherit;"> <p>${this.shortDescription}</p> <p>Made by: <b>${this.authors.join(' ')}</b> Version: ${this.version} | DVN: ${this.DVN}</p> </div> </div> </div> ${events ? ` <div style="padding-top: 8px;"> <details> <summary><span style="color: white"><b>Available event types (click to expand)</b></summary> <div class="codeblock"> <span style="color:#9b9b9b"> ${events.map((e) => `<li>${e}</li>`).join('\n')} </span> <p> You can learn more about what events take what arguments on the <u><span class="wrexlink2" data-url2="${docs}">discord.js documentation.</span></u> </p> </details> </div>` : ''} <div class="container"> Event Type:<br> <input id="eventType" class="round" type="text" value="error"> </div> <div class="container"> First Parameter:<br> <input id="firstArg" class="round" type="text"> </div> <div class="container"> Second Parameter:<br> <input id="secondArg" class="round" type="text"> </div> <div style="float: left; width: 90%; padding-top: 8px;"> <p><u>Note:</u><br> Some events may not require the two arguments and some may not even require any arguments at all. Just leave the boxes empty on those cases. </div><br> </div> <style> .container { float: left; width: 90%; padding-top: 8px; } .codeblock { margin-right: 25px; background-color: rgba(0,0,0,0.20); border-radius: 3.5px; border: 1px solid rgba(255,255,255,0.15); padding: 4px 8px; font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif; transition: border 175ms ease; } span.wrexlink2 { color: #99b3ff; text-decoration: underline; cursor: pointer; } span.wrexlink2:hover { color: #4676b9; } </style>`; } }
JavaScript
class Observable { constructor () { /** * Some desc. * @type {Map<N, any>} */ this._observers = create(); } /** * @param {N} name * @param {function} f */ on (name, f) { setIfUndefined(this._observers, name, create$1).add(f); } /** * @param {N} name * @param {function} f */ once (name, f) { /** * @param {...any} args */ const _f = (...args) => { this.off(name, _f); f(...args); }; this.on(name, _f); } /** * @param {N} name * @param {function} f */ off (name, f) { const observers = this._observers.get(name); if (observers !== undefined) { observers.delete(f); if (observers.size === 0) { this._observers.delete(name); } } } /** * Emit a named event. All registered event listeners that listen to the * specified name will receive the event. * * @todo This should catch exceptions * * @param {N} name The event name. * @param {Array<any>} args The arguments that are applied to the event listener. */ emit (name, args) { // copy all listeners to an array first to make sure that no event is emitted to listeners that are subscribed while the event handler is called. return from((this._observers.get(name) || create()).values()).forEach(f => f(...args)) } destroy () { this._observers = create(); } }
JavaScript
class VarStoragePolyfill { constructor () { this.map = new Map(); } /** * @param {string} key * @param {any} value */ setItem (key, value) { this.map.set(key, value); } /** * @param {string} key */ getItem (key) { return this.map.get(key) } }
JavaScript
class Decoder { /** * @param {Uint8Array} uint8Array Binary data to decode */ constructor (uint8Array) { /** * Decoding target. * * @type {Uint8Array} */ this.arr = uint8Array; /** * Current decoding position. * * @type {number} */ this.pos = 0; } }
JavaScript
class RleDecoder extends Decoder { /** * @param {Uint8Array} uint8Array * @param {function(Decoder):T} reader */ constructor (uint8Array, reader) { super(uint8Array); /** * The reader */ this.reader = reader; /** * Current state * @type {T|null} */ this.s = null; this.count = 0; } read () { if (this.count === 0) { this.s = this.reader(this); if (hasContent(this)) { this.count = readVarUint(this) + 1; // see encoder implementation for the reason why this is incremented } else { this.count = -1; // read the current value forever } } this.count--; return /** @type {T} */ (this.s) } }
JavaScript
class Encoder { constructor () { this.cpos = 0; this.cbuf = new Uint8Array(100); /** * @type {Array<Uint8Array>} */ this.bufs = []; } }
JavaScript
class RleEncoder extends Encoder { /** * @param {function(Encoder, T):void} writer */ constructor (writer) { super(); /** * The writer */ this.w = writer; /** * Current state * @type {T|null} */ this.s = null; this.count = 0; } /** * @param {T} v */ write (v) { if (this.s === v) { this.count++; } else { if (this.count > 0) { // flush counter, unless this is the first value (count = 0) writeVarUint(this, this.count - 1); // since count is always > 0, we can decrement by one. non-standard encoding ftw } this.count = 1; // write first value this.w(this, v); this.s = v; } } }
JavaScript
class UintOptRleEncoder { constructor () { this.encoder = new Encoder(); /** * @type {number} */ this.s = 0; this.count = 0; } /** * @param {number} v */ write (v) { if (this.s === v) { this.count++; } else { flushUintOptRleEncoder(this); this.count = 1; this.s = v; } } toUint8Array () { flushUintOptRleEncoder(this); return toUint8Array(this.encoder) } }
JavaScript
class IntDiffOptRleEncoder { constructor () { this.encoder = new Encoder(); /** * @type {number} */ this.s = 0; this.count = 0; this.diff = 0; } /** * @param {number} v */ write (v) { if (this.diff === v - this.s) { this.s = v; this.count++; } else { flushIntDiffOptRleEncoder(this); this.count = 1; this.diff = v - this.s; this.s = v; } } toUint8Array () { flushIntDiffOptRleEncoder(this); return toUint8Array(this.encoder) } }
JavaScript
class StringEncoder { constructor () { /** * @type {Array<string>} */ this.sarr = []; this.s = ''; this.lensE = new UintOptRleEncoder(); } /** * @param {string} string */ write (string) { this.s += string; if (this.s.length > 19) { this.sarr.push(this.s); this.s = ''; } this.lensE.write(string.length); } toUint8Array () { const encoder = new Encoder(); this.sarr.push(this.s); this.s = ''; writeVarString(encoder, this.sarr.join('')); writeUint8Array(encoder, this.lensE.toUint8Array()); return toUint8Array(encoder) } }
JavaScript
class AbstractConnector extends Observable { /** * @param {Doc} ydoc * @param {any} awareness */ constructor (ydoc, awareness) { super(); this.doc = ydoc; this.awareness = awareness; } }
JavaScript
class DeleteSet { constructor () { /** * @type {Map<number,Array<DeleteItem>>} */ this.clients = new Map(); } }
JavaScript
class Doc extends Observable { /** * @param {DocOpts} [opts] configuration */ constructor ({ guid = uuidv4(), gc = true, gcFilter = () => true, meta = null, autoLoad = false } = {}) { super(); this.gc = gc; this.gcFilter = gcFilter; this.clientID = generateNewClientId(); this.guid = guid; /** * @type {Map<string, AbstractType<YEvent>>} */ this.share = new Map(); this.store = new StructStore(); /** * @type {Transaction | null} */ this._transaction = null; /** * @type {Array<Transaction>} */ this._transactionCleanups = []; /** * @type {Set<Doc>} */ this.subdocs = new Set(); /** * If this document is a subdocument - a document integrated into another document - then _item is defined. * @type {Item?} */ this._item = null; this.shouldLoad = autoLoad; this.autoLoad = autoLoad; this.meta = meta; } /** * Notify the parent document that you request to load data into this subdocument (if it is a subdocument). * * `load()` might be used in the future to request any provider to load the most current data. * * It is safe to call `load()` multiple times. */ load () { const item = this._item; if (item !== null && !this.shouldLoad) { transact(/** @type {any} */ (item.parent).doc, transaction => { transaction.subdocsLoaded.add(this); }, null, true); } this.shouldLoad = true; } getSubdocs () { return this.subdocs } getSubdocGuids () { return new Set(Array.from(this.subdocs).map(doc => doc.guid)) } /** * Changes that happen inside of a transaction are bundled. This means that * the observer fires _after_ the transaction is finished and that all changes * that happened inside of the transaction are sent as one message to the * other peers. * * @param {function(Transaction):void} f The function that should be executed as a transaction * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin * * @public */ transact (f, origin = null) { transact(this, f, origin); } /** * Define a shared data type. * * Multiple calls of `y.get(name, TypeConstructor)` yield the same result * and do not overwrite each other. I.e. * `y.define(name, Y.Array) === y.define(name, Y.Array)` * * After this method is called, the type is also available on `y.share.get(name)`. * * *Best Practices:* * Define all types right after the Yjs instance is created and store them in a separate object. * Also use the typed methods `getText(name)`, `getArray(name)`, .. * * @example * const y = new Y(..) * const appState = { * document: y.getText('document') * comments: y.getArray('comments') * } * * @param {string} name * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ... * @return {AbstractType<any>} The created type. Constructed with TypeConstructor * * @public */ get (name, TypeConstructor = AbstractType) { const type = setIfUndefined(this.share, name, () => { // @ts-ignore const t = new TypeConstructor(); t._integrate(this, null); return t }); const Constr = type.constructor; if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) { if (Constr === AbstractType) { // @ts-ignore const t = new TypeConstructor(); t._map = type._map; type._map.forEach(/** @param {Item?} n */ n => { for (; n !== null; n = n.left) { // @ts-ignore n.parent = t; } }); t._start = type._start; for (let n = t._start; n !== null; n = n.right) { n.parent = t; } t._length = type._length; this.share.set(name, t); t._integrate(this, null); return t } else { throw new Error(`Type with the name ${name} has already been defined with a different constructor`) } } return type } /** * @template T * @param {string} [name] * @return {YArray<T>} * * @public */ getArray (name = '') { // @ts-ignore return this.get(name, YArray) } /** * @param {string} [name] * @return {YText} * * @public */ getText (name = '') { // @ts-ignore return this.get(name, YText) } /** * @param {string} [name] * @return {YMap<any>} * * @public */ getMap (name = '') { // @ts-ignore return this.get(name, YMap) } /** * @param {string} [name] * @return {YXmlFragment} * * @public */ getXmlFragment (name = '') { // @ts-ignore return this.get(name, YXmlFragment) } /** * Converts the entire document into a js object, recursively traversing each yjs type * * @return {Object<string, any>} */ toJSON () { /** * @type {Object<string, any>} */ const doc = {}; this.share.forEach((value, key) => { doc[key] = value.toJSON(); }); return doc } /** * Emit `destroy` event and unregister all event handlers. */ destroy () { from(this.subdocs).forEach(subdoc => subdoc.destroy()); const item = this._item; if (item !== null) { this._item = null; const content = /** @type {ContentDoc} */ (item.content); if (item.deleted) { // @ts-ignore content.doc = null; } else { content.doc = new Doc({ guid: this.guid, ...content.opts }); content.doc._item = item; } transact(/** @type {any} */ (item).parent.doc, transaction => { if (!item.deleted) { transaction.subdocsAdded.add(content.doc); } transaction.subdocsRemoved.add(this); }, null, true); } this.emit('destroyed', [true]); this.emit('destroy', [this]); super.destroy(); } /** * @param {string} eventName * @param {function(...any):any} f */ on (eventName, f) { super.on(eventName, f); } /** * @param {string} eventName * @param {function} f */ off (eventName, f) { super.off(eventName, f); } }
JavaScript
class EventHandler { constructor () { /** * @type {Array<function(ARG0, ARG1):void>} */ this.l = []; } }
JavaScript
class RelativePosition { /** * @param {ID|null} type * @param {string|null} tname * @param {ID|null} item */ constructor (type, tname, item) { /** * @type {ID|null} */ this.type = type; /** * @type {string|null} */ this.tname = tname; /** * @type {ID | null} */ this.item = item; } }
JavaScript
class Transaction { /** * @param {Doc} doc * @param {any} origin * @param {boolean} local */ constructor (doc, origin, local) { /** * The Yjs instance. * @type {Doc} */ this.doc = doc; /** * Describes the set of deleted items by ids * @type {DeleteSet} */ this.deleteSet = new DeleteSet(); /** * Holds the state before the transaction started. * @type {Map<Number,Number>} */ this.beforeState = getStateVector(doc.store); /** * Holds the state after the transaction. * @type {Map<Number,Number>} */ this.afterState = new Map(); /** * All types that were directly modified (property added or child * inserted/deleted). New types are not included in this Set. * Maps from type to parentSubs (`item.parentSub = null` for YArray) * @type {Map<AbstractType<YEvent>,Set<String|null>>} */ this.changed = new Map(); /** * Stores the events for the types that observe also child elements. * It is mainly used by `observeDeep`. * @type {Map<AbstractType<YEvent>,Array<YEvent>>} */ this.changedParentTypes = new Map(); /** * @type {Array<AbstractStruct>} */ this._mergeStructs = []; /** * @type {any} */ this.origin = origin; /** * Stores meta information on the transaction * @type {Map<any,any>} */ this.meta = new Map(); /** * Whether this change originates from this doc. * @type {boolean} */ this.local = local; /** * @type {Set<Doc>} */ this.subdocsAdded = new Set(); /** * @type {Set<Doc>} */ this.subdocsRemoved = new Set(); /** * @type {Set<Doc>} */ this.subdocsLoaded = new Set(); } }
JavaScript
class UndoManager extends Observable { /** * @param {AbstractType<any>|Array<AbstractType<any>>} typeScope Accepts either a single type, or an array of types * @param {UndoManagerOptions} options */ constructor (typeScope, { captureTimeout = 500, deleteFilter = () => true, trackedOrigins = new Set([null]) } = {}) { super(); this.scope = typeScope instanceof Array ? typeScope : [typeScope]; this.deleteFilter = deleteFilter; trackedOrigins.add(this); this.trackedOrigins = trackedOrigins; /** * @type {Array<StackItem>} */ this.undoStack = []; /** * @type {Array<StackItem>} */ this.redoStack = []; /** * Whether the client is currently undoing (calling UndoManager.undo) * * @type {boolean} */ this.undoing = false; this.redoing = false; this.doc = /** @type {Doc} */ (this.scope[0].doc); this.lastChange = 0; this.doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => { // Only track certain transactions if (!this.scope.some(type => transaction.changedParentTypes.has(type)) || (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))) { return } const undoing = this.undoing; const redoing = this.redoing; const stack = undoing ? this.redoStack : this.undoStack; if (undoing) { this.stopCapturing(); // next undo should not be appended to last stack item } else if (!redoing) { // neither undoing nor redoing: delete redoStack this.redoStack = []; } const beforeState = transaction.beforeState; const afterState = transaction.afterState; const now = getUnixTime(); if (now - this.lastChange < captureTimeout && stack.length > 0 && !undoing && !redoing) { // append change to last stack op const lastOp = stack[stack.length - 1]; lastOp.ds = mergeDeleteSets([lastOp.ds, transaction.deleteSet]); lastOp.afterState = afterState; } else { // create a new stack op stack.push(new StackItem(transaction.deleteSet, beforeState, afterState)); } if (!undoing && !redoing) { this.lastChange = now; } // make sure that deleted structs are not gc'd iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => { if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) { keepItem(item, true); } }); this.emit('stack-item-added', [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo' }, this]); }); } clear () { this.doc.transact(transaction => { /** * @param {StackItem} stackItem */ const clearItem = stackItem => { iterateDeletedStructs(transaction, stackItem.ds, item => { if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) { keepItem(item, false); } }); }; this.undoStack.forEach(clearItem); this.redoStack.forEach(clearItem); }); this.undoStack = []; this.redoStack = []; } /** * UndoManager merges Undo-StackItem if they are created within time-gap * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next * StackItem won't be merged. * * * @example * // without stopCapturing * ytext.insert(0, 'a') * ytext.insert(1, 'b') * um.undo() * ytext.toString() // => '' (note that 'ab' was removed) * // with stopCapturing * ytext.insert(0, 'a') * um.stopCapturing() * ytext.insert(0, 'b') * um.undo() * ytext.toString() // => 'a' (note that only 'b' was removed) * */ stopCapturing () { this.lastChange = 0; } /** * Undo last changes on type. * * @return {StackItem?} Returns StackItem if a change was applied */ undo () { this.undoing = true; let res; try { res = popStackItem(this, this.undoStack, 'undo'); } finally { this.undoing = false; } return res } /** * Redo last undo operation. * * @return {StackItem?} Returns StackItem if a change was applied */ redo () { this.redoing = true; let res; try { res = popStackItem(this, this.redoStack, 'redo'); } finally { this.redoing = false; } return res } }
JavaScript
class YEvent { /** * @param {AbstractType<any>} target The changed type. * @param {Transaction} transaction */ constructor (target, transaction) { /** * The type on which this event was created on. * @type {AbstractType<any>} */ this.target = target; /** * The current target on which the observe callback is called. * @type {AbstractType<any>} */ this.currentTarget = target; /** * The transaction that triggered this event. * @type {Transaction} */ this.transaction = transaction; /** * @type {Object|null} */ this._changes = null; } /** * Computes the path from `y` to the changed type. * * The following property holds: * @example * let type = y * event.path.forEach(dir => { * type = type.get(dir) * }) * type === event.target // => true */ get path () { // @ts-ignore _item is defined because target is integrated return getPathTo(this.currentTarget, this.target) } /** * Check if a struct is deleted by this event. * * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. * * @param {AbstractStruct} struct * @return {boolean} */ deletes (struct) { return isDeleted(this.transaction.deleteSet, struct.id) } /** * Check if a struct is added by this event. * * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. * * @param {AbstractStruct} struct * @return {boolean} */ adds (struct) { return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0) } /** * @return {{added:Set<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert:Array<any>}|{delete:number}|{retain:number}>}} */ get changes () { let changes = this._changes; if (changes === null) { const target = this.target; const added = create$1(); const deleted = create$1(); /** * @type {Array<{insert:Array<any>}|{delete:number}|{retain:number}>} */ const delta = []; /** * @type {Map<string,{ action: 'add' | 'update' | 'delete', oldValue: any}>} */ const keys = new Map(); changes = { added, deleted, delta, keys }; const changed = /** @type Set<string|null> */ (this.transaction.changed.get(target)); if (changed.has(null)) { /** * @type {any} */ let lastOp = null; const packOp = () => { if (lastOp) { delta.push(lastOp); } }; for (let item = target._start; item !== null; item = item.right) { if (item.deleted) { if (this.deletes(item) && !this.adds(item)) { if (lastOp === null || lastOp.delete === undefined) { packOp(); lastOp = { delete: 0 }; } lastOp.delete += item.length; deleted.add(item); } // else nop } else { if (this.adds(item)) { if (lastOp === null || lastOp.insert === undefined) { packOp(); lastOp = { insert: [] }; } lastOp.insert = lastOp.insert.concat(item.content.getContent()); added.add(item); } else { if (lastOp === null || lastOp.retain === undefined) { packOp(); lastOp = { retain: 0 }; } lastOp.retain += item.length; } } } if (lastOp !== null && lastOp.retain === undefined) { packOp(); } } changed.forEach(key => { if (key !== null) { const item = /** @type {Item} */ (target._map.get(key)); /** * @type {'delete' | 'add' | 'update'} */ let action; let oldValue; if (this.adds(item)) { let prev = item.left; while (prev !== null && this.adds(prev)) { prev = prev.left; } if (this.deletes(item)) { if (prev !== null && this.deletes(prev)) { action = 'delete'; oldValue = last(prev.content.getContent()); } else { return } } else { if (prev !== null && this.deletes(prev)) { action = 'update'; oldValue = last(prev.content.getContent()); } else { action = 'add'; oldValue = undefined; } } } else { if (this.deletes(item)) { action = 'delete'; oldValue = last(/** @type {Item} */ item.content.getContent()); } else { return // nop } } keys.set(key, { action, oldValue }); } }); this._changes = changes; } return /** @type {any} */ (changes) } }
JavaScript
class AbstractType { constructor () { /** * @type {Item|null} */ this._item = null; /** * @type {Map<string,Item>} */ this._map = new Map(); /** * @type {Item|null} */ this._start = null; /** * @type {Doc|null} */ this.doc = null; this._length = 0; /** * Event handlers * @type {EventHandler<EventType,Transaction>} */ this._eH = createEventHandler(); /** * Deep event handlers * @type {EventHandler<Array<YEvent>,Transaction>} */ this._dEH = createEventHandler(); /** * @type {null | Array<ArraySearchMarker>} */ this._searchMarker = null; } /** * Integrate this type into the Yjs instance. * * * Save this struct in the os * * This type is sent to other client * * Observer functions are fired * * @param {Doc} y The Yjs instance * @param {Item|null} item */ _integrate (y, item) { this.doc = y; this._item = item; } /** * @return {AbstractType<EventType>} */ _copy () { throw methodUnimplemented() } /** * @return {AbstractType<EventType>} */ clone () { throw methodUnimplemented() } /** * @param {AbstractUpdateEncoder} encoder */ _write (encoder) { } /** * The first non-deleted item */ get _first () { let n = this._start; while (n !== null && n.deleted) { n = n.right; } return n } /** * Creates YEvent and calls all type observers. * Must be implemented by each type. * * @param {Transaction} transaction * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. */ _callObserver (transaction, parentSubs) { if (!transaction.local && this._searchMarker) { this._searchMarker.length = 0; } } /** * Observe all events that are created on this type. * * @param {function(EventType, Transaction):void} f Observer function */ observe (f) { addEventHandlerListener(this._eH, f); } /** * Observe all events that are created by this type and its children. * * @param {function(Array<YEvent>,Transaction):void} f Observer function */ observeDeep (f) { addEventHandlerListener(this._dEH, f); } /** * Unregister an observer function. * * @param {function(EventType,Transaction):void} f Observer function */ unobserve (f) { removeEventHandlerListener(this._eH, f); } /** * Unregister an observer function. * * @param {function(Array<YEvent>,Transaction):void} f Observer function */ unobserveDeep (f) { removeEventHandlerListener(this._dEH, f); } /** * @abstract * @return {any} */ toJSON () {} }
JavaScript
class YArrayEvent extends YEvent { /** * @param {YArray<T>} yarray The changed type * @param {Transaction} transaction The transaction object */ constructor (yarray, transaction) { super(yarray, transaction); this._transaction = transaction; } }
JavaScript
class YArray extends AbstractType { constructor () { super(); /** * @type {Array<any>?} * @private */ this._prelimContent = []; /** * @type {Array<ArraySearchMarker>} */ this._searchMarker = []; } /** * Construct a new YArray containing the specified items. * @template T * @param {Array<T>} items * @return {YArray<T>} */ static from (items) { const a = new YArray(); a.push(items); return a } /** * Integrate this type into the Yjs instance. * * * Save this struct in the os * * This type is sent to other client * * Observer functions are fired * * @param {Doc} y The Yjs instance * @param {Item} item */ _integrate (y, item) { super._integrate(y, item); this.insert(0, /** @type {Array<any>} */ (this._prelimContent)); this._prelimContent = null; } _copy () { return new YArray() } /** * @return {YArray<T>} */ clone () { const arr = new YArray(); arr.insert(0, this.toArray().map(el => el instanceof AbstractType ? el.clone() : el )); return arr } get length () { return this._prelimContent === null ? this._length : this._prelimContent.length } /** * Creates YArrayEvent and calls observers. * * @param {Transaction} transaction * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. */ _callObserver (transaction, parentSubs) { super._callObserver(transaction, parentSubs); callTypeObservers(this, transaction, new YArrayEvent(this, transaction)); } /** * Inserts new content at an index. * * Important: This function expects an array of content. Not just a content * object. The reason for this "weirdness" is that inserting several elements * is very efficient when it is done as a single operation. * * @example * // Insert character 'a' at position 0 * yarray.insert(0, ['a']) * // Insert numbers 1, 2 at position 1 * yarray.insert(1, [1, 2]) * * @param {number} index The index to insert content at. * @param {Array<T>} content The array of content */ insert (index, content) { if (this.doc !== null) { transact(this.doc, transaction => { typeListInsertGenerics(transaction, this, index, content); }); } else { /** @type {Array<any>} */ (this._prelimContent).splice(index, 0, ...content); } } /** * Appends content to this YArray. * * @param {Array<T>} content Array of content to append. */ push (content) { this.insert(this.length, content); } /** * Preppends content to this YArray. * * @param {Array<T>} content Array of content to preppend. */ unshift (content) { this.insert(0, content); } /** * Deletes elements starting from an index. * * @param {number} index Index at which to start deleting elements * @param {number} length The number of elements to remove. Defaults to 1. */ delete (index, length = 1) { if (this.doc !== null) { transact(this.doc, transaction => { typeListDelete(transaction, this, index, length); }); } else { /** @type {Array<any>} */ (this._prelimContent).splice(index, length); } } /** * Returns the i-th element from a YArray. * * @param {number} index The index of the element to return from the YArray * @return {T} */ get (index) { return typeListGet(this, index) } /** * Transforms this YArray to a JavaScript Array. * * @return {Array<T>} */ toArray () { return typeListToArray(this) } /** * Transforms this YArray to a JavaScript Array. * * @param {number} [start] * @param {number} [end] * @return {Array<T>} */ slice (start = 0, end = this.length) { return typeListSlice(this, start, end) } /** * Transforms this Shared Type to a JSON object. * * @return {Array<any>} */ toJSON () { return this.map(c => c instanceof AbstractType ? c.toJSON() : c) } /** * Returns an Array with the result of calling a provided function on every * element of this YArray. * * @template T,M * @param {function(T,number,YArray<T>):M} f Function that produces an element of the new Array * @return {Array<M>} A new array with each element being the result of the * callback function */ map (f) { return typeListMap(this, /** @type {any} */ (f)) } /** * Executes a provided function on once on overy element of this YArray. * * @param {function(T,number,YArray<T>):void} f A function to execute on every element of this YArray. */ forEach (f) { typeListForEach(this, f); } /** * @return {IterableIterator<T>} */ [Symbol.iterator] () { return typeListCreateIterator(this) } /** * @param {AbstractUpdateEncoder} encoder */ _write (encoder) { encoder.writeTypeRef(YArrayRefID); } }
JavaScript
class YMapEvent extends YEvent { /** * @param {YMap<T>} ymap The YArray that changed. * @param {Transaction} transaction * @param {Set<any>} subs The keys that changed. */ constructor (ymap, transaction, subs) { super(ymap, transaction); this.keysChanged = subs; } }
JavaScript
class YMap extends AbstractType { /** * * @param {Iterable<readonly [string, any]>=} entries - an optional iterable to initialize the YMap */ constructor (entries) { super(); /** * @type {Map<string,any>?} * @private */ this._prelimContent = null; if (entries === undefined) { this._prelimContent = new Map(); } else { this._prelimContent = new Map(entries); } } /** * Integrate this type into the Yjs instance. * * * Save this struct in the os * * This type is sent to other client * * Observer functions are fired * * @param {Doc} y The Yjs instance * @param {Item} item */ _integrate (y, item) { super._integrate(y, item) ;/** @type {Map<string, any>} */ (this._prelimContent).forEach((value, key) => { this.set(key, value); }); this._prelimContent = null; } _copy () { return new YMap() } /** * @return {YMap<T>} */ clone () { const map = new YMap(); this.forEach((value, key) => { map.set(key, value instanceof AbstractType ? value.clone() : value); }); return map } /** * Creates YMapEvent and calls observers. * * @param {Transaction} transaction * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. */ _callObserver (transaction, parentSubs) { callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs)); } /** * Transforms this Shared Type to a JSON object. * * @return {Object<string,T>} */ toJSON () { /** * @type {Object<string,T>} */ const map = {}; this._map.forEach((item, key) => { if (!item.deleted) { const v = item.content.getContent()[item.length - 1]; map[key] = v instanceof AbstractType ? v.toJSON() : v; } }); return map } /** * Returns the size of the YMap (count of key/value pairs) * * @return {number} */ get size () { return [...createMapIterator(this._map)].length } /** * Returns the keys for each element in the YMap Type. * * @return {IterableIterator<string>} */ keys () { return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0]) } /** * Returns the values for each element in the YMap Type. * * @return {IterableIterator<any>} */ values () { return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1]) } /** * Returns an Iterator of [key, value] pairs * * @return {IterableIterator<any>} */ entries () { return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => [v[0], v[1].content.getContent()[v[1].length - 1]]) } /** * Executes a provided function on once on every key-value pair. * * @param {function(T,string,YMap<T>):void} f A function to execute on every element of this YArray. */ forEach (f) { /** * @type {Object<string,T>} */ const map = {}; this._map.forEach((item, key) => { if (!item.deleted) { f(item.content.getContent()[item.length - 1], key, this); } }); return map } /** * @return {IterableIterator<T>} */ [Symbol.iterator] () { return this.entries() } /** * Remove a specified element from this YMap. * * @param {string} key The key of the element to remove. */ delete (key) { if (this.doc !== null) { transact(this.doc, transaction => { typeMapDelete(transaction, this, key); }); } else { /** @type {Map<string, any>} */ (this._prelimContent).delete(key); } } /** * Adds or updates an element with a specified key and value. * * @param {string} key The key of the element to add to this YMap * @param {T} value The value of the element to add */ set (key, value) { if (this.doc !== null) { transact(this.doc, transaction => { typeMapSet(transaction, this, key, value); }); } else { /** @type {Map<string, any>} */ (this._prelimContent).set(key, value); } return value } /** * Returns a specified element from this YMap. * * @param {string} key * @return {T|undefined} */ get (key) { return /** @type {any} */ (typeMapGet(this, key)) } /** * Returns a boolean indicating whether the specified key exists or not. * * @param {string} key The key to test. * @return {boolean} */ has (key) { return typeMapHas(this, key) } /** * @param {AbstractUpdateEncoder} encoder */ _write (encoder) { encoder.writeTypeRef(YMapRefID); } }
JavaScript
class YTextEvent extends YEvent { /** * @param {YText} ytext * @param {Transaction} transaction */ constructor (ytext, transaction) { super(ytext, transaction); /** * @type {Array<DeltaItem>|null} */ this._delta = null; } /** * Compute the changes in the delta format. * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document. * * @type {Array<DeltaItem>} * * @public */ get delta () { if (this._delta === null) { const y = /** @type {Doc} */ (this.target.doc); this._delta = []; transact(y, transaction => { const delta = /** @type {Array<DeltaItem>} */ (this._delta); const currentAttributes = new Map(); // saves all current attributes for insert const oldAttributes = new Map(); let item = this.target._start; /** * @type {string?} */ let action = null; /** * @type {Object<string,any>} */ const attributes = {}; // counts added or removed new attributes for retain /** * @type {string|object} */ let insert = ''; let retain = 0; let deleteLen = 0; const addOp = () => { if (action !== null) { /** * @type {any} */ let op; switch (action) { case 'delete': op = { delete: deleteLen }; deleteLen = 0; break case 'insert': op = { insert }; if (currentAttributes.size > 0) { op.attributes = {}; currentAttributes.forEach((value, key) => { if (value !== null) { op.attributes[key] = value; } }); } insert = ''; break case 'retain': op = { retain }; if (Object.keys(attributes).length > 0) { op.attributes = {}; for (const key in attributes) { op.attributes[key] = attributes[key]; } } retain = 0; break } delta.push(op); action = null; } }; while (item !== null) { switch (item.content.constructor) { case ContentEmbed: if (this.adds(item)) { if (!this.deletes(item)) { addOp(); action = 'insert'; insert = /** @type {ContentEmbed} */ (item.content).embed; addOp(); } } else if (this.deletes(item)) { if (action !== 'delete') { addOp(); action = 'delete'; } deleteLen += 1; } else if (!item.deleted) { if (action !== 'retain') { addOp(); action = 'retain'; } retain += 1; } break case ContentString: if (this.adds(item)) { if (!this.deletes(item)) { if (action !== 'insert') { addOp(); action = 'insert'; } insert += /** @type {ContentString} */ (item.content).str; } } else if (this.deletes(item)) { if (action !== 'delete') { addOp(); action = 'delete'; } deleteLen += item.length; } else if (!item.deleted) { if (action !== 'retain') { addOp(); action = 'retain'; } retain += item.length; } break case ContentFormat: { const { key, value } = /** @type {ContentFormat} */ (item.content); if (this.adds(item)) { if (!this.deletes(item)) { const curVal = currentAttributes.get(key) || null; if (!equalAttrs(curVal, value)) { if (action === 'retain') { addOp(); } if (equalAttrs(value, (oldAttributes.get(key) || null))) { delete attributes[key]; } else { attributes[key] = value; } } else { item.delete(transaction); } } } else if (this.deletes(item)) { oldAttributes.set(key, value); const curVal = currentAttributes.get(key) || null; if (!equalAttrs(curVal, value)) { if (action === 'retain') { addOp(); } attributes[key] = curVal; } } else if (!item.deleted) { oldAttributes.set(key, value); const attr = attributes[key]; if (attr !== undefined) { if (!equalAttrs(attr, value)) { if (action === 'retain') { addOp(); } if (value === null) { attributes[key] = value; } else { delete attributes[key]; } } else { item.delete(transaction); } } } if (!item.deleted) { if (action === 'insert') { addOp(); } updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content)); } break } } item = item.right; } addOp(); while (delta.length > 0) { const lastOp = delta[delta.length - 1]; if (lastOp.retain !== undefined && lastOp.attributes === undefined) { // retain delta's if they don't assign attributes delta.pop(); } else { break } } }); } return this._delta } }
JavaScript
class YText extends AbstractType { /** * @param {String} [string] The initial value of the YText. */ constructor (string) { super(); /** * Array of pending operations on this type * @type {Array<function():void>?} */ this._pending = string !== undefined ? [() => this.insert(0, string)] : []; /** * @type {Array<ArraySearchMarker>} */ this._searchMarker = []; } /** * Number of characters of this text type. * * @type {number} */ get length () { return this._length } /** * @param {Doc} y * @param {Item} item */ _integrate (y, item) { super._integrate(y, item); try { /** @type {Array<function>} */ (this._pending).forEach(f => f()); } catch (e) { console.error(e); } this._pending = null; } _copy () { return new YText() } /** * @return {YText} */ clone () { const text = new YText(); text.applyDelta(this.toDelta()); return text } /** * Creates YTextEvent and calls observers. * * @param {Transaction} transaction * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. */ _callObserver (transaction, parentSubs) { super._callObserver(transaction, parentSubs); const event = new YTextEvent(this, transaction); const doc = transaction.doc; // If a remote change happened, we try to cleanup potential formatting duplicates. if (!transaction.local) { // check if another formatting item was inserted let foundFormattingItem = false; for (const [client, afterClock] of transaction.afterState.entries()) { const clock = transaction.beforeState.get(client) || 0; if (afterClock === clock) { continue } iterateStructs(transaction, /** @type {Array<Item|GC>} */ (doc.store.clients.get(client)), clock, afterClock, item => { if (!item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat) { foundFormattingItem = true; } }); if (foundFormattingItem) { break } } if (!foundFormattingItem) { iterateDeletedStructs(transaction, transaction.deleteSet, item => { if (item instanceof GC || foundFormattingItem) { return } if (item.parent === this && item.content.constructor === ContentFormat) { foundFormattingItem = true; } }); } transact(doc, (t) => { if (foundFormattingItem) { // If a formatting item was inserted, we simply clean the whole type. // We need to compute currentAttributes for the current position anyway. cleanupYTextFormatting(this); } else { // If no formatting attribute was inserted, we can make due with contextless // formatting cleanups. // Contextless: it is not necessary to compute currentAttributes for the affected position. iterateDeletedStructs(t, t.deleteSet, item => { if (item instanceof GC) { return } if (item.parent === this) { cleanupContextlessFormattingGap(t, item); } }); } }); } callTypeObservers(this, transaction, event); } /** * Returns the unformatted string representation of this YText type. * * @public */ toString () { let str = ''; /** * @type {Item|null} */ let n = this._start; while (n !== null) { if (!n.deleted && n.countable && n.content.constructor === ContentString) { str += /** @type {ContentString} */ (n.content).str; } n = n.right; } return str } /** * Returns the unformatted string representation of this YText type. * * @return {string} * @public */ toJSON () { return this.toString() } /** * Apply a {@link Delta} on this shared YText type. * * @param {any} delta The changes to apply on this element. * @param {object} [opts] * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true. * * * @public */ applyDelta (delta, { sanitize = true } = {}) { if (this.doc !== null) { transact(this.doc, transaction => { const currPos = new ItemTextListPosition(null, this._start, 0, new Map()); for (let i = 0; i < delta.length; i++) { const op = delta[i]; if (op.insert !== undefined) { // Quill assumes that the content starts with an empty paragraph. // Yjs/Y.Text assumes that it starts empty. We always hide that // there is a newline at the end of the content. // If we omit this step, clients will see a different number of // paragraphs, but nothing bad will happen. const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\n') ? op.insert.slice(0, -1) : op.insert; if (typeof ins !== 'string' || ins.length > 0) { insertText(transaction, this, currPos, ins, op.attributes || {}); } } else if (op.retain !== undefined) { formatText(transaction, this, currPos, op.retain, op.attributes || {}); } else if (op.delete !== undefined) { deleteText(transaction, currPos, op.delete); } } }); } else { /** @type {Array<function>} */ (this._pending).push(() => this.applyDelta(delta)); } } /** * Returns the Delta representation of this YText type. * * @param {Snapshot} [snapshot] * @param {Snapshot} [prevSnapshot] * @param {function('removed' | 'added', ID):any} [computeYChange] * @return {any} The Delta representation of this type. * * @public */ toDelta (snapshot, prevSnapshot, computeYChange) { /** * @type{Array<any>} */ const ops = []; const currentAttributes = new Map(); const doc = /** @type {Doc} */ (this.doc); let str = ''; let n = this._start; function packStr () { if (str.length > 0) { // pack str with attributes to ops /** * @type {Object<string,any>} */ const attributes = {}; let addAttributes = false; currentAttributes.forEach((value, key) => { addAttributes = true; attributes[key] = value; }); /** * @type {Object<string,any>} */ const op = { insert: str }; if (addAttributes) { op.attributes = attributes; } ops.push(op); str = ''; } } // snapshots are merged again after the transaction, so we need to keep the // transalive until we are done transact(doc, transaction => { if (snapshot) { splitSnapshotAffectedStructs(transaction, snapshot); } if (prevSnapshot) { splitSnapshotAffectedStructs(transaction, prevSnapshot); } while (n !== null) { if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) { switch (n.content.constructor) { case ContentString: { const cur = currentAttributes.get('ychange'); if (snapshot !== undefined && !isVisible(n, snapshot)) { if (cur === undefined || cur.user !== n.id.client || cur.state !== 'removed') { packStr(); currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' }); } } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) { if (cur === undefined || cur.user !== n.id.client || cur.state !== 'added') { packStr(); currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' }); } } else if (cur !== undefined) { packStr(); currentAttributes.delete('ychange'); } str += /** @type {ContentString} */ (n.content).str; break } case ContentEmbed: { packStr(); /** * @type {Object<string,any>} */ const op = { insert: /** @type {ContentEmbed} */ (n.content).embed }; if (currentAttributes.size > 0) { const attrs = /** @type {Object<string,any>} */ ({}); op.attributes = attrs; currentAttributes.forEach((value, key) => { attrs[key] = value; }); } ops.push(op); break } case ContentFormat: if (isVisible(n, snapshot)) { packStr(); updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content)); } break } } n = n.right; } packStr(); }, splitSnapshotAffectedStructs); return ops } /** * Insert text at a given index. * * @param {number} index The index at which to start inserting. * @param {String} text The text to insert at the specified position. * @param {TextAttributes} [attributes] Optionally define some formatting * information to apply on the inserted * Text. * @public */ insert (index, text, attributes) { if (text.length <= 0) { return } const y = this.doc; if (y !== null) { transact(y, transaction => { const pos = findPosition(transaction, this, index); if (!attributes) { attributes = {}; // @ts-ignore pos.currentAttributes.forEach((v, k) => { attributes[k] = v; }); } insertText(transaction, this, pos, text, attributes); }); } else { /** @type {Array<function>} */ (this._pending).push(() => this.insert(index, text, attributes)); } } /** * Inserts an embed at a index. * * @param {number} index The index to insert the embed at. * @param {Object} embed The Object that represents the embed. * @param {TextAttributes} attributes Attribute information to apply on the * embed * * @public */ insertEmbed (index, embed, attributes = {}) { if (embed.constructor !== Object) { throw new Error('Embed must be an Object') } const y = this.doc; if (y !== null) { transact(y, transaction => { const pos = findPosition(transaction, this, index); insertText(transaction, this, pos, embed, attributes); }); } else { /** @type {Array<function>} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes)); } } /** * Deletes text starting from an index. * * @param {number} index Index at which to start deleting. * @param {number} length The number of characters to remove. Defaults to 1. * * @public */ delete (index, length) { if (length === 0) { return } const y = this.doc; if (y !== null) { transact(y, transaction => { deleteText(transaction, findPosition(transaction, this, index), length); }); } else { /** @type {Array<function>} */ (this._pending).push(() => this.delete(index, length)); } } /** * Assigns properties to a range of text. * * @param {number} index The position where to start formatting. * @param {number} length The amount of characters to assign properties to. * @param {TextAttributes} attributes Attribute information to apply on the * text. * * @public */ format (index, length, attributes) { if (length === 0) { return } const y = this.doc; if (y !== null) { transact(y, transaction => { const pos = findPosition(transaction, this, index); if (pos.right === null) { return } formatText(transaction, this, pos, length, attributes); }); } else { /** @type {Array<function>} */ (this._pending).push(() => this.format(index, length, attributes)); } } /** * @param {AbstractUpdateEncoder} encoder */ _write (encoder) { encoder.writeTypeRef(YTextRefID); } }
JavaScript
class YXmlTreeWalker { /** * @param {YXmlFragment | YXmlElement} root * @param {function(AbstractType<any>):boolean} [f] */ constructor (root, f = () => true) { this._filter = f; this._root = root; /** * @type {Item} */ this._currentNode = /** @type {Item} */ (root._start); this._firstCall = true; } [Symbol.iterator] () { return this } /** * Get the next node. * * @return {IteratorResult<YXmlElement|YXmlText|YXmlHook>} The next node. * * @public */ next () { /** * @type {Item|null} */ let n = this._currentNode; let type = /** @type {any} */ (n.content).type; if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item do { type = /** @type {any} */ (n.content).type; if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) { // walk down in the tree n = type._start; } else { // walk right or up in the tree while (n !== null) { if (n.right !== null) { n = n.right; break } else if (n.parent === this._root) { n = null; } else { n = /** @type {AbstractType<any>} */ (n.parent)._item; } } } } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type))) } this._firstCall = false; if (n === null) { // @ts-ignore return { value: undefined, done: true } } this._currentNode = n; return { value: /** @type {any} */ (n.content).type, done: false } } }
JavaScript
class YXmlFragment extends AbstractType { constructor () { super(); /** * @type {Array<any>|null} */ this._prelimContent = []; } /** * Integrate this type into the Yjs instance. * * * Save this struct in the os * * This type is sent to other client * * Observer functions are fired * * @param {Doc} y The Yjs instance * @param {Item} item */ _integrate (y, item) { super._integrate(y, item); this.insert(0, /** @type {Array<any>} */ (this._prelimContent)); this._prelimContent = null; } _copy () { return new YXmlFragment() } /** * @return {YXmlFragment} */ clone () { const el = new YXmlFragment(); // @ts-ignore el.insert(0, el.toArray().map(item => item instanceof AbstractType ? item.clone() : item)); return el } get length () { return this._prelimContent === null ? this._length : this._prelimContent.length } /** * Create a subtree of childNodes. * * @example * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div') * for (let node in walker) { * // `node` is a div node * nop(node) * } * * @param {function(AbstractType<any>):boolean} filter Function that is called on each child element and * returns a Boolean indicating whether the child * is to be included in the subtree. * @return {YXmlTreeWalker} A subtree and a position within it. * * @public */ createTreeWalker (filter) { return new YXmlTreeWalker(this, filter) } /** * Returns the first YXmlElement that matches the query. * Similar to DOM's {@link querySelector}. * * Query support: * - tagname * TODO: * - id * - attribute * * @param {CSS_Selector} query The query on the children. * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null. * * @public */ querySelector (query) { query = query.toUpperCase(); // @ts-ignore const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query); const next = iterator.next(); if (next.done) { return null } else { return next.value } } /** * Returns all YXmlElements that match the query. * Similar to Dom's {@link querySelectorAll}. * * @todo Does not yet support all queries. Currently only query by tagName. * * @param {CSS_Selector} query The query on the children * @return {Array<YXmlElement|YXmlText|YXmlHook|null>} The elements that match this query. * * @public */ querySelectorAll (query) { query = query.toUpperCase(); // @ts-ignore return Array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query)) } /** * Creates YXmlEvent and calls observers. * * @param {Transaction} transaction * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. */ _callObserver (transaction, parentSubs) { callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction)); } /** * Get the string representation of all the children of this YXmlFragment. * * @return {string} The string representation of all children. */ toString () { return typeListMap(this, xml => xml.toString()).join('') } /** * @return {string} */ toJSON () { return this.toString() } /** * Creates a Dom Element that mirrors this YXmlElement. * * @param {Document} [_document=document] The document object (you must define * this when calling this method in * nodejs) * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks * are presented in the DOM * @param {any} [binding] You should not set this property. This is * used if DomBinding wants to create a * association to the created DOM type. * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} * * @public */ toDOM (_document = document, hooks = {}, binding) { const fragment = _document.createDocumentFragment(); if (binding !== undefined) { binding._createAssociation(fragment, this); } typeListForEach(this, xmlType => { fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null); }); return fragment } /** * Inserts new content at an index. * * @example * // Insert character 'a' at position 0 * xml.insert(0, [new Y.XmlText('text')]) * * @param {number} index The index to insert content at * @param {Array<YXmlElement|YXmlText>} content The array of content */ insert (index, content) { if (this.doc !== null) { transact(this.doc, transaction => { typeListInsertGenerics(transaction, this, index, content); }); } else { // @ts-ignore _prelimContent is defined because this is not yet integrated this._prelimContent.splice(index, 0, ...content); } } /** * Deletes elements starting from an index. * * @param {number} index Index at which to start deleting elements * @param {number} [length=1] The number of elements to remove. Defaults to 1. */ delete (index, length = 1) { if (this.doc !== null) { transact(this.doc, transaction => { typeListDelete(transaction, this, index, length); }); } else { // @ts-ignore _prelimContent is defined because this is not yet integrated this._prelimContent.splice(index, length); } } /** * Transforms this YArray to a JavaScript Array. * * @return {Array<YXmlElement|YXmlText|YXmlHook>} */ toArray () { return typeListToArray(this) } /** * Appends content to this YArray. * * @param {Array<YXmlElement|YXmlText>} content Array of content to append. */ push (content) { this.insert(this.length, content); } /** * Preppends content to this YArray. * * @param {Array<YXmlElement|YXmlText>} content Array of content to preppend. */ unshift (content) { this.insert(0, content); } /** * Returns the i-th element from a YArray. * * @param {number} index The index of the element to return from the YArray * @return {YXmlElement|YXmlText} */ get (index) { return typeListGet(this, index) } /** * Transforms this YArray to a JavaScript Array. * * @param {number} [start] * @param {number} [end] * @return {Array<YXmlElement|YXmlText>} */ slice (start = 0, end = this.length) { return typeListSlice(this, start, end) } /** * Transform the properties of this type to binary and write it to an * BinaryEncoder. * * This is called when this Item is sent to a remote peer. * * @param {AbstractUpdateEncoder} encoder The encoder to write data to. */ _write (encoder) { encoder.writeTypeRef(YXmlFragmentRefID); } }
JavaScript
class YXmlElement extends YXmlFragment { constructor (nodeName = 'UNDEFINED') { super(); this.nodeName = nodeName; /** * @type {Map<string, any>|null} */ this._prelimAttrs = new Map(); } /** * Integrate this type into the Yjs instance. * * * Save this struct in the os * * This type is sent to other client * * Observer functions are fired * * @param {Doc} y The Yjs instance * @param {Item} item */ _integrate (y, item) { super._integrate(y, item) ;(/** @type {Map<string, any>} */ (this._prelimAttrs)).forEach((value, key) => { this.setAttribute(key, value); }); this._prelimAttrs = null; } /** * Creates an Item with the same effect as this Item (without position effect) * * @return {YXmlElement} */ _copy () { return new YXmlElement(this.nodeName) } /** * @return {YXmlElement} */ clone () { const el = new YXmlElement(this.nodeName); const attrs = this.getAttributes(); for (const key in attrs) { el.setAttribute(key, attrs[key]); } // @ts-ignore el.insert(0, el.toArray().map(item => item instanceof AbstractType ? item.clone() : item)); return el } /** * Returns the XML serialization of this YXmlElement. * The attributes are ordered by attribute-name, so you can easily use this * method to compare YXmlElements * * @return {string} The string representation of this type. * * @public */ toString () { const attrs = this.getAttributes(); const stringBuilder = []; const keys = []; for (const key in attrs) { keys.push(key); } keys.sort(); const keysLen = keys.length; for (let i = 0; i < keysLen; i++) { const key = keys[i]; stringBuilder.push(key + '="' + attrs[key] + '"'); } const nodeName = this.nodeName.toLocaleLowerCase(); const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : ''; return `<${nodeName}${attrsString}>${super.toString()}</${nodeName}>` } /** * Removes an attribute from this YXmlElement. * * @param {String} attributeName The attribute name that is to be removed. * * @public */ removeAttribute (attributeName) { if (this.doc !== null) { transact(this.doc, transaction => { typeMapDelete(transaction, this, attributeName); }); } else { /** @type {Map<string,any>} */ (this._prelimAttrs).delete(attributeName); } } /** * Sets or updates an attribute. * * @param {String} attributeName The attribute name that is to be set. * @param {String} attributeValue The attribute value that is to be set. * * @public */ setAttribute (attributeName, attributeValue) { if (this.doc !== null) { transact(this.doc, transaction => { typeMapSet(transaction, this, attributeName, attributeValue); }); } else { /** @type {Map<string, any>} */ (this._prelimAttrs).set(attributeName, attributeValue); } } /** * Returns an attribute value that belongs to the attribute name. * * @param {String} attributeName The attribute name that identifies the * queried value. * @return {String} The queried attribute value. * * @public */ getAttribute (attributeName) { return /** @type {any} */ (typeMapGet(this, attributeName)) } /** * Returns all attribute name/value pairs in a JSON Object. * * @param {Snapshot} [snapshot] * @return {Object<string, any>} A JSON Object that describes the attributes. * * @public */ getAttributes (snapshot) { return typeMapGetAll(this) } /** * Creates a Dom Element that mirrors this YXmlElement. * * @param {Document} [_document=document] The document object (you must define * this when calling this method in * nodejs) * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks * are presented in the DOM * @param {any} [binding] You should not set this property. This is * used if DomBinding wants to create a * association to the created DOM type. * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} * * @public */ toDOM (_document = document, hooks = {}, binding) { const dom = _document.createElement(this.nodeName); const attrs = this.getAttributes(); for (const key in attrs) { dom.setAttribute(key, attrs[key]); } typeListForEach(this, yxml => { dom.appendChild(yxml.toDOM(_document, hooks, binding)); }); if (binding !== undefined) { binding._createAssociation(dom, this); } return dom } /** * Transform the properties of this type to binary and write it to an * BinaryEncoder. * * This is called when this Item is sent to a remote peer. * * @param {AbstractUpdateEncoder} encoder The encoder to write data to. */ _write (encoder) { encoder.writeTypeRef(YXmlElementRefID); encoder.writeKey(this.nodeName); } }
JavaScript
class YXmlEvent extends YEvent { /** * @param {YXmlElement|YXmlFragment} target The target on which the event is created. * @param {Set<string|null>} subs The set of changed attributes. `null` is included if the * child list changed. * @param {Transaction} transaction The transaction instance with wich the * change was created. */ constructor (target, subs, transaction) { super(target, transaction); /** * Whether the children changed. * @type {Boolean} * @private */ this.childListChanged = false; /** * Set of all changed attributes. * @type {Set<string|null>} */ this.attributesChanged = new Set(); subs.forEach((sub) => { if (sub === null) { this.childListChanged = true; } else { this.attributesChanged.add(sub); } }); } }
JavaScript
class YXmlHook extends YMap { /** * @param {string} hookName nodeName of the Dom Node. */ constructor (hookName) { super(); /** * @type {string} */ this.hookName = hookName; } /** * Creates an Item with the same effect as this Item (without position effect) */ _copy () { return new YXmlHook(this.hookName) } /** * @return {YXmlHook} */ clone () { const el = new YXmlHook(this.hookName); this.forEach((value, key) => { el.set(key, value); }); return el } /** * Creates a Dom Element that mirrors this YXmlElement. * * @param {Document} [_document=document] The document object (you must define * this when calling this method in * nodejs) * @param {Object.<string, any>} [hooks] Optional property to customize how hooks * are presented in the DOM * @param {any} [binding] You should not set this property. This is * used if DomBinding wants to create a * association to the created DOM type * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} * * @public */ toDOM (_document = document, hooks = {}, binding) { const hook = hooks[this.hookName]; let dom; if (hook !== undefined) { dom = hook.createDom(this); } else { dom = document.createElement(this.hookName); } dom.setAttribute('data-yjs-hook', this.hookName); if (binding !== undefined) { binding._createAssociation(dom, this); } return dom } /** * Transform the properties of this type to binary and write it to an * BinaryEncoder. * * This is called when this Item is sent to a remote peer. * * @param {AbstractUpdateEncoder} encoder The encoder to write data to. */ _write (encoder) { encoder.writeTypeRef(YXmlHookRefID); encoder.writeKey(this.hookName); } }
JavaScript
class YXmlText extends YText { _copy () { return new YXmlText() } /** * @return {YXmlText} */ clone () { const text = new YXmlText(); text.applyDelta(this.toDelta()); return text } /** * Creates a Dom Element that mirrors this YXmlText. * * @param {Document} [_document=document] The document object (you must define * this when calling this method in * nodejs) * @param {Object<string, any>} [hooks] Optional property to customize how hooks * are presented in the DOM * @param {any} [binding] You should not set this property. This is * used if DomBinding wants to create a * association to the created DOM type. * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} * * @public */ toDOM (_document = document, hooks, binding) { const dom = _document.createTextNode(this.toString()); if (binding !== undefined) { binding._createAssociation(dom, this); } return dom } toString () { // @ts-ignore return this.toDelta().map(delta => { const nestedNodes = []; for (const nodeName in delta.attributes) { const attrs = []; for (const key in delta.attributes[nodeName]) { attrs.push({ key, value: delta.attributes[nodeName][key] }); } // sort attributes to get a unique order attrs.sort((a, b) => a.key < b.key ? -1 : 1); nestedNodes.push({ nodeName, attrs }); } // sort node order to get a unique order nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1); // now convert to dom string let str = ''; for (let i = 0; i < nestedNodes.length; i++) { const node = nestedNodes[i]; str += `<${node.nodeName}`; for (let j = 0; j < node.attrs.length; j++) { const attr = node.attrs[j]; str += ` ${attr.key}="${attr.value}"`; } str += '>'; } str += delta.insert; for (let i = nestedNodes.length - 1; i >= 0; i--) { str += `</${nestedNodes[i].nodeName}>`; } return str }).join('') } /** * @return {string} */ toJSON () { return this.toString() } /** * @param {AbstractUpdateEncoder} encoder */ _write (encoder) { encoder.writeTypeRef(YXmlTextRefID); } }
JavaScript
class Item extends AbstractStruct { /** * @param {ID} id * @param {Item | null} left * @param {ID | null} origin * @param {Item | null} right * @param {ID | null} rightOrigin * @param {AbstractType<any>|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it. * @param {string | null} parentSub * @param {AbstractContent} content */ constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) { super(id, content.getLength()); /** * The item that was originally to the left of this item. * @type {ID | null} */ this.origin = origin; /** * The item that is currently to the left of this item. * @type {Item | null} */ this.left = left; /** * The item that is currently to the right of this item. * @type {Item | null} */ this.right = right; /** * The item that was originally to the right of this item. * @type {ID | null} */ this.rightOrigin = rightOrigin; /** * @type {AbstractType<any>|ID|null} */ this.parent = parent; /** * If the parent refers to this item with some kind of key (e.g. YMap, the * key is specified here. The key is then used to refer to the list in which * to insert this item. If `parentSub = null` type._start is the list in * which to insert to. Otherwise it is `parent._map`. * @type {String | null} */ this.parentSub = parentSub; /** * If this type's effect is reundone this type refers to the type that undid * this operation. * @type {ID | null} */ this.redone = null; /** * @type {AbstractContent} */ this.content = content; /** * bit1: keep * bit2: countable * bit3: deleted * bit4: mark - mark node as fast-search-marker * @type {number} byte */ this.info = this.content.isCountable() ? BIT2 : 0; } /** * This is used to mark the item as an indexed fast-search marker * * @type {boolean} */ set marker (isMarked) { if (((this.info & BIT4) > 0) !== isMarked) { this.info ^= BIT4; } } get marker () { return (this.info & BIT4) > 0 } /** * If true, do not garbage collect this Item. */ get keep () { return (this.info & BIT1) > 0 } set keep (doKeep) { if (this.keep !== doKeep) { this.info ^= BIT1; } } get countable () { return (this.info & BIT2) > 0 } /** * Whether this item was deleted or not. * @type {Boolean} */ get deleted () { return (this.info & BIT3) > 0 } set deleted (doDelete) { if (this.deleted !== doDelete) { this.info ^= BIT3; } } markDeleted () { this.info |= BIT3; } /** * Return the creator clientID of the missing op or define missing items and return null. * * @param {Transaction} transaction * @param {StructStore} store * @return {null | number} */ getMissing (transaction, store) { if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) { return this.origin.client } if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) { return this.rightOrigin.client } if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) { return this.parent.client } // We have all missing ids, now find the items if (this.origin) { this.left = getItemCleanEnd(transaction, store, this.origin); this.origin = this.left.lastId; } if (this.rightOrigin) { this.right = getItemCleanStart(transaction, this.rightOrigin); this.rightOrigin = this.right.id; } if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) { this.parent = null; } // only set parent if this shouldn't be garbage collected if (!this.parent) { if (this.left && this.left.constructor === Item) { this.parent = this.left.parent; this.parentSub = this.left.parentSub; } if (this.right && this.right.constructor === Item) { this.parent = this.right.parent; this.parentSub = this.right.parentSub; } } else if (this.parent.constructor === ID) { const parentItem = getItem(store, this.parent); if (parentItem.constructor === GC) { this.parent = null; } else { this.parent = /** @type {ContentType} */ (parentItem.content).type; } } return null } /** * @param {Transaction} transaction * @param {number} offset */ integrate (transaction, offset) { if (offset > 0) { this.id.clock += offset; this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1)); this.origin = this.left.lastId; this.content = this.content.splice(offset); this.length -= offset; } if (this.parent) { if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) { /** * @type {Item|null} */ let left = this.left; /** * @type {Item|null} */ let o; // set o to the first conflicting item if (left !== null) { o = left.right; } else if (this.parentSub !== null) { o = /** @type {AbstractType<any>} */ (this.parent)._map.get(this.parentSub) || null; while (o !== null && o.left !== null) { o = o.left; } } else { o = /** @type {AbstractType<any>} */ (this.parent)._start; } // TODO: use something like DeleteSet here (a tree implementation would be best) // @todo use global set definitions /** * @type {Set<Item>} */ const conflictingItems = new Set(); /** * @type {Set<Item>} */ const itemsBeforeOrigin = new Set(); // Let c in conflictingItems, b in itemsBeforeOrigin // ***{origin}bbbb{this}{c,b}{c,b}{o}*** // Note that conflictingItems is a subset of itemsBeforeOrigin while (o !== null && o !== this.right) { itemsBeforeOrigin.add(o); conflictingItems.add(o); if (compareIDs(this.origin, o.origin)) { // case 1 if (o.id.client < this.id.client) { left = o; conflictingItems.clear(); } else if (compareIDs(this.rightOrigin, o.rightOrigin)) { // this and o are conflicting and point to the same integration points. The id decides which item comes first. // Since this is to the left of o, we can break here break } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items. // case 2 if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) { left = o; conflictingItems.clear(); } } else { break } o = o.right; } this.left = left; } // reconnect left/right + update parent map/start if necessary if (this.left !== null) { const right = this.left.right; this.right = right; this.left.right = this; } else { let r; if (this.parentSub !== null) { r = /** @type {AbstractType<any>} */ (this.parent)._map.get(this.parentSub) || null; while (r !== null && r.left !== null) { r = r.left; } } else { r = /** @type {AbstractType<any>} */ (this.parent)._start ;/** @type {AbstractType<any>} */ (this.parent)._start = this; } this.right = r; } if (this.right !== null) { this.right.left = this; } else if (this.parentSub !== null) { // set as current parent value if right === null and this is parentSub /** @type {AbstractType<any>} */ (this.parent)._map.set(this.parentSub, this); if (this.left !== null) { // this is the current attribute value of parent. delete right this.left.delete(transaction); } } // adjust length of parent if (this.parentSub === null && this.countable && !this.deleted) { /** @type {AbstractType<any>} */ (this.parent)._length += this.length; } addStruct(transaction.doc.store, this); this.content.integrate(transaction, this); // add parent to transaction.changed addChangedTypeToTransaction(transaction, /** @type {AbstractType<any>} */ (this.parent), this.parentSub); if ((/** @type {AbstractType<any>} */ (this.parent)._item !== null && /** @type {AbstractType<any>} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) { // delete if parent is deleted or if this is not the current attribute value of parent this.delete(transaction); } } else { // parent is not defined. Integrate GC struct instead new GC(this.id, this.length).integrate(transaction, 0); } } /** * Returns the next non-deleted item */ get next () { let n = this.right; while (n !== null && n.deleted) { n = n.right; } return n } /** * Returns the previous non-deleted item */ get prev () { let n = this.left; while (n !== null && n.deleted) { n = n.left; } return n } /** * Computes the last content address of this Item. */ get lastId () { // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1) } /** * Try to merge two items * * @param {Item} right * @return {boolean} */ mergeWith (right) { if ( compareIDs(right.origin, this.lastId) && this.right === right && compareIDs(this.rightOrigin, right.rightOrigin) && this.id.client === right.id.client && this.id.clock + this.length === right.id.clock && this.deleted === right.deleted && this.redone === null && right.redone === null && this.content.constructor === right.content.constructor && this.content.mergeWith(right.content) ) { if (right.keep) { this.keep = true; } this.right = right.right; if (this.right !== null) { this.right.left = this; } this.length += right.length; return true } return false } /** * Mark this Item as deleted. * * @param {Transaction} transaction */ delete (transaction) { if (!this.deleted) { const parent = /** @type {AbstractType<any>} */ (this.parent); // adjust the length of parent if (this.countable && this.parentSub === null) { parent._length -= this.length; } this.markDeleted(); addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length); addChangedTypeToTransaction(transaction, parent, this.parentSub); this.content.delete(transaction); } } /** * @param {StructStore} store * @param {boolean} parentGCd */ gc (store, parentGCd) { if (!this.deleted) { throw unexpectedCase() } this.content.gc(store); if (parentGCd) { replaceStruct(store, this, new GC(this.id, this.length)); } else { this.content = new ContentDeleted(this.length); } } /** * Transform the properties of this type to binary and write it to an * BinaryEncoder. * * This is called when this Item is sent to a remote peer. * * @param {AbstractUpdateEncoder} encoder The encoder to write data to. * @param {number} offset */ write (encoder, offset) { const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin; const rightOrigin = this.rightOrigin; const parentSub = this.parentSub; const info = (this.content.getRef() & BITS5) | (origin === null ? 0 : BIT8) | // origin is defined (rightOrigin === null ? 0 : BIT7) | // right origin is defined (parentSub === null ? 0 : BIT6); // parentSub is non-null encoder.writeInfo(info); if (origin !== null) { encoder.writeLeftID(origin); } if (rightOrigin !== null) { encoder.writeRightID(rightOrigin); } if (origin === null && rightOrigin === null) { const parent = /** @type {AbstractType<any>} */ (this.parent); const parentItem = parent._item; if (parentItem === null) { // parent type on y._map // find the correct key const ykey = findRootTypeKey(parent); encoder.writeParentInfo(true); // write parentYKey encoder.writeString(ykey); } else { encoder.writeParentInfo(false); // write parent id encoder.writeLeftID(parentItem.id); } if (parentSub !== null) { encoder.writeString(parentSub); } } this.content.write(encoder, offset); } }
JavaScript
class Awareness extends Observable { /** * @param {Y.Doc} doc */ constructor (doc) { super(); this.doc = doc; /** * Maps from client id to client state * @type {Map<number, Object<string, any>>} */ this.states = new Map(); /** * @type {Map<number, MetaClientState>} */ this.meta = new Map(); this._checkInterval = setInterval(() => { const now = getUnixTime(); if (this.getLocalState() !== null && (outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ (this.meta.get(doc.clientID)).lastUpdated)) { // renew local clock this.setLocalState(this.getLocalState()); } /** * @type {Array<number>} */ const remove = []; this.meta.forEach((meta, clientid) => { if (clientid !== doc.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) { remove.push(clientid); } }); if (remove.length > 0) { removeAwarenessStates(this, remove, 'timeout'); } }, floor(outdatedTimeout / 10)); doc.on('destroy', () => { this.destroy(); }); this.setLocalState({}); } destroy () { super.destroy(); clearInterval(this._checkInterval); } /** * @return {Object<string,any>|null} */ getLocalState () { return this.states.get(this.doc.clientID) || null } /** * @param {Object<string,any>|null} state */ setLocalState (state) { const clientID = this.doc.clientID; const currLocalMeta = this.meta.get(clientID); const clock = currLocalMeta === undefined ? 0 : currLocalMeta.clock + 1; const prevState = this.states.get(clientID); if (state === null) { this.states.delete(clientID); } else { this.states.set(clientID, state); } this.meta.set(clientID, { clock, lastUpdated: getUnixTime() }); const added = []; const updated = []; const filteredUpdated = []; const removed = []; if (state === null) { removed.push(clientID); } else if (prevState == null) { if (state != null) { added.push(clientID); } } else { updated.push(clientID); if (!equalityDeep(prevState, state)) { filteredUpdated.push(clientID); } } if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) { this.emit('change', [{ added, updated: filteredUpdated, removed }, 'local']); } this.emit('update', [{ added, updated, removed }, 'local']); } /** * @param {string} field * @param {any} value */ setLocalStateField (field, value) { const state = this.getLocalState(); if (state !== null) { state[field] = value; this.setLocalState(state); } } /** * @return {Map<number,Object<string,any>>} */ getStates () { return this.states } }
JavaScript
class SyntheticWorker{ constructor(workerfunc, onMsg){ let funcStr = workerfunc.toString(); if(funcStr.indexOf("function") == 0){ //Fix for next Fix for when Compiled funcStr = funcStr.replace("function", ""); } if(funcStr.indexOf("prototype.") >= 0){ //Fix for IE when not Compiled funcStr = funcStr.replace("prototype.", ""); } // Make a worker from an anonymous function body that instantiates the workerFunction as an onmessage callback let blob = new Blob([ '(function(global) { global.addEventListener(\'message\', function(e) {', 'var cb = function ', funcStr, ';', 'cb(e)', '}, false); } )(this)' ], { type: 'application/javascript' } ); this.blobURL = URL.createObjectURL( blob ); //Generate the Blob URL this.worker = new Worker( this.blobURL ); // Cleanup this.worker.onmessage = (e)=>{if(e.data.term) worker.terminate(); else if(onMsg) onMsg(e);}; } terminate(){ if(this.worker){ this.worker.terminate(); URL.revokeObjectURL( this.blobURL ); } } postMessage(msg){ if(this.worker) this.worker.postMessage(msg); } }
JavaScript
class DeviceCollection extends cr.ui.ArrayDataModel { /** * @param {!Array<!bluetooth.mojom.DeviceInfo>} array The starting * collection of devices. */ constructor(array) { super(array); // Keep track of MAC addresses which were previously found via scan, but // are no longer being advertised or nearby. Used to inform isRemoved(). /** @private {!Object<string, boolean>} */ this.removedDevices_ = {}; } /** * Finds the Device in the collection with the matching address. * @param {string} address */ getByAddress(address) { for (let i = 0; i < this.length; i++) { const device = this.item(i); if (address == device.address) { return device; } } return null; } /** * Adds or updates a Device with new DeviceInfo. * @param {!bluetooth.mojom.DeviceInfo} deviceInfo */ addOrUpdate(deviceInfo) { this.removedDevices_[deviceInfo.address] = false; const oldDeviceInfo = this.getByAddress(deviceInfo.address); if (oldDeviceInfo) { // Update rssi if it's valid const rssi = (deviceInfo.rssi && deviceInfo.rssi.value) || (oldDeviceInfo.rssi && oldDeviceInfo.rssi.value); // The rssi property may be null, so it must be re-assigned. Object.assign(oldDeviceInfo, deviceInfo); oldDeviceInfo.rssi = {value: rssi}; this.updateIndex(this.indexOf(oldDeviceInfo)); } else { this.push(deviceInfo); } } /** * Marks the Device as removed. * @param {!bluetooth.mojom.DeviceInfo} deviceInfo */ remove(deviceInfo) { const device = this.getByAddress(deviceInfo.address); assert(device, 'Device does not exist.'); this.removedDevices_[deviceInfo.address] = true; this.updateIndex(this.indexOf(device)); } /** * Return true if device was "removed" -- previously found via scan but * either no longer advertising or no longer nearby. * @param {!bluetooth.mojom.DeviceInfo} deviceInfo */ isRemoved(deviceInfo) { return !!this.removedDevices_[deviceInfo.address]; } }
JavaScript
class CronProcesses { // Cron processes enum kinds start. get emailServiceApiCallHookProcessor() { return 'emailServiceApiCallHookProcessor'; } get cronProcessesMonitor() { return 'cronProcessesMonitor'; } get bgJobProcessor() { return 'bgJobProcessor'; } get notificationJobProcessor() { return 'notificationJobProcessor'; } get webhookJobPreProcessor() { return 'webhookJobPreProcessor'; } get pepoMobileEventJobProcessor() { return 'pepoMobileEventJobProcessor'; } get socketJobProcessor() { return 'socketJobProcessor'; } get pixelJobProcessor() { return 'pixelJobProcessor'; } get cdnCacheInvalidationProcessor() { return 'cdnCacheInvalidationProcessor'; } get pushNotificationHookProcessor() { return 'pushNotificationHookProcessor'; } get pushNotificationAggregator() { return 'pushNotificationAggregator'; } get webhookProcessor() { return 'webhookProcessor'; } get userSocketConnArchival() { return 'userSocketConnArchival'; } get retryPendingReceiptValidation() { return 'retryPendingReceiptValidation'; } get monitorOstEventHooks() { return 'monitorOstEventHooks'; } get reValidateAllReceipts() { return 'reValidateAllReceipts'; } get populatePopularityCriteria() { return 'populatePopularityCriteria'; } get populateUserData() { return 'populateUserData'; } get populateUserWeeklyData() { return 'populateUserWeeklyData'; } get zoomMeetingTracker() { return 'zoomMeetingTracker'; } get channelTrendingRankGenerator() { return 'channelTrendingRankGenerator'; } // Cron processes enum types end // Status enum types start get runningStatus() { return 'running'; } get stoppedStatus() { return 'stopped'; } get inactiveStatus() { return 'inactive'; } // Status enum types end. get kinds() { const oThis = this; return { '1': oThis.emailServiceApiCallHookProcessor, '2': oThis.cronProcessesMonitor, '3': oThis.bgJobProcessor, '4': oThis.notificationJobProcessor, '5': oThis.socketJobProcessor, '6': oThis.pushNotificationHookProcessor, '7': oThis.pushNotificationAggregator, '8': oThis.userSocketConnArchival, '9': oThis.retryPendingReceiptValidation, '10': oThis.pepoMobileEventJobProcessor, '11': oThis.reValidateAllReceipts, '12': oThis.cdnCacheInvalidationProcessor, '13': oThis.pixelJobProcessor, '14': oThis.monitorOstEventHooks, '15': oThis.populatePopularityCriteria, '16': oThis.webhookJobPreProcessor, '17': oThis.webhookProcessor, '18': oThis.populateUserData, '19': oThis.populateUserWeeklyData, '20': oThis.zoomMeetingTracker, '21': oThis.channelTrendingRankGenerator }; } get invertedKinds() { const oThis = this; invertedKinds = invertedKinds || util.invert(oThis.kinds); return invertedKinds; } get statuses() { const oThis = this; return { '1': oThis.runningStatus, '2': oThis.stoppedStatus, '3': oThis.inactiveStatus }; } get invertedStatuses() { const oThis = this; invertedStatuses = invertedStatuses || util.invert(oThis.statuses); return invertedStatuses; } // Restart timeouts for crons. get continuousCronRestartInterval() { return 30 * 60 * 1000; } get cronRestartInterval5Mins() { return 5 * 60 * 1000; } // Cron types based on running time. get continuousCronsType() { return 'continuousCrons'; } get periodicCronsType() { return 'periodicCrons'; } }
JavaScript
class MapViewEnvironment { constructor(m_mapView, options) { this.m_mapView = m_mapView; this.m_fog = new MapViewFog_1.MapViewFog(this.m_mapView.scene); if (options.addBackgroundDatasource !== false) { this.m_backgroundDataSource = new BackgroundDataSource_1.BackgroundDataSource(); this.m_mapView.addDataSource(this.m_backgroundDataSource); } if (options.backgroundTilingScheme !== undefined && this.m_backgroundDataSource !== undefined) { this.m_backgroundDataSource.setTilingScheme(options.backgroundTilingScheme); } this.updateClearColor(); } get lights() { var _a; return (_a = this.m_createdLights) !== null && _a !== void 0 ? _a : []; } get fog() { return this.m_fog; } updateBackgroundDataSource() { if (this.m_backgroundDataSource) { this.m_backgroundDataSource.updateStorageLevelOffset(); } } setBackgroundTheme(theme) { if (theme !== undefined && this.m_backgroundDataSource !== undefined) { this.m_backgroundDataSource.setTheme(theme); } } update() { this.m_fog.update(this.m_mapView, this.m_mapView.viewRanges.maximum); if (this.m_skyBackground !== undefined && this.m_mapView.projection.type === harp_geoutils_1.ProjectionType.Planar) { this.m_skyBackground.updateCamera(this.m_mapView.camera); } this.updateLights(); } updateClearColor(theme) { if (theme !== undefined && theme.clearColor !== undefined) { this.m_mapView.renderer.setClearColor(new THREE.Color(theme.clearColor), theme.clearAlpha); } else { this.m_mapView.renderer.setClearColor(exports.DEFAULT_CLEAR_COLOR, theme === null || theme === void 0 ? void 0 : theme.clearAlpha); } } updateSkyBackground(theme) { if (this.m_skyBackground instanceof SkyBackground_1.SkyBackground && theme.sky !== undefined) { // there is a sky in the view and there is a sky option in the theme. Update the colors this.updateSkyBackgroundColors(theme.sky, theme.clearColor); } else if (this.m_skyBackground === undefined && theme.sky !== undefined) { // there is no sky in the view but there is a sky option in the theme this.addNewSkyBackground(theme.sky, theme.clearColor); return; } else if (this.m_skyBackground instanceof SkyBackground_1.SkyBackground && theme.sky === undefined) { // there is a sky in the view, but not in the theme this.removeSkyBackGround(); } } updateLighting(theme) { var _a; if (this.m_createdLights) { this.m_createdLights.forEach((light) => { this.m_mapView.scene.remove(light); }); } (_a = this.m_overlayCreatedLights) === null || _a === void 0 ? void 0 : _a.forEach(light => { this.m_mapView.overlayScene.remove(light); if (light instanceof THREE.DirectionalLight) { this.m_mapView.overlayScene.remove(light.target); } }); if (theme.lights !== undefined) { this.m_createdLights = []; this.m_overlayCreatedLights = []; theme.lights.forEach((lightDescription) => { const light = ThemeHelpers_1.createLight(lightDescription); if (!light) { logger.warn(`MapView: failed to create light ${lightDescription.name} of type ${lightDescription.type}`); return; } this.m_mapView.scene.add(light); if (light.isDirectionalLight) { const directionalLight = light; // This is needed so that the target is updated automatically, see: // https://threejs.org/docs/#api/en/lights/DirectionalLight.target this.m_mapView.scene.add(directionalLight.target); } this.m_createdLights.push(light); const clonedLight = light.clone(); this.m_mapView.overlayScene.add(clonedLight); if (clonedLight instanceof THREE.DirectionalLight) { this.m_mapView.overlayScene.add(clonedLight.target.clone()); } }); } } /** * Update the directional light camera. Note, this requires the cameras to first be updated. */ updateLights() { // TODO: HARP-9479 Globe doesn't support shadows. if (!this.m_mapView.shadowsEnabled || this.m_mapView.projection.type === harp_geoutils_1.ProjectionType.Spherical || this.m_createdLights === undefined || this.m_createdLights.length === 0) { return; } const points = [ // near plane points { x: -1, y: -1, z: -1 }, { x: 1, y: -1, z: -1 }, { x: -1, y: 1, z: -1 }, { x: 1, y: 1, z: -1 }, // far planes points { x: -1, y: -1, z: 1 }, { x: 1, y: -1, z: 1 }, { x: -1, y: 1, z: 1 }, { x: 1, y: 1, z: 1 } ]; const transformedPoints = points.map((p, i) => this.m_mapView.ndcToView(p, cache.frustumPoints[i])); this.m_createdLights.forEach(element => { const directionalLight = element; if (directionalLight.isDirectionalLight === true) { const lightDirection = cache.vector3[0]; lightDirection.copy(directionalLight.target.position); lightDirection.sub(directionalLight.position); lightDirection.normalize(); const normal = cache.vector3[1]; if (this.m_mapView.projection.type === harp_geoutils_1.ProjectionType.Planar) { // -Z points to the camera, we can't use Projection.surfaceNormal, because // webmercator and mercator give different results. normal.set(0, 0, -1); } else { // Enable shadows for globe... //this.projection.surfaceNormal(target, normal); } // The camera of the shadow has the same height as the map camera, and the target is // also the same. The position is then calculated based on the light direction and // the height // using basic trigonometry. const tilt = this.m_mapView.tilt; const cameraHeight = this.m_mapView.targetDistance * Math.cos(THREE.MathUtils.degToRad(tilt)); const lightPosHyp = cameraHeight / normal.dot(lightDirection); directionalLight.target.position .copy(this.m_mapView.worldTarget) .sub(this.m_mapView.camera.position); directionalLight.position.copy(this.m_mapView.worldTarget); directionalLight.position.addScaledVector(lightDirection, -lightPosHyp); directionalLight.position.sub(this.m_mapView.camera.position); directionalLight.updateMatrixWorld(); directionalLight.shadow.updateMatrices(directionalLight); const camera = directionalLight.shadow.camera; const pointsInLightSpace = transformedPoints.map(p => this.viewToLightSpace(p.clone(), camera)); const box = new THREE.Box3(); pointsInLightSpace.forEach(point => { box.expandByPoint(point); }); camera.left = box.min.x; camera.right = box.max.x; camera.top = box.max.y; camera.bottom = box.min.y; // Moving back to the light the near plane in order to catch high buildings, that // are not visible by the camera, but existing on the scene. camera.near = -box.max.z * 0.95; camera.far = -box.min.z; camera.updateProjectionMatrix(); } }); } addNewSkyBackground(sky, clearColor) { if (sky.type === "gradient" && sky.groundColor === undefined) { sky.groundColor = harp_utils_1.getOptionValue(clearColor, "#000000"); } this.m_skyBackground = new SkyBackground_1.SkyBackground(sky, this.m_mapView.projection.type, this.m_mapView.camera); this.m_mapView.scene.background = this.m_skyBackground.texture; } removeSkyBackGround() { this.m_mapView.scene.background = null; if (this.m_skyBackground !== undefined) { this.m_skyBackground.dispose(); this.m_skyBackground = undefined; } } updateSkyBackgroundColors(sky, clearColor) { var _a; if (sky.type === "gradient" && sky.groundColor === undefined) { sky.groundColor = harp_utils_1.getOptionValue(clearColor, "#000000"); } if (this.m_skyBackground !== undefined) { this.m_skyBackground.updateTexture(sky, this.m_mapView.projection.type); this.m_mapView.scene.background = (_a = this.m_skyBackground) === null || _a === void 0 ? void 0 : _a.texture; } } /** * Transfer from view space to camera space. * @param viewPos - position in view space, result is stored here. */ viewToLightSpace(viewPos, camera) { return viewPos.applyMatrix4(camera.matrixWorldInverse); } }
JavaScript
class Interpolate extends React.Component{ static propTypes = { template: PropTypes.string.isRequired }; render(){ const preJsxString = this.props.template || "" let interpolations = _.omit(this.props,["template"]) const regx = /<(.*)>(.*?)<\/\1>/g let readyForProcessing = preJsxString.replace(regx, (match)=> `%~%${match}%~%`) const stringSegments = readyForProcessing.split("%~%") let segments = stringSegments .map((str, index)=>{ let matches = regx.exec(str) let reactFn = matches && interpolations[matches[1]] if(typeof(reactFn) == 'function'){ return React.cloneElement(reactFn(matches[2]), {key: index}) }else if(typeof(reactFn) == "object" && reactFn){ return React.createElement("span", {key: index, style: reactFn}, matches[2]) }else if(typeof(reactFn) == 'string'){ return React.createElement("span", {key: index, className: reactFn}, matches[2]) }else{ return React.createElement("span", {key: index}, str) } }) return( <span> {segments} </span> ) } }
JavaScript
class ArticleBlock extends React.Component { constructor(props) { super(props); this.state = { data: [], articleData: null, loaded: false, }; this.handleReturnClick = this.handleReturnClick.bind(this) } /** * Load articles via Drupal JSON:API. */ componentDidMount() { fetch('/jsonapi/node/article?sort=-created&page[limit]=3') .then(response => response.json()) .then(data => this.setState({ data: data.data, loaded: true })); } /** * Add article data to state when clicking on an article link. * * @param article * @param e */ handleClick(article, e) { e.preventDefault(); this.setState({ articleData : article }); } /** * Returns article data from state and displays list. * @param e */ handleReturnClick(e) { e.preventDefault(); this.setState({ articleData : null }); } render() { const { data, articleData, loaded } = this.state; if (!loaded) { return <p>Loading ...</p>; } if (data.length === 0) { return <p>No results</p>; } // Display actual article. if (articleData) { return <Article article={articleData} returnClick={this.handleReturnClick} />; } // Display list of articles. return ( <div> <ul> {data.map(article => <li key={article.id}> <a href="#" onClick={this.handleClick.bind(this, article)}>{article.attributes.title}</a> </li> )} </ul> </div> ); } }
JavaScript
class components extends Component { state = {}; render() { return ( <TouchableOpacity style={{ borderWidth: 1, borderColor: 'rgba(0,0,0,0.2)', alignItems: 'center', justifyContent: 'center', width: 15, height: 15, backgroundColor: 'black', borderRadius: 50 }} /> ); } }
JavaScript
class BB8Filter extends BaseFilter{ constructor(val, applyTo, defaultCommand = { command: "roll", args: [100,100]}){ super(val, applyTo); this.defaultCommand = defaultCommand; } filter(newState, env, detector){ let resultState = this.defaultCommand; if(newState in this.valueToFilter[newState]){ newState.command = this.valueToFilter[newState].command; newState.args = this.valueToFilter[newState].args; } return resultState; } }
JavaScript
class CalciteSortableList { constructor() { /** * The selector for the handle elements. */ this.handleSelector = "calcite-handle"; /** * When true, disabled prevents interaction. This state shows items with lower opacity/grayed. */ this.disabled = false; /** * When true, content is waiting to be loaded. This state shows a busy indicator. */ this.loading = false; this.handleActivated = false; this.items = []; this.observer = new MutationObserver(() => { this.items = Array.from(this.el.children); this.setUpDragAndDrop(); }); } // -------------------------------------------------------------------------- // // Lifecycle // // -------------------------------------------------------------------------- connectedCallback() { this.items = Array.from(this.el.children); this.setUpDragAndDrop(); this.beginObserving(); } disconnectedCallback() { this.observer.disconnect(); this.cleanUpDragAndDrop(); } calciteHandleNudgeHandler(event) { const sortItem = this.items.find((item) => { return item.contains(event.detail.handle) || event.composedPath().includes(item); }); const lastIndex = this.items.length - 1; const startingIndex = this.items.indexOf(sortItem); let appendInstead = false; let buddyIndex; switch (event.detail.direction) { case "up": event.preventDefault(); if (startingIndex === 0) { appendInstead = true; } else { buddyIndex = startingIndex - 1; } break; case "down": event.preventDefault(); if (startingIndex === lastIndex) { buddyIndex = 0; } else if (startingIndex === lastIndex - 1) { appendInstead = true; } else { buddyIndex = startingIndex + 2; } break; default: return; } this.observer.disconnect(); if (appendInstead) { sortItem.parentElement.appendChild(sortItem); } else { sortItem.parentElement.insertBefore(sortItem, this.items[buddyIndex]); } this.items = Array.from(this.el.children); event.detail.handle.activated = true; event.detail.handle.setFocus(); this.beginObserving(); } // -------------------------------------------------------------------------- // // Private Methods // // -------------------------------------------------------------------------- setUpDragAndDrop() { this.cleanUpDragAndDrop(); const options = { dataIdAttr: "id", group: this.group, handle: this.handleSelector, // Changed sorting within list onUpdate: () => { this.items = Array.from(this.el.children); this.calciteListOrderChange.emit(); }, // Element dragging started onStart: () => { this.observer.disconnect(); }, // Element dragging ended onEnd: () => { this.beginObserving(); } }; if (this.dragSelector) { options.draggable = this.dragSelector; } this.sortable = Sortable.create(this.el, options); } cleanUpDragAndDrop() { var _a; (_a = this.sortable) === null || _a === void 0 ? void 0 : _a.destroy(); this.sortable = null; } beginObserving() { this.observer.observe(this.el, { childList: true, subtree: true }); } // -------------------------------------------------------------------------- // // Render Methods // // -------------------------------------------------------------------------- render() { return h("slot", null); } static get is() { return "calcite-sortable-list"; } static get encapsulation() { return "shadow"; } static get originalStyleUrls() { return { "$": ["calcite-sortable-list.scss"] }; } static get styleUrls() { return { "$": ["calcite-sortable-list.css"] }; } static get properties() { return { "dragSelector": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "Specifies which items inside the element should be draggable." }, "attribute": "drag-selector", "reflect": false }, "group": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "The list's group identifier.\n\nTo drag elements from one list into another, both lists must have the same group value." }, "attribute": "group", "reflect": false }, "handleSelector": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "The selector for the handle elements." }, "attribute": "handle-selector", "reflect": false, "defaultValue": "\"calcite-handle\"" }, "disabled": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "When true, disabled prevents interaction. This state shows items with lower opacity/grayed." }, "attribute": "disabled", "reflect": true, "defaultValue": "false" }, "loading": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "When true, content is waiting to be loaded. This state shows a busy indicator." }, "attribute": "loading", "reflect": true, "defaultValue": "false" } }; } static get states() { return { "handleActivated": {} }; } static get events() { return [{ "method": "calciteListOrderChange", "name": "calciteListOrderChange", "bubbles": true, "cancelable": true, "composed": true, "docs": { "tags": [], "text": "Emitted when the order of the list has changed." }, "complexType": { "original": "any", "resolved": "any", "references": {} } }]; } static get elementRef() { return "el"; } static get listeners() { return [{ "name": "calciteHandleNudge", "method": "calciteHandleNudgeHandler", "target": undefined, "capture": false, "passive": false }]; } }
JavaScript
class Event { /** * Creates a new event list item from a given Firestore appt document. * @param {external:DocumentSnapshot} doc - The appt's Firestore document * snapshot. */ constructor(doc) { Object.entries(doc.data()).forEach((entry) => { this[entry[0]] = entry[1]; }); this.id = doc.id; this.render = window.app.render; this.actions = {}; this.data = {}; } /** * Renders the appointment list item given a template string. * @param {string} [template='appt-list-item'] - The ID of the template to * render for this appt list item (i.e. supervisor or normal). * @see {@link Templates} */ renderSelf(template = 'appt-list-item') { /** * Ensures that actions are not shown when user is on mobile. */ const combine = (opts) => { if (window.app.onMobile) opts.showAction = false; return opts; }; this.el = this.render.template( template, combine( Utils.combineMaps( { photo: typeof this.other === 'object' ? this.other.photo : undefined, viewUser: typeof this.other === 'object' ? () => { User.viewUser(this.other.email); } : undefined, id: this.id, title: this.title, subtitle: this.subtitle, timestamp: this.timestamp, go_to_appt: (event) => { if ($(event.target).closest('button,img').length) return; this.dialog.view(); }, }, this.data ) ) ); } }
JavaScript
class FileMonitor { /** * Constrcuts a new FileStateManager using the given file state implementation * to compare files */ constructor(fileStateClass) { /** * Map of the initially loaded files from the state file * * @type {Map.<string, BaseFileState>} * @private */ this._loadedFiles = new Map(); /** * Map containing processed files * * @type {Map.<string, BaseFileState>} * @private */ this._processedFiles = new Map(); /** * Map with state of changed files * * @type {Map.<string, string>} * @private */ this._changedFiles = new Map(); if (!fileStateClass || !(fileStateClass.prototype instanceof BaseFileState)) { throw new TypeError('You need to provide a valid file state class which extends BaseFileState'); } /** * The file state class used to compare two files * * @type {BaseFileState} * @private */ this._fileStateClass = fileStateClass; } static get FILE_STATUS_CREATED() { return FILE_STATUS_CREATED; } static get FILE_STATUS_CHANGED() { return FILE_STATUS_CHANGED; } static get FILE_STATUS_DELETED() { return FILE_STATUS_DELETED; } /** * Loads cached file state information from a state file into this FileMonitor * instance * * Returns true opon successfully loading the previous state file. If no * previous state file is available or its content can not be parsed, this * method will return false and the FileMonitor instance is left untouched. * * @param {string} statePathAndFilename Full path to the state file * @return {boolean} True if the state file was loaded successfully, false if not */ load(statePathAndFilename) { if (!fs.existsSync(statePathAndFilename)) { return false; } try { let stateJson = JSON.parse(fs.readFileSync(statePathAndFilename).toString()); for (let stateEntry of stateJson.files) { let fileState = new this._fileStateClass(stateEntry); this._loadedFiles.set(fileState.path, fileState); } return true; } catch (e) { // possibly corrupted state data, just silently ignore it } return false; } /** * Write the current file states back to disk * * @param {string} statePathAndFilename Full path to the state file */ write(statePathAndFilename) { let stateData = { files: [] }; for (let fileState of this._processedFiles.values()) { stateData.files.push(fileState.toJson()); } fs.ensureDirSync(path.dirname(statePathAndFilename)); fs.writeFileSync(statePathAndFilename, JSON.stringify(stateData)); } /** * Monitor a new file or directory with this state monitor * * @param {string} pathToMonitor Full path of the file or directory to be monitored */ monitorPath(pathToMonitor) { if (!fs.existsSync(pathToMonitor)) { return; } let stats = fs.lstatSync(pathToMonitor); if (stats.isFile()) { this.updateFileState(pathToMonitor); } else if (stats.isDirectory()) { for (let entryName of fs.readdirSync(pathToMonitor)) { let fullPath = path.join(pathToMonitor, entryName); this.monitorPath(fullPath); } } } /** * Detects changes to the file and updates its state * * If the file did not exists in our loaded state before, add it as a new one. * For existing files check wether they have changed and update the file states * map and move them from the loaded map to processed. * * @param {string} pathAndFilename Full path and filename of the file to update * @private */ updateFileState(pathAndFilename) { let newFileState = new this._fileStateClass({path: pathAndFilename}); let existingFileState = this._loadedFiles.get(pathAndFilename); if (existingFileState === undefined) { this._changedFiles.set(pathAndFilename, FILE_STATUS_CREATED); this._processedFiles.set(pathAndFilename, newFileState); } else { this._loadedFiles.delete(pathAndFilename); if (newFileState.isDifferentThan(existingFileState)) { this._changedFiles.set(pathAndFilename, FILE_STATUS_CHANGED); this._processedFiles.set(pathAndFilename, newFileState); } else { this._processedFiles.set(pathAndFilename, existingFileState); } } } /** * Updates the file monitor with the set of paths, replacing any previously * monitored files. * * @param {Array.<string>} paths Array of new paths to monitor */ update(paths) { if (!Array.isArray(paths)) { throw new TypeError('The file monitor needs to be updated with an array of paths.'); } this._loadedFiles.clear(); this._processedFiles.forEach((fileState, path) => { this._loadedFiles.set(path, fileState); }); this._processedFiles.clear(); this._changedFiles.clear(); paths.forEach(path => { this.monitorPath(path); }); } /** * Gets a map of all changed files and their respective FILE_STATUS_* value * * @return {Map.<string, string>} */ getChangedFiles() { let changedFiles = new Map(this._changedFiles); for (let removedFile of this._loadedFiles.values()) { changedFiles.set(removedFile.path, FILE_STATUS_DELETED); } return changedFiles; } }
JavaScript
class MobileSprite extends AnimatedSprite { constructor(params, EntityManager){ super(params, EntityManager); if(utilities.isFunction(params.onMovement)) { this.onMovement = params.onMovement; this.onMovement.bind(this); } if(utilities.isFunction(params.onDirectionChange)){ this.onDirectionChange = params.onDirectionChange; this.onDirectionChange.bind(this); } else { this.onDirectionChange = newDirection => { this.CurrentAnimation = newDirection.direction; }; } EntityManager.attachComponent(this, "Movement", Object.assign({}, { onDirectionChange:(direction)=>{this.onDirectionChange(direction);}, onMoveX: val=>{this.updateRenderPosition("x", val);}, onMoveY: val=>{this.updateRenderPosition("y", val);} }, params)); /** * Attach a second timer component to the entity which we use to control our movement over time. */ EntityManager.attachComponent(this, { "Timer": { "movementTimer": (utilities.exists(params.movementTimer)) ? Object.assign({}, { onUpdate: delta=> { this.messageToComponent("Movement", "move", delta); } }, params.movementTimer) : { onUpdate: delta=> { this.messageToComponent("Movement", "move", delta); } } } } ); } updateRenderPosition(axis, val){ let data = {}; data[axis] = val; this.messageToComponent("Renderer", "setPosition", data); if(utilities.isFunction(this.onMovement)){ this.onMovement.call(this, data); } } }
JavaScript
class Error404 extends Component { constructor(props) { super(props); this.state= { } } componentDidMount() { } render() { return (<div className='container'> <div className="success-message card"> <h5 className='red-text text-lighten-1'><img src={ require('./dino.gif') } className="ab" /> Error ! Page Not Found</h5> <hr style={{color: 'rgba(0,0,0,.3)'}} /> <h5> <Icon> error_outline</Icon>The page you requested was not found!</h5> </div> </div>); } }
JavaScript
class GenericAPIClient { /** * Creates an instance of GenericAPIClient. * @param {string} [$baseURL=''] a base url to prepend to all request urls except for the ones with root urls * @param {RequestInit} [$baseClientConfig={}] a default config for requests */ constructor($baseURL = '', $baseClientConfig = {}) { this.$baseURL = $baseURL; this.$baseClientConfig = $baseClientConfig; this.$fetchHandler = window.fetch ? window.fetch.bind(window) : defaultFetch; } /** * Makes requests using request factory and resolves config merge conflicts. * * @private */ $request(url, fetchConfig, overrideDefaultConfig = false) { if (!url.match(/^(\w+:)?\/\//)) { url = this.$baseURL ? new URL(url, this.$baseURL).href : url; } return this.$requestFactory(url, overrideDefaultConfig ? fetchConfig : Object.assign({}, this.$baseClientConfig, fetchConfig, { headers: Object.assign({}, (this.$baseClientConfig.headers || {}), (fetchConfig.headers || {})) }), this.$fetchHandler); } /** * Processes the response before allowing to return its value from request function. * Override this function to provide custom response interception. * Keep in mind that this function does not have to return a promise. * * @protected * @param {Response} response the response returned from fetchHandler * @returns {*} default: the same response * @memberof GenericAPIClient */ $responseHandler(response) { if (response.ok) { return response; } else { throw new ResponseError(GenericAPIClient.handleStatus(response.status), response.status, response); } } /** * Processes the request error before allowing to throw it upstack. * Override this function to provide custom response error handling. * Return value instead of throwing for soft error handling. * * @protected * @param e the error catched from the request promise * @param url a url string that would be passed into the request function * @param config a request config that would be passed into the request function * @param request a function that performs a request (for retrying purposes) * @memberof GenericAPIClient */ //@ts-ignore $errorHandler(e, url, config, request) { if (e instanceof ResponseError) { throw e; } else { // Network error! throw new ResponseError('Unkown Error: ', ResponseErrors.UnknownError, e, { url, config, request }); } } /** * A general request factory function. * Calls request and error handlers, can be used for pre-processing the url and request config before sending. * Override for a completely custom request & response handling behaviour. * * @protected * @param url a url string that would be passed into the request function * @param config a request config that would be passed into the request function * @param requestFunction */ $requestFactory(url, config, requestFunction) { return requestFunction(url, config) .then(r => this.$responseHandler(r)) .catch(e => this.$errorHandler(e, url, config, requestFunction)); } /** * Request method alias factory. * Used to quickly produce alias function for class' decendants. * Override at your own risk. * * @protected * @param {string} method HTTP method (GET, PUT, POST, etc) to alias * @returns an alias function for request * @memberof GenericAPIClient */ $alias(method) { return function (url, fetchConfig = this.$baseClientConfig, overrideDefaultConfig) { fetchConfig.method = method ? method.toUpperCase() : (fetchConfig.method || 'GET').toUpperCase(); return this.$request(url, fetchConfig, overrideDefaultConfig); }; } static handleStatus(status = -1) { return ResponseErrors[status] || ResponseErrors[-1]; } }
JavaScript
class ImportSteps { static visitUserImport(repository) { ImportSteps.visitImport('user', repository); } static visitServerImport(repository) { ImportSteps.visitImport('server', repository); } static visitImport(type, repository) { if (repository) { cy.presetRepositoryCookie(repository); } cy.visit('/import#' + type); cy.get('.ot-splash').should('not.be.visible'); cy.get('#import-' + type).should('be.visible'); cy.get('.ot-loader').should('not.be.visible'); return ImportSteps; } static openImportURLDialog(importURL) { cy.get('#import-user .import-from-url-btn').click(); ImportSteps.getModal() .find('.url-import-form input[name="dataUrl"]') .type(importURL) .should('have.value', importURL); return ImportSteps; } static openImportTextSnippetDialog() { cy.get('#import-user .import-rdf-snippet-btn').click(); ImportSteps.getModal().find('#wb-import-textarea').should('be.visible'); return ImportSteps; } static clickImportUrlButton() { cy.get('#wb-import-importUrl').click(); return ImportSteps; } static selectRDFFormat(rdfFormat) { cy.get('.modal-footer .import-format-dropdown').within(() => { cy.get('.import-format-dropdown-btn').click(); cy.get('.dropdown-item').contains(rdfFormat).click().should('not.be.visible'); }); return ImportSteps; } static fillRDFTextSnippet(snippet) { ImportSteps.getSnippetTextarea().type(snippet).should('have.value', snippet); return ImportSteps; } static pasteRDFTextSnippet(snippet) { ImportSteps.getSnippetTextarea().invoke('val', snippet).trigger('change'); return ImportSteps; } static clickImportTextSnippetButton() { cy.get('#wb-import-importText').click(); return ImportSteps; } static removeUploadedFiles() { ImportSteps.selectAllUserFiles(); cy.get('#wb-import-removeEntries').click(); cy.get('#wb-import-fileInFiles').should('be.hidden'); return ImportSteps; } static selectAllUserFiles() { cy.get('#import-user .select-all-files').check(); return ImportSteps; } static getSnippetTextarea() { return cy.get('#wb-import-textarea'); } static selectServerFile(filename) { // Forcing it because often times cypress sees it with zero width and height although it's // clearly visible. ImportSteps.getServerFileElement(filename).find('.import-file-checkbox').click({force: true}); return ImportSteps; } static selectAllServerFiles() { cy.get('#import-server .select-all-files').check(); return ImportSteps; } static importServerFiles(changeSettings) { if (changeSettings) { // TODO: Check for dialog? cy.get('#import-server .import-btn').click(); } else { cy.get('#import-server .import-dropdown-btn').click() .should('have.attr', 'aria-expanded', 'true'); cy.get('#import-server .import-without-change-btn').click(); } return ImportSteps; } static importFromSettingsDialog() { // Dialog should disappear ImportSteps.getModal(). find('.modal-footer > .btn-primary') .click() .should('not.exist'); return ImportSteps; } static getSettingsForm() { return ImportSteps.getModal().find('.settings-form'); } static fillBaseURI(baseURI) { ImportSteps.getSettingsForm().find('input[name="baseURI"]').type(baseURI).should('have.value', baseURI); return ImportSteps; } static selectNamedGraph() { ImportSteps.getSettingsForm().find('.named-graph-option').check(); return ImportSteps; } static fillNamedGraph(namedGraph) { ImportSteps.getSettingsForm().find('.named-graph-input').type(namedGraph).should('have.value', namedGraph); return ImportSteps; } static expandAdvancedSettings() { ImportSteps.getSettingsForm().within(() => { cy.get('.toggle-advanced-settings').click(); cy.get('.advanced-settings').should('be.visible'); }); return ImportSteps; } static enablePreserveBNodes() { ImportSteps.getSettingsForm().find('input[name="preserveBNodeIDs"]').check(); return ImportSteps; } static resetStatusOfUploadedFiles() { // Button should disappear cy.get('#import-server #wb-import-clearStatuses').click().should('not.be.visible'); return ImportSteps; } static resetStatusOfUploadedFile(filename) { // List is re-rendered -> ensure it is detached ImportSteps .getServerFileElement(filename) .find('.import-status .import-status-reset') .click() .should('not.exist'); return ImportSteps; } static verifyImportStatusDetails(fileToSelect, details) { ImportSteps.getServerFileElement(fileToSelect).find('.import-status .import-status-info').then(infoIconEl => { cy.wrap(infoIconEl).should('be.visible'); cy.wrap(infoIconEl).trigger('mouseover'); cy.get('.popover-content').then(content => { cy.wrap(content).should('be.visible'); if (details instanceof Array) { details.forEach(text => { cy.wrap(content).should('contain', text); }) } else { cy.wrap(content).should('contain', details); } }); cy.wrap(infoIconEl).trigger('mouseout'); cy.get('.popover-content').should('not.be.visible').and('not.exist'); }); return ImportSteps; } static verifyImportStatus(filename, message) { ImportSteps .getServerFileElement(filename) .find('.import-status .import-status-message') .should('be.visible').and('contain', message); return ImportSteps; } static verifyNoImportStatus(filename) { ImportSteps .getServerFileElement(filename) .find('.import-status') .should('not.be.visible'); return ImportSteps; } static getServerFileElement(filename) { // Find the element containing the filename and get then the parent row element return cy.get('#wb-import-fileInFiles .import-file-header') .contains(filename) .parentsUntil('.import-file-row') .parent(); } static getModal() { return cy.get('.modal') .should('be.visible') .and('not.have.class', 'ng-animate') .and('have.class', 'in'); } }
JavaScript
class Settings extends React.Component { constructor(props) { super(props); this.state = { height: window.innerHeight, } //Binding the local functions to this this.handleChange = this.handleChange.bind(this); this.classFix = this.classFix.bind(this); this.updateWindowSize = this.updateWindowSize.bind(this); } updateWindowSize() { this.setState({height: window.innerHeight}); } componentWillMount(){ window.addEventListener("resize",this.updateWindowSize); } componentWillUnmount(){ window.removeEventListener("resize",this.updateWindowSize); } handleChange(id){ //If else tree due to the existence of radio buttons and how the behave differently to checkboxes //If the element being clicked is one of the "public"/"private" radio buttons if (id == "queue-private-setting" || id == "queue-public-setting"){ const newVal = id == "queue-private-setting" ? true : false; //[ADD] Something here to ask them if they are sure they want to do it because people who are listening will be kicked off this.props.update({"queue-privacy": newVal}); } //If the element being clicked is one of the access code radio buttons else if (id == "queue-access-invite-setting" || id == "queue-access-code-setting" || id == "queue-access-none-setting"){ const newVal = id.split("-")[2]; this.props.update({"access-method": newVal}); if (id == "queue-access-code-setting") { this.props.loadCode(); } } //if the element being clicked is a checkbox else { let updater = {}; updater[id] = !this.props.settings[id]; console.log(updater); this.props.update(updater); } } classFix(bool, type){ if (bool) { if (type == "radio") { return " checked-radio" } else { return " checked-checkbox" } } else { return "" } } render(){ let overflowFix = {}; if (this.state.height < 800) { overflowFix = { overflowY: "scroll", } } return ( <div style={overflowFix} id="queue-settings" className="queue-display"> <div id="general-queue-settings"> <h2 id="general-queue-settings-header" className="queue-settings-header">General</h2> <div className="queue-setting-option"> <div className="queue-setting-option-radio"> <span onClick={(e) => {this.handleChange("queue-private-setting")}} className={"queue-settings-radio-better" + this.classFix(this.props.settings["queue-privacy"], "radio")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-radio" id="queue-private-setting" type="radio" name="public-private" checked={this.props.settings["queue-privacy"]}/> <label className="queue-settings-label" htmlFor="queue-private-setting">Private</label> <span onClick={(e) => {this.handleChange("queue-public-setting")}} className={"queue-settings-radio-better" + this.classFix(!this.props.settings["queue-privacy"], "radio")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-radio" id="queue-public-setting" type="radio" name="public-private" checked={!this.props.settings["queue-privacy"]}/> <label className="queue-settings-label" htmlFor="queue-public-setting">Public</label> </div> {this.props.settings["queue-privacy"] ? <p className="queue-setting-description">Private: Only you can see and listen to what you're listening to</p> : <p className="queue-setting-description">Public: Others can see listen to what you're listening to</p>} </div> <div className="queue-setting-option"> <span onClick={(e) => {this.handleChange("remove-after-played")}} className={"queue-settings-checkbox-better" + this.classFix(this.props.settings["remove-after-played"], "checkbox")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-checkbox" id="remove-after-played" type="checkbox" checked={this.props.settings["remove-after-played"]}/> <label className="queue-settings-label" htmlFor="remove-after-played">Remove played</label> <p className="queue-setting-description">Remove the song from the queue once it is finished playing (off will move it to the bottom)</p> </div> <div className="queue-setting-option"> <span onClick={(e) => {this.handleChange("auto-fill-queue")}} className={"queue-settings-checkbox-better" + this.classFix(this.props.settings["auto-fill-queue"], "checkbox")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-checkbox" id="auto-fill-queue" type="checkbox" checked={this.props.settings["auto-fill-queue"]}/> <label className="queue-settings-label" htmlFor="auto-fill-queue">Autoplay</label> <p className="queue-setting-description">Find new songs to add to the queue once it is empty</p> </div> </div> <div id="friend-access-queue-settings"> <h2 id="friend-access-queue-settings-header" className="queue-settings-header">Follower Access</h2> <div className="queue-setting-option"> <span onClick={(e) => {this.handleChange("queue-access-invite-setting")}} className={"queue-settings-radio-better" + this.classFix(this.props.settings["access-method"] == "invite", "radio")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-radio" id="queue-access-invite-setting" type="radio" name="access-method" checked={this.props.settings["access-method"] == "invite"}/> <label className="queue-settings-label" htmlFor="queue-access-invite-setting">Invite Only</label> <span onClick={(e) => {this.handleChange("queue-access-code-setting")}} className={"queue-settings-radio-better" + this.classFix(this.props.settings["access-method"] == "code", "radio")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-radio" id="queue-access-code-setting" type="radio" name="access-method" checked={this.props.settings["access-method"] == "code"}/> <label className="queue-settings-label" htmlFor="queue-access-code-setting">Access Code</label> <span onClick={(e) => {this.handleChange("queue-access-none-setting")}} className={"queue-settings-radio-better" + this.classFix(this.props.settings["access-method"] == "none", "radio")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-radio" id="queue-access-none-setting" type="radio" name="access-method" checked={this.props.settings["access-method"] == "none"}/> <label className="queue-settings-label" htmlFor="queue-access-none-setting">None</label> {this.props.settings["access-method"] == "invite" ? <p className="queue-setting-description">Invite Only: Invite a follower for them to have access</p> : (this.props.settings["access-method"] == "code" ? <p className="queue-setting-description">Access Code: Generate a code that followers can use to gain access</p> : <p className="queue-setting-description">None: You are the only person who can edit this queue</p>)} </div> {this.props.settings["access-method"] == "code" ? <div id="access-code-container">{this.props.codeLoading ? <p>Loading...</p> : this.props.code}</div> : null} <div className="queue-setting-option" hidden={this.props.settings["access-method"] != "invite"}> <span onClick={(e) => {this.handleChange("allow-friend-invite")}} className={"queue-settings-checkbox-better" + this.classFix(this.props.settings["allow-friend-invite"], "checkbox")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-checkbox" id="allow-friend-invite" type="checkbox" checked={this.props.settings["allow-friend-invite"]}/> <label className="queue-settings-label" htmlFor="allow-friend-invite">Friend invite</label> <p className="queue-setting-description">Allow followers who have access to invite other users</p> </div> <div className="queue-setting-option"> <span onClick={(e) => {this.handleChange("allow-friend-add")}} className={"queue-settings-checkbox-better" + this.classFix(this.props.settings["allow-friend-add"], "checkbox")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-checkbox" id="allow-friend-add" type="checkbox" checked={this.props.settings["allow-friend-add"]}/> <label className="queue-settings-label" htmlFor="allow-friend-add">Friend add</label> <p className="queue-setting-description">Allow followers who have add songs to the queue</p> </div> <div className="queue-setting-option"> <span onClick={(e) => {this.handleChange("allow-friend-remove")}} className={"queue-settings-checkbox-better" + this.classFix(this.props.settings["allow-friend-remove"], "checkbox")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-checkbox" id="allow-friend-remove" type="checkbox" checked={this.props.settings["allow-friend-remove"]}/> <label className="queue-settings-label" htmlFor="allow-friend-remove">Friend remove</label> <p className="queue-setting-description">Allow followers who have access to remove songs from the queue</p> </div> <div className="queue-setting-option"> <span onClick={(e) => {this.handleChange("allow-friend-control")}} className={"queue-settings-checkbox-better" + this.classFix(this.props.settings["allow-friend-control"], "checkbox")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-checkbox" id="allow-friend-control" type="checkbox" checked={this.props.settings["allow-friend-control"]}/> <label className="queue-settings-label" htmlFor="allow-friend-control">Friend control</label> <p className="queue-setting-description">Allow followers who have access to pause, skip, and rewind songs</p> </div> <div className="queue-setting-option"> <span onClick={(e) => {this.handleChange("allow-friend-order")}} className={"queue-settings-checkbox-better" + this.classFix(this.props.settings["allow-friend-order"], "checkbox")}></span> <input disabled={!this.props.settings.owned} readOnly className="queue-settings-checkbox" id="allow-friend-order" type="checkbox" checked={this.props.settings["allow-friend-order"]}/> <label className="queue-settings-label" htmlFor="allow-friend-order">Friend shuffle</label> <p className="queue-setting-description">Allow followers who have access to change the order of the queue</p> </div> </div> </div> ) } }
JavaScript
class Authentication extends Controller { /** * Make sure that user sending the request is authenticated. * * 1. First get schema & CRUD operation user is trying to access * 2. If endpoint doesnt require authentication then proceed * 3. If endpoint requires authentication then: * - Check if there is a token present in any of these headers: Authorization, Cookie, X-access-token * - Check that token is a valid JWT * - Check if a login record for this token exists * - Check if user is authorized to access the requested CRUD operation on this endpoint */ static async ensureAuthenticated(req, res, next) { try { req.operation = Controller.getCRUDFromRequest(req) // Check if authorization is required if (req.schema.access[req.operation].roles.includes('anon')) { // Proceed since anonymous can access this resource & operation return next() } else { const unauthorizedError = Controller.makeError('UnauthorizedError', 'Access denied') // Get token // TODO: Also look for the token in query params const token = Authentication.getTokenFromRequest(req) if (!token) throw unauthorizedError // TODO: Save token and decoded user in cache, check cache first const { validToken, decoded } = await checkToken(token) if (!validToken || !decoded) throw unauthorizedError // TODO: Save login in cache, check cache first // Check that there is a login record with this token const loginRecord = await Login.findOne({ token: validToken }) if (!loginRecord) throw unauthorizedError req.user = decoded || null // If it's root user continue, otherwise check user permissions if (req.user.roles.includes('root')) return next() else { const authorized = Authentication.checkPermissions(req) if (authorized) return next() else { let err = new Error('Invalid permission') err.name = 'ForbiddenError' throw err } } } } catch (err) { return next(err) } } // Check privileges/permissions of user sending the request static checkPermissions(req) { var authorized = false if (!req.user) return authorized = false if (Array.isArray(req.user.roles) && req.user.roles.length <= 0) req.user.roles = ['anon'] const schema = req.schema // console.log(`Requested operation ${req.operation.toUpperCase()} on protected endpoint: ${req.resource} `) const hasRole = haveCommonElements(schema.access[req.operation].roles, req.user.roles) if (hasRole) authorized = true else authorized = false return authorized } static getTokenFromRequest(req) { let token // Prioritize the token from the query params if (req.queryParsed.token) { token = req.queryParsed.token } else { token = req.headers['authorization'] || req.headers['x-access-token'] || null // Express headers are auto converted to lowercase // If testing, check the cookie if (req.headers['user-agent'].includes('node-superagent')) { token = token || req.cookies.token || null } } if (token && token.startsWith('Bearer')) { token = token.split(' ')[1] } return token } }
JavaScript
class ImageDeltaCompressor { /** * Compresses a target image based on a difference from a source image. * * @param {Image|png.Image} targetData - The image we want to compress. * @param {Buffer} targetBuffer - The image we want to compress in its png buffer representation. * @param {Image|png.Image} sourceData - The baseline image by which a compression will be performed. * @param {number} [blockSize=10] - How many pixels per block. * @return {Buffer} - The compression result. */ static compressByRawBlocks(targetData, targetBuffer, sourceData, blockSize = 10) { // If there's no image to compare to, or the images are in different // sizes, we simply return the encoded target. if ( !targetData || !sourceData || sourceData.width !== targetData.width || sourceData.height !== targetData.height ) { return targetBuffer } // The number of bytes comprising a pixel (depends if there's an Alpha channel). // targetData.data[6] bits: 1 palette, 2 color, 4 alpha // IMPORTANT: png-async always return data in following format RGBA. const pixelLength = 4 const imageSize = {width: targetData.width, height: targetData.height} // IMPORTANT: Notice that the pixel bytes are (A)BGR! const targetPixels = rgbaToAbgrColors(targetData.data, pixelLength) const sourcePixels = rgbaToAbgrColors(sourceData.data, pixelLength) // Calculating how many block columns and rows we've got. const blockColumnsCount = Math.trunc( targetData.width / blockSize + (targetData.width % blockSize === 0 ? 0 : 1), ) const blockRowsCount = Math.trunc( targetData.height / blockSize + (targetData.height % blockSize === 0 ? 0 : 1), ) // Writing the header const stream = new WritableBufferStream() const blocksStream = new WritableBufferStream() stream.write(PREAMBLE) stream.write(Buffer.from([COMPRESS_BY_RAW_BLOCKS_FORMAT])) // since we don't have a source ID, we write 0 length (Big endian). stream.writeShort(0) // Writing the block size (Big endian) stream.writeShort(blockSize) let compareResult for (let channel = 0; channel < 3; channel += 1) { // The image is RGB, so all that's left is to skip the Alpha channel if there is one. const actualChannelIndex = pixelLength === 4 ? channel + 1 : channel let blockNumber = 0 for (let blockRow = 0; blockRow < blockRowsCount; blockRow += 1) { for (let blockColumn = 0; blockColumn < blockColumnsCount; blockColumn += 1) { compareResult = compareAndCopyBlockChannelData( sourcePixels, targetPixels, imageSize, pixelLength, blockSize, blockColumn, blockRow, actualChannelIndex, ) if (!compareResult.isIdentical) { blocksStream.writeByte(channel) blocksStream.writeInt(blockNumber) blocksStream.write(compareResult.buffer) // If the number of bytes already written is greater then the number of bytes for the // uncompressed target, we just return the uncompressed target. // NOTE: we need take in account that it will be compressed at the end by zlib if ( stream.getBuffer().length + blocksStream.getBuffer().length * DEFLATE_BUFFER_RATE > targetBuffer.length ) { return targetBuffer } } blockNumber += 1 } } } const blocksBuffer = zlib.deflateRawSync(blocksStream.getBuffer(), { level: zlib.Z_BEST_COMPRESSION, }) stream.write(blocksBuffer) if (stream.getBuffer().length > targetBuffer.length) { return targetBuffer } return stream.getBuffer() } }
JavaScript
class CollectionDialog extends Component { /** */ static getUseableLabel(resource, index) { return (resource && resource.getLabel && resource.getLabel().length > 0) ? resource.getLabel().getValue() : String(index + 1); } /** */ constructor(props) { super(props); this.state = { filter: null }; this.hideDialog = this.hideDialog.bind(this); } /** */ setFilter(filter) { this.setState({ filter }); } /** */ hideDialog() { const { hideCollectionDialog, windowId, } = this.props; hideCollectionDialog(windowId); } /** */ selectCollection(c) { const { collectionPath, manifestId, showCollectionDialog, windowId, } = this.props; showCollectionDialog(c.id, [...collectionPath, manifestId], windowId); } /** */ goToPreviousCollection() { const { collectionPath, showCollectionDialog, windowId } = this.props; showCollectionDialog( collectionPath[collectionPath.length - 1], collectionPath.slice(0, -1), windowId, ); } /** */ selectManifest(m) { const { addWindow, collectionPath, manifestId, setWorkspaceAddVisibility, updateWindow, windowId, } = this.props; if (windowId) { updateWindow(windowId, { canvasId: null, collectionPath: [...collectionPath, manifestId], manifestId: m.id, }); } else { addWindow({ collectionPath: [...collectionPath, manifestId], manifestId: m.id }); } this.hideDialog(); setWorkspaceAddVisibility(false); } /** */ dialogContainer() { const { containerId, windowId } = this.props; return document.querySelector(`#${containerId} #${windowId}`); } /** */ placeholder() { const { classes } = this.props; return ( <Dialog className={classes.dialog} onClose={this.hideDialog} open container={this.dialogContainer()} BackdropProps={this.backdropProps()} > <DialogTitle id="select-collection" disableTypography> <Skeleton className={classes.placeholder} variant="text" /> </DialogTitle> <ScrollIndicatedDialogContent> <Skeleton className={classes.placeholder} variant="text" /> <Skeleton className={classes.placeholder} variant="text" /> </ScrollIndicatedDialogContent> </Dialog> ); } /** */ backdropProps() { const { classes } = this.props; return { classes: { root: classes.dialog } }; } /** */ render() { const { classes, collection, error, isMultipart, manifest, ready, t, } = this.props; const { filter } = this.state; if (error) return null; // If this component is optimistically rendering ahead of the window its in // force a re-render so that it is placed correctly. The right thing here is // to maybe pass a ref. if (!this.dialogContainer()) { this.forceUpdate(); return <></>; } if (!ready) return this.placeholder(); const rights = manifest && (asArray(manifest.getProperty('rights') || manifest.getProperty('license'))); const requiredStatement = manifest && asArray(manifest.getRequiredStatement()).filter(l => l.getValue()).map(labelValuePair => ({ label: null, values: labelValuePair.getValues(), })); const collections = manifest.getCollections(); const currentFilter = filter || (collections.length > 0 ? 'collections' : 'manifests'); return ( <Dialog className={classes.dialog} onClose={this.hideDialog} container={this.dialogContainer()} BackdropProps={this.backdropProps()} open > <DialogTitle id="select-collection" disableTypography> <Typography component="div" variant="overline"> { t(isMultipart ? 'multipartCollection' : 'collection') } </Typography> <Typography variant="h3"> {CollectionDialog.getUseableLabel(manifest)} </Typography> </DialogTitle> <ScrollIndicatedDialogContent className={classes.dialogContent}> { collection && ( <Button startIcon={<ArrowBackIcon />} onClick={() => this.goToPreviousCollection()} > {CollectionDialog.getUseableLabel(collection)} </Button> )} <div className={classes.collectionMetadata}> <ManifestInfo manifestId={manifest.id} /> <CollapsibleSection id="select-collection-rights" label={t('attributionTitle')} > { requiredStatement && ( <LabelValueMetadata labelValuePairs={requiredStatement} defaultLabel={t('attribution')} /> )} { rights && rights.length > 0 && ( <> <Typography variant="subtitle2" component="dt">{t('rights')}</Typography> { rights.map(v => ( <Typography variant="body1" component="dd" key={v}> <Link target="_blank" rel="noopener noreferrer" href={v}> {v} </Link> </Typography> )) } </> ) } </CollapsibleSection> </div> <div className={classes.collectionFilter}> {manifest.getTotalCollections() > 0 && ( <Chip clickable color={currentFilter === 'collections' ? 'primary' : 'default'} onClick={() => this.setFilter('collections')} label={t('totalCollections', { count: manifest.getTotalCollections() })} /> )} {manifest.getTotalManifests() > 0 && ( <Chip clickable color={currentFilter === 'manifests' ? 'primary' : 'default'} onClick={() => this.setFilter('manifests')} label={t('totalManifests', { count: manifest.getTotalManifests() })} /> )} </div> { currentFilter === 'collections' && ( <MenuList> { collections.map(c => ( <MenuItem key={c.id} onClick={() => { this.selectCollection(c); }}> {CollectionDialog.getUseableLabel(c)} </MenuItem> )) } </MenuList> )} { currentFilter === 'manifests' && ( <MenuList> { manifest.getManifests().map(m => ( <MenuItem key={m.id} onClick={() => { this.selectManifest(m); }}> {CollectionDialog.getUseableLabel(m)} </MenuItem> )) } </MenuList> )} </ScrollIndicatedDialogContent> <DialogActions> <Button onClick={this.hideDialog}> {t('close')} </Button> </DialogActions> </Dialog> ); } }
JavaScript
class Category extends Component { constructor() { super(); this.state = { min_price: 0, max_price: 10000000, select_view: "gallery", sort_by: "price-desc", itemsData: [], make: 'all', model: 'all', }; } // figure out what listings we should be displaying client-side componentWillMount() { // http request spoof const { match, location, history } = this.props; const self = this; // check if :listing is set, and use it if it is let listing = ""; if (match.params.listings != undefined) { listing = "/" + match.params.listings; } // try to parse url query parameters const queryParams = qs.parse(this.props.location.search); const { min_price, max_price, select_view, sort_by } = queryParams; if (min_price != undefined) { console.log("willmount queryParams: "); console.log(queryParams); axios .get( `/api/${match.params.city}/${match.params.category}${listing}?min_price=${min_price}&max_price=${max_price}&select_view=${select_view}&sort_by=${sort_by}` ) .then(function(response) { self.setState( { itemsData: response.data }, () => { // console.log(self.state); } ); }) .catch(function(error) { console.log(error); }); } else { // otherwise do a regular request axios .get(`/api/${match.params.city}/${match.params.category}${listing}`) .then(function(response) { self.setState( { itemsData: response.data }, () => { // console.log(self.state); } ); }) .catch(function(error) { console.log(error); }); } } // only show images in the housing and for-sale categories showImages = (url, price) => { const match = this.props.match; console.log(match.params.category) if (match.params.category == 'for-sale' || match.params.category == 'housing' ) { return ( <div className="image" style={{ backgroundImage: `url('${url}')` }} > <div className="price">{price}</div> </div> ); } else { return (""); } } // get all the item data and loop through it to display loopItems = () => { // for formatting currency without decimals var formatter = new Intl.NumberFormat("en-US", { style: "currency", minimumFractionDigits: 2, currency: "USD" }); var cityTranslator = { 'la': 'Los Angeles, CA', 'nyc': 'New York City, NY', 'mia': 'Miami, FL', 'bos': 'Boston, MA' } const match = this.props.match; let addr = `/${match.params.city}/${match.params.category}` if (match.params.listings != undefined) { addr += ("/" + match.params.listings) } else { addr += "/x" } return this.state.itemsData.map((item, index) => { return ( <Link to={`${addr}/${item.id}`} className="item" key={item.id}> {this.showImages(item.images, formatter.format(item.price))} <div className="details"> <h5>{`${item.title}`}</h5> <i className="fa fa-star"></i> <h6>{cityTranslator[item.city]}</h6> </div> </Link> ); }); }; // only show make and model selectors if we are in /cars-and-trucks/ showMakeModel = () => { const { match, location, history } = this.props; if (match.params.listings == "cars-and-trucks") { return ( <div style={{ display: "flex" }} > <div className="form-group make"> <label>Make</label> <select name="make" className="make-select" onChange={this.handleChange} > <option value="all">All</option> {this.displayMakeOptions()} </select> </div> <div className="form-group model"> <label>Model</label> <select name="model" className="model-select" onChange={this.handleChange} > <option value="all">All</option> {this.displayModelOptions()} </select> </div> </div> ); } }; // handler for filter changes handleChange = event => { const name = event.target.name; const value = event.target.type == "checkbox" ? event.target.checked : event.target.value; this.setState( { [name]: value }, () => { console.log(this.state); if (name == 'make') { this.getModelOptions() } } ); }; // handle update button click submitFilters = () => { const self = this; let { match, location, history } = this.props; const { min_price, max_price, select_view, sort_by, make, model } = this.state; // check if :listing is set, and use it if it is let listing = ""; if (match.params.listings != undefined) { listing = "/" + match.params.listings; } // this is the old way that refreshes the page // document.location.href = `/${match.params.city}/${match.params.category}${listing}?min_price=${min_price}&max_price=${max_price}&select_view=${select_view}&sort_by=${sort_by}`; let newSearch = `min_price=${min_price}&max_price=${max_price}&select_view=${select_view}&sort_by=${sort_by}&make=${make}&model=${model}`; history.push( `/${match.params.city}/${match.params.category}${listing}?min_price=${min_price}&max_price=${max_price}&select_view=${select_view}&sort_by=${sort_by}&make=${make}&model=${model}` ); location = this.props.location; console.log(newSearch); let queryParams = qs.parse(newSearch); if (queryParams.min_price != undefined) { axios .get( `/api/${match.params.city}/${match.params.category}${listing}?min_price=${queryParams.min_price}&max_price=${queryParams.max_price}&select_view=${queryParams.select_view}&sort_by=${queryParams.sort_by}&make=${queryParams.make}&model=${queryParams.model}` ) .then(function(response) { self.setState( { itemsData: response.data }, () => { console.log(self.state); } ); }) .catch(function(error) { console.log(error); }); } }; // get the car make options from data // works, but it's options are restricted to the results given the first time, // so you have to click back to All after to switch makes displayMakeOptions = () => { let makes = this.state.itemsData.map((item) => item.make) makes = [...new Set(makes)] makes.sort() return makes.map((item, i) => { return ( <option value={item} key={i}>{item}</option> ) }) } // get the car model options from data and filter by make if set getModelOptions = () => { let newmodels = this.state.itemsData console.log(this.state.make) if (this.state.make != 'all') { newmodels = newmodels.filter((item) => { return ( item.make == this.state.make ) }) } newmodels = newmodels.map((item) => item.model) newmodels = [...new Set(newmodels)] newmodels = newmodels.sort() return newmodels } // display the model selector options displayModelOptions = () => { let models = this.getModelOptions() return models.map((item, i) => { return ( <option value={item} key={i}>{item}</option> ) }) } render() { let { match, location, history } = this.props; // no results if (this.state.itemsData.length == 0) { return ( <div className="oops"> <h1> Sorry, no results found. </h1> </div> ); } let gallery = (this.state.select_view == "gallery") if (match.params.category != 'for-sale' && match.params.category != 'housing' ) { gallery = false; } return ( <div className="listings"> <div className="container"> <section id="filter"> <div className="form-group price"> <label>Price</label> <div className="minmax"> <select name="min_price" className="min-price" value={this.state.min_price} onChange={this.handleChange} > <option value="0">min</option> <option value="10000">10,000</option> <option value="50000">50,000</option> <option value="100000">100,000</option> </select> <select name="max_price" className="max-price" value={this.state.max_price} onChange={this.handleChange} > <option value="10000">10,000</option> <option value="50000">50,000</option> <option value="100000">100,000</option> <option value="10000000">max</option> </select> </div> </div> {this.showMakeModel()} <div className="form-group button"> <div className="primary-btn" onClick={this.submitFilters}> Update </div> <div className="clear-btn">Clear</div> </div> </section> </div> <section id="content"> <div className="container"> <div className="whitebox"> <section id="options"> <div className="form-group view-dropdown"> <select name="select_view" className="select-view" value={this.state.select_view} onChange={this.handleChange} > <option value="gallery">Gallery</option> <option value="list">List</option> </select> </div> <div className="form-group sort"> <select name="sort_by" className="sort-by" value={this.state.sort_by} onChange={this.handleChange} > <option value="price-dsc">Price - Highest</option> <option value="price-asc">Price - Lowest</option> <option value="date-dsc">Newest</option> <option value="date-asc">Oldest</option> </select> </div> </section> <section id='results' className={`${gallery ? '' : 'listview'}`}>{this.loopItems()}</section> </div> </div> </section> </div> ); } }
JavaScript
class NigerianPhone { allPrefixes = { 'mtn': [ '0803', '0703', '0903', '0806', '0706', '0813', '0814', '0816', '0810', '0906', '07025', '07026', '0704' ], 'glo': ['0805', '0705', '0905', '0807', '0815', '0905', '0811'], 'airtel': ['0802', '0902', '0701', '0808', '0708', '0812', '0901', '0907'], '9mobile': ['0809', '0909', '0817', '0818', '0908'], 'ntel': ['0804'], 'smile': ['0702'], 'multilinks': ['0709', '07027'], 'visafone': ['07025', '07026', '0704'], 'starcomms': ['07028', '07029', '0819'], 'zoom': ['0707'], } allAreaCodes = { 'Lagos': '01', 'Ibadan': '02', 'Abuja': '09', 'Ado-Ekiti': '30', 'Ilorin': '31', 'New Bussa': '33', 'Akure': '34', 'Oshogbo': '35', 'Ile-Ife': '36', 'Ijebu-Ode': '37', 'Oyo': '38', 'Abeokuta': '39', 'Wukari': '41', 'Enugu': '42', 'Abakaliki': '43', 'Makurdi': '44', 'Ogoja': '45', 'Onitsha': '46', 'Lafia': '47', 'Awka': '48', 'Ikare': '50', 'Owo': '51', 'Benin City': '52', 'Warri': '53', 'Sapele': '54', 'Agbor': '55', 'Asaba': '56', 'Auchi': '57', 'Lokoja': '58', 'Okitipupa': '59', 'Sokoto': '60', 'Kafanchan': '61', 'Kaduna': '62', 'Gusau': '63', 'Kano': '64', 'Katsina': '65', 'Minna': '66', 'Kontagora': '67', 'Birnin-Kebbi': '68', 'Zaria': '69', 'Pankshin': '73', 'Azare': '71', 'Gombe': '72', 'Jos': '73', 'Yola': '75', 'Maiduguri': '76', 'Bauchi': '77', 'Hadejia': '78', 'Jalingo': '79', 'Aba, Nigeria': '82', 'Owerri': '83', 'Port Harcourt': '84', 'Uyo': '85', 'Ahoada': '86', 'Calabar': '87', 'Umuahia': '88', 'Yenagoa': '89', 'Ubiaja': '55', 'Kwara': '31', 'Igarra': '57', 'Ughelli': '53', 'Uromi': '57' }; prefixes = []; areaCodes = []; isValidPhone = false; isValidLandLine = false; line = ''; constructor(line = null) { for (var i in this.allPrefixes) { for (var j in this.allPrefixes[i]) { this.prefixes.push(this.allPrefixes[i][j]); } } for (var k in this.allAreaCodes) { this.areaCodes.push(this.allAreaCodes[k]); } if (line) { this.setLine(line); this.isValid(); } } setLine(line) { this.line = line.replace(/\D/g, '');; } isValid() { // contains country calling code if (this.line.substring(0, 3) == '234') { //phone number if (this.line.length == 13) { //replace country code 234 with 0 for further analysis let stripCcc = this.line.replace('234', '0'); //contains valid phone prefix if (this.prefixes.includes(stripCcc.substring(0, 5)) || this.prefixes.includes(stripCcc.substring(0, 4))) { this.isValidPhone = true; return true; } } // is a land line else if (this.line.length == 11) { // replace country code (234) let stripCcc = this.line.replace(this.line.substring(0, 3), ''); // contains valid 2-digit area code if (this.areaCodes.includes(this.line.substring(0, 2)) && stripCcc.length == 7) { this.isValidLandLine = true; return true; } } } // doesn't contain country calling code else { // check if it starts with any prefix [0807,0906 etc..] if (this.line.substring(0, 1) == '0' && this.line.length == 11 && (this.prefixes.includes(this.line.substring(0, 5)) || this.prefixes.includes(this.line.substring(0, 4)))) { this.isValidPhone = true; return true; } // check if it starts with any prefix without 0 e.g [807,906, 701 etc..] else if (this.line.length == 10 && (this.prefixes.includes(this.line.substring(0, 4)) || this.prefixes.includes(this.line.substring(0, 3)))) { // add the missing zero for completion this.line = '0' + this.line; this.isValidPhone = true; return true; } // check if it's a land line starting with 0 else if (this.line.substring(0, 1) == 0 && this.areaCodes.includes(this.line.replace(this.line.substring(0, 1), '').substring(0, 2)) && this.line.length == 8) { this.isValidLandLine = true; return true; } } return false; } formatted() { if (this.line.substring(0, 3) == '234') { return this.line.replace(this.line.substring(0, 3), '0'); } return this.line; } getNetwork() { if (this.isMtn()) { return 'mtn'; } else if (this.isGlo()) { return 'glo'; } else if (this.isAirtel()) { return 'airtel'; } else if (this.is9mobile()) { return '9mobile'; } else if (this.isSmile()) { return 'smile'; } else if (this.isMultilinks()) { return 'multilinks'; } else if (this.isVisafone()) { return 'visafone'; } else if (this.isNtel()) { return 'ntel'; } else if (this.isStarcomms()) { return 'starcomms'; } else if (this.isZoom()) { return 'zoom'; } else { return 'unknown'; } } getAreaCode() { let formatted = this.formatted(); let removedZero = formatted.replace('0', ''); let areaCode = removedZero.substring(0, 2); for (var i in this.allAreaCodes.length) { if (areaCode == this.allAreaCodes[i]) { return this.allAreaCodes[i]; } } return null; } isMtn() { return (this.allPrefixes['visafone'].includes(this.formatted().substring(0, 5)) || this.allPrefixes['mtn'].includes(this.formatted().substring(0, 4))); } isGlo() { return (this.allPrefixes['glo'].includes(this.formatted().substring(0, 4))); } isAirtel() { return (this.allPrefixes['airtel'].includes(this.formatted().substring(0, 4))); } is9mobile() { return (this.allPrefixes['9mobile'].includes(this.formatted().substring(0, 4))); } isSmile() { return (this.allPrefixes['smile'].includes(this.formatted().substring(0, 4))); } isMultilinks() { return (this.allPrefixes['multilinks'].includes(this.formatted().substring(0, 5)) || this.allPrefixes['multilinks'].includes(this.formatted().substring(0, 4))); } isVisafone() { return (this.allPrefixes['visafone'].includes(this.formatted().substring(0, 5)) || this.allPrefixes['visafone'].includes(this.formatted().substring(0, 4))); } isNtel() { return (this.allPrefixes['ntel'].includes(this.formatted().substring(0, 4))); } isStarcomms() { return (this.allPrefixes['starcomms'].includes(this.formatted().substring(0, 5)) || this.allPrefixes['starcomms'].includes(this.formatted().substring(0, 4))); } isZoom() { return (this.allPrefixes['zoom'].includes(this.formatted().substring(0, 4))); } getPrefixesByNetwork(network) { return this.allPrefixes[network]; } getNetworkByPrefix(area) { for (var i in this.allPrefixes) { if (this.allPrefixes[i].includes(area)) { return i; } } return null; } getAreaCodeByName(area) { for (var i in this.areaCodes) { if (i == area) { return this.areaCodes[i]; } } return null; } }
JavaScript
class Extra { /** * constructor * @param filename the svg file * @param elements list of attributes */ constructor(elements) { this.elements = elements; } }
JavaScript
class PanelDescriptor extends composite_1.CompositeDescriptor { constructor(ctor, id, name, cssClass, order, _commandId) { super(ctor, id, name, cssClass, order, _commandId); } }
JavaScript
class TogglePanelAction extends actions_1.Action { constructor(id, label, panelId, panelService, layoutService, cssClass) { super(id, label, cssClass); this.panelId = panelId; this.panelService = panelService; this.layoutService = layoutService; } run() { if (this.isPanelFocused()) { this.layoutService.setPanelHidden(true); } else { this.panelService.openPanel(this.panelId, true); } return Promise.resolve(); } isPanelActive() { var _a; const activePanel = this.panelService.getActivePanel(); return ((_a = activePanel) === null || _a === void 0 ? void 0 : _a.getId()) === this.panelId; } isPanelFocused() { const activeElement = document.activeElement; const panelPart = this.layoutService.getContainer("workbench.parts.panel" /* PANEL_PART */); return !!(this.isPanelActive() && activeElement && panelPart && dom_1.isAncestor(activeElement, panelPart)); } }
JavaScript
class AddLeaseForm extends React.Component { //creates a lease object when the submit button of the form is clicked //once the states are created it is passed to addLease(home component) through an object for simplicity createLease(event) { event.preventDefault(); console.log('Creating Lease') const lease = { type: 'lease', name: this.name.value, msrp: this.msrp.value, term: this.term.value, downPayment: this.downPayment.value, milesCovered: this.milesCovered.value, miles: this.miles.value, costMileOver: this.costMileOver.value, totalPerMonth: '', totalPerMile: '', } this.props.addLease(lease); //clears the form for the next entry this.leaseForm.reset(); } render() { return ( <div> <form ref={(input) => this.leaseForm = input} className="finance-edit" onSubmit={(e) => this.createLease(e)}> <div> <label htmlFor="name">Name*:</label> <input ref={(input) => this.name = input} id="name" type="text" placeholder="* Lease Name" required /> </div> <div> <label htmlFor="msrp">MSRP*:</label> <input ref={(input) => this.msrp = input} id="msrp" type="number" placeholder="* MSRP Value" required /> </div> <div> <label htmlFor="term">Term*:</label> <input ref={(input) => this.term = input} id="term" type="number" placeholder="* Term Period" required/> </div> <div> <label htmlFor="down">Down Payment*:</label> <input ref={(input) => this.downPayment = input} id="down" type="number" placeholder="* Down Payment %" required /> </div> <div> <label htmlFor="milesL">Miles Covered in Lease*:</label> <input ref={(input) => this.milesCovered = input} id="milesL" type="number" placeholder="* Max Miles" required /> </div> <div> <label htmlFor="miles">Miles Driven per Year*:</label> <input ref={(input) => this.miles = input} id="miles" type="number" placeholder="* Miles Per Year" required/> </div> <div id="last"> <label htmlFor="mileOver">¢ Per Mile*:</label> <input ref={(input) => this.costMileOver = input} id="mileOver" type="number" placeholder="* ¢ Per Mile" required/> </div> <button type="submit">+ Add Item</button> </form> </div> ) } }
JavaScript
class RetargetScheduleProperties { /** * Create a RetargetScheduleProperties. * @property {string} [currentResourceId] The resource Id of the virtual * machine on which the schedule operates * @property {string} [targetResourceId] The resource Id of the virtual * machine that the schedule should be retargeted to */ constructor() { } /** * Defines the metadata of RetargetScheduleProperties * * @returns {object} metadata of RetargetScheduleProperties * */ mapper() { return { required: false, serializedName: 'RetargetScheduleProperties', type: { name: 'Composite', className: 'RetargetScheduleProperties', modelProperties: { currentResourceId: { required: false, serializedName: 'currentResourceId', type: { name: 'String' } }, targetResourceId: { required: false, serializedName: 'targetResourceId', type: { name: 'String' } } } } }; } }
JavaScript
class CharReferenceInterval { constructor(start, end, reference) { if (start > end) { throw new Error("Start must be less or equal End"); } this._start = start; this._end = end; this._reference = reference; } get start() { return this._start; } get end() { return this._end; } get reference() { return this._reference; } inRange(symbol) { return symbol >= this._start && symbol <= this._end; } }
JavaScript
class LocalSigner extends AbstractSigner { /** * Sign a given Deploy Object with the corresponding key. * * @param {DeployUtil.Deploy} deploy - Deploy object * @param {Object} options - Options object * @param {AsymmetricKey} options.key - AsymmetricKey of the user. * @returns {Promise<DeployUtil.Deploy>} - Signed deploy object */ static async sign(deploy, options = {}) { try { return DeployUtil.signDeploy(deploy, options.key); } catch (e) { console.log(e); throw new SignError(); } } }
JavaScript
class State { /** * @constructor * @param {Object} - input object */ constructor(data) { this._data = data; this._listeners = []; // vars used when lock is on this._lock = false; this._old_data = undefined; this._changed_namespaces = []; } /** * Initial call to create instance * * @param {Object} payload - input object * @return {State} instance of the State Class */ static create(data) { return new this(data); } /** * Execute listener functions * @private */ _notify(namespace) { let namespaces = _clone(this._changed_namespaces); namespaces.push(namespace); this._listeners.forEach((listener) => { // continue if namespaces doesn't match if ( !_detect_match(namespaces, listener.namespace) ) return; let old_val = _get_descendant_path(this._old_data, listener.namespace), new_val = _get_descendant_path(this._data, listener.namespace); if ( !_has_diff(old_val, new_val) ) return; listener.fn(old_val, new_val); }); } /** * Returns function to remove listeners * @private */ _off(index) { let listeners = this._listeners; return function() { listeners.splice(index, 1); } } }
JavaScript
class CustomDataSource extends pgrid.dataSource.JSData { constructor(resource, options) { super(resource, options); this._jsdataDS = new pgrid.dataSource.JSData(resource); } query(options) { return this._jsdataDS.query(options).then(({ totalCount, items, }) => { const filteredItems = _.filter(items, item => item.CustomerID[0] !== 'A'); return { totalCount, items: filteredItems, }; }); } }
JavaScript
class CustomerAddressApiService extends ApiService { constructor(httpClient, loginService, apiEndpoint = 'customer-address') { super(httpClient, loginService, apiEndpoint); this.name = 'customerAddressService'; } getListByCustomerId(customerId, page, limit, additionalParams = {}, additionalHeaders = {}) { const headers = this.getBasicHeaders(additionalHeaders); let params = {}; if (page >= 1) { params.page = page; } if (limit > 0) { params.limit = limit; } params = Object.assign(params, additionalParams); // Switch to the general search end point when we're having a search term if ((params.term && params.term.length) || (params.filter && params.filter.length)) { return this.httpClient .post(`${this.getApiBasePath(null, 'search')}`, params, { headers }) .then((response) => { return ApiService.handleResponse(response); }); } return this.httpClient .get(this.getApiBasePath(), { params, headers }) .then((response) => { return ApiService.handleResponse(response); }); } }
JavaScript
class User { constructor(id, name) { this._id = id ? parseInt(id) : undefined; this._userName = name; } getID() { return this._id; } getUserName() { return this._userName; } /** * Users this user is following * @param {number} userID of a user this user is following * @returns {undefined} */ addFollowing(userID) { if (userID) { if (!this._following) { this._following = new Set(); } this._following.add(userID); } } /** * Useers this user is followed by * @param {number} userID of a user this user is followed by * @returns {undefined} */ addFollowedBy(userID) { if (userID) { if (!this._followedBy) { this._followedBy = new Set(); } this._followedBy.add(userID); } } /** * * @param {object} subObject Inthe format of: * https://dev.twitch.tv/docs/api/reference#Get-Broadcaster-Subscriptions * * { "broadcaster_id": "141981764", "broadcaster_login": "twitchdev", "broadcaster_name": "TwitchDev", "gifter_id": "12826", "gifter_login": "twitch", "gifter_name": "Twitch", "is_gift": true, "tier": "1000", "plan_name": "Channel Subscription (twitchdev)", "user_id": "527115020", "user_name": "twitchgaming", "user_login": "twitchgaming" } * @returns {undefined} */ addSubscribedTo(subObject) { if (subObject) { if (!this._subscribedTo) { this._subscribedTo = {}; } this._subscribedTo[subObject.broadcaster_id] = subObject; } } getFollowingCounts() { return this._following ? this._following.size : undefined; } getFollowedByCounts() { return this._followedBy ? this._followedBy.size : undefined; } getSubscribedToCount() { return this._subscribedTo ? Object.keys(this._subscribedTo).length : undefined; } /** * Check if this user is following the target user * * @param {number} targetUserID of a user to check if this user is following by that user * @returns {Boolean|undefined} returns true if this this user is following the target user */ isFollowing(targetUserID) { return this._following ? this._following.has(targetUserID) : undefined; } isFollowingCurrent() { return this.isFollowing(filter.getChannelId()); } /** * Check if this user is followed by the target user * * @param {number} targetUserID of a user to check if this user is followed by that user * @returns {Boolean|undefined} returns true if this this user is following the target user */ isFollowedBy(targetUserID) { return this._followedBy ? this._followedBy.has(targetUserID) : undefined; } /** * Returns subscription info for current channel * * @param {number} targetUserID of a user to check if this user is subscribed to that user * @returns {Object} subscribed info */ getSubscribedTo(targetUserID) { return this._subscribedTo ? this._subscribedTo[targetUserID] : undefined; } getSubscribedToCurrent() { return this.getSubscribedTo(filter.getChannelId()); } /** * Returns general info about this user to display * * @returns {Object} JSON overviw of this user */ getInfo() { const info = { following: this.isFollowingCurrent() } const subscribedObj = this.getSubscribedToCurrent(); if (subscribedObj) { info.is_subscribed = true; info.tier = subscribedObj.tier; info.plan_name = subscribedObj.plan_name; if (subscribedObj.is_gift) { info.gifter_name = subscribedObj.gifter_name; } } else { info.is_subscribed = false; } return info; } /** * Returns css string to display for the info icon * * @returns {string} css class depends on subscribed or not */ getInfoCss() { const subObj = this.getSubscribedTo(filter.getChannelId()); return subObj ? 'subscribed' : 'not-subscribed'; } /** * returns if a user is selected based on the searchString. * @returns {boolean} weather if this user is applicable or not */ isApplicable() { if (filter.getSearchString() === followingFlag) { return Boolean(this.isFollowingCurrent()); } else if (filter.getSearchString() === notFollowingFlag) { return !this.isFollowingCurrent(); } else if (filter.getSearchString() && filter.getSearchString().indexOf(':') !== 0) { // filtering for string like return this._userName.toLowerCase().indexOf(filter.getSearchString()) > -1; } else { // not a valid filter, returning true return true; } } }
JavaScript
class Calling extends Model { // enum of all possible titles static TITLES = { BROTHER: 'Brother', SISTER: 'Sister', ELDER: 'Elder', }; }
JavaScript
class Triennial { /** * Builds a Triennial object * @param {number} [hebrewYear] Hebrew Year (default current year) */ constructor(hebrewYear) { hebrewYear = hebrewYear || new HDate().getFullYear(); if (hebrewYear < 5744) { throw new RangeError(`Invalid Triennial year ${hebrewYear}`); } if (!triennialAliyot) { triennialAliyot = Triennial.getTriennialAliyot(); } this.startYear = Triennial.getCycleStartYear(hebrewYear); this.sedraArray = []; this.bereshit = Array(4); for (let yr = 0; yr < 4; yr++) { const sedra = HebrewCalendar.getSedra(this.startYear + yr, false); const arr = sedra.getSedraArray(); this.bereshit[yr] = this.sedraArray.length + arr.indexOf(0); this.sedraArray = this.sedraArray.concat(arr); } // find the first Saturday on or after Rosh Hashana const rh = new HDate(1, months.TISHREI, this.startYear); const firstSaturday = rh.onOrAfter(6); this.firstSaturday = firstSaturday.abs(); this.calcVariationOptions(); this.readings = this.cycleReadings(this.variationOptions); } /** * @param {string} parsha parsha name ("Bereshit" or "Achrei Mot-Kedoshim") * @param {number} yearNum 0 through 2 for which year of Triennial cycle * @return {Object<string,Aliyah>} a map of aliyot 1-7 plus "M" */ getReading(parsha, yearNum) { const reading = shallowCopy({}, this.readings[parsha][yearNum]); if (reading.aliyot) { Object.values(reading.aliyot).map((aliyah) => calculateNumVerses(aliyah)); } return reading; } /** * @return {number} */ getStartYear() { return this.startYear; } /** * Returns triennial year 1, 2 or 3 based on this Hebrew year * @param {number} year Hebrew year * @return {number} */ static getYearNumber(year) { if (year < 5744) { throw new RangeError(`Invalid Triennial year ${year}`); } return ((year - 5744) % 3) + 1; } /** * Returns Hebrew year that this 3-year triennial cycle began * @param {number} year Hebrew year * @return {number} */ static getCycleStartYear(year) { return year - (this.getYearNumber(year) - 1); } /** * First, determine if a doubled parsha is read [T]ogether or [S]eparately * in each of the 3 years. Yields a pattern like 'SSS', 'STS', 'TTT', 'TTS'. * @private * @param {number} id * @return {string} */ getThreeYearPattern(id) { let pattern = ''; for (let yr = 0; yr <= 2; yr ++) { let found = this.sedraArray.indexOf(-1 * id, this.bereshit[yr]); if (found > this.bereshit[yr + 1]) { found = -1; } const pat = (found == -1) ? 'S' : 'T'; pattern += pat; } return pattern; } /** * @private */ calcVariationOptions() { const option = this.variationOptions = Object.create(null); doubled.forEach((id) => { const pattern = this.getThreeYearPattern(id); const name = getDoubledName(id); // Next, look up the pattern in JSON to determine readings for each year. // For "all-together", use "Y" pattern to imply Y.1, Y.2, Y.3 const variation = (pattern === 'TTT') ? 'Y' : parshiyotObj[name].triennial.patterns[pattern]; if (typeof variation === 'undefined') { throw new Error(`Can't find pattern ${pattern} for ${name}, startYear=${this.startYear}`); } const p1 = parshiot[id]; const p2 = parshiot[id + 1]; option[name] = option[p1] = option[p2] = variation; }); } /** * @return {string} */ debug() { let str = `Triennial cycle started year ${this.startYear}\n`; doubled.forEach((id) => { const pattern = this.getThreeYearPattern(id); const name = getDoubledName(id); const variation = this.variationOptions[name]; str += ` ${name} ${pattern} (${variation})\n`; }); return str; } /** * Builds a lookup table readings["Bereshit"][0], readings["Matot-Masei"][2] * @private * @param {Object} cycleOption * @return {Map<string,Object[]>} */ cycleReadings(cycleOption) { const readings = Object.create(null); parshiot.forEach((parsha) => { readings[parsha] = Array(3); }); readings[VEZOT_HABERAKHAH] = Array(3); doubled.map(getDoubledName).forEach((parsha) => { readings[parsha] = Array(3); }); for (let yr = 0; yr <= 2; yr ++) { this.cycleReadingsForYear(cycleOption, readings, yr); } return readings; } /** * @private * @param {string} option * @param {Map<string,Object[]>} readings * @param {number} yr */ cycleReadingsForYear(option, readings, yr) { const startIdx = this.bereshit[yr]; const endIdx = this.bereshit[yr + 1]; for (let i = startIdx; i < endIdx; i++) { const id = this.sedraArray[i]; if (typeof id !== 'number') { continue; } const h = (id < 0) ? getDoubledName(-id) : parshiot[id]; const variationKey = isSometimesDoubled[id] ? option[h] : 'Y'; const variation = variationKey + '.' + (yr + 1); const a = triennialAliyot[h][variation]; if (!a) { throw new Error(`can't find ${h} year ${yr} (variation ${variation})`); } const aliyot = clone(a); // calculate numVerses for the subset of aliyot that don't cross chapter boundaries Object.keys(aliyot).forEach((num) => calculateNumVerses(aliyot[num])); readings[h][yr] = { aliyot, date: new HDate(this.firstSaturday + (i * 7)), }; } // create links for doubled doubled.forEach((id) => { const h = getDoubledName(id); const combined = readings[h][yr]; const p1 = parshiot[id]; const p2 = parshiot[id + 1]; if (combined) { readings[p1][yr] = readings[p2][yr] = {readTogether: h, date: combined.date}; } else { readings[h][yr] = { readSeparately: true, date1: readings[p1][yr].date, date2: readings[p2][yr].date, }; } }); const vezotAliyot = triennialAliyot[VEZOT_HABERAKHAH]['Y.1']; readings[VEZOT_HABERAKHAH][yr] = { aliyot: vezotAliyot, date: new HDate(23, months.TISHREI, this.startYear + yr), }; } /** * Walks parshiyotObj and builds lookup table for triennial aliyot * @private * @return {Object} */ static getTriennialAliyot() { const triennialAliyot = Object.create(null); const triennialAliyotAlt = Object.create(null); // build a lookup table so we don't have to follow num/variation/sameas Object.keys(parshiyotObj).forEach((parsha) => { const value = parshiyotObj[parsha]; const book = BOOK[value.book]; if (value.triennial) { // Vezot Haberakhah has no triennial triennialAliyot[parsha] = Triennial.resolveSameAs(parsha, book, value.triennial); if (value.triennial.alt) { triennialAliyotAlt[parsha] = Triennial.resolveSameAs(parsha, book, value.triennial.alt); } } }); // TODO: handle triennialAliyotAlt also return triennialAliyot; } /** * Transforms input JSON with sameAs shortcuts like "D.2":"A.3" to * actual aliyot objects for a given variation/year * @private * @param {string} parsha * @param {string} book * @param {Object} triennial * @return {Object} */ static resolveSameAs(parsha, book, triennial) { const variations = triennial.years || triennial.variations; if (typeof variations === 'undefined') { throw new Error(`Parashat ${parsha} has no years or variations`); } // first pass, copy only alyiot definitions from parshiyotObj into lookup table const lookup = Object.create(null); Object.keys(variations).forEach((variation) => { const aliyot = variations[variation]; if (typeof aliyot === 'object') { const dest = Object.create(null); Object.keys(aliyot).forEach((num) => { const src = aliyot[num]; const reading = {k: book, b: src.b, e: src.e}; if (src.v) { reading.v = src.v; } dest[num] = reading; }); lookup[variation] = dest; } }); // second pass to resolve sameas strings (to simplify later lookups) Object.keys(variations).forEach((variation) => { const aliyot = variations[variation]; if (typeof aliyot === 'string') { if (typeof lookup[aliyot] === 'undefined') { throw new Error(`Can't find source for ${parsha} ${variation} sameas=${aliyot}`); } lookup[variation] = lookup[aliyot]; } }); return lookup; } }
JavaScript
class Data { /** * This constructor initializes the data properties * @param {Number} id * @param {string} name * @param {Number} age */ constructor(id, name, age) { this.id = id; this.name = name; this.age = age; } /** * Get the ID property * @return {Number} */ getId = () =>this.id; /** * Get the name property * @return {string} */ getName = () =>this.name; /** * Get the age property * @return {string} */ getAge = () =>this.age; }
JavaScript
class Option extends Base { constructor(text, destination, location) { super(location); const privates = { text: text, destination: destination } privateProps.set(this, privates); } /** @memberof Statement.Option * @instance * @returns {string} the text that this statement should output */ get text() { return privateProps.get(this).text } /** @memberof Statement.Option * @instance * @returns {string} the name of the destination node that this statement links to */ get destination() { return privateProps.get(this).destination } }
JavaScript
class DepthCalculator { calculateDepth(arr, depth = 1) { let newArr = []; if (arr.length === 0) newArr.push(depth); for (let i = 0; i < arr.length; i++) { if (typeof arr[i] === "object") { newArr.push(this.calculateDepth(arr[i], depth + 1)); } else { newArr.push(depth); } } return Math.max(...newArr); } }
JavaScript
class OeComponentCreator extends OEAjaxMixin(PolymerElement) { static get is() { return 'oe-component-creator'; } static get template() { return html` <style include="iron-flex iron-flex-alignment"> :host { display: block; position: relative; height: 500px; width: 500px; } .step-container { height: calc(100% - 40px); } #step-selector,.creation-container{ height:100%; } .prop { font-size: 12px; padding: 4px 8px; margin: 6px 0px; background: var(--dark-primary-color); border-radius: 4px; max-width: 200px; } paper-checkbox { --paper-checkbox-unchecked-color: rgba(255, 255, 255, 0.6); --paper-checkbox-checked-color: #ffffff; --paper-checkbox-checkmark-color: #000000; --paper-checkbox-label-color: #ffffff; --paper-checkbox-label: { max-width: 150px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } } .template-desc { font-size: 12px; font-family: 'Roboto-Light'; padding: 6px 0px; } .step { height: 100%; } .step-content { height: calc(100% - 56px); overflow: auto; padding: 0px 16px; } .step-title,.list-header { height: 40px; line-height: 40px; font-size: 16px; padding: 8px 16px; } paper-radio-button { display: block; padding: 8px 0px; --paper-radio-button-unchecked-color: rgba(255, 255, 255, 0.6); --paper-radio-button-checked-color: rgba(255, 255, 255, 0.6); --paper-radio-button-label-color: rgba(255, 255, 255, 0.6); } oe-input { --paper-input-container-focus-color: #ffffff; --paper-input-container-input-color: rgba(255, 255, 255, 0.6); --paper-input-container-color: rgba(255, 255, 255, 0.6); } oe-combo { --paper-input-container-focus-color: #ffffff; --paper-input-container-input-color: rgba(255, 255, 255, 0.6); --paper-input-container-color: rgba(255, 255, 255, 0.6); } .main-layout{ height: calc(100% - 40px); } .main-layout > div{ height:100%; } .more-props { padding: 12px 0px; } .prop-list { padding: 8px 0px; border-top: 2px solid var(--dark-primary-color); } .helper-text { font-size: 12px; font-style: italic; opacity: 0.54; margin-top: 8px; } #step-selector { width: 200px; background: var(--light-primary-color); } .list-item { height: 40px; padding: 8px 16px; box-sizing: border-box; } .list-item::before { content: ' '; width: 12px; height: 12px; margin-right: 10px; border-radius: 50%; flex-shrink: 0; background: var(--default-text-color); display: inline-block; position: relative; } .list-item.active::before { background: var(--accent-color); } .list-item.invalid::before { background: var(--error-color); } .navigation-section{ background: var(--dark-primary-color); height:40px; } .template-no-model paper-radio-button[type="form"]{ display: none; } </style> <div class="layout horizontal creation-container"> <div class="layout vertical flex"> <iron-pages selected=[[selectedStep]] class="flex main-layout"> <div id="name-model-section"> <div class="step-title">Name the page and configure</div> <div class="step-content"> <oe-input label="Page Name" value="{{uiComponent.name}}" field-id="name" required pattern="^([a-zA-Z0-9]+)((-[a-zA-Z0-9]+)+)$" id="componentName" user-error-message='{"patternMismatch":"Polymer name should contain a - hyphen"}'></oe-input> <oe-async-validator fields='["name"]' model={{uiComponent}} requesturl='[[_validateUrl(uiComponent.name)]]' ensure="absent" error="component name already in use"></oe-async-validator> <oe-combo id="modelName" show-refresh value="{{uiComponent.modelName}}" label="Search Models" displayproperty="name" valueproperty="name" listurl="[[_getRestApiUrl('/ModelDefinitions?filter[fields][name]=true')]]" on-pt-item-confirmed="_getModelData" on-blur="_getModelData"></oe-combo> <div hidden$="[[!isModelObtained]]"> <div class="more-props"> <paper-checkbox checked="{{uiComponent.autoInjectFields}}">Auto Inject Fields</paper-checkbox> <div class="helper-text">Properties updated in the model will be injected in the form automatically</div> </div> <div class="prop-list"> <template is="dom-repeat" items="[[modelMeta.modelProperties]]"> <div class="prop"> <paper-checkbox checked="{{item.applied}}" class="prop-item">[[item.name]]</paper-checkbox> </div> </template> </div> </div> </div> </div> <div id="template-selection-section"> <div class="step-title">Choose template</div> <div class$="step-content template-[[_getTemplateType(uiComponent.modelName)]]"> <paper-radio-group selected="{{uiComponent.templateName}}"> <template is="dom-repeat" items="[[templateList]]"> <paper-radio-button name="{{item.file}}" type$="[[item.type]]"> <div class="layout vertical"> <label>[[item.file]]</label> <paper-tooltip class="template-desc" position="top" hidden$="[[!item.description]]">[[item.description]]</paper-tooltip> </div> </paper-radio-button> </template> </paper-radio-group> </div> </div> </iron-pages> <div class="navigation-section layout horizontal center justified"> <paper-button class="secondary-btn" on-tap="_showComponentsList">CANCEL</paper-button> <paper-button class="secondary-btn" hidden="[[hidePrevNavigation]]" on-tap="_showPrevStep">BACK</paper-button> <paper-button class="primary-btn" on-tap="_showNextStep">[[buttonTitle]]</paper-button> </div> </div> <div id="step-selector"> <div class="list-header">Create new page</div> <iron-selector selected="{{selectedStep}}"> <template is="dom-repeat" items="{{stepList}}" as="step"> <div name$="[[index]]" class$="list-item [[_computeStepStatus(selectedStep,index)]]">{{step}}</div> </template> </iron-selector> </div> </div> `; } _computeStepStatus(curStep, index) { if (curStep === index) { return 'active'; } if (index === 0) { this.$.componentName.validate(); this.$.modelName.validate(); return this.$.componentName.invalid || this.$.modelName.invalid ? 'invalid' : ''; } else { return this.uiComponent.templateName ? '' : 'invalid'; } } constructor() { super(); this.stepList = ["Name & Model", "Template selection"]; this._resetFields(); this.makeAjaxCall("designer/templates", "GET", null, null, null, null, function (err, resp) { if (err) { this.fire("oe-show-error", "Error fetching templates"); return; } resp.forEach(this._getDescription.bind(this)); this.set("templateList", resp); this.fire("update-templatelist",resp); }.bind(this)); } _getRestApiUrl(url) { return window.OEUtils._getRestApiUrl(url); } _validateUrl(name) { return window.OEUtils._getRestApiUrl('/UIComponents?filter={"where":{"name":"' + name + '"}}'); } _getModelData() { var self = this; var model = this.uiComponent.modelName; var isValidModel = !this.$.modelName.invalid; if (isValidModel && model && model.length > 0) { if (model == this._currModel) { return; } this._currModel = model; this.makeAjaxCall(window.OEUtils._getRestApiUrl('/UIComponent/modelmeta/') + model, 'get', null, null, null, null, function (err, res) { self._currModel = null; if (err) { self.fire('oe-show-error', 'Error in Fetching Model Meta'); return; } self.generateFieldsArr(res); self.set('isModelObtained', true); }); } else { self.set('isModelObtained', false); self.set('modelMeta.modelProperties', []); } } generateFieldsArr(resp) { var properties = []; var meta = {}; var modelData = resp[this.uiComponent.modelName]; modelData.properties && Object.keys(modelData.properties).forEach(function (prop) { var modelprop = { name: prop, 'config': modelData.properties[prop], 'applied': true }; if (prop[0] == '_' || prop == 'id' || prop == 'scope') { return; } else { properties.push(modelprop); } }); meta.modelProperties = properties; meta.modelName = this.uiComponent.modelName; meta.autoInjectFields = true; this.set('modelMeta', meta); } static get observers() { return ['stepChanged(selectedStep)']; } _showComponentsList() { this.fire("show-component-list"); } stepChanged(step) { if (step === 1) { this.set('buttonTitle', 'SAVE'); } else { this.set('buttonTitle', 'NEXT'); } this.set('hidePrevNavigation', step === 0); } _showNextStep() { if (this.selectedStep === 0) { this.selectedStep++; } else { var isValid = !(this.$.componentName.invalid || this.$.modelName.invalid); if (isValid) { this.createPage(); } else { this.fire('oe-show-error', "Please fill all the fields"); } } } createPage() { var self = this; var apiurl = window.OEUtils._getRestApiUrl('/UIComponents'); var payload = this.uiComponent; if (payload.modelName) { if (payload.autoInjectFields) { payload.excludeFields = this.modelMeta.modelProperties.filter(function (p) { return !p.applied; }).map(function (prop) { return prop.name; }); } else { payload.fields = this.modelMeta.modelProperties.filter(function (p) { return p.applied; }).map(function (prop) { return { fieldId: prop.name }; }); } } this.makeAjaxCall(apiurl, 'post', payload, null, null, function (err, res) { if (!err) { self.fire('component-created', res); self.fire('oe-show-success', 'Component successfully created'); } else { self.resolveError(err); } }); } _resetFields() { this.set('isModelObtained', false); this.set('uiComponent', { name: "", templateName: "default-form.html", fields: [], excludeFields: [], autoInjectFields: false }); this.set('selectedStep', 0); this.set('lastVisitedTabIndex', 0); this.set('buttonTitle', 'NEXT'); } _showPrevStep() { if (this.selectedStep > 0) { this.selectedStep--; } } _getDescription(template) { var descKey = "@description"; var lines = template.content.split('\n'); var descLine = lines.find(function (line) { return !!line.match(descKey); }); if (descLine) { template.description = descLine.trim().substring(descLine.lastIndexOf(descKey) + descKey.length, descLine.length).trim(); } else { template.description = ""; } } _getTemplateType(modelName) { return (modelName && modelName.length) ? "has-model" : "no-model"; } }
JavaScript
class VectorOblique extends LayerOblique { static get className() { return 'vcs.vcm.layer.oblique.VectorOblique'; } /** * @param {import("@vcmap/core").Oblique} map * @param {VectorImplementationOptions} options */ constructor(map, options) { super(map, options); /** @type {import("ol/source").Vector<import("ol/geom/Geometry").default>} */ this.obliqueSource = new VectorSource({}); /** * @type {Object<string, Object<string, import("ol/events").EventsKey>>} * @private */ this._featureListeners = {}; /** * @type {Array<import("ol/events").EventsKey>} * @private */ this._sourceListener = []; /** * The extent of the current image for which features where fetched * @type {import("ol/extent").Extent|null} */ this.currentExtent = null; /** * The image name for which the current features where fetched * @type {string|null} */ this.fetchedFeaturesForImageName = null; /** * @type {Object<string, (number|boolean)>} * @private */ this._updatingMercator = {}; /** * @type {Object<string, (number|boolean|null)>} * @private */ this._updatingOblique = {}; /** * @type {Array<Function>} * @private */ this._featureVisibilityListeners = []; /** * @type {import("@vcmap/core").GlobalHider} */ this.globalHider = getGlobalHider(); /** * @type {import("ol/source").Vector<import("ol/geom/Geometry").default>} */ this.source = options.source; /** * @type {import("@vcmap/core").StyleItem} */ this.style = options.style; /** * @type {import("@vcmap/core").FeatureVisibility} */ this.featureVisibility = options.featureVisibility; /** * @type {import("ol/layer").Vector<import("ol/source").Vector<import("ol/geom/Geometry").default>>|null} */ this.olLayer = null; } /** * @inheritDoc * @returns {import("ol/layer").Vector<import("ol/source").Vector<import("ol/geom/Geometry").default>>} */ getOLLayer() { return new OLVectorLayer({ visible: false, source: this.obliqueSource, style: this.style.style, }); } /** * @param {import("@vcmap/core").StyleItem} style * @param {boolean=} silent */ // eslint-disable-next-line no-unused-vars updateStyle(style, silent) { this.style = style; if (this.initialized) { this.olLayer.setStyle(this.style.style); } } /** * clears the current image and fetches features for the next * @private */ _onObliqueImageChanged() { this._clearCurrentImage(); this._fetchFeaturesInView(); } /** * @param {import("ol").Feature<import("ol/geom/Geometry").default>} feature * @returns {boolean} * @private */ _featureInExtent(feature) { if (this.currentExtent) { const geometry = feature.getGeometry(); if (geometry) { return geometry[alreadyTransformedToImage] || geometry.intersectsExtent(this.currentExtent); } } return false; } /** * @protected */ _addSourceListeners() { this._sourceListener.push(/** @type {import("ol/events").EventsKey} */ (this.source.on('addfeature', /** @param {import("ol/source/Vector").VectorSourceEvent} event */ (event) => { const { feature } = event; if (this._featureInExtent(feature)) { this.addFeature(event.feature); } }))); this._sourceListener.push(/** @type {import("ol/events").EventsKey} */ (this.source.on('removefeature', /** @param {import("ol/source/Vector").VectorSourceEvent} event */ (event) => { this.removeFeature(event.feature); }))); this._sourceListener.push(/** @type {import("ol/events").EventsKey} */ (this.source.on('changefeature', /** @param {import("ol/source/Vector").VectorSourceEvent} event */ (event) => { const { feature } = event; const newFeatureId = feature.getId(); if (!this._featureListeners[newFeatureId] && this._featureInExtent(feature)) { this.addFeature(feature); } }))); } /** * @inheritDoc * @returns {Promise<void>} */ async activate() { if (!this.active) { await super.activate(); if (this.active) { this.olLayer.setVisible(true); if (this._featureVisibilityListeners.length === 0) { this._featureVisibilityListeners = synchronizeFeatureVisibilityWithSource(this.featureVisibility, this.source, this.globalHider); } this._addSourceListeners(); this._imageChangedListener = this.map.imageChanged.addEventListener(this._onObliqueImageChanged.bind(this)); await this._fetchFeaturesInView(); } } } /** * @param {import("ol").Feature<import("ol/geom/Geometry").default>} originalFeature * @returns {Promise<void>} * @private */ addFeature(originalFeature) { if (!this.active) { this.fetchedFeaturesForImageName = null; } if ( this.active && this.currentExtent ) { const id = originalFeature.getId(); const originalGeometry = originalFeature.getGeometry(); if (originalFeature[doNotTransform]) { if ( originalGeometry && !this.obliqueSource.getFeatureById(id) ) { this.obliqueSource.addFeature(originalFeature); } return Promise.resolve(); } if (this.obliqueSource.getFeatureById(id)) { return Promise.resolve(); } const obliqueFeature = new Feature({}); obliqueFeature.setId(id); obliqueFeature[originalFeatureSymbol] = originalFeature; setNewGeometry(originalFeature, obliqueFeature); obliqueFeature.setStyle(originalFeature.getStyle()); this._setFeatureListeners(originalFeature, obliqueFeature); return this._convertToOblique(originalFeature, obliqueFeature) .then(() => { this.obliqueSource.addFeature(obliqueFeature); }); } return Promise.resolve(); } /** * @param {Object<string, import("ol/events").EventsKey>} listeners * @param {import("ol").Feature<import("ol/geom/Geometry").default>} originalFeature * @param {import("ol").Feature<import("ol/geom/Geometry").default>} obliqueFeature * @private */ _originalGeometryChanged(listeners, originalFeature, obliqueFeature) { unByKey(listeners.originalGeometryChanged); unByKey(listeners.obliqueGeometryChanged); setNewGeometry(originalFeature, obliqueFeature); this.updateObliqueGeometry(originalFeature, obliqueFeature); listeners.originalGeometryChanged = /** @type {import("ol/events").EventsKey} */ (originalFeature .getGeometry().on('change', this.updateObliqueGeometry.bind(this, originalFeature, obliqueFeature))); listeners.obliqueGeometryChanged = /** @type {import("ol/events").EventsKey} */ (obliqueFeature .getGeometry().on('change', this.updateMercatorGeometry.bind(this, originalFeature, obliqueFeature))); } /** * @param {import("ol").Feature<import("ol/geom/Geometry").default>} originalFeature * @param {import("ol").Feature<import("ol/geom/Geometry").default>} obliqueFeature * @private */ _setFeatureListeners(originalFeature, obliqueFeature) { const featureId = obliqueFeature.getId(); const listeners = { originalFeatureGeometryChanged: /** @type {import("ol/events").EventsKey} */ (originalFeature.on('change:geometry', () => { const originalGeometry = originalFeature.getGeometry(); if (originalGeometry[actuallyIsCircle]) { unByKey(listeners.originalGeometryChanged); listeners.originalGeometryChanged = /** @type {import("ol/events").EventsKey} */ (originalFeature .getGeometry().on('change', () => { if (this._updatingMercator[featureId]) { return; } delete originalGeometry[actuallyIsCircle]; this._originalGeometryChanged(listeners, originalFeature, obliqueFeature); })); return; } this._originalGeometryChanged(listeners, originalFeature, obliqueFeature); })), originalFeatureChanged: /** @type {import("ol/events").EventsKey} */ (originalFeature .on('change', () => { obliqueFeature.setStyle(originalFeature.getStyle()); })), originalGeometryChanged: /** @type {import("ol/events").EventsKey} */ (originalFeature .getGeometry().on('change', this.updateObliqueGeometry.bind(this, originalFeature, obliqueFeature))), obliqueGeometryChanged: /** @type {import("ol/events").EventsKey} */ (obliqueFeature .getGeometry().on('change', this.updateMercatorGeometry.bind(this, originalFeature, obliqueFeature))), }; this._featureListeners[featureId] = listeners; } /** * @param {import("ol").Feature<import("ol/geom/Geometry").default>} originalFeature * @param {import("ol").Feature<import("ol/geom/Geometry").default>} obliqueFeature * @returns {Promise<void>} * @private */ async _convertToOblique(originalFeature, obliqueFeature) { const id = originalFeature.getId(); const vectorGeometry = originalFeature.getGeometry(); const imageGeometry = obliqueFeature.getGeometry(); this._updatingOblique[id] = true; if (!vectorGeometry[alreadyTransformedToImage]) { await mercatorGeometryToImageGeometry(vectorGeometry, imageGeometry, this.map.currentImage); } else { obliqueFeature.getGeometry().setCoordinates(vectorGeometry.getCoordinates()); } this._updatingOblique[id] = null; } /** * @param {import("ol").Feature<import("ol/geom/Geometry").default>} originalFeature * @param {import("ol").Feature<import("ol/geom/Geometry").default>} obliqueFeature */ updateObliqueGeometry(originalFeature, obliqueFeature) { const id = originalFeature.getId(); if (this._updatingMercator[id]) { return; } if (this._updatingOblique[id] != null) { clearTimeout(/** @type {number} */ (this._updatingOblique[id])); } this._updatingOblique[id] = setTimeout(() => { this._convertToOblique(originalFeature, obliqueFeature); }, 200); } /** * @param {import("ol").Feature<import("ol/geom/Geometry").default>} originalFeature * @param {import("ol").Feature<import("ol/geom/Geometry").default>} obliqueFeature */ updateMercatorGeometry(originalFeature, obliqueFeature) { const id = originalFeature.getId(); if (this._updatingOblique[id]) { return; } if (this._updatingMercator[id] != null) { clearTimeout(/** @type {number} */ (this._updatingMercator[id])); } const imageName = this.fetchedFeaturesForImageName; this._updatingMercator[id] = setTimeout(async () => { const originalGeometry = getPolygonizedGeometry(originalFeature, false); if (originalGeometry[actuallyIsCircle]) { originalFeature.setGeometry(originalGeometry); } const imageGeometry = getPolygonizedGeometry(obliqueFeature, true); this._updatingMercator[id] = true; await imageGeometryToMercatorGeometry( imageGeometry, originalGeometry, this.map.collection.getImageByName(imageName), ); this._updatingMercator[id] = null; }, 200); } /** * Synchronizes image Features if the geometry has been changed. * also clears source and featureListeners */ _clearCurrentImage() { Object.values(this._featureListeners) .forEach((listeners) => { unByKey(Object.values(listeners)); }); this._featureListeners = {}; this._updatingOblique = {}; this._updatingMercator = {}; this.obliqueSource.getFeatures().forEach((f) => { const original = f[originalFeatureSymbol]; if (original) { delete original[obliqueGeometry]; delete original.getGeometry()[alreadyTransformedToImage]; } }); this.obliqueSource.clear(true); this.fetchedFeaturesForImageName = null; } /** * Fetches the features within the extent of the current image * @private */ _fetchFeaturesInView() { if ( this.active && this.map.currentImage && this.fetchedFeaturesForImageName !== this.map.currentImage.name ) { this.currentExtent = this.map.getExtentOfCurrentImage() .getCoordinatesInProjection(mercatorProjection); this.source.forEachFeatureInExtent(this.currentExtent, (feature) => { this.addFeature(feature); }); this.source.forEachFeature((feature) => { if (feature.getGeometry()[alreadyTransformedToImage]) { this.addFeature(feature); } }); this.fetchedFeaturesForImageName = this.map.currentImage.name; } } /** * @param {import("ol").Feature<import("ol/geom/Geometry").default>} feature * @private */ removeFeature(feature) { const feat = this.obliqueSource.getFeatureById(feature.getId()); if (feat) { const id = /** @type {string} */ (feat.getId()); const listeners = this._featureListeners[id]; if (listeners) { unByKey(Object.values(listeners)); delete this._featureListeners[id]; } this.obliqueSource.removeFeature(feat); } } /** * @inheritDoc */ deactivate() { super.deactivate(); if (this.olLayer) { this.olLayer.setVisible(false); } this._featureVisibilityListeners.forEach((cb) => { cb(); }); this._featureVisibilityListeners = []; unByKey(this._sourceListener); this._sourceListener = []; if (this._imageChangedListener) { this._imageChangedListener(); this._imageChangedListener = null; } this._clearCurrentImage(); } /** * @inheritDoc */ destroy() { if (this.olLayer) { this.map.removeOLLayer(this.olLayer); } this.olLayer = null; unByKey(this._sourceListener); this._sourceListener = []; if (this._imageChangedListener) { this._imageChangedListener(); this._imageChangedListener = null; } this.obliqueSource.clear(true); Object.values(this._updatingOblique).forEach((timer) => { if (timer != null) { clearTimeout(/** @type {number} */ (timer)); } }); Object.values(this._updatingMercator).forEach((timer) => { if (timer != null) { clearTimeout(/** @type {number} */ (timer)); } }); this._clearCurrentImage(); super.destroy(); } }
JavaScript
class Checkbox extends Component { /** * Upgrades all Checkbox AUI components. * @returns {Array} Returns an array of all newly upgraded components. */ static upgradeElements() { let components = []; Array.from(document.querySelectorAll(SELECTOR_COMPONENT)).forEach(element => { if (!Component.isElementUpgraded(element)) { components.push(new Checkbox(element)); } }); return components; }; /** * Returns all AUI component instances within the given container * @param {HTMLElement} container The container element to search for components * @returns {Array} Returns an array of all newly upgraded components. */ static get(container = document) { let components = []; if (container) { Array.from(container.querySelectorAll(SELECTOR_COMPONENT)).forEach(element => { components.push(element.auiCheckbox); }); } return components; } constructor(element) { super(element, NAMESPACE); } init() { super.init(); this._input = this._element.querySelector(`.${CLASS_INPUT}`); this._input.addEventListener('change', this._changeHandler = (event) => this._onChange(event)); this._input.addEventListener('focus', this._focusHandler = (event) => this._onFocus(event)); this._input.addEventListener('blur', this._blurHandler = (event) => this._onBlur(event)); // Insert box with tick after label element: this._label = this._element.querySelector(`.${CLASS_LABEL}`); let box = document.createElement('span'); box.classList.add(CLASS_BOX); this._label.parentNode.insertBefore(box, this._label.nextSibling); let tick = document.createElement('span'); tick.classList.add(CLASS_TICK); box.appendChild(tick); this.updateClasses(); } updateClasses() { this.checkDisabled(); this.checkToggleState(); this.checkFocus(); } /** * Check the disabled state and update field accordingly. */ checkDisabled() { if (this._input.disabled) { this._element.classList.add(CLASS_IS_DISABLED); } else { this._element.classList.remove(CLASS_IS_DISABLED); } } /** * Check the toggle state and update field accordingly. */ checkToggleState() { if (this._input.checked) { this._element.classList.add(CLASS_IS_CHECKED); } else { this._element.classList.remove(CLASS_IS_CHECKED); } } /** * Check the focus state and update field accordingly. */ checkFocus() { if (Boolean(this._element.querySelector(':focus'))) { this._element.classList.add(CLASS_IS_FOCUS); } else { this._element.classList.remove(CLASS_IS_FOCUS); } } /** * Enable checkbox */ enable() { this._input.disabled = false; this.updateClasses(); } /** * Disable checkbox */ disable() { this._input.disabled = true; this.updateClasses(); } /** * Check checkbox */ check() { this._input.checked = true; this.updateClasses(); } /** * Uncheck checkbox */ uncheck() { this._input.checked = false; this.updateClasses(); } /** * Uncheck checkbox */ toggle() { if (this._input.checked) { this.uncheck(); } else { this.check(); } } /** * Dispose component */ dispose() { super.dispose(); this._input.removeEventListener('change', this._changeHandler); this._input.removeEventListener('focus', this._focusHandler); this._input.removeEventListener('blur', this._blurHandler); this._element.removeChild(this._element.querySelector(`.${CLASS_BOX}`)); } /** * Event Handler */ _onChange(event) { this.updateClasses(); } // TODO Find out why unfocus is triggered on mousedown _onFocus(event) { this._element.classList.add(CLASS_IS_FOCUS); } _onBlur(event) { this._element.classList.remove(CLASS_IS_FOCUS); } /** * Getter and Setter */ get input() { return this._input; } get checked() { return this._input.checked = true; } set checked(value) { if (value) { this.check(); } else { this.uncheck(); } } get disabled() { return this._input.disabled = true; } set disabled(value) { if (value) { this.disable(); } else { this.enable(); } } }
JavaScript
class InMemoryUploader extends OffChainUploader { constructor (options) { super(); this._inMemoryAdapter = new InMemoryAdapter(); } async upload (data, label, preferredUrl) { await super.upload(data, label, preferredUrl); return this._inMemoryAdapter.upload(data); } }
JavaScript
class QuizComplete extends Component { componentDidMount() { clearLocalNotification() .then(setLocalNotification) } render() { const { navigation, restartQuiz, numCorrect, numCards } = this.props const score = Math.round(numCorrect*100.0/numCards) return ( <View style={styles.container}> <Text style={styles.largeFont}> Quiz complete! </Text> <Text style={styles.mediumFont}> Your Score: </Text> <Text style={styles.largeFont}> {score}% </Text> <FlashcardsButton onPress={restartQuiz}> Restart Quiz </FlashcardsButton> <FlashcardsButton onPress={() => navigation.goBack()}> Back to Deck </FlashcardsButton> </View> ) } }
JavaScript
class Projects extends Component { render() { return ( <section className="s3-projects"> <h1 className="title">My Projects</h1> <div className="project-container"> <div className="project-wrapper"> <div className="project"> <img class="thumbnail" src={require("./../../images/instapix.png")} /> <div className="project-preview"> <h6 class="project-title">Instapix</h6> <p class="project-intro"> Instagram Clone that uses a Parse backend and utilizes the camera. Allows the user to see posts and submit posts to the custom Parse database. </p> </div> </div> <div className="project"> <img class="thumbnail" src={require("./../../images/cherper.png")} /> <div className="project-preview"> <h6 class="project-title">Cherper</h6> <p class="project-intro"> Twitter Clone that uses OAuth authentication. Allows a user to read and post tweets from their timeline. </p> </div> </div> <div className="project"> <img class="thumbnail" src={require("./../../images/runica.png")} /> <div className="project-preview"> <h6 class="project-title">Runica</h6> <p class="project-intro"> Mulitplayer 2D game made in Unity. </p> </div> </div> <div className="project"> <img class="thumbnail" src={require("./../../images/pr.jpg")} /> <div className="project-preview"> <h6 class="project-title">Planet Rocket</h6> <p class="project-intro"> Web Application that helps users find a target audience. Uses a MERN Stack(MongoDB, Express, React, Node) </p> </div> </div> </div> </div> </section> )} }
JavaScript
class LCARSText extends LCARSComponent { constructor(name, label, x, y, properties) { super(name, label, x, y, properties); this.static = LCARS.ES_STATIC; // Text is always static. this.textColor = this.getColor(); this.drawText(); if(this.blinking) { this.setBlinking(true); } } getTextAnchor() { if((this.properties & LCARS.ES_LABEL) == 0) { this.properties |= LCARS.ES_LABEL_W; } return super.getTextAnchor(); } drawShape() { return ""; } getTextX() { return 0; } getTextY() { return 0; } setBlinking(enabled, color, duration) { /** If the duration argument is null, set a default blink duration. */ if(duration == null) { duration = LCARS.BLINK_DURATION_WARNING; } /** If blinking is enabled... */ if(enabled) { /** Create the DOM object for the shape's text animation, and set its attributes. */ this.textAnimateElement = document.createElementNS(LCARS.svgNS, "animate"); this.textAnimateElement.setAttribute("attributeType", "XML"); this.textAnimateElement.setAttribute("attributeName", "fill"); this.textAnimateElement.setAttribute("values", this.getBlinkColors(color)); this.textAnimateElement.setAttribute("dur", duration); this.textAnimateElement.setAttribute("repeatCount", "indefinite"); /** Append the animation element to the text element. */ this.textElement.appendChild(this.textAnimateElement); } /** Else if blinking is not enabled... */ else { /** If the text animate element exists, remove it. */ if(this.textAnimateElement != null) { this.textElement.removeChild(this.textAnimateElement); } } } }
JavaScript
class BGAtomTreeItemFontSizer { constructor(treeViewEl,state) { this.treeViewEl = treeViewEl; this.dynStyles = new BGStylesheet(); this.fontSizeToLineHeightPercent = 230; // this is about the equivalent % to the atom hardcoded css 11px/25px font/lineHeight\ // handle incoming serialized state from the last run if (state && state.active) { this.fontSizeToLineHeightPercent = state.lineHeight; this.setFontSize(state.fontSize, true); } } // set the new font size by adjusting the existing fontSize by a number of pixels. Nagative numbers make the font smaller adjustFontSize(delta) { this.setFontSize(this.getFontSize() + delta); } // resetting returns to the default Atom styling resetFontSize() { if (this.dynStyles && this.cssListItemRule) { this.cssListItemRule = this.dynStyles.deleteRule(this.cssListItemRule); this.cssListHighlightRule = this.dynStyles.deleteRule(this.cssListHighlightRule); this.cssListHighlightRuleRoot = this.dynStyles.deleteRule(this.cssListHighlightRuleRoot); } if (this.treeViewEl) this.treeViewEl.style.fontSize = ''; } // set the new size in pixels async setFontSize(fontSize, fromCtor) { // if not yet set or if the fontSizeToLineHeightPercent has changed, set a dynamic rule to override the line-height if (!this.cssListItemRule || this.fontSizeToLineHeightPercent != this.lastFontSizeToLineHeightPercent) { this.cssListItemRule = this.dynStyles.updateRule(this.cssListItemRule, ` .tool-panel.tree-view .list-item { line-height: ${this.fontSizeToLineHeightPercent}% !important; } `); this.lastFontSizeToLineHeightPercent = this.fontSizeToLineHeightPercent; } // set the font size at the top of the tree-view and it will affect all the item text this.treeViewEl.style.fontSize = fontSize+'px'; // the highlight bar is also hardcoded to 25px so create a dynamic rule to set it // to determine the height, we query the height of a list-item. The root is not a good choice because themes can style it // differently. If the root node is collapsed, expand it so that we have a regular list-item to query if (this.treeViewEl.getElementsByClassName('list-item').length <= 1) { atom.commands.dispatch(this.treeViewEl, 'core:move-to-top'); atom.commands.dispatch(this.treeViewEl, 'tree-view:expand-item'); for (var i=0; i<10 && this.treeViewEl.getElementsByClassName('list-item').length <= 1; i++) await bgAsyncSleep(100); } var lineBoxHeight = 0; if (this.treeViewEl.getElementsByClassName('list-item').length > 1) lineBoxHeight = this.treeViewEl.getElementsByClassName('list-item')[1].getBoundingClientRect().height; else lineBoxHeight = Math.trunc(fontSize * this.fontSizeToLineHeightPercent /100); this.cssListHighlightRule = this.dynStyles.updateRule(this.cssListHighlightRule, ` .tool-panel.tree-view .list-item.selected::before, .tool-panel.tree-view .list-nested-item.selected::before { height:${lineBoxHeight}px !important; } `); // only for the intial call from th constructor to restore the previous state, do we yeild. This is only because the root // tree item does not have its actual size until later. Appearently some Atom code changes something that affects its height (fromCtor) ? await bgAsyncSleep(1) : null; var rootLineBoxHeight = 0; if (this.treeViewEl.getElementsByClassName('list-item').length > 0) { rootLineBoxHeight = this.treeViewEl.getElementsByClassName('list-item')[0].getBoundingClientRect().height; } else { rootLineBoxHeight = lineBoxHeight; } this.cssListHighlightRuleRoot = this.dynStyles.updateRule(this.cssListHighlightRuleRoot, ` .tool-panel.tree-view .project-root.selected::before { height:${rootLineBoxHeight}px !important;} `); // this.cssListItemRule = this.dynStyles.updateRule(this.cssListItemRule, [ // ` // .tool-panel.tree-view .list-item { // line-height: ${this.fontSizeToLineHeightPercent}% !important; // }`, // ` // .tool-panel.tree-view .list-item.selected::before, .tool-panel.tree-view .list-nested-item.selected::before { // height:"+lineBoxHeight+"px !important; // }`, // ` // .tool-panel.tree-view .project-root.selected::before { // height:${rootLineBoxHeight}px !important;} // `]); } // return the existing size in pixels getFontSize() { if (!this.treeViewEl) return 11; var currentFontSize = parseInt(this.treeViewEl.style.fontSize); if (!currentFontSize) { currentFontSize = parseInt(window.getComputedStyle(this.treeViewEl, null).fontSize); } return currentFontSize; } setItemLineHightPercentage(lineHeightPercent) { this.fontSizeToLineHeightPercent = lineHeightPercent; this.setFontSize(this.getFontSize()); } adjustItemLineHightPercentage(delta) { this.fontSizeToLineHeightPercent += delta; this.setFontSize(this.getFontSize()); } serialize() { return { active: (this.cssListItemRule ? true:false), fontSize: this.getFontSize(), lineHeight: this.fontSizeToLineHeightPercent } } dispose() { this.resetFontSize() } }
JavaScript
class Bookmark extends Component { constructor(props) { super(props); this.state = { bookmarkName: '', bookmarkURL: '', }; } // Update state to reflect inputs handleChange(event) { let newState = {}; newState[event.target.name] = event.target.value; this.setState(newState); } // Create a new bookmark createNewBookmark(event) { event.preventDefault(); this.setState({ bookmarkName: '', bookmarkURL: '' }); this.props.createBookmarkCallback(this.state.bookmarkName, this.state.bookmarkURL) } render() { return ( <div className="col-xs-12 col-sm-6"> <Button color='success' onClick={this.props.toggleCreateBookmark}> <i className={'fa fa-' + (this.props.open ? 'minus' : 'plus')} aria-hidden='true'></i> {this.props.open ? ' Cancel' : ' Add Link'} </Button> <Collapse isOpen={this.props.open} className='mt-2'> <Form> <FormGroup> <InputGroup> <InputGroupAddon>Name</InputGroupAddon> <Input type='text' name="bookmarkName" id='bookmarkName' onChange={(e) => this.handleChange(e)} placeholder='Enter custom name...' value={this.state.bookmarkName} /> </InputGroup> </FormGroup> <FormGroup> <InputGroup> <InputGroupAddon>URL</InputGroupAddon> <Input type='text' name="bookmarkURL" id='bookmarkURL' onChange={(e) => this.handleChange(e)} placeholder='Enter URL...' value={this.state.bookmarkURL} /> </InputGroup> </FormGroup> <Button onClick={(e) => this.createNewBookmark(e)} disabled={(this.state.bookmarkName.length === 0) && (this.state.bookmarkURL.length === 0)} color="primary"> <i className='fa fa-plus' aria-hidden='true'></i> Add Bookmark </Button> </Form> </Collapse> </div> ); } }