language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class DappReadOnly extends Component { state = { value: null }; async componentDidMount() { const web3 = await getReadOnlyWeb3(); const simpleStorage = await SimpleStorageContract.createWithWeb3(web3); const value = await simpleStorage.get(); this.setState({ value }); this.valueChangedSubscription = simpleStorage.listenValueChanged(value => { this.setState({ value }); }); } componentWillUnmount() { this.valueChangedSubscription(); } render() { const { value } = this.state; return "value: " + (value !== null ? value : "..."); } }
JavaScript
class PagingIterator { /** * Determine if a response is iterable * @param {Object} response - The API response * @returns {boolean} Whether the response is iterable */ static isIterable(response) { var isGetOrPostRequest = (response.request && (response.request.method === 'GET' || response.request.method === 'POST')), hasEntries = (response.body && Array.isArray(response.body.entries)), notEventStream = (response.body && !response.body.next_stream_position); return Boolean(isGetOrPostRequest && hasEntries && notEventStream); } /** * @constructor * @param {Object} response - The original API response * @param {BoxClient} client - An API client to make further requests * @returns {void} * @throws {Error} Will throw when collection cannot be paged */ constructor(response, client) { if (!PagingIterator.isIterable(response)) { throw new Error('Cannot create paging iterator for non-paged response!'); } var data = response.body; if (Number.isSafeInteger(data.offset)) { this.nextField = PAGING_MODES.OFFSET; this.nextValue = data.offset; } else if (typeof data.next_marker === 'undefined') { // Default to a finished marker collection when there's no field present, // since some endpoints indicate completed paging this way this.nextField = PAGING_MODES.MARKER; this.nextValue = null; } else { this.nextField = PAGING_MODES.MARKER; this.nextValue = data.next_marker; } this.limit = data.limit || data.entries.length; this.done = false; var href = response.request.href.split('?')[0]; this.options = { headers: response.request.headers, qs: querystring.parse(response.request.uri.query) }; if (response.request.body) { if (Object.prototype.toString.call(response.request.body) === '[object Object]') { this.options.body = response.request.body; } else { this.options.body = JSON.parse(response.request.body); } } // querystring.parse() makes everything a string, ensure numeric params are the correct type if (this.options.qs.limit) { this.options.qs.limit = parseInt(this.options.qs.limit, 10); } if (this.options.qs.offset) { this.options.qs.offset = parseInt(this.options.qs.offset, 10); } delete this.options.headers.Authorization; if (response.request.method === 'GET') { this.fetch = client.get.bind(client, href); } if (response.request.method === 'POST') { this.fetch = client.post.bind(client, href); } this.buffer = response.body.entries; this.queue = new PromiseQueue(1, Infinity); this._updatePaging(response); } /** * Update the paging parameters for the iterator * @private * @param {Object} response - The latest API response * @returns {void} */ _updatePaging(response) { var data = response.body; if (this.nextField === PAGING_MODES.OFFSET) { this.nextValue += this.limit; if (Number.isSafeInteger(data.total_count)) { this.done = data.offset + this.limit >= data.total_count; } else { this.done = data.entries.length === 0; } } else if (this.nextField === PAGING_MODES.MARKER) { if (data.next_marker) { this.nextValue = data.next_marker; } else { this.nextValue = null; this.done = true; } } if (response.request.method === 'GET') { this.options.qs[this.nextField] = this.nextValue; } else if (response.request.method === 'POST') { this.options.body[this.nextField] = this.nextValue; let bodyString = JSON.stringify(this.options.body); this.options.headers['content-length'] = bodyString.length; } } /** * Fetch the next page of results * @returns {Promise} Promise resolving to iterator state */ _getData() { return this.fetch(this.options) .then(response => { if (response.statusCode !== 200) { throw errors.buildUnexpectedResponseError(response); } this._updatePaging(response); this.buffer = this.buffer.concat(response.body.entries); if (this.buffer.length === 0) { if (this.done) { return { value: undefined, done: true }; } // If we didn't get any data in this page, but the paging // parameters indicate that there is more data, attempt // to fetch more. This occurs in multiple places in the API return this._getData(); } return { value: this.buffer.shift(), done: false }; }); } /** * Fetch the next page of the collection * @returns {Promise} Promise resolving to iterator state */ next() { if (this.buffer.length > 0) { return Promise.resolve({ value: this.buffer.shift(), done: false }); } if (this.done) { return Promise.resolve({ value: undefined, done: true }); } return this.queue.add(this._getData.bind(this)); } /** * Fetch the next marker * @returns {string|int} String that is the next marker or int that is the next offset */ getNextMarker() { return this.nextValue; } }
JavaScript
class MetricFilter extends core_1.Resource { /** * @stability stable */ constructor(scope, id, props) { var _b; super(scope, id); this.metricName = props.metricName; this.metricNamespace = props.metricNamespace; // It looks odd to map this object to a singleton list, but that's how // we're supposed to do it according to the docs. // // > Currently, you can specify only one metric transformation for // > each metric filter. If you want to specify multiple metric // > transformations, you must specify multiple metric filters. // // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-metricfilter.html new logs_generated_1.CfnMetricFilter(this, 'Resource', { logGroupName: props.logGroup.logGroupName, filterPattern: props.filterPattern.logPatternString, metricTransformations: [{ metricNamespace: props.metricNamespace, metricName: props.metricName, metricValue: (_b = props.metricValue) !== null && _b !== void 0 ? _b : '1', defaultValue: props.defaultValue, }], }); } /** * Return the given named metric for this Metric Filter. * * @default avg over 5 minutes * @stability stable */ metric(props) { return new aws_cloudwatch_1.Metric({ metricName: this.metricName, namespace: this.metricNamespace, statistic: 'avg', ...props, }).attachTo(this); } }
JavaScript
class GridProElement extends InlineEditingMixin(GridElement) { static get is() { return 'vaadin-grid-pro'; } static get version() { return '2.0.3'; } }
JavaScript
class V1alpha1EKSCredentialsSpec { /** * Constructs a new <code>V1alpha1EKSCredentialsSpec</code>. * @alias module:model/V1alpha1EKSCredentialsSpec * @param accountID {String} */ constructor(accountID) { V1alpha1EKSCredentialsSpec.initialize(this, accountID); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, accountID) { obj['accountID'] = accountID; } /** * Constructs a <code>V1alpha1EKSCredentialsSpec</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/V1alpha1EKSCredentialsSpec} obj Optional instance to populate. * @return {module:model/V1alpha1EKSCredentialsSpec} The populated <code>V1alpha1EKSCredentialsSpec</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new V1alpha1EKSCredentialsSpec(); if (data.hasOwnProperty('accessKeyID')) { obj['accessKeyID'] = ApiClient.convertToType(data['accessKeyID'], 'String'); } if (data.hasOwnProperty('accountID')) { obj['accountID'] = ApiClient.convertToType(data['accountID'], 'String'); } if (data.hasOwnProperty('credentialsRef')) { obj['credentialsRef'] = V1SecretReference.constructFromObject(data['credentialsRef']); } if (data.hasOwnProperty('secretAccessKey')) { obj['secretAccessKey'] = ApiClient.convertToType(data['secretAccessKey'], 'String'); } } return obj; } /** * @return {String} */ getAccessKeyID() { return this.accessKeyID; } /** * @param {String} accessKeyID */ setAccessKeyID(accessKeyID) { this['accessKeyID'] = accessKeyID; } /** * @return {String} */ getAccountID() { return this.accountID; } /** * @param {String} accountID */ setAccountID(accountID) { this['accountID'] = accountID; } /** * @return {module:model/V1SecretReference} */ getCredentialsRef() { return this.credentialsRef; } /** * @param {module:model/V1SecretReference} credentialsRef */ setCredentialsRef(credentialsRef) { this['credentialsRef'] = credentialsRef; } /** * @return {String} */ getSecretAccessKey() { return this.secretAccessKey; } /** * @param {String} secretAccessKey */ setSecretAccessKey(secretAccessKey) { this['secretAccessKey'] = secretAccessKey; } }
JavaScript
class InputDataService { /** * Create an array of ProjectData * @param {PathFromSystemRoot[]} projectPaths * @param {Partial<GatherFilesConfig>} gatherFilesConfig * @returns {ProjectInputData[]} */ static createDataObject(projectPaths, gatherFilesConfig = {}) { /** @type {ProjectInputData[]} */ const inputData = projectPaths.map(projectPath => ({ project: /** @type {Project} */ ({ name: pathLib.basename(projectPath), path: projectPath, }), entries: this.gatherFilesFromDir(projectPath, { ...this.defaultGatherFilesConfig, ...gatherFilesConfig, }), })); // @ts-ignore return this._addMetaToProjectsData(inputData); } /** * From 'main/file.js' or '/main/file.js' to './main/file.js' * @param {string} mainEntry * @returns {PathRelativeFromProjectRoot} */ static __normalizeMainEntry(mainEntry) { if (mainEntry.startsWith('/')) { return /** @type {PathRelativeFromProjectRoot} */ (`.${mainEntry}`); } if (!mainEntry.startsWith('.')) { return `./${mainEntry}`; } return /** @type {PathRelativeFromProjectRoot} */ (mainEntry); } /** * @param {PathFromSystemRoot} projectPath * @returns {Project} */ static getProjectMeta(projectPath) { /** @type {Partial<Project>} */ const project = { path: projectPath }; // Add project meta info try { const file = pathLib.resolve(projectPath, 'package.json'); const pkgJson = JSON.parse(fs.readFileSync(file, 'utf8')); // eslint-disable-next-line no-param-reassign project.mainEntry = this.__normalizeMainEntry(pkgJson.main || './index.js'); // eslint-disable-next-line no-param-reassign project.name = pkgJson.name; // TODO: also add meta info whether we are in a monorepo or not. // We do this by checking whether there is a lerna.json on root level. // eslint-disable-next-line no-empty project.version = pkgJson.version; } catch (e) { LogService.warn(/** @type {string} */ (e)); } project.commitHash = this._getCommitHash(projectPath); return /** @type {Project} */ (project); } /** * @param {PathFromSystemRoot} projectPath * @returns {string|'[not-a-git-root]'|undefined} */ static _getCommitHash(projectPath) { let commitHash; let isGitRepo; try { isGitRepo = fs.lstatSync(pathLib.resolve(projectPath, '.git')).isDirectory(); // eslint-disable-next-line no-empty } catch (_) {} if (isGitRepo) { try { // eslint-disable-next-line camelcase const hash = child_process .execSync('git rev-parse HEAD', { cwd: projectPath, }) .toString('utf-8') .slice(0, -1); // eslint-disable-next-line no-param-reassign commitHash = hash; } catch (e) { LogService.warn(/** @type {string} */ (e)); } } else { commitHash = '[not-a-git-root]'; } return commitHash; } /** * Adds context with code (c.q. file contents), project name and project 'main' entry * @param {ProjectInputData[]} inputData * @returns {ProjectInputDataWithMeta[]} */ static _addMetaToProjectsData(inputData) { return /** @type {* & ProjectInputDataWithMeta[]} */ ( inputData.map(projectObj => { // Add context obj with 'code' to files /** @type {ProjectInputDataWithMeta['entries'][]} */ const newEntries = []; projectObj.entries.forEach(entry => { const code = fs.readFileSync(entry, 'utf8'); const file = getFilePathRelativeFromRoot( toPosixPath(entry), toPosixPath(projectObj.project.path), ); if (pathLib.extname(file) === '.html') { const extractedScripts = AstService.getScriptsFromHtml(code); // eslint-disable-next-line no-shadow extractedScripts.forEach((code, i) => { newEntries.push({ file: /** @type {PathRelativeFromProjectRoot} */ (`${file}#${i}`), context: { code }, }); }); } else { newEntries.push({ file, context: { code } }); } }); const project = this.getProjectMeta(toPosixPath(projectObj.project.path)); return { project, entries: newEntries }; }) ); } /** * Gets all project directories/paths from './submodules' * @type {PathFromSystemRoot[]} a list of strings representing all entry paths for projects we want to query */ static get targetProjectPaths() { if (this.__targetProjectPaths) { return this.__targetProjectPaths; } const submoduleDir = pathLib.resolve( __dirname, '../../../providence-input-data/search-targets', ); let dirs; try { dirs = fs.readdirSync(submoduleDir); } catch (_) { return []; } return dirs .map(dir => /** @type {PathFromSystemRoot} */ (pathLib.join(submoduleDir, dir))) .filter(dirPath => fs.lstatSync(dirPath).isDirectory()); } /** * @type {PathFromSystemRoot[]} a list of strings representing all entry paths for projects we want to query */ static get referenceProjectPaths() { if (this.__referenceProjectPaths) { return this.__referenceProjectPaths; } let dirs; try { const referencesDir = pathLib.resolve(__dirname, '../../../providence-input-data/references'); dirs = fs.readdirSync(referencesDir); dirs = dirs .map(dir => pathLib.join(referencesDir, dir)) .filter(dirPath => fs.lstatSync(dirPath).isDirectory()); // eslint-disable-next-line no-empty } catch (_) {} return /** @type {PathFromSystemRoot[]} */ (dirs); } static set referenceProjectPaths(v) { this.__referenceProjectPaths = ensureArray(v); } static set targetProjectPaths(v) { this.__targetProjectPaths = ensureArray(v); } /** * @type {GatherFilesConfig} */ static get defaultGatherFilesConfig() { return { extensions: ['.js'], allowlist: ['!node_modules/**', '!bower_components/**', '!**/*.conf.js', '!**/*.config.js'], depth: Infinity, }; } /** * @param {PathFromSystemRoot} startPath * @param {GatherFilesConfig} cfg * @param {boolean} withoutDepth */ static getGlobPattern(startPath, cfg, withoutDepth = false) { // if startPath ends with '/', remove let globPattern = startPath.replace(/\/$/, ''); if (process.platform === 'win32') { globPattern = globPattern.replace(/^.:/, '').replace(/\\/g, '/'); } if (!withoutDepth) { if (typeof cfg.depth === 'number' && cfg.depth !== Infinity) { globPattern += `/*`.repeat(cfg.depth + 1); } else { globPattern += `/**/*`; } } return { globPattern }; } /** * Gets an array of files for given extension * @param {PathFromSystemRoot} startPath - local filesystem path * @param {Partial<GatherFilesConfig>} customConfig - configuration object * @returns {PathFromSystemRoot[]} result list of file paths */ static gatherFilesFromDir(startPath, customConfig = {}) { const cfg = { ...this.defaultGatherFilesConfig, ...customConfig, }; if (!customConfig.omitDefaultAllowlist) { cfg.allowlist = [ ...this.defaultGatherFilesConfig.allowlist, ...(customConfig.allowlist || []), ]; } const allowlistModes = ['npm', 'git', 'all']; if (customConfig.allowlistMode && !allowlistModes.includes(customConfig.allowlistMode)) { throw new Error( `[gatherFilesConfig] Please provide a valid allowListMode like "${allowlistModes.join( '|', )}". Found: "${customConfig.allowlistMode}"`, ); } /** @type {string[]} */ let gitIgnorePaths = []; /** @type {string[]} */ let npmPackagePaths = []; const hasGitIgnore = getGitignoreFile(startPath); const allowlistMode = cfg.allowlistMode || (hasGitIgnore ? 'git' : 'npm'); if (allowlistMode === 'git') { gitIgnorePaths = getGitIgnorePaths(startPath); } else if (allowlistMode === 'npm') { npmPackagePaths = getNpmPackagePaths(startPath); } const removeFilter = gitIgnorePaths; const keepFilter = npmPackagePaths; cfg.allowlist.forEach(allowEntry => { const { negated, pattern } = isNegatedGlob(allowEntry); if (negated) { removeFilter.push(pattern); } else { keepFilter.push(allowEntry); } }); let { globPattern } = this.getGlobPattern(startPath, cfg); globPattern += `.{${cfg.extensions.map(e => e.slice(1)).join(',')},}`; const globRes = multiGlobSync(globPattern); let filteredGlobRes; if (removeFilter.length || keepFilter.length) { filteredGlobRes = globRes.filter(filePath => { const localFilePath = toPosixPath(filePath).replace(`${toPosixPath(startPath)}/`, ''); // @ts-expect-error let shouldRemove = removeFilter.length && anymatch(removeFilter, localFilePath); // @ts-expect-error let shouldKeep = keepFilter.length && anymatch(keepFilter, localFilePath); if (shouldRemove && shouldKeep) { // Contradicting configs: the one defined by end user takes highest precedence // If the match came from allowListMode, it loses. // @ts-expect-error if (allowlistMode === 'git' && anymatch(gitIgnorePaths, localFilePath)) { // shouldRemove was caused by .gitignore, shouldKeep by custom allowlist shouldRemove = false; // @ts-expect-error } else if (allowlistMode === 'npm' && anymatch(npmPackagePaths, localFilePath)) { // shouldKeep was caused by npm "files", shouldRemove by custom allowlist shouldKeep = false; } } if (removeFilter.length && shouldRemove) { return false; } if (!keepFilter.length) { return true; } return shouldKeep; }); } if (!filteredGlobRes || !filteredGlobRes.length) { LogService.warn(`No files found for path '${startPath}'`); return []; } // reappend startPath // const res = filteredGlobRes.map(f => pathLib.resolve(startPath, f)); return /** @type {PathFromSystemRoot[]} */ (filteredGlobRes.map(toPosixPath)); } // TODO: use modern web config helper /** * Allows the user to provide a providence.conf.js file in its repository root */ static getExternalConfig() { throw new Error( `[InputDataService.getExternalConfig]: Until fully ESM: use 'src/program/utils/get-providence=conf.mjs instead`, ); } /** * Gives back all monorepo package paths * @param {PathFromSystemRoot} rootPath * @returns {ProjectNameAndPath[]|undefined} */ static getMonoRepoPackages(rootPath) { // [1] Look for npm/yarn workspaces const pkgJson = getPackageJson(rootPath); if (pkgJson && pkgJson.workspaces) { return getPathsFromGlobList(pkgJson.workspaces, rootPath); } // [2] Look for lerna packages const lernaJson = getLernaJson(rootPath); if (lernaJson && lernaJson.packages) { return getPathsFromGlobList(lernaJson.packages, rootPath); } // TODO: support forward compatibility for npm? return undefined; } }
JavaScript
class Snapshotter { /** * @param {SnapshotterOptions} [options] All `Snapshotter` configuration options. */ constructor(options = {}) { ow(options, ow.object.exactShape({ eventLoopSnapshotIntervalSecs: ow.optional.number, cpuSnapshotIntervalSecs: ow.optional.number, memorySnapshotIntervalSecs: ow.optional.number, clientSnapshotIntervalSecs: ow.optional.number, snapshotHistorySecs: ow.optional.number, maxBlockedMillis: ow.optional.number, maxUsedMemoryRatio: ow.optional.number, maxUsedCpuRatio: ow.optional.number, maxClientErrors: ow.optional.number, log: ow.optional.object, })); const { eventLoopSnapshotIntervalSecs = 0.5, cpuSnapshotIntervalSecs = 1, memorySnapshotIntervalSecs = 1, clientSnapshotIntervalSecs = 1, snapshotHistorySecs = 30, maxBlockedMillis = 50, maxUsedMemoryRatio = 0.7, maxUsedCpuRatio = 0.95, maxClientErrors = 3, log = defaultLog, } = options; /** @type {defaultLog.Log} */ this.log = log.child({ prefix: 'Snapshotter' }); this.eventLoopSnapshotIntervalMillis = eventLoopSnapshotIntervalSecs * 1000; this.memorySnapshotIntervalMillis = memorySnapshotIntervalSecs * 1000; this.clientSnapshotIntervalMillis = clientSnapshotIntervalSecs * 1000; this.cpuSnapshotIntervalMillis = cpuSnapshotIntervalSecs * 1000; this.snapshotHistoryMillis = snapshotHistorySecs * 1000; this.maxBlockedMillis = maxBlockedMillis; this.maxUsedMemoryRatio = maxUsedMemoryRatio; this.maxUsedCpuRatio = maxUsedCpuRatio; this.maxClientErrors = maxClientErrors; this.maxMemoryBytes = (parseInt(process.env[ENV_VARS.MEMORY_MBYTES], 10) * 1024 * 1024) || null; this.cpuSnapshots = []; this.eventLoopSnapshots = []; this.memorySnapshots = []; this.clientSnapshots = []; this.eventLoopInterval = null; this.memoryInterval = null; this.clientInterval = null; this.cpuInterval = null; this.lastLoggedCriticalMemoryOverloadAt = null; // We need to pre-bind those functions to be able to successfully remove listeners. this._snapshotCpuOnPlatform = this._snapshotCpuOnPlatform.bind(this); this._snapshotMemoryOnPlatform = this._snapshotMemoryOnPlatform.bind(this); } /** * Starts capturing snapshots at configured intervals. * @return {Promise<void>} */ async start() { await this._ensureCorrectMaxMemory(); // Start snapshotting. this.eventLoopInterval = betterSetInterval(this._snapshotEventLoop.bind(this), this.eventLoopSnapshotIntervalMillis); this.clientInterval = betterSetInterval(this._snapshotClient.bind(this), this.clientSnapshotIntervalMillis); if (isAtHome()) { events.on(ACTOR_EVENT_NAMES.SYSTEM_INFO, this._snapshotCpuOnPlatform); events.on(ACTOR_EVENT_NAMES.SYSTEM_INFO, this._snapshotMemoryOnPlatform); } else { this.cpuInterval = betterSetInterval(this._snapshotCpuOnLocal.bind(this), this.cpuSnapshotIntervalMillis); this.memoryInterval = betterSetInterval(this._snapshotMemoryOnLocal.bind(this), this.memorySnapshotIntervalMillis); } } /** * Stops all resource capturing. * @return {Promise<void>} */ async stop() { betterClearInterval(this.eventLoopInterval); betterClearInterval(this.memoryInterval); betterClearInterval(this.cpuInterval); betterClearInterval(this.clientInterval); events.removeListener(ACTOR_EVENT_NAMES.SYSTEM_INFO, this._snapshotCpuOnPlatform); events.removeListener(ACTOR_EVENT_NAMES.SYSTEM_INFO, this._snapshotMemoryOnPlatform); // Allow microtask queue to unwind before stop returns. await new Promise((resolve) => setImmediate(resolve)); } /** * Returns a sample of latest memory snapshots, with the size of the sample defined * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history. * @param {number} [sampleDurationMillis] * @return {Array<*>} */ getMemorySample(sampleDurationMillis) { return this._getSample(this.memorySnapshots, sampleDurationMillis); } /** * Returns a sample of latest event loop snapshots, with the size of the sample defined * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history. * @param {number} [sampleDurationMillis] * @return {Array<*>} */ getEventLoopSample(sampleDurationMillis) { return this._getSample(this.eventLoopSnapshots, sampleDurationMillis); } /** * Returns a sample of latest CPU snapshots, with the size of the sample defined * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history. * @param {number} [sampleDurationMillis] * @return {Array<*>} */ getCpuSample(sampleDurationMillis) { return this._getSample(this.cpuSnapshots, sampleDurationMillis); } /** * Returns a sample of latest Client snapshots, with the size of the sample defined * by the sampleDurationMillis parameter. If omitted, it returns a full snapshot history. * @param {number} sampleDurationMillis * @return {Array<*>} */ getClientSample(sampleDurationMillis) { return this._getSample(this.clientSnapshots, sampleDurationMillis); } /** * Finds the latest snapshots by sampleDurationMillis in the provided array. * @param {Array<*>} snapshots * @param {number} [sampleDurationMillis] * @return {Array<*>} * @ignore * @protected * @internal */ _getSample(snapshots, sampleDurationMillis) { // eslint-disable-line class-methods-use-this if (!sampleDurationMillis) return snapshots; const sample = []; let idx = snapshots.length; if (!idx) return sample; const latestTime = snapshots[idx - 1].createdAt; while (idx--) { const snapshot = snapshots[idx]; if (latestTime - snapshot.createdAt <= sampleDurationMillis) sample.unshift(snapshot); else break; } return sample; } /** * Creates a snapshot of current memory usage * using the Apify platform `systemInfo` event. * @param {*} systemInfo * @ignore * @protected * @internal */ _snapshotMemoryOnPlatform(systemInfo) { const now = new Date(); this._pruneSnapshots(this.memorySnapshots, now); const { memCurrentBytes } = systemInfo; const snapshot = { createdAt: now, isOverloaded: memCurrentBytes / this.maxMemoryBytes > this.maxUsedMemoryRatio, usedBytes: memCurrentBytes, }; this.memorySnapshots.push(snapshot); this._memoryOverloadWarning(systemInfo); } /** * Creates a snapshot of current memory usage * using the Apify platform `systemInfo` event. * @param {Function} intervalCallback * @return {Promise<void>} * @ignore * @protected * @internal */ async _snapshotMemoryOnLocal(intervalCallback) { try { const now = new Date(); const memInfo = await getMemoryInfo(); const { mainProcessBytes, childProcessesBytes } = memInfo; this._pruneSnapshots(this.memorySnapshots, now); const usedBytes = mainProcessBytes + childProcessesBytes; const snapshot = { createdAt: now, isOverloaded: usedBytes / this.maxMemoryBytes > this.maxUsedMemoryRatio, usedBytes, }; this.memorySnapshots.push(snapshot); } catch (err) { this.log.exception(err, 'Memory snapshot failed.'); } finally { intervalCallback(); } } /** * Checks for critical memory overload and logs it to the console. * @param {*} systemInfo * @ignore * @protected * @internal */ _memoryOverloadWarning({ memCurrentBytes }) { const now = new Date(); if (this.lastLoggedCriticalMemoryOverloadAt && now.getTime() < this.lastLoggedCriticalMemoryOverloadAt.getTime() + CRITICAL_OVERLOAD_RATE_LIMIT_MILLIS) return; const maxDesiredMemoryBytes = this.maxUsedMemoryRatio * this.maxMemoryBytes; const reserveMemory = this.maxMemoryBytes * (1 - this.maxUsedMemoryRatio) * RESERVE_MEMORY_RATIO; const criticalOverloadBytes = maxDesiredMemoryBytes + reserveMemory; const isCriticalOverload = memCurrentBytes > criticalOverloadBytes; if (isCriticalOverload) { const usedPercentage = Math.round((memCurrentBytes / this.maxMemoryBytes) * 100); const toMb = (bytes) => Math.round(bytes / (1024 ** 2)); this.log.warning('Memory is critically overloaded. ' + `Using ${toMb(memCurrentBytes)} MB of ${toMb(this.maxMemoryBytes)} MB (${usedPercentage}%). Consider increasing the actor memory.`); this.lastLoggedCriticalMemoryOverloadAt = now; } } /** * Creates a snapshot of current event loop delay. * @param {Function} intervalCallback * @ignore * @protected * @internal */ _snapshotEventLoop(intervalCallback) { const now = new Date(); this._pruneSnapshots(this.eventLoopSnapshots, now); const snapshot = { createdAt: now, isOverloaded: false, exceededMillis: 0, }; const previousSnapshot = this.eventLoopSnapshots[this.eventLoopSnapshots.length - 1]; if (previousSnapshot) { const { createdAt } = previousSnapshot; const delta = now.getTime() - createdAt - this.eventLoopSnapshotIntervalMillis; if (delta > this.maxBlockedMillis) snapshot.isOverloaded = true; snapshot.exceededMillis = Math.max(delta - this.maxBlockedMillis, 0); } this.eventLoopSnapshots.push(snapshot); intervalCallback(); } /** * Creates a snapshot of current CPU usage * using the Apify platform `systemInfo` event. * @param {Object} systemInfo * @ignore * @protected * @internal */ _snapshotCpuOnPlatform(systemInfo) { const { cpuCurrentUsage, isCpuOverloaded } = systemInfo; const createdAt = (new Date(systemInfo.createdAt)); this._pruneSnapshots(this.cpuSnapshots, createdAt); this.cpuSnapshots.push({ createdAt, isOverloaded: isCpuOverloaded, usedRatio: Math.ceil(cpuCurrentUsage / 100), }); } /** * Creates a snapshot of current CPU usage * using OS provided metrics. * @param {Function} intervalCallback * @ignore * @protected * @internal */ _snapshotCpuOnLocal(intervalCallback) { const now = new Date(); this._pruneSnapshots(this.eventLoopSnapshots, now); const ticks = this._getCurrentCpuTicks(); const snapshot = { createdAt: now, isOverloaded: false, ticks, usedRatio: 0, }; const previousSnapshot = this.cpuSnapshots[this.cpuSnapshots.length - 1]; if (previousSnapshot) { const { ticks: prevTicks } = previousSnapshot; const idleTicksDelta = ticks.idle - prevTicks.idle; const totalTicksDelta = ticks.total - prevTicks.total; const usedCpuRatio = 1 - (idleTicksDelta / totalTicksDelta); if (usedCpuRatio > this.maxUsedCpuRatio) snapshot.isOverloaded = true; snapshot.usedRatio = Math.ceil(usedCpuRatio); } this.cpuSnapshots.push(snapshot); intervalCallback(); } /** * @ignore * @protected * @internal */ _getCurrentCpuTicks() { // eslint-disable-line class-methods-use-this const cpus = os.cpus(); return cpus.reduce((acc, cpu) => { const cpuTimes = Object.values(cpu.times); return { idle: acc.idle + cpu.times.idle, total: acc.total + cpuTimes.reduce((sum, num) => sum + num), }; }, { idle: 0, total: 0 }); } /** * Creates a snapshot of current API state by checking for * rate limit errors. Only errors produced by a 2nd retry * of the API call are considered for snapshotting since * earlier errors may just be caused by a random spike in * number of requests and do not necessarily signify API * overloading. * * @param intervalCallback * @ignore * @protected * @internal */ _snapshotClient(intervalCallback) { const now = new Date(); this._pruneSnapshots(this.clientSnapshots, now); const allErrorCounts = apifyClient.stats.rateLimitErrors; const currentErrCount = allErrorCounts[CLIENT_RATE_LIMIT_ERROR_RETRY_COUNT] || 0; // Handle empty snapshots array const snapshot = { createdAt: now, isOverloaded: false, rateLimitErrorCount: currentErrCount, }; const previousSnapshot = this.clientSnapshots[this.clientSnapshots.length - 1]; if (previousSnapshot) { const { rateLimitErrorCount } = previousSnapshot; const delta = currentErrCount - rateLimitErrorCount; if (delta > this.maxClientErrors) snapshot.isOverloaded = true; } this.clientSnapshots.push(snapshot); intervalCallback(); } /** * Removes snapshots that are older than the snapshotHistorySecs option * from the array (destructively - in place). * @param {Array<*>} snapshots * @param {Date} now * @ignore * @protected * @internal */ _pruneSnapshots(snapshots, now) { let oldCount = 0; for (let i = 0; i < snapshots.length; i++) { const { createdAt } = snapshots[i]; if (now.getTime() - createdAt > this.snapshotHistoryMillis) oldCount++; else break; } snapshots.splice(0, oldCount); } /** * Calculate max memory for platform or local usage. * @ignore * @protected * @internal */ async _ensureCorrectMaxMemory() { if (this.maxMemoryBytes) return; const { totalBytes } = await getMemoryInfo(); if (isAtHome()) { this.maxMemoryBytes = totalBytes; } else { this.maxMemoryBytes = Math.ceil(totalBytes / 4); // NOTE: Log as AutoscaledPool, so that users are not confused what "Snapshotter" is this.log.info(`Setting max memory of this run to ${Math.round(this.maxMemoryBytes / 1024 / 1024)} MB. Use the ${ENV_VARS.MEMORY_MBYTES} environment variable to override it.`); // eslint-disable-line max-len } } }
JavaScript
class WfsLayer extends React.Component { constructor(props) { super(props); const { icon, color, style: layerStyle } = props; this.layer = null; this.styles = createStyle(icon, color, layerStyle); } static propTypes = { map: PropTypes.instanceOf(OpenLayersMap), index: PropTypes.number, url: PropTypes.string.isRequired, typename: PropTypes.string.isRequired, version: PropTypes.string, outputFormat: PropTypes.string, srsName: PropTypes.string, icon: PropTypes.string, color: PropTypes.string, extra: PropTypes.object, filters: PropTypes.arrayOf(PropTypes.object), style: PropTypes.object, maxZoom: PropTypes.number, } static defaultProps = { version: '1.1.0', outputFormat: 'application/json', srsName: 'EPSG:3857', maxZoom: 15, } buildRequest(extent) { const { filters = [], outputFormat, url, srsName, typename, version } = this.props; const typenameParameter = (version.startsWith('2') ? 'typeNames' : 'typeName'); return URI(url) .query({ service: 'WFS', version, request: 'GetFeature', [typenameParameter]: typename, outputFormat, srsName, bbox: extent.join(',') + ',' + srsName, ...filters.reduce((result, filter) => { const name = `filter-${filter.attribute}-${filter.type}`; const value = filter.value; result[name] = value; return result; }, {}), }) .toString(); } buildStyleFunction() { return ((feature) => (this.styles[feature.getGeometry().getType()] || this.styles['Point'])); } componentDidMount() { const { color, icon, index, extra, map, maxZoom } = this.props; if (map) { const source = new VectorSource({ format: new GeoJSON(), url: this.buildRequest.bind(this), strategy: bboxLoadingStrategy, }); source.on('addfeature', (e) => { e.feature.set(FEATURE_COLOR_PROPERTY, color || null, true); e.feature.set(FEATURE_ICON_PROPERTY, icon || null, true); if (extra) { Object.keys(extra).map((key) => { e.feature.set(key, extra[key] || null, true); }); } }, this); const style = this.buildStyleFunction(); this.layer = new VectorLayer({ source, style, maxResolution: map.getView().getResolutionForZoom(maxZoom), }); map.getLayers().insertAt(index, this.layer); } } componentWillUnmount() { if ((this.props.map) && (this.layer)) { this.props.map.removeLayer(this.layer); this.layer = null; } } render() { return null; } }
JavaScript
class Node { constructor(value, left = null, right = null) { this.value = value; this.left = left; this.right = right; } }
JavaScript
class BinarySearchTree extends BinaryTree { add(value) { // accepts a value, and adds a new node with that value in the correct location in the binary search tree let nodeToAdd = new Node(value); let currentNode = this.root; if (nodeToAdd.value === currentNode.value) { throw new RangeError('Values must be unique!'); } if (!currentNode) { currentNode = nodeToAdd; } else { _add(nodeToAdd, currentNode); } function _add(nodeToAdd, currentNode) { while (currentNode.value !== nodeToAdd.value) { if (nodeToAdd.value < currentNode.value) { if (!currentNode.left) { currentNode.left = nodeToAdd; return; } else { currentNode = currentNode.left; _add(nodeToAdd, currentNode); } } else { if (!currentNode.right) { currentNode.right = nodeToAdd; return; } else { currentNode = currentNode.right; _add(nodeToAdd, currentNode); } } } } } contains(value) { // accept a value, and returns a boolean indicating whether or not the value is in the tree at least once let currentNode = this.root; while (currentNode) { if (currentNode.value === value) { return true; } if (currentNode.value > value) { currentNode = currentNode.left; } else { currentNode = currentNode.right; } } return false; } }
JavaScript
class VaultSecretGroup { /** * Create a VaultSecretGroup. * @member {object} [sourceVault] The relative URL of the Key Vault * containing all of the certificates in VaultCertificates. * @member {string} [sourceVault.id] Resource Id * @member {array} [vaultCertificates] The list of key vault references in * SourceVault which contain certificates. */ constructor() { } /** * Defines the metadata of VaultSecretGroup * * @returns {object} metadata of VaultSecretGroup * */ mapper() { return { required: false, serializedName: 'VaultSecretGroup', type: { name: 'Composite', className: 'VaultSecretGroup', modelProperties: { sourceVault: { required: false, serializedName: 'sourceVault', type: { name: 'Composite', className: 'SubResource' } }, vaultCertificates: { required: false, serializedName: 'vaultCertificates', type: { name: 'Sequence', element: { required: false, serializedName: 'VaultCertificateElementType', type: { name: 'Composite', className: 'VaultCertificate' } } } } } } }; } }
JavaScript
class Speler { constructor(n) { this.naam = n; this.resterendeBeurten = null; } kiesLetter() { // kies een letter if (key >= 'a' && key <= 'z') { spel.controleerInvoer(); } } }
JavaScript
class Galgje { constructor(s,b) { this.speler = s; this.maximaalAantalBeurten = 10; this.speler.resterendeBeurten = this.maximaalAantalBeurten; this.beeldjes = b; this.woord = 'angstschreeuw'; this.letters = []; this.geraden = []; this.pogingen = [0]; this.maakRijLetters(); } maakRijLetters() { for (var l = 0;l < this.woord.length;l++) { this.letters.push(this.woord.substr(l,1)); this.geraden.push(false); } } controleerInvoer() { // mag deze invoer? if (this.speler.resterendeBeurten > 0 && !this.woordIsGeraden()) { this.verwerkInvoer(); this.teken(); } } verwerkInvoer() { // verwerk de invoer this.pogingen.push(key); var letterZitInWoord = false; for (var l = 0;l < this.letters.length;l++) { if (this.letters[l] == key) { letterZitInWoord = true; this.geraden[l] = true; } } if (!letterZitInWoord) { this.speler.resterendeBeurten--; } } woordIsGeraden() { var geraden = true; for (var b = 0;b < this.geraden.length;b++) { if (!this.geraden[b]) { geraden = false; } } return geraden; } teken() { // teken de speltoestand push(); background('lightcyan'); noStroke(); textFont("Courier"); textSize(40); textAlign(CENTER,CENTER); var tekst=""; for (var l = 0;l < this.letters.length;l++) { if (this.geraden[l]) { tekst += this.letters[l]+" "; } else { tekst += "_ "; } } tekst=tekst.substr(0,tekst.length-1); text(tekst,12,0,canvas.width,70); image(this.beeldjes[this.maximaalAantalBeurten - this.speler.resterendeBeurten],(canvas.width-300) / 2,75,300,300); textSize(80); if (this.speler.resterendeBeurten == 0) { fill('red'); text("VERLOREN :(",0,0,canvas.width,300); } if (this.woordIsGeraden()) { fill('green'); text("Goed gedaan, "+this.speler.naam,0,100,canvas.width,300); } pop(); } }
JavaScript
class PathfinderSimple extends Pathfinder { /** * @inheritdoc */ get name() { return 'Pathfinder Simple'; } constructor() { super(); } /** * @inheritdoc */ getSkillMod(character, skillName) { if (skillName === 'Appraise') return CharSheetUtils.getSheetAttr(character, 'appraise'); if (skillName === 'Heal') return CharSheetUtils.getSheetAttr(character, 'heal'); if (skillName === 'Knowledge(Arcana)') return CharSheetUtils.getSheetAttr(character, 'knowledge_arcana'); if (skillName === 'Knowledge(Dungeoneering)') return CharSheetUtils.getSheetAttr(character, 'knowledge_dungeoneering'); if (skillName === 'Knowledge(Engineering)') return CharSheetUtils.getSheetAttr(character, 'knowledge_engineering'); if (skillName === 'Knowledge(Geography)') return CharSheetUtils.getSheetAttr(character, 'knowledge_geography'); if (skillName === 'Knowledge(History)') return CharSheetUtils.getSheetAttr(character, 'knowledge_history'); if (skillName === 'Knowledge(Local)') return CharSheetUtils.getSheetAttr(character, 'knowledge_local'); if (skillName === 'Knowledge(Nature)') return CharSheetUtils.getSheetAttr(character, 'knowledge_nature'); if (skillName === 'Knowledge(Nobility)') return CharSheetUtils.getSheetAttr(character, 'knowledge_nobility'); if (skillName === 'Knowledge(Planes)') return CharSheetUtils.getSheetAttr(character, 'knowledge_planes'); if (skillName === 'Knowledge(Religion)') return CharSheetUtils.getSheetAttr(character, 'knowledge_religion'); if (skillName === 'Linguistics') return CharSheetUtils.getSheetAttr(character, 'linguistics'); if (skillName === 'Perception') return CharSheetUtils.getSheetAttr(character, 'perception'); if (skillName === 'Sense Motive') return CharSheetUtils.getSheetAttr(character, 'sense_motive'); if (skillName === 'Spellcraft') return CharSheetUtils.getSheetAttr(character, 'spellcraft'); if (skillName === 'Survival') return CharSheetUtils.getSheetAttr(character, 'survival'); } }
JavaScript
class MerossPlatform { constructor (log, config, api) { // Don't load the plugin if these aren't accessible for any reason if (!log || !api) { return } // Begin plugin initialisation try { this.api = api this.consts = require('./utils/constants') this.funcs = require('./utils/functions') this.log = log this.cloudClient = false this.deviceConf = {} this.devicesInHB = new Map() this.hideChannels = [] this.hideMasters = [] this.ignoredDevices = [] this.localUUIDs = [] // Retrieve the user's chosen language file this.lang = require('./utils/lang-en') // Make sure user is running Homebridge v1.3 or above if (!api.versionGreaterOrEqual || !api.versionGreaterOrEqual('1.3.0')) { throw new Error(this.lang.hbVersionFail) } // Check the user has configured the plugin if (!config) { throw new Error(this.lang.pluginNotConf) } // Log some environment info for debugging this.log( '%s v%s | Node %s | HB v%s | HAPNodeJS v%s%s...', this.lang.initialising, plugin.version, process.version, api.serverVersion, api.hap.HAPLibraryVersion(), config.plugin_map ? ' | HOOBS v3' : require('os') .hostname() .includes('hoobs') ? ' | HOOBS v4' : '' ) // Apply the user's configuration this.config = this.consts.defaultConfig this.applyUserConfig(config) // Set up the Homebridge events this.api.on('didFinishLaunching', () => this.pluginSetup()) this.api.on('shutdown', () => this.pluginShutdown()) } catch (err) { // Catch any errors during initialisation const eText = this.funcs.parseError(err, [this.lang.hbVersionFail, this.lang.pluginNotConf]) log.warn('***** %s. *****', this.lang.disabling) log.warn('***** %s. *****', eText) } } applyUserConfig (config) { // These shorthand functions save line space during config parsing const logDefault = (k, def) => { this.log.warn('%s [%s] %s %s.', this.lang.cfgItem, k, this.lang.cfgDef, def) } const logDuplicate = k => { this.log.warn('%s [%s] %s.', this.lang.cfgItem, k, this.lang.cfgDup) } const logIgnore = k => { this.log.warn('%s [%s] %s.', this.lang.cfgItem, k, this.lang.cfgIgn) } const logIgnoreItem = k => { this.log.warn('%s [%s] %s.', this.lang.cfgItem, k, this.lang.cfgIgnItem) } const logIncrease = (k, min) => { this.log.warn('%s [%s] %s %s.', this.lang.cfgItem, k, this.lang.cfgLow, min) } const logQuotes = k => { this.log.warn('%s [%s] %s.', this.lang.cfgItem, k, this.lang.cfgQts) } const logRemove = k => { this.log.warn('%s [%s] %s.', this.lang.cfgItem, k, this.lang.cfgRmv) } // Begin applying the user's config for (const [key, val] of Object.entries(config)) { switch (key) { case 'cloudRefreshRate': case 'refreshRate': { if (typeof val === 'string') { logQuotes(key) } const intVal = parseInt(val) if (isNaN(intVal)) { logDefault(key, this.consts.defaultValues[key]) } else if (intVal !== 0 && intVal < this.consts.minValues[key]) { logIncrease(key, this.consts.minValues[key]) } else if (intVal === 0 || intVal > 600) { this.config[key] = 600 } else { this.config[key] = intVal } break } case 'connection': { const inSet = this.consts.allowed[key].includes(val) if (typeof val !== 'string' || !inSet) { logIgnore(key) } else { this.config[key] = val === 'default' ? this.consts.defaultValues[key] : val } break } case 'debug': case 'debugFakegato': case 'disableDeviceLogging': case 'disablePlugin': case 'ignoreHKNative': if (typeof val === 'string') { logQuotes(key) } this.config[key] = val === 'false' ? false : !!val break case 'diffuserDevices': case 'garageDevices': case 'humidifierDevices': case 'lightDevices': case 'multiDevices': case 'purifierDevices': case 'rollerDevices': case 'sensorDevices': case 'singleDevices': if (Array.isArray(val) && val.length > 0) { val.forEach(x => { if ( !x.serialNumber || !x.name || (((config.connection === 'local' && !x.connection) || x.connection === 'local') && (!x.deviceUrl || !x.model)) ) { logIgnoreItem(key) return } const id = x.serialNumber.toLowerCase().replace(/[^a-z0-9]+/g, '') if (Object.keys(this.deviceConf).includes(id)) { logDuplicate(key + '.' + id) return } const entries = Object.entries(x) if (entries.length === 1) { logRemove(key + '.' + id) return } this.deviceConf[id] = {} for (const [k, v] of entries) { if (!this.consts.allowed[key].includes(k)) { logRemove(key + '.' + id + '.' + k) continue } switch (k) { case 'adaptiveLightingShift': case 'brightnessStep': case 'garageDoorOpeningTime': case 'inUsePowerThreshold': case 'lowBattThreshold': { if (typeof v === 'string') { logQuotes(key + '.' + id + '.' + k) } const intVal = parseInt(v) if (isNaN(intVal)) { logDefault(key + '.' + id + '.' + k, this.consts.defaultValues[k]) this.deviceConf[id][k] = this.consts.defaultValues[k] } else if (intVal < this.consts.minValues[k]) { logIncrease(key + '.' + id + '.' + k, this.consts.minValues[k]) this.deviceConf[id][k] = this.consts.minValues[k] } else { this.deviceConf[id][k] = intVal } break } case 'connection': case 'overrideLogging': case 'showAs': { const inSet = this.consts.allowed[k].includes(v) if (typeof v !== 'string' || !inSet) { logIgnore(key + '.' + id + '.' + k) } else { this.deviceConf[id][k] = v === 'default' ? this.consts.defaultValues[k] : v } break } case 'deviceUrl': case 'firmwareRevision': case 'model': case 'name': case 'serialNumber': case 'temperatureSource': case 'userkey': if (typeof v !== 'string' || v === '') { logIgnore(key + '.' + id + '.' + k) } else { this.deviceConf[id][k] = v.trim() if (k === 'deviceUrl') { this.localUUIDs.push(id) } } break case 'hideChannels': { if (typeof v !== 'string' || v === '') { logIgnore(key + '.' + id + '.' + k) } else { const channels = v.split(',') channels.forEach(channel => { this.hideChannels.push(id + channel.replace(/[^0-9]+/g, '')) this.deviceConf[id][k] = v }) } break } case 'ignoreDevice': if (typeof v === 'string') { logQuotes(key + '.' + id + '.' + k) } if (!!v && v !== 'false') { this.ignoredDevices.push(id) } break case 'reversePolarity': if (typeof v === 'string') { logQuotes(key + '.' + id + '.' + k) } this.deviceConf[id][k] = v === 'false' ? false : !!v break } } }) } else { logIgnore(key) } break case 'name': case 'platform': case 'plugin_map': break case 'password': case 'username': if (typeof val !== 'string') { logIgnore(key) } else { this.config[key] = val } break case 'userkey': if (typeof val !== 'string') { logIgnore(key) } else { const userkey = val.toLowerCase().replace(/[^a-z0-9]+/g, '') if (userkey.length === 32) { this.config[key] = userkey } else { logIgnore(key) } } break default: logRemove(key) break } } } async pluginSetup () { // Plugin has finished initialising so now onto setup try { // Log that the plugin initialisation has been successful this.log('%s.', this.lang.initialised) // If the user has disabled the plugin then remove all accessories if (this.config.disablePlugin) { this.devicesInHB.forEach(accessory => this.removeAccessory(accessory)) throw new Error(this.lang.disabled) } // Require any libraries that the accessory instances use this.colourUtils = require('./utils/colour-utils') this.cusChar = new (require('./utils/custom-chars'))(this.api) this.eveChar = new (require('./utils/eve-chars'))(this.api) this.eveService = require('./fakegato/fakegato-history')(this.api) // Persist files are used to store device info that can be used by my other plugins try { this.storageData = storage.create({ dir: require('path').join(this.api.user.persistPath(), '/../bwp91_cache'), forgiveParseErrors: true }) await this.storageData.init() this.storageClientData = true } catch (err) { if (this.config.debug) { const eText = this.funcs.parseError(err) this.log.warn('%s %s.', this.lang.storageSetupErr, eText) } } // If the user has configured cloud username and password then get a device list let cloudDevices = [] try { if (!this.config.username || !this.config.password) { throw new Error(this.lang.missingCreds) } this.cloudClient = new (require('./connection/http'))(this) this.accountDetails = await this.cloudClient.login() cloudDevices = await this.cloudClient.getDevices() // Initialise the cloud configured devices into Homebridge cloudDevices.forEach(device => this.initialiseDevice(device)) } catch (err) { const eText = this.funcs.parseError(err, [this.lang.missingCreds]) this.log.warn('%s %s.', this.lang.disablingCloud, eText) this.cloudClient = false this.accountDetails = { key: this.config.userkey } } // Check if a user key has been configured if the credentials aren't present if (this.cloudClient || this.config.userkey) { // Initialise the local configured devices into Homebridge Object.values(this.deviceConf) .filter(el => el.deviceUrl) .forEach(async device => await this.initialiseDevice(device)) } else { // Cloud client disabled and no user key - plugin will be useless throw new Error(this.lang.noCredentials) } // Check for redundant accessories or those that have been ignored but exist this.devicesInHB.forEach(accessory => { switch (accessory.context.connection) { case 'cloud': case 'hybrid': if (!cloudDevices.some(el => el.uuid === accessory.context.serialNumber)) { this.removeAccessory(accessory) } break case 'local': if (!this.localUUIDs.includes(accessory.context.serialNumber)) { this.removeAccessory(accessory) } break default: // Should be a never case this.removeAccessory(accessory) break } }) // Log that the plugin setup has been successful with a welcome message const randIndex = Math.floor(Math.random() * this.lang.zWelcome.length) setTimeout(() => this.log('%s. %s', this.lang.complete, this.lang.zWelcome[randIndex]), 2000) } catch (err) { // Catch any errors during setup const eText = this.funcs.parseError(err, [this.lang.disabled, this.lang.noCredentials]) this.log.warn('***** %s. *****', this.lang.disabling) this.log.warn('***** %s. *****', eText) this.pluginShutdown() } } pluginShutdown () { // A function that is called when the plugin fails to load or Homebridge restarts try { // Close the mqtt connection for the accessories with an open connection if (this.cloudClient) { this.devicesInHB.forEach(accessory => { if (accessory.mqtt) { accessory.mqtt.disconnect() } if (accessory.refreshInterval) { clearInterval(accessory.refreshInterval) } if (accessory.powerInterval) { clearInterval(accessory.powerInterval) } }) this.cloudClient.logout() } } catch (err) { // No need to show errors at this point } } async initialiseDevice (device) { try { // Local devices don't have the uuid already set if (device.deviceUrl) { // Rename some properties to fit the format of a cloud device device.uuid = device.serialNumber device.deviceType = device.model.toUpperCase().replace(/[-]+/g, '') device.devName = device.name device.channels = [] // Retrieve how many channels this device has const channelCount = this.funcs.hasProperty( this.consts.models.switchMulti, device.deviceType ) ? this.consts.models.switchMulti[device.deviceType] : device.deviceType === 'MSG200' ? 3 : 1 // Create a list of channels to fit the format of a cloud device if (channelCount > 1) { for (let index = 0; index <= channelCount; index++) { device.channels.push({}) } } } // Get any user configured entry for this device const deviceConf = this.deviceConf[device.uuid] || {} // Generate a unique id for the accessory const hbUUID = this.api.hap.uuid.generate(device.uuid) device.firmware = deviceConf.firmwareRevision || device.fmwareVersion device.hbDeviceId = device.uuid device.model = device.deviceType.toUpperCase().replace(/[-]+/g, '') // Add context information for the plugin-ui and instance to use const context = { channel: 0, channelCount: device.channels.length, connection: deviceConf.deviceUrl ? 'local' : deviceConf.connection || this.config.connection, deviceUrl: deviceConf.deviceUrl, domain: device.domain, firmware: device.firmware, hidden: false, isOnline: false, model: device.model, options: deviceConf, serialNumber: device.uuid, userkey: deviceConf.userkey || this.accountDetails.key } // Set the logging level for this device context.enableLogging = !this.config.disableDeviceLogging context.enableDebugLogging = this.config.debug switch (deviceConf.overrideLogging) { case 'standard': context.enableLogging = true context.enableDebugLogging = false break case 'debug': context.enableLogging = true context.enableDebugLogging = true break case 'disable': context.enableLogging = false context.enableDebugLogging = false break } // Find the correct instance determined by the device model let accessory if (this.consts.models.switchSingle.includes(device.model)) { /**************** SWITCHES (SINGLE) ****************/ const instance = deviceConf.showAs || this.consts.defaultValues.showAs // Set up the accessory and instance accessory = this.devicesInHB.get(hbUUID) || this.addAccessory(device) accessory.context = { ...accessory.context, ...context } accessory.control = new (require('./device/' + instance + '-single'))(this, accessory) /***************/ } else if (this.funcs.hasProperty(this.consts.models.switchMulti, device.model)) { /*************** SWITCHES (MULTI) ***************/ const instance = deviceConf.showAs || this.consts.defaultValues.showAs // Loop through the channels for (const index in device.channels) { // Check the entry exists if (!this.funcs.hasProperty(device.channels, index)) { return } const subdeviceObj = { ...device } const extraContext = {} // Generate the Homebridge UUID from the device uuid and channel index const uuidSub = device.uuid + index subdeviceObj.hbDeviceId = uuidSub const hbUUIDSub = this.api.hap.uuid.generate(uuidSub) // Supply a device name for the channel accessories if (index > 0) { subdeviceObj.devName = device.channels[index].devName || device.devName + ' SW' + index } // Check if the user has chosen to hide any channels for this device let subAcc if (this.hideChannels.includes(device.uuid + index)) { // The user has hidden this channel so if it exists then remove it if (this.devicesInHB.has(hbUUIDSub)) { this.removeAccessory(this.devicesInHB.get(hbUUIDSub)) } // If this is the main channel then add it to the array of hidden masters if (index === '0') { this.hideMasters.push(device.uuid) // Add the sub accessory, but hidden, to Homebridge extraContext.hidden = true extraContext.enableLogging = false extraContext.enableDebugLogging = false subAcc = this.addAccessory(subdeviceObj, true) } else { continue } } else { // The user has not hidden this channel subAcc = this.devicesInHB.get(hbUUIDSub) || this.addAccessory(subdeviceObj) } // Add the context information to the accessory extraContext.channel = parseInt(index) subAcc.context = { ...subAcc.context, ...context, ...extraContext } // Create the device type instance for this accessory subAcc.control = new (require('./device/' + instance + '-multi'))(this, subAcc) // This is used for later in this function for logging if (index === '0') { accessory = subAcc } else { // Update any changes to the accessory to the platform this.api.updatePlatformAccessories(plugin.name, plugin.alias, [subAcc]) this.devicesInHB.set(subAcc.UUID, subAcc) } } /**************/ } else if (this.consts.models.lightDimmer.includes(device.model)) { /************** LIGHTS (DIMMER) **************/ accessory = this.devicesInHB.get(hbUUID) || this.addAccessory(device) accessory.context = { ...accessory.context, ...context } accessory.control = new (require('./device/light-dimmer'))(this, accessory) /*************/ } else if (this.consts.models.lightRGB.includes(device.model)) { /*********** LIGHTS (RGB) ***********/ accessory = this.devicesInHB.get(hbUUID) || this.addAccessory(device) accessory.context = { ...accessory.context, ...context } accessory.control = new (require('./device/light-rgb'))(this, accessory) /**********/ } else if (this.consts.models.lightCCT.includes(device.model)) { /*********** LIGHTS (CCT) ***********/ accessory = this.devicesInHB.get(hbUUID) || this.addAccessory(device) accessory.context = { ...accessory.context, ...context } accessory.control = new (require('./device/light-cct'))(this, accessory) /**********/ } else if (this.consts.models.garage.includes(device.model)) { /*********** GARAGE DOORS ***********/ if (device.model === 'MSG200') { // If a main accessory exists from before then remove it so re-added as hidden if (this.devicesInHB.has(hbUUID)) { this.removeAccessory(this.devicesInHB.get(hbUUID)) } // First, setup the main, hidden, accessory that will process the control and updates accessory = this.addAccessory(device, true) accessory.context = { ...accessory.context, ...context, ...{ hidden: true } } accessory.control = new (require('./device/garage-main'))(this, accessory) // Loop through the channels for (const index in device.channels) { // Check the entry exists and also skip the channel 0 entry if (!this.funcs.hasProperty(device.channels, index) || index === '0') { continue } const subdeviceObj = { ...device } const extraContext = {} // Generate the Homebridge UUID from the device uuid and channel index const uuidSub = device.uuid + index subdeviceObj.hbDeviceId = uuidSub const hbUUIDSub = this.api.hap.uuid.generate(uuidSub) // Supply a device name for the channel accessories if (index > 0) { device.devName = device.channels[index].devName || device.devName + ' SW' + index } // Check if the user has chosen to hide any channels for this device if (this.hideChannels.includes(device.uuid + index)) { // The user has hidden this channel so if it exists then remove it if (this.devicesInHB.has(hbUUIDSub)) { this.removeAccessory(this.devicesInHB.get(hbUUIDSub)) } continue } // The user has not hidden this channel const subAcc = this.devicesInHB.get(hbUUIDSub) || this.addAccessory(subdeviceObj) // Add the context information to the accessory extraContext.channel = parseInt(index) subAcc.context = { ...subAcc.context, ...context, ...extraContext } // Create the device type instance for this accessory subAcc.control = new (require('./device/garage-sub'))(this, subAcc, accessory) // Update any changes to the accessory to the platform this.api.updatePlatformAccessories(plugin.name, plugin.alias, [subAcc]) this.devicesInHB.set(subAcc.UUID, subAcc) } } else { accessory = this.devicesInHB.get(hbUUID) || this.addAccessory(device) accessory.context = { ...accessory.context, ...context } accessory.control = new (require('./device/garage-single'))(this, accessory) } /**********/ } else if (this.consts.models.roller.includes(device.model)) { /************* ROLLING MOTORS *************/ accessory = this.devicesInHB.get(hbUUID) || this.addAccessory(device) accessory.context = { ...accessory.context, ...context } accessory.control = new (require('./device/roller'))(this, accessory) /***********/ } else if (this.consts.models.purifier.includes(device.model)) { /******** PURIFIERS ********/ accessory = this.devicesInHB.get(hbUUID) || this.addAccessory(device) accessory.context = { ...accessory.context, ...context } accessory.control = new (require('./device/purifier'))(this, accessory) /******/ } else if (this.consts.models.diffuser.includes(device.model)) { /******** DIFFUSERS ********/ accessory = this.devicesInHB.get(hbUUID) || this.addAccessory(device) accessory.context = { ...accessory.context, ...context } accessory.control = new (require('./device/diffuser'))(this, accessory) /******/ } else if (this.consts.models.humidifier.includes(device.model)) { /********** HUMIDIFIERS **********/ accessory = this.devicesInHB.get(hbUUID) || this.addAccessory(device) accessory.context = { ...accessory.context, ...context } accessory.control = new (require('./device/humidifier'))(this, accessory) /******/ } else if (this.consts.models.hubMain.includes(device.model)) { /********** SENSOR HUBS **********/ // At the moment, cloud connection is necessary to get a subdevice list if (!this.cloudClient) { throw new Error(this.lang.sensorNoCloud) } // First, setup the main, hidden, accessory that will process the incoming updates accessory = this.addAccessory(device, true) accessory.context = { ...accessory.context, ...context, ...{ hidden: true } } accessory.control = new (require('./device/hub-main'))(this, accessory) // Then request and initialise a list of subdevices const subdevices = await this.cloudClient.getSubDevices(device) if (!Array.isArray(subdevices)) { throw new Error(this.lang.sensorNoSubs) } subdevices.forEach(subdevice => { try { // Create an object to mimic the addAccessory data const subdeviceObj = { ...device } const uuidSub = device.uuid + subdevice.subDeviceId const hbUUIDSub = this.api.hap.uuid.generate(uuidSub) subdeviceObj.devName = subdevice.subDeviceName || subdevice.subDeviceId subdeviceObj.hbDeviceId = uuidSub subdeviceObj.model = subdevice.subDeviceType.toUpperCase().replace(/[-]+/g, '') // Check the subdevice model is supported if (!this.consts.models.hubSub.includes(subdeviceObj.model)) { // Not supported, so show a log message with helpful info for a github issue this.log.warn( '[%s] %s:\n%s', subdeviceObj.devName, this.lang.notSupp, JSON.stringify(subdeviceObj) ) return } // Obtain or add this subdevice to Homebridge const subAcc = this.devicesInHB.get(hbUUIDSub) || this.addAccessory(subdeviceObj) // Add helpful context info to the accessory object subAcc.context = { ...subAcc.context, ...context, ...{ subSerialNumber: subdevice.subDeviceId } } // Create the device type instance for this accessory switch (subdeviceObj.model) { case 'MS100': subAcc.control = new (require('./device/hub-sensor'))(this, subAcc) break case 'MTS100V3': case 'MTS150': subAcc.control = new (require('./device/hub-valve'))(this, subAcc, accessory) break } // Update any changes to the accessory to the platform this.api.updatePlatformAccessories(plugin.name, plugin.alias, [subAcc]) this.devicesInHB.set(subAcc.UUID, subAcc) } catch (err) { const eText = this.funcs.parseError(err) this.log.warn('[%s] %s %s.', subdevice.subDeviceName, this.lang.devNotAdd, eText) } }) /*********/ } else { /******************** UNSUPPORTED AS OF YET ********************/ this.log.warn('[%s] %s:\n%s', device.devName, this.lang.notSupp, JSON.stringify(device)) return /*******************/ } // Log the device initialisation this.log('[%s] %s [%s].', accessory.displayName, this.lang.devInit, device.uuid) // Extra debug logging when set, show the device JSON info if (accessory.context.enableDebugLogging) { this.log('[%s] %s: %s.', accessory.displayName, this.lang.jsonInfo, JSON.stringify(device)) } // Update any changes to the accessory to the platform this.api.updatePlatformAccessories(plugin.name, plugin.alias, [accessory]) this.devicesInHB.set(accessory.UUID, accessory) } catch (err) { // Catch any errors during device initialisation const eText = this.funcs.parseError(err, [ this.lang.accNotFound, this.lang.sensorNoCloud, this.lang.sensorNoSubs ]) this.log.warn('[%s] %s %s.', device.devName, this.lang.devNotInit, eText) } } addAccessory (device, hidden = false) { // Add an accessory to Homebridge try { const accessory = new this.api.platformAccessory( device.devName, this.api.hap.uuid.generate(device.hbDeviceId) ) // If it isn't a hidden device then set the accessory characteristics if (!hidden) { accessory .getService(this.api.hap.Service.AccessoryInformation) .setCharacteristic(this.api.hap.Characteristic.Name, device.devName) .setCharacteristic(this.api.hap.Characteristic.ConfiguredName, device.devName) .setCharacteristic(this.api.hap.Characteristic.SerialNumber, device.uuid) .setCharacteristic(this.api.hap.Characteristic.Manufacturer, this.lang.brand) .setCharacteristic(this.api.hap.Characteristic.Model, device.model) .setCharacteristic( this.api.hap.Characteristic.FirmwareRevision, device.firmware || plugin.version ) .setCharacteristic(this.api.hap.Characteristic.Identify, true) // Register the accessory if it hasn't been hidden by the user this.api.registerPlatformAccessories(plugin.name, plugin.alias, [accessory]) this.log('[%s] %s.', device.devName, this.lang.devAdd) } // Configure for good practice this.configureAccessory(accessory) // Return the new accessory return accessory } catch (err) { // Catch any errors during add const eText = this.funcs.parseError(err) this.log.warn('[%s] %s %s.', device.devName, this.lang.devNotAdd, eText) return false } } configureAccessory (accessory) { // Set the correct firmware version if we can if (this.api && accessory.context.firmware) { accessory .getService(this.api.hap.Service.AccessoryInformation) .updateCharacteristic( this.api.hap.Characteristic.FirmwareRevision, accessory.context.firmware ) } // Add the configured accessory to our global map this.devicesInHB.set(accessory.UUID, accessory) } updateAccessory (accessory) { this.api.updatePlatformAccessories(plugin.name, plugin.alias, [accessory]) if (accessory.context.isOnline) { this.log('[%s] %s.', accessory.displayName, this.lang.repOnline) } else { this.log.warn('[%s] %s.', accessory.displayName, this.lang.repOffline) } } removeAccessory (accessory) { try { // Remove an accessory from Homebridge if (!accessory.context.hidden) { this.api.unregisterPlatformAccessories(plugin.name, plugin.alias, [accessory]) } this.devicesInHB.delete(accessory.UUID) this.log('[%s] %s.', accessory.displayName, this.lang.devRemove) } catch (err) { // Catch any errors during remove const eText = this.funcs.parseError(err) this.log.warn('[%s] %s %s.', accessory.displayName, this.lang.devNotRemove, eText) } } async sendUpdate (accessory, toSend) { // Variable res is the response from either the cloud mqtt update or local http request let res // Generate the method variable determined from an empty payload or not toSend.method = toSend.method || (Object.keys(toSend.payload).length === 0 ? 'GET' : 'SET') // Always try local control first, even for cloud devices try { // Check the user has this mode turned on if (accessory.context.connection === 'cloud') { throw new Error(this.lang.noHybridMode) } // Check we have the user key if (!accessory.context.userkey) { throw new Error(this.lang.noUserKey) } // Certain models aren't supported for local control if (this.consts.noLocalControl.includes(accessory.context.model)) { throw new Error(this.lang.notSuppLocal) } // Obtain the IP address, either manually configured or from Meross polling data const ipAddress = accessory.context.deviceUrl || accessory.context.ipAddress // Check the IP address exists if (!ipAddress) { throw new Error(this.lang.noIP) } // Generate the timestamp, messageId and sign from the userkey const timestamp = Math.floor(Date.now() / 1000) const messageId = this.funcs.generateRandomString(32) const sign = crypto .createHash('md5') .update(messageId + accessory.context.userkey + timestamp) .digest('hex') // Generate the payload to send const data = { header: { from: 'http://' + ipAddress + '/config', messageId, method: toSend.method, namespace: toSend.namespace, payloadVersion: 1, sign, timestamp, triggerSrc: 'iOSLocal', uuid: accessory.context.serialNumber }, payload: toSend.payload || {} } // Log the update if user enabled if (accessory.context.enableDebugLogging) { this.log('[%s] %s: %s.', accessory.displayName, this.lang.sendUpdate, JSON.stringify(data)) } // Send the request to the device res = await axios({ url: 'http://' + ipAddress + '/config', method: 'post', headers: { 'content-type': 'application/json' }, data, responseType: 'json', timeout: toSend.method === 'GET' || accessory.context.connection === 'local' ? 9000 : 4000 }) // Check the response properties based on whether it is a control or request update switch (toSend.method) { case 'GET': { // Validate the response, checking for payload property if (!res.data || !res.data.payload) { throw new Error(this.lang.invalidResponse) } // Check there have been no IP changes and we are querying a different device if ( res.data.header.from !== '/appliance/' + accessory.context.serialNumber + '/publish' ) { throw new Error(this.lang.wrongDevice) } break } case 'SET': { // Check the response if (!res.data || !res.data.header || res.data.header.method === 'ERROR') { throw new Error(this.lang.reqFail + ' - ' + JSON.stringify(res.data.payload.error)) } break } } } catch (err) { if (accessory.context.connection === 'local') { // An error occurred and cloud mode is disabled so report the error back throw err } else { // An error occurred and we can try sending the request via the cloud if (accessory.context.enableDebugLogging) { const eText = this.funcs.parseError(err, [ this.lang.noHybridMode, this.lang.notSuppLocal, this.lang.noUserKey, this.lang.noIP, this.lang.wrongDevice ]) this.log('[%s] %s %s.', accessory.displayName, this.lang.revertToCloud, eText) } // Send the update via cloud mqtt res = await accessory.mqtt.sendUpdate(toSend) } } // Return the response return res } }
JavaScript
class RouterWrapperWithAuth0 extends Component { /** * Combine the router props with the other props that get * passed to the exported component. This way, it is possible for * the PrintLayout, UserAccountScreen, and other components to * receive the LegIcon or other needed props. */ _combineProps = routerProps => { return { ...this.props, ...routerProps } } render () { const { auth0Config, processSignIn, routerConfig, showAccessTokenError, showLoginError } = this.props const router = ( <ConnectedRouter basename={routerConfig && routerConfig.basename} history={history}> <div> <Switch> <Route exact path={[ // App root '/', // Load app with preset lat/lon/zoom and optional router // NOTE: All params will be cast to :id in matchContentToUrl due // to a quirk with react-router. // https://github.com/ReactTraining/react-router/issues/5870#issuecomment-394194338 '/@/:latLonZoomRouter', '/start/:latLonZoomRouter', // Route viewer (and route ID). '/route', '/route/:id', // Stop viewer (and stop ID). '/stop', '/stop/:id' ]} render={() => <WebappWithRouter {...this.props} />} /> <Route // This route lets new or existing users edit or set up their account. path={'/account'} component={routerProps => { const props = this._combineProps(routerProps) return <UserAccountScreen {...props} /> }} /> <Route path={'/savetrip'} component={(routerProps) => { const props = this._combineProps(routerProps) return <SavedTripScreen isCreating {...props} /> }} /> <Route path={'/savedtrips/:id'} component={(routerProps) => { const props = this._combineProps(routerProps) return <SavedTripScreen {...props} /> }} /> <Route path={'/savedtrips'} component={SavedTripList} /> <Route // This route is called immediately after login by Auth0 // and by the onRedirectCallback function from /lib/util/auth.js. // For new users, it displays the account setup form. // For existing users, it takes the browser back to the itinerary search prior to login. path={'/signedin'} component={routerProps => { const props = this._combineProps(routerProps) return <AfterSignInScreen {...props} /> }} /> <Route path='/print' component={routerProps => { const props = this._combineProps(routerProps) return <PrintLayout {...props} /> }} /> {/* For any other route, simply return the web app. */} <Route render={() => <WebappWithRouter {...this.props} />} /> </Switch> </div> </ConnectedRouter> ) return ( auth0Config ? ( <Auth0Provider audience={AUTH0_AUDIENCE} clientId={auth0Config.clientId} domain={auth0Config.domain} onAccessTokenError={showAccessTokenError} onLoginError={showLoginError} onRedirectCallback={processSignIn} onRedirecting={BeforeSignInScreen} redirectUri={URL_ROOT} scope={AUTH0_SCOPE} > {router} </Auth0Provider> ) : router ) } }
JavaScript
class Sampler { constructor(gl, location) { this.bindTexture = function (texture, unit) { if (texture.bind(unit)) { gl.uniform1i(location, unit); return true; } return false; }; } }
JavaScript
class PuppeteerLiveViewBrowser extends EventEmitter { constructor(browser, opts = {}) { super(); this.browser = browser; this.pages = new Map(); // To track all pages and their creation order for listing this.pageIds = new WeakMap(); // To avoid iteration over pages this.loadedPages = new WeakSet(); // To just track loaded state this.pageIdCounter = 0; checkParamOrThrow(opts.id, 'opts.id', 'String'); checkParamOrThrow(opts.screenshotTimeoutMillis, 'opts.screenshotTimeoutMillis', 'Maybe Number'); this.id = opts.id; this.screenshotTimeoutMillis = opts.screenshotTimeoutMillis || DEFAULT_SCREENSHOT_TIMEOUT_MILLIS; // Since the page can be in any state when the user requests // a screenshot, we need to keep track of it ourselves. browser.on('targetcreated', this._onTargetCreated.bind(this)); // Clean up resources after page close browser.on('targetdestroyed', this._onTargetDestroyed.bind(this)); // Clean up resources after browser close (in Server) browser.on('disconnected', this._onBrowserDisconnected.bind(this)); } /** * Initiates screenshot and HTML capturing of a Page by attaching * a listener to Page "load" events. If the first Page is already loaded, * it captures immediately. * * This function is invoked as a response to a Client side command "renderPage", * which is issued by clicking on a Page listing on the Browser Index page. * Once capturing starts, new screenshot and HTML will be served to Client * with each Page load. * @param {Page} page Puppeteer Page instance. */ startCapturing(page) { const id = this.pageIds.get(page); if (!id) return; const capture = () => { log.debug(`Capturing page. ID: ${id}`); this._getScreenshotAndHtml(page) .then(({ image, html }) => { this.emit(id, { id, url: page.url(), image, html, }); }) .catch((err) => { this.emit(id, { id, url: page.url(), error: err, }); log.error(err); }); }; // Capture immediately for loaded pages if (this.loadedPages.has(page)) capture(); // Setup recurrent capturing page.on('load', () => { if (this.listenerCount(id)) capture(); }); } /** * Clears the capturing listener setup by startCapturing() to prevent * unnecessary load on both Server and Client. * * Client side, the function is invoked by clicking the "back" button * on a page detail (screenshot + HTML). * * @param {Page} page */ stopCapturing(page) { const id = this.pageIds.get(page); this.removeAllListeners(id); } /** * The getScreenshotAndHtml method simply retrieves the page's HTML * content, takes a screenshot and returns both as a promise. * Unfortunately, nothing prevents the Page from being closed while * the screenshot is being taken, which results into error. * Therefore, the method prevents the page from being closed * by replacing its close method and handling the page close * itself once the screenshot has been taken. * * @param {Page} page Puppeteer's Page * @returns {Promise<Buffer>} screenshot * @private * @ignore */ _getScreenshotAndHtml(page) { // Replace page's close function to prevent a close // while the screenshot is being taken. const { close } = page; let closed; let closeArgs; let closeResolve; page.close = (...args) => { if (!closed) closeArgs = args; closed = true; return new Promise((resolve) => { closeResolve = resolve; }); }; const cleanup = () => { // Replace the stolen close() method or call it, // if it should've been called externally. if (closed) { close.apply(page, closeArgs) .then(closeResolve); } else { page.close = close.bind(page); } }; return Promise.props({ image: page.screenshot(), html: page.content(), }) .timeout(this.screenshotTimeoutMillis, 'Puppeteer Live View: Screenshot timed out.') .finally(cleanup); } /** * Handler invoked whenever a Target is created in a Puppeteer's Browser. * @param {Target} target * @private */ _onTargetCreated(target) { if (target.type() !== 'page') return; target.page() .then((page) => { const id = `${this.id}_PAGE_${++this.pageIdCounter}`; this.pages.set(id, page); this.pageIds.set(page, id); this.emit('pagecreated', { id, browserId: this.id, url: page.url(), }); page.on('load', () => { this.loadedPages.add(page); // Page is loaded }); // Using "framenavigated" on main Frame since "targetchanged" does not seem reliable page.on('framenavigated', (frame) => { if (frame !== page.mainFrame()) return; this.loadedPages.delete(page); this.emit('pagenavigated', { id, url: frame.url(), }); }); }) .catch(err => log.error(err)); } /** * Handler invoked whenever a Target is destroyed in a Puppeteer's Browser. * @param {Target} target * @private */ _onTargetDestroyed(target) { if (target.type() !== 'page') return; target.page() .then((page) => { const id = this.pageIds.get(page); this.pages.delete(id); this.emit('pagedestroyed', { id, }); }) .catch(err => log.error(err)); } /** * Handler invoked whenever a Browser is destroyed / disconnected in Puppeteer. * @param {Browser} browser * @private */ _onBrowserDisconnected(browser) { this.emit('disconnected', browser); } }
JavaScript
class PuppeteerLiveViewServer extends EventEmitter { constructor() { super(); const containerPort = process.env[ENV_VARS.CONTAINER_PORT] || LOCAL_ENV_VARS[ENV_VARS.CONTAINER_PORT]; this.liveViewPort = parseInt(containerPort, 10); if (!(this.liveViewPort >= 0 && this.liveViewPort <= 65535)) { throw new Error(`Cannot start LiveViewServer - invalid port specified by the ${ ENV_VARS.CONTAINER_PORT} environment variable (was "${containerPort}").`); } this.liveViewUrl = process.env[ENV_VARS.CONTAINER_URL] || LOCAL_ENV_VARS[ENV_VARS.CONTAINER_URL]; this.browsers = new Set(); this.browserIdCounter = 0; this.httpServer = null; } /** * Adds an instance of PuppeteerLiveViewBrowser (not Puppeteer.Browser) * to the server's list of managed browsers. * * @param {PuppeteerLiveViewBrowser} browser */ addBrowser(browser) { this.browsers.add(browser); this.emit('browsercreated', browser); browser.on('disconnected', () => this.deleteBrowser(browser)); } /** * Removes an instance of PuppeteerLiveViewBrowser (not Puppeteer.Browser) * from the server's list of managed browsers. * @param {PuppeteerLiveViewBrowser} browser */ deleteBrowser(browser) { this.browsers.delete(browser); this.emit('browserdestroyed', browser); browser.removeAllListeners(); } /** * Starts an HTTP and a WebSocket server on a port defined in `CONTAINER_PORT` environment * variable or a randomly-selected port. * * @return {Promise} resolves when HTTP server starts listening */ startServer() { const server = http.createServer(this._httpRequestListener.bind(this)); const wss = new WebSocket.Server({ server }); wss.on('connection', this._wsRequestListener.bind(this)); return promisifyServerListen(server)(this.liveViewPort) .then(() => { log.info(`Live view is now available at ${this.liveViewUrl}`); this.httpServer = server; }); } /** * Request handler function that returns a simple HTML index page * with embedded JavaScript that will establish a WebSocket connection * between the server and the client. * @param {http.IncomingMessage} req * @param {http.ServerResponse} res * @private * @ignore */ _httpRequestListener(req, res) { const body = layout(this.liveViewUrl); res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': Buffer.byteLength(body), }); res.end(body); } /** * This function fires with each new WebSocket connection and manages * the socket's messages. * @param {WebSocket} ws * @private * @ignore */ _wsRequestListener(ws) { const BAD_REQUEST = { message: 'Bad Request', status: 400, }; const NOT_FOUND = { message: 'Not Found', status: 404, }; // Traverses browsers to find a page with ID const findPage = (id) => { let page; let browser; for (const b of this.browsers) { // eslint-disable-line if (b.pages.has(id)) { page = b.pages.get(id); browser = b; break; } } return [browser, page]; }; const COMMANDS = { renderIndex: () => sendCommand(ws, 'renderIndex', { html: indexPage(this.browsers) }), // When the user selects a Page from the Index renderPage: (msg) => { const { id } = msg.data || {}; const [browser, page] = findPage(id); if (!page) return sendCommand(ws, 'error', NOT_FOUND); browser.startCapturing(page); browser.on(id, (pageData) => { if (pageData.error) sendCommand(ws, 'renderPage', { html: errorPage(pageData) }); else sendCommand(ws, 'renderPage', { html: detailPage(pageData) }); }); }, // When the user clicks on the back button quitPage: (msg) => { const { id } = msg.data || {}; const [browser, page] = findPage(id); if (!page) return; // no need to send error browser.stopCapturing(page); }, }; log.debug('WebSocket connection to Puppeteer Live View established.'); ws.on('message', (msg) => { try { msg = JSON.parse(msg); } catch (err) { return sendCommand(ws, 'error', BAD_REQUEST); } // Validate command and send response const { command } = msg; const fn = COMMANDS[command]; if (!fn || typeof fn !== 'function') return sendCommand(ws, 'error', BAD_REQUEST); fn(msg); }); this._setupCommandHandles(ws); // Send first Index after WS connection is established sendCommand(ws, 'renderIndex', { html: indexPage(this.browsers) }); } /** * Invoked from the _wsRequestListener, this function only groups * all browser related event handling into a single package. * @param {WebSocket} ws * @private * @ignore */ _setupCommandHandles(ws) { const attachListeners = (browser) => { const createListener = p => sendCommand(ws, 'createPage', p); const destroyListener = p => sendCommand(ws, 'destroyPage', p); const updateListener = p => sendCommand(ws, 'updatePage', p); browser.on('pagecreated', createListener); browser.on('pagedestroyed', destroyListener); browser.on('pagenavigated', updateListener); // Clean up to prevent listeners firing into closed sockets (on page refresh) ws.on('close', () => { browser.removeListener('pagecreated', createListener); browser.removeListener('pagedestroyed', destroyListener); browser.removeListener('pagenavigated', updateListener); }); }; // Since this function fires when a socket opens, some browsers // and pages already exist and we need to get messages about those too. this.browsers.forEach(attachListeners); const createListener = (browser) => { attachListeners(browser); sendCommand(ws, 'createBrowser', { id: browser.id }); }; const destroyListener = (browser) => { sendCommand(ws, 'destroyBrowser', { id: browser.id }); }; this.on('browsercreated', createListener); this.on('browserdestroyed', destroyListener); // Clean up to prevent listeners firing into closed sockets (on page refresh) ws.on('close', () => { this.removeListener('browsercreated', createListener); this.removeListener('browserdestroyed', destroyListener); }); } }
JavaScript
class LRU{ constructor(){ // the least recently used item this.first = null; // the most recently used item this.last = null; // a list of all items in the lru list this.items = {}; this.elements = 0; this.numPoints = 0; } size(){ return this.elements; } contains(node){ return this.items[node.id] == null; } touch(node){ if (!node.loaded) { return; } let item; if (this.items[node.id] == null) { // add to list item = new LRUItem(node); item.previous = this.last; this.last = item; if (item.previous !== null) { item.previous.next = item; } this.items[node.id] = item; this.elements++; if (this.first === null) { this.first = item; } this.numPoints += node.numPoints; } else { // update in list item = this.items[node.id]; if (item.previous === null) { // handle touch on first element if (item.next !== null) { this.first = item.next; this.first.previous = null; item.previous = this.last; item.next = null; this.last = item; item.previous.next = item; } } else if (item.next === null) { // handle touch on last element } else { // handle touch on any other element item.previous.next = item.next; item.next.previous = item.previous; item.previous = this.last; item.next = null; this.last = item; item.previous.next = item; } } } remove(node){ let lruItem = this.items[node.id]; if (lruItem) { if (this.elements === 1) { this.first = null; this.last = null; } else { if (!lruItem.previous) { this.first = lruItem.next; this.first.previous = null; } if (!lruItem.next) { this.last = lruItem.previous; this.last.next = null; } if (lruItem.previous && lruItem.next) { lruItem.previous.next = lruItem.next; lruItem.next.previous = lruItem.previous; } } delete this.items[node.id]; this.elements--; this.numPoints -= node.numPoints; } } getLRUItem(){ if (this.first === null) { return null; } let lru = this.first; return lru.node; } toString(){ let string = '{ '; let curr = this.first; while (curr !== null) { string += curr.node.id; if (curr.next !== null) { string += ', '; } curr = curr.next; } string += '}'; string += '(' + this.size() + ')'; return string; } freeMemory(){ if (this.elements <= 1) { return; } while (this.numPoints > Potree.pointLoadLimit) { let element = this.first; let node = element.node; this.disposeDescendants(node); } } disposeDescendants(node){ let stack = []; stack.push(node); while (stack.length > 0) { let current = stack.pop(); // console.log(current); current.dispose(); this.remove(current); for (let key in current.children) { if (current.children.hasOwnProperty(key)) { let child = current.children[key]; if (child.loaded) { stack.push(current.children[key]); } } } } } }
JavaScript
class LasLazLoader { constructor (version, extension) { if (typeof (version) === 'string') { this.version = new Version(version); } else { this.version = version; } this.extension = extension; } static progressCB () { } load (node) { if (node.loaded) { return; } let url = node.getURL(); if (this.version.equalOrHigher('1.4')) { url += `.${this.extension}`; } let xhr = XHRFactory.createXMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.status === 0) { let buffer = xhr.response; this.parse(node, buffer); } else { console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + url); } } }; xhr.send(null); } async parse(node, buffer){ let lf = new LASFile(buffer); let handler = new LasLazBatcher(node); try{ await lf.open(); lf.isOpen = true; }catch(e){ console.log("failed to open file. :("); return; } let header = await lf.getHeader(); let skip = 1; let totalRead = 0; let totalToRead = (skip <= 1 ? header.pointsCount : header.pointsCount / skip); let hasMoreData = true; while(hasMoreData){ let data = await lf.readData(1000 * 1000, 0, skip); handler.push(new LASDecoder(data.buffer, header.pointsFormatId, header.pointsStructSize, data.count, header.scale, header.offset, header.mins, header.maxs)); totalRead += data.count; LasLazLoader.progressCB(totalRead / totalToRead); hasMoreData = data.hasMoreData; } header.totalRead = totalRead; header.versionAsString = lf.versionAsString; header.isCompressed = lf.isCompressed; LasLazLoader.progressCB(1); try{ await lf.close(); lf.isOpen = false; }catch(e){ console.error("failed to close las/laz file!!!"); throw e; } } handle (node, url) { } }
JavaScript
class NodeLoader{ constructor(url){ this.url = url; } async load(node){ if(node.loaded || node.loading){ return; } node.loading = true; Potree.numNodesLoading++; // console.log(node.name, node.numPoints); // if(loadedNodes.has(node.name)){ // // debugger; // } // loadedNodes.add(node.name); try{ if(node.nodeType === 2){ await this.loadHierarchy(node); } let {byteOffset, byteSize} = node; let urlOctree = `${this.url}/../octree.bin`; let first = byteOffset; let last = byteOffset + byteSize - 1n; let buffer; if(byteSize === 0n){ buffer = new ArrayBuffer(0); console.warn(`loaded node with 0 bytes: ${node.name}`); }else { let response = await fetch(urlOctree, { headers: { 'content-type': 'multipart/byteranges', 'Range': `bytes=${first}-${last}`, }, }); buffer = await response.arrayBuffer(); } let workerPath; if(this.metadata.encoding === "BROTLI"){ workerPath = Potree.scriptPath + '/workers/2.0/DecoderWorker_brotli.js'; }else { workerPath = Potree.scriptPath + '/workers/2.0/DecoderWorker.js'; } let worker = Potree.workerPool.getWorker(workerPath); worker.onmessage = function (e) { let data = e.data; let buffers = data.attributeBuffers; Potree.workerPool.returnWorker(workerPath, worker); let geometry = new THREE.BufferGeometry(); for(let property in buffers){ let buffer = buffers[property].buffer; if(property === "position"){ geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(buffer), 3)); }else if(property === "rgba"){ geometry.addAttribute('rgba', new THREE.BufferAttribute(new Uint8Array(buffer), 4, true)); }else if(property === "NORMAL"){ //geometry.addAttribute('rgba', new THREE.BufferAttribute(new Uint8Array(buffer), 4, true)); geometry.addAttribute('normal', new THREE.BufferAttribute(new Float32Array(buffer), 3)); }else if (property === "INDICES") { let bufferAttribute = new THREE.BufferAttribute(new Uint8Array(buffer), 4); bufferAttribute.normalized = true; geometry.addAttribute('indices', bufferAttribute); }else { const bufferAttribute = new THREE.BufferAttribute(new Float32Array(buffer), 1); let batchAttribute = buffers[property].attribute; bufferAttribute.potree = { offset: buffers[property].offset, scale: buffers[property].scale, preciseBuffer: buffers[property].preciseBuffer, range: batchAttribute.range, }; geometry.addAttribute(property, bufferAttribute); } } // indices ?? node.density = data.density; node.geometry = geometry; node.loaded = true; node.loading = false; Potree.numNodesLoading--; }; let pointAttributes = node.octreeGeometry.pointAttributes; let scale = node.octreeGeometry.scale; let box = node.boundingBox; let min = node.octreeGeometry.offset.clone().add(box.min); let size = box.max.clone().sub(box.min); let max = min.clone().add(size); let numPoints = node.numPoints; let offset = node.octreeGeometry.loader.offset; let message = { name: node.name, buffer: buffer, pointAttributes: pointAttributes, scale: scale, min: min, max: max, size: size, offset: offset, numPoints: numPoints }; worker.postMessage(message, [message.buffer]); }catch(e){ node.loaded = false; node.loading = false; Potree.numNodesLoading--; console.log(`failed to load ${node.name}`); console.log(e); console.log(`trying again!`); } } parseHierarchy(node, buffer){ let view = new DataView(buffer); let tStart = performance.now(); let bytesPerNode = 22; let numNodes = buffer.byteLength / bytesPerNode; let octree = node.octreeGeometry; // let nodes = [node]; let nodes = new Array(numNodes); nodes[0] = node; let nodePos = 1; for(let i = 0; i < numNodes; i++){ let current = nodes[i]; let type = view.getUint8(i * bytesPerNode + 0); let childMask = view.getUint8(i * bytesPerNode + 1); let numPoints = view.getUint32(i * bytesPerNode + 2, true); let byteOffset = view.getBigInt64(i * bytesPerNode + 6, true); let byteSize = view.getBigInt64(i * bytesPerNode + 14, true); // if(byteSize === 0n){ // // debugger; // } if(current.nodeType === 2){ // replace proxy with real node current.byteOffset = byteOffset; current.byteSize = byteSize; current.numPoints = numPoints; }else if(type === 2){ // load proxy current.hierarchyByteOffset = byteOffset; current.hierarchyByteSize = byteSize; current.numPoints = numPoints; }else { // load real node current.byteOffset = byteOffset; current.byteSize = byteSize; current.numPoints = numPoints; } current.nodeType = type; if(current.nodeType === 2){ continue; } for(let childIndex = 0; childIndex < 8; childIndex++){ let childExists = ((1 << childIndex) & childMask) !== 0; if(!childExists){ continue; } let childName = current.name + childIndex; let childAABB = createChildAABB(current.boundingBox, childIndex); let child = new OctreeGeometryNode(childName, octree, childAABB); child.name = childName; child.spacing = current.spacing / 2; child.level = current.level + 1; current.children[childIndex] = child; child.parent = current; // nodes.push(child); nodes[nodePos] = child; nodePos++; } // if((i % 500) === 0){ // yield; // } } let duration = (performance.now() - tStart); // if(duration > 20){ // let msg = `duration: ${duration}ms, numNodes: ${numNodes}`; // console.log(msg); // } } async loadHierarchy(node){ let {hierarchyByteOffset, hierarchyByteSize} = node; let hierarchyPath = `${this.url}/../hierarchy.bin`; let first = hierarchyByteOffset; let last = first + hierarchyByteSize - 1n; let response = await fetch(hierarchyPath, { headers: { 'content-type': 'multipart/byteranges', 'Range': `bytes=${first}-${last}`, }, }); let buffer = await response.arrayBuffer(); this.parseHierarchy(node, buffer); // let promise = new Promise((resolve) => { // let generator = this.parseHierarchy(node, buffer); // let repeatUntilDone = () => { // let result = generator.next(); // if(result.done){ // resolve(); // }else{ // requestAnimationFrame(repeatUntilDone); // } // }; // repeatUntilDone(); // }); // await promise; } }
JavaScript
class EptLoader { static async load(file, callback) { let response = await fetch(file); let json = await response.json(); let url = file.substr(0, file.lastIndexOf('ept.json')); let geometry = new Potree.PointCloudEptGeometry(url, json); let root = new Potree.PointCloudEptGeometryNode(geometry); geometry.root = root; geometry.root.load(); callback(geometry); } }
JavaScript
class EptLaszipLoader { load(node) { if (node.loaded) return; let url = node.url() + '.laz'; let xhr = XHRFactory.createXMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { let buffer = xhr.response; this.parse(node, buffer); } else { console.log('Failed ' + url + ': ' + xhr.status); } } }; xhr.send(null); } async parse(node, buffer){ let lf = new LASFile(buffer); let handler = new EptLazBatcher(node); try{ await lf.open(); lf.isOpen = true; const header = await lf.getHeader(); { let i = 0; let toArray = (v) => [v.x, v.y, v.z]; let mins = toArray(node.key.b.min); let maxs = toArray(node.key.b.max); let hasMoreData = true; while(hasMoreData){ const data = await lf.readData(1000000, 0, 1); let d = new LASDecoder( data.buffer, header.pointsFormatId, header.pointsStructSize, data.count, header.scale, header.offset, mins, maxs); d.extraBytes = header.extraBytes; d.pointsFormatId = header.pointsFormatId; handler.push(d); i += data.count; hasMoreData = data.hasMoreData; } header.totalRead = i; header.versionAsString = lf.versionAsString; header.isCompressed = lf.isCompressed; await lf.close(); lf.isOpen = false; } }catch(err){ console.error('Error reading LAZ:', err); if (lf.isOpen) { await lf.close(); lf.isOpen = false; } throw err; } } }
JavaScript
class DeviceOrientationControls extends EventDispatcher{ constructor(viewer){ super(); this.viewer = viewer; this.renderer = viewer.renderer; this.scene = null; this.sceneControls = new THREE.Scene(); this.screenOrientation = window.orientation || 0; let deviceOrientationChange = e => { this.deviceOrientation = e; }; let screenOrientationChange = e => { this.screenOrientation = window.orientation || 0; }; if ('ondeviceorientationabsolute' in window) { window.addEventListener('deviceorientationabsolute', deviceOrientationChange); } else if ('ondeviceorientation' in window) { window.addEventListener('deviceorientation', deviceOrientationChange); } else { console.warn("No device orientation found."); } // window.addEventListener('deviceorientation', deviceOrientationChange); window.addEventListener('orientationchange', screenOrientationChange); } setScene (scene) { this.scene = scene; } update (delta) { let computeQuaternion = function (alpha, beta, gamma, orient) { let quaternion = new THREE.Quaternion(); let zee = new THREE.Vector3(0, 0, 1); let euler = new THREE.Euler(); let q0 = new THREE.Quaternion(); euler.set(beta, gamma, alpha, 'ZXY'); quaternion.setFromEuler(euler); quaternion.multiply(q0.setFromAxisAngle(zee, -orient)); return quaternion; }; if (typeof this.deviceOrientation !== 'undefined') { let alpha = this.deviceOrientation.alpha ? THREE.Math.degToRad(this.deviceOrientation.alpha) : 0; let beta = this.deviceOrientation.beta ? THREE.Math.degToRad(this.deviceOrientation.beta) : 0; let gamma = this.deviceOrientation.gamma ? THREE.Math.degToRad(this.deviceOrientation.gamma) : 0; let orient = this.screenOrientation ? THREE.Math.degToRad(this.screenOrientation) : 0; let quaternion = computeQuaternion(alpha, beta, gamma, orient); viewer.scene.cameraP.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w); } } }
JavaScript
class LabelValueMetadata extends Component { /** * render * @return {String} - HTML markup for the component */ render() { const { defaultLabel, labelValuePairs } = this.props; if (labelValuePairs.length === 0) { return (<></>); } /* eslint-disable react/no-array-index-key */ // Disabling array index key for dt/dd elements as // they are intended to display metadata that will not // need to be re-rendered internally in any meaningful way return ( <dl className={ns('label-value-metadata')}> {labelValuePairs.reduce((acc, labelValuePair, i) => acc.concat([ <Typography component="dt" key={`label-${i}`} variant="subtitle2">{labelValuePair.label || defaultLabel}</Typography>, <Typography component="dd" key={`value-${i}`} variant="body1"> <SanitizedHtml htmlString={labelValuePair.value} ruleSet="iiif" /> </Typography>, ]), [])} </dl> ); /* eslint-enable react/no-array-index-key */ } }
JavaScript
class ActivateCommand extends BaseCommand { // command arguments static args = [ { name: "workflows", required: true, description: "List of workflow keys seperated by a comma.", parse: input => input.trim().split(",") } ] // command flags static flags = { // append base command flags ...BaseCommand.flags, // append base command flags destination: flags.string({ char: "d", description: "Destination config - user or org", options: ["user", "org"], required: true }), // collect user emails emails: flags.string({ char: "e", default: "", description: "List of emails seperated by comma" }) } /** * Ask the user which workflow should be used. * * @param {Array.<object>} workflows - List of workflows. */ async ask(workflows) { const clearWorkflows = workflows.map((w) => ({ data: `Name: ${w.display_name.en}\n Is Global Workflow: ${w.org === "global"}`, id: w.id })) const message = `We found multiple workflows that matched your query. Please select the releavnt workflow` return inquirer.prompt([{ type: "list", name: "workflow", message, choices: clearWorkflows.map((op) => op.data) }]).then((answer) => { return clearWorkflows.find((op) => op.data === answer.workflow) }) } /** * Activate the selected workflow on the destination. * * @param {string} workflows - Workflow keys */ async _activateWorkflow(workflows) { // resolve access token const accessToken = await this.accessToken // init workflow client const client = new WorkflowsClient(accessToken) // get workflow id let workflowIds = [] for (const key of workflows) { const workflows = await client.list([ [CONF_KEYS_MAP["workflows"], "==", key], ]) if (workflows && workflows.length) { const workflow = workflows.length > 1 ? await this.ask(workflows) : workflows[0] workflowIds.push(workflow.id) } else { throw new Error(`couldn't find workflow key: ${key}`) } } // build payload const payload = { [this.flags.destination]: { append: workflowIds } } if (this.flags.destination === "user") { payload.user.emails = this.flags.emails.split(/,/g).filter(email => !!email) } // make request to activate endpoint await client.updateActiveWorkflows(payload) } /** * Run the activate command */ async run() { // get key const { workflows } = this.args // start spinner // cli.ux.action.start(`Activating workflows ${workflows.join(",")}`) try { // update the user's organization await this._activateWorkflow(workflows) // stop spinner cli.ux.action.start(`Activating workflows ${workflows.join(",")}`) cli.ux.action.stop() } catch (err) { debugError(err) this.error(`Unable to activate workflow.\n${err}`) } } }
JavaScript
class Graph { // defining vertex array and // adjacent list constructor (noOfVertices) { this.noOfVertices = noOfVertices this.AdjList = new Map() } // functions to be implemented // addVertex(v) // addEdge(v, w) // printGraph() // bfs(v) // dfs(v) // add vertex to the graph addVertex (v) { // initialize the adjacent list with a // null array this.AdjList.set(v, []) } // add edge to the graph addEdge (v, w) { // get the list for vertex v and put the // vertex w denoting edge between v and w this.AdjList.get(v).push(w) // Since graph is undirected, // add an edge from w to v also this.AdjList.get(w).push(v) } // Prints the vertex and adjacency list printGraph () { // get all the vertices const getKeys = this.AdjList.keys() // iterate over the vertices for (const i of getKeys) { // great the corresponding adjacency list // for the vertex const getValues = this.AdjList.get(i) let conc = '' // iterate over the adjacency list // concatenate the values into a string for (const j of getValues) { conc += j + ' ' } // print the vertex and its adjacency list console.log(i + ' -> ' + conc) } } }
JavaScript
class Recorder extends component_1.Tube { /** * Create a new recorder component that will record to a writable stream. * @param {Stream} fileStream The stream to save the messages to. * @return {undefined} */ constructor(fileStream) { const incoming = stream_factory_1.default.recorder('incoming', fileStream); const outgoing = stream_factory_1.default.recorder('outgoing', fileStream); const interleaved = { incoming, outgoing }; const streamsFinished = []; for (const [key, value] of Object.entries(interleaved)) { streamsFinished.push(new Promise((resolve) => value.on('finish', () => { const timestamp = Date.now(); const message = null; const type = key; fileStream.write(JSON.stringify({ type, timestamp, message }, null, 2)); fileStream.write(',\n'); resolve(); }))); } // start of file: begin JSON array fileStream.write('[\n'); // end of file: close JSON array Promise.all(streamsFinished) .then(() => { fileStream.write(JSON.stringify(null)); fileStream.write('\n]\n'); }) .catch(() => { /** ignore */ }); super(incoming, outgoing); } /** * Create a new recorder component that will record to a file. * @param {String} filename The name of the file (relative to cwd) * @return {RecorderComponent} */ static toFile(filename = 'data.json') { const cwd = process.cwd(); const fileStream = fs_1.createWriteStream(path_1.join(cwd, filename)); return new Recorder(fileStream); } }
JavaScript
class UserHelper { constructor() { this.response = null; } //Register a NEW USER async registerNewUser(userObject) { //Create, setup, send request to server, wait for the response (async/await) and save the respponse from server to response property (variable) await supertest(process.env.BASE_URL) //Setup a request method - POST and an endpoint - /auth .post('/user') //Setup payload - object with 2 keys - login and password (and their values) .send(userObject) //Save a response from server to esponse property (variable) .then((res) => { this.response = res; }); } // //Login async login(email, password) { //Create, setup, send request to server, wait for the response (async/await) and save the respponse from server to response property (variable) await supertest(process.env.BASE_URL) //Setup a request method - POST and an endpoint - /auth .post('/user/login') //Setup payload - object with 2 keys - login and password (and their values) .send({ email: email, password: password }) //Save a response from server to esponse property (variable) .then((res) => { this.response = res; }); } //Login async confirmEmail(link) { //Create, setup, send request to server, wait for the response (async/await) and save the respponse from server to response property (variable) await supertest(link) //Setup a request method - POST and an endpoint - /auth .get('') //Save a response from server to esponse property (variable) .then((res) => { this.response = res; }); } }
JavaScript
class Bounding { constructor({game, world, lat, lon, range} = {}) { const {x, y} = geo_to_screenspace(lat, lon); const lat_offset = range / LAT_MINUTES_MILES / MINUTES_PER_DEGREE * LAT_S; const lon_offset = range / LON_MINUTES_MILES / MINUTES_PER_DEGREE * LON_S; this.x = x - lat_offset; this.y = y - lon_offset; this.w = lat_offset * 2; this.h = lon_offset * 2; this.box = game.add.graphics(0, 0); this.box.lineStyle(4, Peer.COL_SEARCH, 1.0); this.box.drawRect(this.x, this.y, this.w, this.h); world.bounding_group.add(this.box); } }
JavaScript
class Peer { static COL_DEFAULT = 0xFFFFFF; static COL_SEARCH = 0x80ff00; constructor({game, world, name, lat, lon} = {}) { this.game = game; this.world = world; this.group = game.add.group(); this.group.position = geo_to_screenspace(lat, lon); this.dot = game.add.graphics(0, 0); this.dot.beginFill(Peer.COL_DEFAULT); this.dot.drawCircle(0, 0, 10); this.dot.endFill(); this.nametag = game.add.text(0, 0 + 20, `${name}`, {fontSize: "12px", fill: "#FFFFFF"}); this.nametag.anchor.setTo(0.5, 0.5); this.location = game.add.text(0, 0 + 40, `${lat}, ${lon}`, {fontSize: "12px", fill: "#FFFFFF"}); this.location.anchor.setTo(0.5, 0.5); this.group.add(this.dot); this.group.add(this.nametag); this.group.add(this.location); this.palette = new Palette({game: game, peer: this}); this.palette.group.position = {x: this.group.position.x + 20, y: this.group.position.y}; this.group.onChildInputDown.add(() => { for (const [pubstring, peer] of this.world.peers) { peer.palette.group.visible = false; } this.palette.group.visible = true; this.world.bg.events.onInputDown.add(() => { this.palette.group.visible = false; }); }); this.world.peer_group.add(this.group); this.enable(); } color(color) { this.dot.tint = color; this.nametag.tint = color; this.location.tint = color; // The following line corrects a bug in Phaser which messes up tinting behavior this.dot.graphicsData[0]._fillTint = 0xFFFFFF; } move(x, y, duration) { const move_tween = this.game.add.tween(this.group.position). to({x: x, y: y}, duration, Phaser.Easing.Linear.None, true, 0, 0, false); this.palette.group.position = {x: x, y: y}; } enable() { this.dot.inputEnabled = true; this.nametag.inputEnabled = true; this.location.inputEnabled = true; this.dot.input.useHandCursor = true; this.nametag.input.useHandCursor = true; this.location.input.useHandCursor = true; } disable() { this.dot.inputEnabled = false; this.nametag.inputEnabled = false; this.location.inputEnabled = false; } }
JavaScript
class Queue { /** * Create a queue. * @param {Discord.Message} message Discord.Message */ constructor(message) { /** * Stream dispatcher. * @type {Discord.StreamDispatcher} */ this.dispatcher = null; /** * Voice connection. * @type {Discord.VoiceConnection} */ this.connection = null; /** * Stream volume. * @type {number} */ this.volume = 50; /** * List of songs * @type {Song[]} */ this.songs = []; /** * Whether stream is currently stopped. * @type {boolean} */ this.stopped = false; /** * Whether or not the last song was skipped. * @type {boolean} */ this.skipped = false; /** * Whether or not the stream is currently playing. * @type {boolean} */ this.playing = true; /** * Whether or not the stream is currently paused. * @type {boolean} */ this.pause = false; /** * Type of repeat mode (0 is disabled, 1 is repeating a song, 2 is repeating all the playlist) * @type {number} */ this.repeatMode = 0; /** * Whether or not the autoplay mode is enabled. * @type {boolean} */ this.autoplay = true; /** * `@2.0.0` Queue audio filter. * Available filters: {@link Filter} * @type {Filter} */ this.filter = null; /** * `@2.2.0` Message which initialize the queue * @type {Discord.Message} */ this.initMessage = message; /** * `@2.5.0` ytdl stream * @type {Readable} */ this.stream = null; /** * `@2.7.0` What time in the song to begin (in milliseconds). * @type {number} */ this.beginTime = 0; } /** * Formatted duration string. * @type {string} */ get formattedDuration() { return formatDuration(this.duration * 1000) } /** * Queue's duration. * @type {number} */ get duration() { return this.songs.reduce((prev, next) => prev + next.duration, 0) } /** * `@2.7.0` What time in the song is playing (in milliseconds). * @type {number} */ get currentTime() { return this.dispatcher.streamTime + this.beginTime; } /** * `@2.8.0` Formatted {@link Queue#currentTime} string. * @type {string} */ get formattedCurrentTime() { return formatDuration(this.currentTime); } }
JavaScript
class CheckoutCreditCard { constructor() { this.tokens = []; } mountFrames() { console.log('Mount checkout frames..'); } handlePaymentUsingToken(e) { document.getElementById('checkout--container').classList.add('hidden'); document.getElementById('pay-now-with-token--container').classList.remove('hidden'); document.getElementById('save-card--container').style.display = 'none'; document .querySelector('input[name=token]') .value = e.target.dataset.token; } handlePaymentUsingCreditCard(e) { document.getElementById('checkout--container').classList.remove('hidden'); document.getElementById('pay-now-with-token--container').classList.add('hidden'); document.getElementById('save-card--container').style.display = 'grid'; const payButton = document.getElementById('pay-button'); const publicKey = document.querySelector('meta[name="public-key"]').content ?? ''; const form = document.getElementById('payment-form'); Frames.init(publicKey); Frames.addEventHandler(Frames.Events.CARD_VALIDATION_CHANGED, function (event) { payButton.disabled = !Frames.isCardValid(); }); Frames.addEventHandler(Frames.Events.CARD_TOKENIZATION_FAILED, function (event) { pay.button.disabled = false; }); Frames.addEventHandler(Frames.Events.CARD_TOKENIZED, function (event) { payButton.disabled = true; document.querySelector( 'input[name="gateway_response"]' ).value = JSON.stringify(event); document.querySelector( 'input[name="store_card"]' ).value = document.querySelector( 'input[name=token-billing-checkbox]:checked' ).value; document.getElementById('server-response').submit(); }); form.addEventListener('submit', function (event) { event.preventDefault(); Frames.submitCard(); }); } completePaymentUsingToken(e) { let btn = document.getElementById('pay-now-with-token'); btn.disabled = true; btn.querySelector('svg').classList.remove('hidden'); btn.querySelector('span').classList.add('hidden'); document.getElementById('server-response').submit(); } handle() { this.handlePaymentUsingCreditCard(); Array .from(document.getElementsByClassName('toggle-payment-with-token')) .forEach((element) => element.addEventListener('click', this.handlePaymentUsingToken)); document .getElementById('toggle-payment-with-credit-card') .addEventListener('click', this.handlePaymentUsingCreditCard); document .getElementById('pay-now-with-token') .addEventListener('click', this.completePaymentUsingToken); } }
JavaScript
class SeedBrowserScene extends Phaser.Scene { /** * Creates an instance of SeedBrowserScene. * @memberof SeedBrowserScene */ constructor() { super('SeedBrowserScene'); } /** * Creates the content of the scene. * * @memberof SeedBrowserScene */ create() { const seed = ROT.RNG.getUniformInt(0, Number.MAX_SAFE_INTEGER); ROT.RNG.setSeed(seed); this.map = new SimplexMap(this, 'tiles', this.cache.json.get('mapConfig')); this.graphics = this.add.graphics(); for (let x = 0; x < 1024; x += 1) { for (let y = 0; y < 576; y += 1) { this.graphics.fillStyle({ waterTile: color.darkblue, ford: color.blue, marsh: color.green, grass: color.darkgreen, tree: color.darkbrown, bush: color.green, gravel: color.darkgray, mountain: color.gray, redFlower: color.red, yellowFlower: color.yellow, portalTile: color.white, stoneFloor: color.darkgray, gate: color.lightgray, stoneWall: color.gray, dirt: color.brown, sand: color.yellow, palmTree: color.green, }[this.map.getTileFrame(x - 512, y - 288)]); this.graphics.fillPoint(x, y); } } new TextButton({ onPointerUp: () => { this.scene.start('GameScene'); }, origin: 0.5, scene: this, text: 'Start new game with seed: ' + ROT.RNG.getSeed(), x: 512, y: 440, }); new TextButton({ onPointerUp: () => { this.scene.restart(); }, origin: 0.5, scene: this, text: 'Change seed', x: 512, y: 490, }); new TextButton({ onPointerUp: () => { this.scene.scene.start('MenuScene'); this.scene.scale.off('leavefullscreen'); }, origin: 0.5, scene: this, text: 'Back to main menu', x: 512, y: 540, }); } }
JavaScript
class Transition extends Animate { constructor(options) { super(options); // collect from pose, when from was not complete options.from = options.from || {}; for (const i in options.to) { if (Utils.isUndefined(options.from[i])) options.from[i] = this.object.props(i); } /** * timing function */ this.ease = options.ease || Tween.Ease.InOut; /** * from pose */ this.from = options.from; /** * to pose */ this.to = options.to; } /** * calculate next frame pose * @private * @return {object} pose state */ nextPose() { const pose = {}; const t = this.ease(this.progress / this.duration); for (const i in this.to) { pose[i] = this.linear(this.from[i], this.to[i], t); this.object.props(i, pose[i]); } return pose; } }
JavaScript
class AnteiGuild extends Guild { /** * @typedef {external:GuildJSON} AnteiGuildJSON * @property {SettingsJSON} settings The per guild settings */ /** * @param {...*} args Normal D.JS Guild args */ constructor(...args) { super(...args); /** * The guild level settings for this context (guild || default) * @since 0.0.1 * @type {Settings} */ this.settings = this.client.gateways.guilds.get(this.id, true); } /** * The language configured for this guild * @type {?Language} */ get language() { return this.client.languages.get(this.settings.language) || null; } /** * Returns the JSON-compatible object of this instance. * @since 0.0.1 * @returns {AnteiGuildJSON} */ toJSON() { return { ...super.toJSON(), settings: this.settings.toJSON() }; } }
JavaScript
class LoggedUsers { constructor() { this.users = new Map(); } userInfoByID(userID) { return this.users.get(userID); } userInfoBySocketID(socketID) { for (var [userID, userInfo] of this.users) { if (userInfo.socketID == socketID) { return userInfo; } } return null; } addUserInfo(user, socketID) { let userInfo = {user: user, socketID: socketID}; this.users.set(user.id, userInfo); return userInfo; } removeUserInfoByID(userID) { let userInfo = this.userInfoByID(userID); if (userInfo === null) { return null; } let cloneUserInfo = Object.assign({}, userInfo); this.users.delete(userID); return cloneUserInfo; } removeUserInfoBySocketID(socketID) { let userInfo = this.userInfoBySocketID(socketID); if (userInfo === null) { return null; } let cloneUserInfo = Object.assign({}, userInfo); this.users.delete(userInfo.user.id); return cloneUserInfo; } getUsersInfoOfDepartment(departmentID) { let usersInfo= []; for (var [userID, userInfo] of this.users) { if (userInfo.user.department_id == departmentID) { usersInfo.push(userInfo); } } return usersInfo; } }
JavaScript
class Checkbox extends React.Component { constructor(props) { super(props); this.state = {checked: props.checked}; } componentWillReceiveProps(newProps) { this.setState({checked: newProps.checked}); } render() { const {checked} = this.state; return ( <input type="checkbox" checked={checked} {...omit(['checked', 'setProps'], this.props)} onClick={() => { if (this.props.setProps) { this.props.setProps({ checked: !checked }); } else { this.setState({checked: !checked}); } }} data-dash-is-loading={ (this.props.loading_state && this.props.loading_state.is_loading) || undefined } /> ); } }
JavaScript
class DestroyerService extends Service { /** * i18n service used to translate notifications messages. * * @access private * @type {Intl} */ @service('intl') intl; /** * Sweet Alert service used to show the confirmation dialog. * * @access private * @type {Swal} */ @service('swal') swal; /** * Notify service that creates alert notifications * * @access private * @type {Notify} */ @service('notify') notify; /** * Error resolver service used to resolve the error that occurred during destructuring of a model. * * @access private * @type {ErrorResolver} */ @service('error-resolver') resolver; /** * Executes the `execute` task that would acutally performs the removal of the model in question. * This method returms a `Promise` that is empty. * * @param {DS.Model|Object} model Model to be destroyed * @param {Object} options Options for the executor * @param {Function} options.save Save hook that is invoked by the executor, defaults to `model.save()` * @param {Object} options.success Success message that is shown when the model is destroyed * @returns {Promise} */ // eslint-disable-next-line ember/classic-decorator-hooks destroy(model, options = {}) { return this.executor.perform(model, options); } /** * Ember Concurrent task that performs the destruction of the model. * * @access private * @type {Task} */ @task({ drop: true }) * executor(model = null, options = {}) { if (model == null) { return null; } // expand the options and assign the defaults const { destroy, success, ...labels } = defaults({ ...options }, { destroy: defaultDestroy, success: DEFAULT_DELETED_MESSAGE, title: CONFIRM_DELETE_TITLE_MESSAGE, text: CONFIRM_DELETE_TEXT_MESSAGE, cancelButtonText: CONFIRM_DELETE_CANCEL_MESSAGE, confirmButtonText: CONFIRM_DELETE_CONFIRM_MESSAGE, showConfirmation: true, }); log('Attempting to destroy model:', model); assert('Invalid `destroy` option parameter. It needs to be a function', isFunction(destroy)); assert('Invalid `success` option parameter. It needs to be a string', isString(success)); let result = null; try { result = yield perform(this.swal, this.intl, destroy, model, labels); if (result === null) { return result; } handleSuccess(this.intl, this.notify, success); } catch (error) { if (isAbortError(error)) { return model; } handleError(error, model, this.resolver); } return result; } }
JavaScript
class NoopChange { constructor() { this.description = 'No operation.'; this.order = Infinity; this.path = null; } apply() { return Promise.resolve(); } }
JavaScript
class InsertChange { constructor(path, pos, toAdd) { this.path = path; this.pos = pos; this.toAdd = toAdd; if (pos < 0) { throw new Error('Negative positions are invalid'); } this.description = `Inserted ${toAdd} into position ${pos} of ${path}`; this.order = pos; } /** * This method does not insert spaces if there is none in the original string. */ apply(host) { return host.read(this.path).then(content => { const prefix = content.substring(0, this.pos); const suffix = content.substring(this.pos); return host.write(this.path, `${prefix}${this.toAdd}${suffix}`); }); } }
JavaScript
class RemoveChange { constructor(path, pos, toRemove) { this.path = path; this.pos = pos; this.toRemove = toRemove; if (pos < 0) { throw new Error('Negative positions are invalid'); } this.description = `Removed ${toRemove} into position ${pos} of ${path}`; this.order = pos; } apply(host) { return host.read(this.path).then(content => { const prefix = content.substring(0, this.pos); const suffix = content.substring(this.pos + this.toRemove.length); // TODO: throw error if toRemove doesn't match removed string. return host.write(this.path, `${prefix}${suffix}`); }); } }
JavaScript
class ReplaceChange { constructor(path, pos, oldText, newText) { this.path = path; this.pos = pos; this.oldText = oldText; this.newText = newText; if (pos < 0) { throw new Error('Negative positions are invalid'); } this.description = `Replaced ${oldText} into position ${pos} of ${path} with ${newText}`; this.order = pos; } apply(host) { return host.read(this.path).then(content => { const prefix = content.substring(0, this.pos); const suffix = content.substring(this.pos + this.oldText.length); const text = content.substring(this.pos, this.pos + this.oldText.length); if (text !== this.oldText) { return Promise.reject(new Error(`Invalid replace: "${text}" != "${this.oldText}".`)); } // TODO: throw error if oldText doesn't match removed string. return host.write(this.path, `${prefix}${this.newText}${suffix}`); }); } }
JavaScript
class WorkbenchPage extends React.Component { constructor(props) { super(props); } _init() { this._initNavigatorDelegates(); } _initNavigatorDelegates() { let _srv = this.props.srv.getServiceByName("workbenchNavigatorService"); if (!_srv) { return false; } let _updated = _srv.addDelegates({ delegates: { hamburgerIconClick: this._navigatorHamburgerClick, navLoginLogoutClick: this._navigatorLoginClick, navWikiClick: this._navigatorWikiClick, navAboutClick: this._navigatorAboutClick } }); if (_updated) { console.log('updated delegate for workbenchNavigatorService'); this.props.srv.updateServiceByName("workbenchNavigatorService", _srv); } } /* -------------------------------- */ /* navigator related delegate(s) */ /* - every app should declare */ /* its own delegate */ /* implementations */ /* -------------------------------- */ _navigatorHamburgerClick() { console.log('clicked the hamburger ver2'); } _navigatorLoginClick() { console.log('nav login/logout click'); } _navigatorWikiClick() { console.log('nav wiki clicked'); } _navigatorAboutClick() { console.log('nav about clicked'); } componentDidMount() { this._init(); } render() { return ( <div> <WorkbenchNavigator srv={this.props.srv} /> </div> ); } }
JavaScript
class TerrainGameMode extends GameMode { constructor() { super(); this.world = null; this.character = null; } /** @override */ async load() { // Create world. const renderer = defaultEraRenderer(); this.world = new World() .withPhysics() .addRenderer(renderer) .addCameraForRenderer(Camera.get().buildPerspectiveCamera(), renderer) .withQualityAdjustment(new QualityAdjuster()); // Create environment. const environment = await new Environment().loadFromFile( 'environment.json' ); this.world.setEnvironment(environment); // Create character. this.character = new FreeRoamEntity(); await this.world.add(this.character); this.world.attachCameraToEntity(this.character); Controls.get().registerEntity(this.character); Controls.get().usePointerLockControls(); // Load terrain. await this.loadTerrain(); } /** @override */ async start() {} /** * Generates terrain. * @async */ async loadTerrain() { console.time('load'); textureWorkerPool.prewarm(); const terrainMap = new TerrainMap(/* tileSize= */ 64, /* scale=*/ 40.0); terrainMap.setTerrainTileClass(CustomTerrainTile); await terrainMap.loadFromFile('heightmaps/simple.gltf'); terrainMap.tiles.forEach((tile) => this.world.add(tile)); textureWorkerPool.drain(); console.timeEnd('load'); } }
JavaScript
class V1SessionAffinityConfig { static getAttributeTypeMap() { return V1SessionAffinityConfig.attributeTypeMap; } }
JavaScript
class Data { /** * Do not call the constructor directly. Instead, please use the factory * method "build" to instantiate this class. * @param {!Array<string>} metrics Names of the metrics. Note that index of * the metric names must match to the index of corresponding metric value * in the array of metric values list returned by any element in data. * @param {SeriesList} data An array of Series. Each element can * represent a slice or a version of a model. */ constructor(metrics, data) { /** @private {!Array<string>} */ this.metrics_ = metrics; /** @private {SeriesList} */ this.data_ = data; /** * A lazily initialized object caching numerical metric values. * @private {!Object<!Object<number>>} */ this.cachedNumericalMetricValue_ = {}; /** * The lazily initalized feature strings. * @private {!Array<string>} */ this.cachedFeatureStrings_ = []; /** * Mapping from a feature name to its data series. * This is used to quickly fetch a metric value for a given feature. * @private {!Object<!Series>} */ this.featureDataSeries_ = {}; this.data_.forEach((/** !Series */ dataSeries) => { const feature = dataSeries.getFeatureString(); this.featureDataSeries_[feature] = dataSeries; this.cachedNumericalMetricValue_[feature] = {}; }); } /** * @return {!Array<string>} The keys of the data series feature object. * Empty array in case 'featureDataSeries_' is not defined. * @export */ getFeatureDataSeriesKeys() { if (this.featureDataSeries_) { return Object.keys(this.featureDataSeries_); } return []; } /** * @param {string} metric * @return {number} Index of a given metric in the metric list, or -1 if not * found. * @export */ getMetricIndex(metric) { return this.metrics_.indexOf(metric); } /** * @return {!Array<string>} The metrics list. The returned list should not be * mutated and is treated as read-only. * @export */ getMetrics() { return this.metrics_; } /** * @return {SeriesList} The Series list. The returned list should not be * mutated and is treated as read-only. * @export */ getSeriesList() { return this.data_; } /** * Filters the data series based on the given criterion function. * @param {function(!Series): boolean} filterFn * @return {!Data} Filtered data. * @export */ filter(filterFn) { return new Data(this.metrics_, this.data_.filter(filterFn)); } /** * Computes the value range for a specified column from the DataSeries list. * @param {string} metric Metric name. * @return {{min: number, max: number}} Value range for the specified column. * @export */ getColumnRange(metric) { return this.data_.reduce((prev, cur) => { const feature = cur.getFeatureString(); const value = this.getMetricValue(feature, metric); if (!isNaN(value) && value != null) { return { 'min': Math.min(prev.min, value), 'max': Math.max(prev.max, value) }; } else { // If the metric is not set, exclude it when determining range. return prev; } }, {'min': Infinity, 'max': -Infinity}); } /** * Gets the data series corresponding to a feature. * @param {string} feature Feature of which the data series is to be fetched. * The feature must exist in the data. * @return {!Series|undefined} The data series of the feature. * @private */ getSeries_(feature) { return this.featureDataSeries_[feature]; } /** * @param {string} feature Feature of which the data series is to be fetched. * The feature must exist in the data. * @return {(string|number)} The id for the series with the named feature. The * return value will be an integer if it can be parsed properly or a * string if not. If there is no series matching the feature, simply echo * the feature back. * @export */ getFeatureId(feature) { const series = this.getSeries_(feature); return series && series.getFeatureIdForMatching() || feature; } /** * Gets all the metric values for a given feature. * @param {string} feature Feature of which the metric values are to be * fetched. The feature must exist in the data. * @return {!Array<number>} The metric values for the feature or empty array * if feature not available * @export */ getAllMetricValues(feature) { const series = this.getSeries_(feature); return series ? series.getMetricValuesList() : []; } /** * Gets one metric value for a given feature. If it is a complex type, use * CellRenderer to get the value we use for sorting in table view. If it is * string, parse it as float. The result is cached. * @param {string} feature Feature of which the metric value is to be fetched. * The feature must exist in the data. * @param {string} metric Metric (name) of which the value is to be fetched. * The metric must exist in the data's metric list. * @return {number} The metric value for a feature or NaN if the metric is not * available. * @export */ getMetricValue(feature, metric) { if (this.cachedNumericalMetricValue_[feature][metric] === undefined) { const metricIndex = this.getMetricIndex(metric); let value = this.getAllMetricValues(feature)[metricIndex]; value = value != null ? value : NaN; if (goog.isObject(value)) { value = CellRenderer.renderValue(value)['v']; } else if (typeof value === 'string') { value = parseFloat(value); } this.cachedNumericalMetricValue_[feature][metric] = value; } return this.cachedNumericalMetricValue_[feature][metric]; } /** * @return {!Array<string>} The features of all slices. * @export */ getFeatures() { if (!this.cachedFeatureStrings_.length) { this.cachedFeatureStrings_ = this.data_.map((slice) => { return slice.getFeatureString(); }); } return this.cachedFeatureStrings_; } /** * @param {string} feature * @return {!Array<number|string>} A data table row that contains the feature * in the beginning and then the metric values. * @private */ getDataTableRow_(feature) { const values = this.getAllMetricValues(feature); return [feature].concat(values); } /** * @override * @export */ getDataTable() { return this.data_.map( dataSeries => this.getDataTableRow_(dataSeries.getFeatureString())); } /** * @return {boolean} Whether the data is empty, i.e. has no features or has no * metrics. */ isEmpty() { return !this.data_.length || !this.metrics_.length; } /** * Checks if the two Data's are equal. Two data objects are equal if one is * out from the other but has all the data series as the other one. They * should have the same references to the metrics array and the data series in * the data series list (this.data_). * @param {!Data} data * @return {boolean} Whether the two Data are equal. * @export */ equals(data) { const dataSeriesList = data.getSeriesList(); if (this.metrics_ !== data.getMetrics() || this.data_.length != dataSeriesList.length) { return false; } for (let i = 0; i < this.data_.length; i++) { if (this.data_[i] !== dataSeriesList[i]) { return false; } } return true; } /** * Metrics data is always ready to render. * @override * @export */ readyToRender() { return !this.isEmpty(); } /** * @override * @export */ getHeader(requiredColumns) { return [Constants.Column.FEATURE].concat(requiredColumns); } /** * @override * @export */ getFormats(specifiedFormats) { const desiredFormats = Object.assign({}, specifiedFormats); desiredFormats[Constants.Column.FEATURE] = { 'type': Constants.MetricValueFormat.ROW_ID }; return desiredFormats; } /** * @override * @export */ applyOverride(value, override) { const transform = override['transform']; return transform ? transform(value) : value; } }
JavaScript
class Series { /** * @param {string} columnName * @param {string} featureString * @param {!Array<SeriesValue>} values */ constructor(columnName, featureString, values) { /** * @private {string} */ this.columnName_ = columnName; /** * @private {string} */ this.featureString_ = featureString; /** * @private {number} */ this.parsedFeatureId_ = CellRenderer.parseRowId(featureString); /** * The feature id used for matching. * @private {string|number} */ this.featureIdForMatching_ = isNaN(this.parsedFeatureId_) ? this.featureString_ : this.parsedFeatureId_; /** * @private {!Array<SeriesValue>} */ this.values_ = values; } /** * @return {string} Returns the column name associated with this row. */ getColumnName() { return this.columnName_; } /** * @return {string} Returns the feature id of this row. * @export */ getFeatureString() { return this.featureString_; } /** * @return {string|number} Returns the parsed feature id. * @export */ getFeatureIdForMatching() { return this.featureIdForMatching_; } /** * @return {!Array<SeriesValue>} Returns the metric value list. * @export */ getMetricValuesList() { return this.values_; } }
JavaScript
class HdtDatasource extends Datasource { constructor(options) { let supportedFeatureList = ['quadPattern', 'triplePattern', 'limit', 'offset', 'totalCount']; super(options, supportedFeatureList); options = options || {}; // Switch to external HDT datasource if the `external` flag is set if (options.external) return new ExternalHdtDatasource(options); this._hdtFile = (options.file || '').replace(/^file:\/\//, ''); } // Loads the HDT datasource async _initialize() { this._hdtDocument = await hdt.fromFile(this._hdtFile); } // Writes the results of the query to the given quad stream _executeQuery(query, destination) { // Only the default graph has results if (query.graph && query.graph.termType !== 'DefaultGraph') { destination.setProperty('metadata', { totalCount: 0, hasExactCount: true }); destination.close(); return; } let dataFactory = this.dataFactory; this._hdtDocument.searchTriples(query.subject ? RdfString.termToString(query.subject) : null, query.predicate ? RdfString.termToString(query.predicate) : null, query.object ? RdfString.termToString(query.object) : null, { limit: query.limit, offset: query.offset }) .then((result) => { let triples = result.triples, estimatedTotalCount = result.totalCount, hasExactCount = result.hasExactCount; // Ensure the estimated total count is as least as large as the number of triples let tripleCount = triples.length, offset = query.offset || 0; if (tripleCount && estimatedTotalCount < offset + tripleCount) estimatedTotalCount = offset + (tripleCount < query.limit ? tripleCount : 2 * tripleCount); destination.setProperty('metadata', { totalCount: estimatedTotalCount, hasExactCount: hasExactCount }); // Add the triples to the output for (let i = 0; i < tripleCount; i++) destination._push(RdfString.stringQuadToQuad(triples[i], dataFactory)); destination.close(); }, (error) => { destination.emit('error', error); }); } // Closes the data source close(done) { // Close the HDT document if it is open if (this._hdtDocument) { this._hdtDocument.close().then(done, done); delete this._hdtDocument; } // If initialization was still pending, close immediately after initializing else if (!this.initialized) this.on('initialized', this.close.bind(this, done)); } }
JavaScript
class RouteComponentRenderer extends Component { componentDidMount() { // Calling loadData on initial rendering (on client side). callLoadData(this.props); handleLocationChanged(this.props.dispatch, this.props.location); } componentDidUpdate(prevProps) { // Call for handleLocationChanged affects store/state // and it generates an unnecessary update. if (prevProps.location !== this.props.location) { // Calling loadData after initial rendering (on client side). // This makes it possible to use loadData as default client side data loading technique. // However it is better to fetch data before location change to avoid "Loading data" state. callLoadData(this.props); handleLocationChanged(this.props.dispatch, this.props.location); } } render() { const { route, match, location, staticContext } = this.props; const { component: RouteComponent, authPage = 'SignupPage', extraProps } = route; const canShow = canShowComponent(this.props); if (!canShow) { staticContext.unauthorized = true; } return canShow ? ( <LoadableComponentErrorBoundary> <RouteComponent params={match.params} location={location} {...extraProps} /> </LoadableComponentErrorBoundary> ) : ( <NamedRedirect name={authPage} state={{ from: `${location.pathname}${location.search}${location.hash}` }} /> ); } }
JavaScript
class Component extends Entity { /** * Component constructor * * @constructor * @param {Object} attributes */ constructor (attributes) { // @debug // console.log('LVL99:Component:constructor', { // arguments // }) super(attributes) } /** * Extend the Component's properties with any {Object} arguments */ extend () { // @debug // console.log('LVL99:Component:extend', { // arguments // }) // Concat all the publicMethods into one array (since merge doesn't do that with plain arrays) let args = [...arguments] let allPublicMethods = ComponentProperties._properties.publicMethods.slice(0) args.forEach((arg) => { let hasPublicMethods = objectPath.get(arg, '_properties.publicMethods') if (hasPublicMethods && hasPublicMethods instanceof Array) { allPublicMethods = allPublicMethods.concat(hasPublicMethods) } }) allPublicMethods = Array.from(new Set(allPublicMethods)) // Extend the component's properties with the instantiated attributes and concatenated public methods super.extend(ComponentProperties, ...args, { _properties: { publicMethods: allPublicMethods } }) } /** * Get the component's element * * @return {undefined|jQueryObject} */ getElem () { // Soft return if (!this.getAttr('elem') && (!this.getAttr('$elem') || !this.getAttr('$elem').length)) { console.warn(`${this.NS}.getElem: no elem was found for this component. This may cause problems with components which rely on the elem attribute.`) return undefined } // Elem (or $elem) is set to string if (typeof this.getAttr('elem') === 'string' || typeof this.getAttr('$elem') === 'string') { let $elem = $(this.getAttr('elem')) if ($elem.length) { this.setAttr('elem', $elem[0]) this.setAttr('$elem', $elem) } } // Get & set the element if (this.getAttr('elem') && !this.getAttr('$elem')) { this.setAttr($(this.getAttr('elem'))) } return this.getAttr('$elem') } /** * Mark the Component's element with necessary attributes */ markElem () { // Mark the element if (this.getElem() && this.getElem().length) { if (!this.getElem().attr('data-component')) { this.getElem().attr('data-component', this.NS) } if (!this.getElem().attr('data-component-id')) { this.getElem().attr('data-component-id', this.uuid) } this.triggerEvent('markElem:end') } } /** * Get the target to apply the CSS state classes to * * @return {undefined|jQueryObject} */ getClassTarget () { // Prioritise attr let $classTarget = this.getAttr('$classTarget') // Not found in attr? Use prop if (!$classTarget || !$classTarget.length) { $classTarget = this.getProp('$classTarget') } // Not found in prop? Use elem if (!$classTarget || !$classTarget.length) { $classTarget = this.getElem() // Ensure set as attr this.setAttr('$classTarget', $classTarget) } return $classTarget } /** * Get the attributes from the DOM element and place into the Component instance * * @return {Object} */ loadAttrs () { if (this.getElem() && this.getElem().is('[data-component-attributes]')) { let attrs = {} // Attempt to get the attributes from the DOM element try { attrs = JSON.parse(this.getElem().attr('data-component-attributes')) } catch (e) { console.error(`[${this.NS}] loadAttrs: Error loading attributes from DOM element`) } this._attributes = merge(this._attributes, attrs) // Once loaded, remove the component attributes from the DOM this.getElem().removeAttr('data-component-attributes') return this._attributes } } /** * Initialise Component */ init () { super.init(...arguments) // @debug // console.log(`[${this.NS:init}]`) // Track that the component has been initialised if (!trackComponents.hasOwnProperty(this.NS)) { trackComponents[this.NS] = { instances: { [`${this.uuid}`]: this } } } else { trackComponents[this.NS].instances[`${this.uuid}`] = this } // @debug // console.log(trackComponents) // Mark the element this.markElem() /** * Attach Component's public methods to targets * Public methods can be triggered on the targets via `$(target).trigger('NAMESPACE:publicMethodName')` */ let publicMethods = this.getProp('publicMethods') if (publicMethods && publicMethods.length) { publicMethods.forEach((trigger) => { let triggerDetails = {} // Already object if (typeof trigger === 'object') { triggerDetails = trigger } else if (typeof trigger === 'string') { if (/^{/.test(trigger) || /[:;]/.test(trigger)) { triggerDetails = extractTriggerDetails(trigger) } else { triggerDetails.do = trigger } } // If empty, set `on` to `do` value (consider it a custom event to invoke, e.g. 'init' would invoke 'init' on this Component) if (!objectPath.has(triggerDetails, 'on')) { triggerDetails.on = triggerDetails.do } // Context should always be this Component triggerDetails.context = this // Get the Component's method let method = undefined try { method = triggerDetails.context[triggerDetails.do] } catch (e) { throw new Error(`[${this.NS}] init: public method '${triggerDetails.do}' was not found on this component`) } // @debug // console.log(`[${this.NS}] init: public method "${triggerDetails.do}"`, { // triggerDetails, // method // }) // Only attach public method if it hasn't been attached already or has a target if (!triggerDetails.hasOwnProperty('target') && Object.keys(trackComponents[this.NS].instances).length > 1) { // @debug // console.warn(`[${this.NS}] init: public method ${this.NS}:${triggerDetails.do} already assigned. Skipping...`) return } // Attach the method as a custom event to the target if (typeof method === 'function') { // Wrap the method into a closure let doComponentMethod = (jQueryEvent) => { // @debug // console.log(`Triggered ${this.NS}:${triggerDetails.do}`, { // _class: this, // _method: method, // jQueryEvent, // args: arguments // }) method.call(this, jQueryEvent) } // Attach to the target document with a particular element selector if (triggerDetails.selector) { this.bindEventToTargetSelector(triggerDetails.on, triggerDetails.selector, doComponentMethod, triggerDetails.target) // Attach to the target } else { this.bindEventToTarget(triggerDetails.on, doComponentMethod, triggerDetails.target) } // Error } else { // @debug // console.log(this, trigger, triggerDetails) throw new Error(`[${this.NS}] init: public method '${triggerDetails.do}' is not a valid function`) } }) } /** * Load any attributes that were attached to the DOM element */ this.loadAttrs() /** * @trigger NAMESPACE:init:end * @param {Component} */ this.triggerEvent('init:end') } /** * Destroy and tear down the component */ destroy () { // @TODO tear down the house! // @TODO remove the bound public events // @TODO other garbage collection/memory management /** * @trigger NAMESPACE:destroy:beforeend * @param {Component} */ this.triggerEvent('destroy:beforeend') super.destroy(...arguments) } /** * Bind method to custom event on target * Event names are automatically namespaced using the Component's _NS property. * To not use namespaced events, preface with `dom:` * * @param {String} eventName * @param {Function} method * @param {Object} target Default is `document`. This is the target DOM element which the custom event will bubble up to */ bindEventToTarget (eventName, method, target) { // Default to document if (!target) { target = document } else { // Special string values to get the actual object switch (target) { case 'document': target = document break case 'window': target = window break case 'self': target = this.getElem()[0] break } } // Extract the target event names from the input given let eventNames = extractTargetEventNames(eventName, this.NS) // @debug // console.log(`[${this.NS}] bindEventToTarget`, { // eventName, // method, // target, // triggerName: targetEventNames // }) // Assign the trigger if (eventNames) { $(target).on(eventNames.join(' '), method) } } /** * Bind method to custom event on target with an element selector. * Event names are automatically namespaced using the Component's _NS property. * * @param {String} eventName * @param {String} selector Target a specific element (via query selector) to trigger the event * @param {Function} method * @param {Object} target Default is `document`. This is the target DOM element which the custom event will bubble up to */ bindEventToTargetSelector (eventName, selector, method, target) { target = getTargetBySelector(target, this) selector = getTargetSelector(selector, this) let eventNames = extractTargetEventNames(eventName, this.NS) // @debug // console.log(`[${this.NS}] bindEventToTargetSelector`, { // eventName, // selector, // method, // target, // triggerName: `${this.NS}:${eventName}` // }) if (eventNames) { $(target).on(eventNames.join(' '), selector, method) } } /** * Trigger a custom document event on the Component. * The event triggered will be `NAMESPACE:eventName`. * * @param {String} eventName * @param {Any} ...args */ triggerEvent (eventName, ...args) { // @debug // console.log(`[${this.NS}] triggerEvent: ${this.NS}:${eventName}`) // Always pass the component as the first argument parameter $doc.trigger(`${this.NS}:${eventName}`, [this, ...args]) } /** * Trigger a custom document event on an element on the Component. * The event triggered will be `NAMESPACE:eventName`. * * @param {String} eventName * @param {String} selector * @param {Any} ...args */ triggerEventOnSelector (eventName, selector, ...args) { selector = getTargetSelector(selector, this) // @debug // console.log(`[${this.NS}] triggerEventOnSelector: ${this.NS}:${eventName}`) // Always pass the component as the first argument parameter $(selector).trigger(`${this.NS}:${eventName}`, [this, ...args]) } }
JavaScript
class CcPricingProduct extends LitElement { static get properties () { return { action: { type: String }, currency: { type: Object }, description: { type: String }, error: { type: Boolean, reflect: true }, features: { type: Array }, icon: { type: String }, name: { type: String }, plans: { type: Array }, temporality: { type: Array }, }; } constructor () { super(); this.action = 'add'; this.currency = CURRENCY_EUR; this.features = []; this.temporality = DEFAULT_TEMPORALITY; } _onAddPlan ({ detail: plan }) { const productName = this.name; dispatchCustomEvent(this, 'add-plan', { productName, ...plan }); } render () { const skeleton = (this.plans == null || this.features == null); const name = skeleton ? SKELETON_NAME : this.name; const description = skeleton ? SKELETON_DESCRIPTION : this.description; return html` <slot name="head"> <div class="head"> <div class="head-info"> <slot name="icon"> <cc-img class="product-logo" src="${ifDefined(this.icon)}" ?skeleton="${skeleton}"></cc-img> </slot> <div class="name"> <slot name="name"> <span class="${classMap({ skeleton })}">${name}</span> </slot> </div> </div> ${skeleton && !this.error ? html` <slot> <div> <span class="description skeleton">${description}</span> </div> </slot> ` : ''} ${!skeleton && !this.error ? html` <slot>${description}</slot> ` : ''} </div> </slot> ${this.error ? html` <cc-error>${i18n('cc-pricing-product.error')}</cc-error> ` : ''} ${skeleton && !this.error ? html` <cc-loader></cc-loader> ` : ''} ${!skeleton && !this.error ? html` <cc-pricing-table class="pricing-table" .plans=${this.plans} .features=${this.features} .currency=${this.currency} .temporality=${this.temporality} action=${this.action} @cc-pricing-table:add-plan=${this._onAddPlan} ></cc-pricing-table> ` : ''} `; } static get styles () { return [ // language=CSS skeletonStyles, css` :host { background-color: #ffffff; display: block; } .head { display: grid; gap: 1em; grid-auto-rows: min-content; padding: 1em; } /* We cannot use cc-flex-gap because of a double slot */ .head-info { display: flex; flex-wrap: wrap; /* reset gap for browsers that support gap for flexbox */ gap: 0; margin: -0.5em; } .product-logo, slot[name="icon"]::slotted(*), .name { margin: 0.5em; } .product-logo, slot[name=icon]::slotted(*) { --cc-img-fit: contain; border-radius: 0.25em; display: block; height: 3em; width: 3em; } .name { align-self: center; font-size: 1.5em; font-weight: bold; } /* Slotted description */ .description { line-height: 1.5; } .pricing-table { overflow: auto; } .skeleton { background-color: #bbb; } :host([error]) .skeleton, :host([error]) [skeleton] { --cc-skeleton-state: paused; } cc-loader { min-height: 20em; } cc-error { padding: 0 1em 1em; } `, ]; } }
JavaScript
class Login extends React.Component { constructor(props) { super(props); this.state = {} this.loginUser = this.loginUser.bind(this); this.verifyUser = this.verifyUser.bind(this); } loginUser(e) { e.preventDefault(); const email = document.getElementById('login-email').value; const password = document.getElementById('login-password').value; let userData = {}; userData.email = email; userData.password = password; this.verifyUser(userData); } verifyUser(userData) { let that = this; let xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if(xhr.status === 302 && xhr.readyState === 4) { let userData = JSON.parse(xhr.responseText); localStorage.setItem('token', userData.token); localStorage.setItem('userId', userData.id); browserHistory.push('dashboard'); that.props.setUserData(xhr.responseText); } } xhr.open('POST', '/login'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(userData)); } render() { return ( <div> <h3>Login to Dashboard</h3> <form id="login-form" onSubmit={this.loginUser}> <input id="login-email" type="email" name="email" placeholder="email" /> <input id="login-password" type="password" name="password" placeholder="password" /> <button id="login-submit" type="submit">Login to dashboard</button> </form> <h5><Link to="/signup">Sign up</Link></h5> </div> ) } }
JavaScript
class ApplyModification extends Component { static propTypes = { dialogueStage: PropTypes.string.isRequired, applyModification: PropTypes.func.isRequired, setDialogueStage: PropTypes.func.isRequired, }; onConfirm = () => { this.props.setDialogueStage(dialogueStages.closed); this.props.applyModification(); }; onClose = () => { this.props.setDialogueStage(dialogueStages.closed); }; render() { const { dialogueStage } = this.props; if (dialogueStage !== dialogueStages.application) { return null; } return ( <Modal isOpen onRequestClose={this.onClose}> <div className="flex items-center w-full p-3 bg-primary-700 text-xl uppercase text-base-100"> <div className="flex flex-1">Apply Network Policies</div> <Icon.X className="h-4 w-4 cursor-pointer" onClick={this.onClose} /> </div> <div className="leading-normal p-3 border-b border-base-300 bg-base-100"> Applying network policies can impact running deployments. <br /> Do you wish to continue? </div> <div className="flex m-3 justify-end"> <button type="button" className="btn btn-base" onClick={this.onClose}> Cancel </button> <button type="button" className="btn ml-3 bg-primary-600 text-base-100 h-9 hover:bg-primary-700" onClick={this.onConfirm} > Apply </button> </div> </Modal> ); } }
JavaScript
class CountdownButton extends Component { render() { let { myId, btnName, innerClick = null } = this.props; return ( <span onClick = {()=>{ innerClick(myId) }}> <button className="clockButton" onClick={()=>{console.log("Button called")}}>{btnName}</button> </span> ); } }
JavaScript
class EventHubConnectionValidationListResult { /** * Create a EventHubConnectionValidationListResult. * @property {array} [value] The list of Kusto event hub connection * validation errors. */ constructor() { } /** * Defines the metadata of EventHubConnectionValidationListResult * * @returns {object} metadata of EventHubConnectionValidationListResult * */ mapper() { return { required: false, serializedName: 'EventHubConnectionValidationListResult', type: { name: 'Composite', className: 'EventHubConnectionValidationListResult', modelProperties: { value: { required: false, serializedName: 'value', type: { name: 'Sequence', element: { required: false, serializedName: 'EventHubConnectionValidationResultElementType', type: { name: 'Composite', className: 'EventHubConnectionValidationResult' } } } } } } }; } }
JavaScript
class ArgValidationTree { /** * The tree of argument validation definitions and dependencies. * The options at the root of the tree are implied by the options closer to leafs. * Nodes also have links to functions which needs to be executed in order to validate the option. * Not all validation options must be covered by the tree. For example, "anyValueAllowed" validation option * is a modifier which alternates some other validations but does not have an execution function for itself. * @type {Object} */ static get VALIDATION_TREE() { if (this.tree === undefined) { this.tree = Object.freeze({ impliers: { nonNull: { validationFunc: this.isNonNull, impliers: { isSubjects: { validationFunc: this.isSubjects, impliers: { subjectsNonEmpty: { validationFunc: this.areSubjectsNonEmpty }, validSubjects: { validationFunc: this.areValidSubjects }, subjectRolesOnly: { validationFunc: this.areSubjectRolesOnly }, subjectIdsOnly: { validationFunc: this.areSubjectIdsOnly } } }, isChannels: { validationFunc: this.isChannels, impliers: { channelsNonEmpty: { validationFunc: this.areChannelsNonEmpty }, validChannels: { validationFunc: this.areValidChannels }, validTextChannels: { validationFunc: this.areValidTextChannels }, validVoiceChannels: { validationFunc: this.areValidVoiceChannels } } }, isTime: { validationFunc: this.isTime, impliers: { timeDistanceOnly: { validationFunc: this.isTimeDistanceOnly }, timeScheduleOnly: { validationFunc: this.isTimeScheduleOnly }, nonZeroShift: { validationFunc: this.isNonZeroShift } } }, isArray: { validationFunc: this.isArray, impliers: { isIdsArray: { validationFunc: this.isIdsArray } } }, isOnOff: { validationFunc: this.isOnOff }, isInteger: { validationFunc: this.isInteger, impliers: { isNonNegativeInteger: { validationFunc: this.isNonNegativeInteger } } } } } } }); } return this.tree; } /** * Auto-completes validation options according to the dependencies' tree. * Adds validation options which are implied by existing options. * @param {CommandArgDef} argDef the argument definition */ static async autoCompleteValidationOptions(argDef) { const thiz = this; async function onLastEntry(argDef, traversalStack) { const currentElement = traversalStack[traversalStack.length - 1]; // Check each option only once during the traversal, but before its children. if (argDef.validationOptions[currentElement.name] === true) { thiz.autoCompleteValidationFromStack(argDef, traversalStack); } } await this.traverseTreeWithActions(argDef, { onLastEntry }); } /** * Auto-completes validation options according to the current state of the validation tree's traversal stack. * Should be called from a traversal function. * @param {CommandArgDef} argDef the argument definition * @param {Array<Object>} stack the current traversal stack of the validation tree */ static autoCompleteValidationFromStack(argDef, stack) { for (let i = stack.length - 1; i >= 1; i--) { argDef.validationOptions[stack[i].name] = true; } } /** * Validates values of a command's arguments. * @param {Command} command the command to validate */ static async validateCommandArguments(command) { const args = Object.values(command.constructor.getDefinedArgs()); const results = []; for (const argDef of args) { const argValue = command[argDef.name]; results.push(this.validateArgument(argDef, argValue, command)); } await Promise.all(results); } /** * Validates a command's argument value according to it's definition and validation options. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {Command} command the command having the argument */ static async validateArgument(argDef, argValue, command) { async function onFirstEntry(argDef, traversalStack, argValue, command) { const currentElement = traversalStack[traversalStack.length - 1]; // Check each option only once during the traversal, but before its children. if (argDef.validationOptions[currentElement.name] === true) { if (currentElement.func !== undefined) { await currentElement.func(argDef, argValue, command); } } } await this.traverseTreeWithActions(argDef, { onFirstEntry }, argValue, command); } /** * Traverses the validation tree and performs actions at specific points (if such actions are defined). * Can throw errors (for example, if validation is not passed). * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object<Function>} traverseActions the set of functions to be called during the traversal * @param {Object} argDef the argument value (can be undefined, if not running for a command) * @param {Command} command the command instance (can be undefined, if running not for an instance) */ static async traverseTreeWithActions(argDef, traverseActions, argValue, command) { const traversalStack = []; traversalStack.push({ children: this.VALIDATION_TREE.impliers, name: null, childIndex: 0 }); while (traversalStack.length > 0) { const currentElement = traversalStack[traversalStack.length - 1]; let childrenKeys = []; if (currentElement.children !== undefined && currentElement.children !== null) { childrenKeys = Object.keys(currentElement.children); } const currentIndex = currentElement.childIndex; // Tree traversal must be synchronized. /* eslint-disable no-await-in-loop */ if (traverseActions.onFirstEntry !== undefined && traverseActions.onFirstEntry !== null && currentIndex === 0) { await traverseActions.onFirstEntry(argDef, traversalStack, argValue, command); } if (currentIndex >= childrenKeys.length) { if (traverseActions.onLastEntry !== undefined && traverseActions.onLastEntry !== null) { await traverseActions.onLastEntry(argDef, traversalStack, argValue, command); } traversalStack.pop(); if (traversalStack.length > 0) { traversalStack[traversalStack.length - 1].childIndex++; } } else { traversalStack.push({ children: currentElement.children[childrenKeys[currentIndex]].impliers, name: childrenKeys[currentIndex], childIndex: 0, func: currentElement.children[childrenKeys[currentIndex]].validationFunc }); } /* eslint-enable no-await-in-loop */ } } /** * Validates a command's argument value against the nonNull condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {Command} command the command having the argument */ static async isNonNull(argDef, argValue, command) { if (argValue === undefined || argValue === null) { ArgValidationTree.generateValidationError(argDef, command, 'no arg provided:', 'arg_validation_no_arg'); } } /** * Validates a command's argument value against the isSubjects condition. * If singleEntity option is true, then also checks the count of subjects (should be 1). * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {Command} command the command having the argument */ static async isSubjects(argDef, argValue, command) { if (!(argValue instanceof DiscordSubjectsArg)) { ArgValidationTree.generateValidationError( argDef, command, 'wrong subjects provided:', 'arg_validation_wrong_subjects' ); } if (argDef.validationOptions.singleEntity && (argValue.subjectIds.length + argValue.subjectRoles.length) > 1) { ArgValidationTree.generateValidationError(argDef, command, 'subjects array length > 1:', 'arg_validation_non_single_subject_array'); } } /** * Validates a command's argument value against the subjectsNonEmpty condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {Command} command the command having the argument */ static async areSubjectsNonEmpty(argDef, argValue, command) { if (argValue.isEmpty()) { ArgValidationTree.generateValidationError(argDef, command, 'no subjects provided:', 'arg_validation_no_subjects'); } } /** * Validates a command's argument value against the validSubjects condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async areValidSubjects(argDef, argValue, command) { if (!(argDef.validationOptions.anyValueAllowed === true && argValue.subjectIds[0] === OhUtils.ANY_VALUE)) { if (await argValue.validateDiscordSubjectsArg(command.context, command.orgId)) { ArgValidationTree.generateValidationError( argDef, command, 'wrong subjects provided:', 'arg_validation_wrong_subjects' ); } } } /** * Validates a command's argument value against the subjectRolesOnly condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async areSubjectRolesOnly(argDef, argValue, command) { if (!(argDef.validationOptions.anyValueAllowed === true && argValue.subjectIds[0] === OhUtils.ANY_VALUE)) { if (argValue.subjectIds.length > 0) { ArgValidationTree.generateValidationError( argDef, command, 'subject ids provided instead of roles:', 'arg_validation_only_roles_allowed' ); } } } /** * Validates a command's argument value against the subjectIdsOnly condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async areSubjectIdsOnly(argDef, argValue, command) { if (!(argDef.validationOptions.anyValueAllowed === true && argValue.subjectIds[0] === OhUtils.ANY_VALUE)) { if (argValue.subjectRoles.length > 0) { ArgValidationTree.generateValidationError( argDef, command, 'subject roles provided instead of ids:', 'arg_validation_only_ids_allowed' ); } } } /** * Validates a command's argument value against the isChannels condition. * If singleEntity option is true, then also checks the count of channels (should be 1). * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async isChannels(argDef, argValue, command) { if (!(argValue instanceof DiscordChannelsArg)) { ArgValidationTree.generateValidationError( argDef, command, 'wrong channels provided:', 'arg_validation_wrong_channels' ); } if (argDef.validationOptions.singleEntity && argValue.channels.length > 1) { ArgValidationTree.generateValidationError(argDef, command, 'channels array length > 1:', 'arg_validation_non_single_channel_array'); } } /** * Validates a command's argument value against the channelsNonEmpty condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async areChannelsNonEmpty(argDef, argValue, command) { if (argValue.isEmpty()) { ArgValidationTree.generateValidationError(argDef, command, 'no channels provided:', 'arg_validation_no_channels'); } } /** * Validates a command's argument value against the validChannels condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async areValidChannels(argDef, argValue, command) { if (!(argDef.validationOptions.anyValueAllowed === true && argValue.channels[0] === OhUtils.ANY_VALUE)) { if (await argValue.validateDiscordChannelsArg(command.context, command.orgId)) { ArgValidationTree.generateValidationError( argDef, command, 'wrong channels provided:', 'arg_validation_wrong_channels' ); } } } /** * Validates a command's argument value against the validTextChannels condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async areValidTextChannels(argDef, argValue, command) { if (!(argDef.validationOptions.anyValueAllowed === true && argValue.channels[0] === OhUtils.ANY_VALUE)) { if (await argValue.validateDiscordTextChannelsArg(command.context, command.orgId)) { ArgValidationTree.generateValidationError( argDef, command, 'wrong text channels provided:', 'arg_validation_wrong_text_channels' ); } } } /** * Validates a command's argument value against the validVoiceChannels condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async areValidVoiceChannels(argDef, argValue, command) { if (!(argDef.validationOptions.anyValueAllowed === true && argValue.channels[0] === OhUtils.ANY_VALUE)) { if (await argValue.validateDiscordVoiceChannelsArg(command.context, command.orgId)) { ArgValidationTree.generateValidationError( argDef, command, 'wrong voice channels provided:', 'arg_validation_wrong_voice_channels' ); } } } /** * Validates a command's argument value against the isTime condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async isTime(argDef, argValue, command) { if (!(argValue instanceof TimeArg)) { ArgValidationTree.generateValidationError(argDef, command, 'wrong time provided:', 'arg_validation_wrong_time'); } } /** * Validates a command's argument value against the timeDistanceOnly condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async isTimeDistanceOnly(argDef, argValue, command) { if (argValue.timeType !== TimeArg.DISTANCE_TYPE) { ArgValidationTree.generateValidationError( argDef, command, 'schedule provided instead of distance:', 'arg_validation_time_only_distance_allowed' ); } } /** * Validates a command's argument value against the timeScheduleOnly condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async isTimeScheduleOnly(argDef, argValue, command) { if (argValue.timeType !== TimeArg.SCHEDULE_TYPE && argValue.timeType !== TimeArg.SCHEDULE_REPEAT_TYPE) { ArgValidationTree.generateValidationError( argDef, command, 'distance provided instead of schedule:', 'arg_validation_time_only_schedule_allowed' ); } } /** * Validates a command's argument value against the nonZeroShift condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async isNonZeroShift(argDef, argValue, command) { if (argValue.timeType === TimeArg.DISTANCE_TYPE && argValue.totalMillisecondsShift === 0) { ArgValidationTree.generateValidationError(argDef, command, '0 shift time:', 'arg_validation_time_zero_shift'); } } /** * Validates a command's argument value against the isArray condition. * If singleEntity option is true, then also checks the count of elements (should be 1). * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async isArray(argDef, argValue, command) { if (!Array.isArray(argValue)) { ArgValidationTree.generateValidationError(argDef, command, 'wrong array:', 'arg_validation_wrong_array'); } if (argDef.validationOptions.singleEntity && argValue.length > 1) { ArgValidationTree.generateValidationError(argDef, command, 'array length > 1:', 'arg_validation_non_single_entity_array'); } } /** * Validates a command's argument value against the isIdsArray condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async isIdsArray(argDef, argValue, command) { for (const value of argValue) { if (!value.match(/^\d+$/) || Number.parseInt(value, 10) < 0) { ArgValidationTree.generateValidationError( argDef, command, 'wrong ids array:', 'arg_validation_wrong_ids_array' ); } } } /** * Validates a command's argument value against the isOnOff condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {Command} command the command having the argument */ static async isOnOff(argDef, argValue, command) { if (typeof argValue !== 'boolean') { const acceptableStrings = [ command.langManager.getString('arg_boolean_off'), command.langManager.getString('arg_boolean_on'), command.langManager.getString('arg_boolean_false'), command.langManager.getString('arg_boolean_true') ]; ArgValidationTree.generateValidationError(argDef, command, 'wrong on/off arg:', 'arg_validation_wrong_on_off', [ acceptableStrings.join(', ') ]); } } /** * Validates a command's argument value against the isInteger condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async isInteger(argDef, argValue, command) { if (!argValue.match(/^[-+]?\d+$/) || argValue === '') { ArgValidationTree.generateValidationError( argDef, command, 'wrong integer:', 'arg_validation_wrong_integer' ); } } /** * Validates a command's argument value against the isNonNegativeInteger condition. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Object} argValue the argument value * @param {string} commandName the command name */ static async isNonNegativeInteger(argDef, argValue, command) { if (Number.parseInt(argValue, 10) < 0) { ArgValidationTree.generateValidationError( argDef, command, 'wrong non-negative integer:', 'arg_validation_wrong_non_negative_integer' ); } } /** * Creates and throws a public error as a result of validation violation for an argument. * @throws BotPublicError * @param {CommandArgDef} argDef the argument definition * @param {Command} command the command having the argument * @param {string} logText the string to be logged internally * @param {string} publicTextId the id of the text to be displayed to the users * @param {Array<string>} additionalArguments the additional arguments for the public string (besides the alias) */ static generateValidationError(argDef, command, logText, publicTextId, additionalArguments) { const commandName = command.constructor.getCommandInterfaceName(); const mainAlias = command.langManager.getString(argDef.aliasIds[0]); let publicTextsArray = [mainAlias]; if (additionalArguments !== undefined) { publicTextsArray = publicTextsArray.concat(additionalArguments); } command.context.log.e(commandName + ' validateArgs: ' + logText + ' ' + mainAlias); throw new BotPublicError(command.langManager.getString(publicTextId, publicTextsArray)); } }
JavaScript
class Parser { options = { ...defaults }; // The resStore stores all translation keys including unused ones resStore = {}; // The resScan only stores translation keys parsed from code resScan = {}; // The all plurals suffixes for each of target languages. pluralSuffixes = {}; constructor(options) { this.options = normalizeOptions({ ...this.options, ...options }); const lngs = this.options.lngs; const namespaces = this.options.ns; lngs.forEach((lng) => { this.resStore[lng] = this.resStore[lng] || {}; this.resScan[lng] = this.resScan[lng] || {}; this.pluralSuffixes[lng] = ensureArray(getPluralSuffixes(lng, this.options.pluralSeparator)); if (this.pluralSuffixes[lng].length === 0) { this.log(`No plural rule found for: ${lng}`); } namespaces.forEach((ns) => { const resPath = this.formatResourceLoadPath(lng, ns); this.resStore[lng][ns] = {}; this.resScan[lng][ns] = {}; try { if (fs.existsSync(resPath)) { this.resStore[lng][ns] = JSON.parse(fs.readFileSync(resPath, 'utf-8')); } } catch (err) { this.error(`Unable to load resource file ${chalk.yellow(JSON.stringify(resPath))}: lng=${lng}, ns=${ns}`); this.error(err); } }); }); this.log(`options=${JSON.stringify(this.options, null, 2)}`); } log(...args) { const { debug } = this.options; if (debug) { console.log.apply(this, [chalk.cyan('i18next-scanner:')].concat(args)); } } error(...args) { console.error.apply(this, [chalk.red('i18next-scanner:')].concat(args)); } formatResourceLoadPath(lng, ns) { const options = this.options; const regex = { lng: new RegExp(_.escapeRegExp(options.interpolation.prefix + 'lng' + options.interpolation.suffix), 'g'), ns: new RegExp(_.escapeRegExp(options.interpolation.prefix + 'ns' + options.interpolation.suffix), 'g') }; return options.resource.loadPath .replace(regex.lng, lng) .replace(regex.ns, ns); } formatResourceSavePath(lng, ns) { const options = this.options; const regex = { lng: new RegExp(_.escapeRegExp(options.interpolation.prefix + 'lng' + options.interpolation.suffix), 'g'), ns: new RegExp(_.escapeRegExp(options.interpolation.prefix + 'ns' + options.interpolation.suffix), 'g') }; return options.resource.savePath .replace(regex.lng, lng) .replace(regex.ns, ns); } fixStringAfterRegExp(strToFix) { let fixedString = _.trim(strToFix); // Remove leading and trailing whitespace const firstChar = fixedString[0]; // Ignore key with embedded expressions in string literals if (firstChar === '`' && fixedString.match(/\${.*?}/)) { if (fixedString.endsWith('}`')) { fixedString = fixedString.replace(/\$\{(.+?)\}/g, ""); } else { return null } } if (_.includes(['\'', '"', '`'], firstChar)) { // Remove first and last character fixedString = fixedString.slice(1, -1); } // restore multiline strings fixedString = fixedString.replace(/(\\\n|\\\r\n)/g, ''); // JavaScript character escape sequences // https://mathiasbynens.be/notes/javascript-escapes // Single character escape sequences // Note: IE < 9 treats '\v' as 'v' instead of a vertical tab ('\x0B'). If cross-browser compatibility is a concern, use \x0B instead of \v. // Another thing to note is that the \v and \0 escapes are not allowed in JSON strings. fixedString = fixedString.replace(/(\\b|\\f|\\n|\\r|\\t|\\v|\\0|\\\\|\\"|\\')/g, (match) => eval(`"${match}"`)); // * Octal escapes have been deprecated in ES5. // * Hexadecimal escape sequences: \\x[a-fA-F0-9]{2} // * Unicode escape sequences: \\u[a-fA-F0-9]{4} fixedString = fixedString.replace(/(\\x[a-fA-F0-9]{2}|\\u[a-fA-F0-9]{4})/g, (match) => eval(`"${match}"`)); return fixedString; } // i18next.t('ns:foo.bar') // matched // i18next.t("ns:foo.bar") // matched // i18next.t('ns:foo.bar') // matched // i18next.t("ns:foo.bar", { count: 1 }); // matched // i18next.t("ns:foo.bar" + str); // not matched parseFuncFromString(content, opts = {}, customHandler = null) { if (_.isFunction(opts)) { customHandler = opts; opts = {}; } const funcs = (opts.list !== undefined) ? ensureArray(opts.list) : ensureArray(this.options.func.list); if (funcs.length === 0) { return this; } const matchFuncs = funcs .map(func => ('(?:' + func + ')')) .join('|') .replace(/\./g, '\\.'); // `\s` matches a single whitespace character, which includes spaces, tabs, form feeds, line feeds and other unicode spaces. const matchSpecialCharacters = '[\\r\\n\\s]*'; const stringGroup = matchSpecialCharacters + '(' + // backtick (``) '`(?:[^`\\\\]|\\\\(?:.|$))*`' + '|' + // double quotes ("") '"(?:[^"\\\\]|\\\\(?:.|$))*"' + '|' + // single quote ('') '\'(?:[^\'\\\\]|\\\\(?:.|$))*\'' + ')' + matchSpecialCharacters; const pattern = '(?:(?:^\\s*)|[^a-zA-Z0-9_])' + '(?:' + matchFuncs + ')' + '\\(' + stringGroup + '(?:[\\,]' + stringGroup + ')?' + '[\\,\\)]'; const re = new RegExp(pattern, 'gim'); let r; while ((r = re.exec(content))) { const options = {}; const full = r[0]; let key = this.fixStringAfterRegExp(r[1], true); if (!key) { continue; } if (r[2] !== undefined) { const defaultValue = this.fixStringAfterRegExp(r[2], false); if (!defaultValue) { continue; } options.defaultValue = defaultValue; } const endsWithComma = (full[full.length - 1] === ','); if (endsWithComma) { const { propsFilter } = { ...opts }; let code = matchBalancedParentheses(content.substr(re.lastIndex)); if (typeof propsFilter === 'function') { code = propsFilter(code); } try { const syntax = code.trim() !== '' ? parse('(' + code + ')') : {}; const props = _.get(syntax, 'body[0].expression.properties') || []; // http://i18next.com/docs/options/ const supportedOptions = [ 'defaultValue', 'defaultValue_plural', 'count', 'context', 'contextList', 'ns', 'keySeparator', 'nsSeparator', ]; props.forEach((prop) => { if (_.includes(supportedOptions, prop.key.name)) { if (prop.value.type === 'Literal') { options[prop.key.name] = prop.value.value; } else if (prop.value.type === 'TemplateLiteral') { options[prop.key.name] = prop.value.quasis .map(element => element.value.cooked) .join(''); } else { // Unable to get value of the property options[prop.key.name] = ''; } } }); } catch (err) { this.error(`Unable to parse code "${code}"`); this.error(err); } } if (customHandler) { customHandler(key, options); continue; } this.set(key, options); } return this; } // Parses translation keys from `Trans` components in JSX // <Trans i18nKey="some.key">Default text</Trans> parseTransFromString(content, opts = {}, customHandler = null) { if (_.isFunction(opts)) { customHandler = opts; opts = {}; } const { transformOptions = {}, // object component = this.options.trans.component, // string i18nKey = this.options.trans.i18nKey, // string defaultsKey = this.options.trans.defaultsKey, // string fallbackKey, // boolean|function acorn: acornOptions = this.options.trans.acorn, // object } = { ...opts }; const parseJSXElement = (node) => { if (!node) { return; } ensureArray(node.openingElement.attributes).forEach(attribute => { const value = attribute.value; if (!(value && value.type === 'JSXExpressionContainer')) { return; } const expression = value.expression; if (!(expression && expression.type === 'JSXElement')) { return; } parseJSXElement(expression); }); ensureArray(node.children).forEach(childNode => { if (childNode.type === 'JSXElement') { parseJSXElement(childNode); } }); if (node.openingElement.name.name !== component) { return; } const attr = ensureArray(node.openingElement.attributes) .reduce((acc, attribute) => { if (attribute.type !== 'JSXAttribute' || attribute.name.type !== 'JSXIdentifier') { return acc; } const { name } = attribute.name; if (attribute.value.type === 'Literal') { acc[name] = attribute.value.value; } else if (attribute.value.type === 'JSXExpressionContainer') { const expression = attribute.value.expression; // Identifier if (expression.type === 'Identifier') { acc[name] = expression.name; } // Literal if (expression.type === 'Literal') { acc[name] = expression.value; } // Object Expression if (expression.type === 'ObjectExpression') { const properties = ensureArray(expression.properties); acc[name] = properties.reduce((obj, property) => { if (property.value.type === 'Literal') { obj[property.key.name] = property.value.value; } else if (property.value.type === 'TemplateLiteral') { obj[property.key.name] = property.value.quasis .map(element => element.value.cooked) .join(''); } else { // Unable to get value of the property obj[property.key.name] = ''; } return obj; }, {}); } // Template Literal if (expression.type === 'TemplateLiteral') { acc[name] = expression.quasis .map(element => element.value.cooked) .join(''); } } return acc; }, {}); const transKey = _.trim(attr[i18nKey]); const defaultsString = attr[defaultsKey] || ''; if (typeof defaultsString !== 'string') { this.log(`defaults value must be a static string, saw ${chalk.yellow(defaultsString)}`); } // https://www.i18next.com/translation-function/essentials#overview-options const tOptions = attr.tOptions; const options = { ...tOptions, defaultValue: defaultsString || nodesToString(node.children), fallbackKey: fallbackKey || this.options.trans.fallbackKey }; if (Object.prototype.hasOwnProperty.call(attr, 'count')) { options.count = Number(attr.count) || 0; } if (Object.prototype.hasOwnProperty.call(attr, 'ns')) { if (typeof options.ns !== 'string') { this.log(`The ns attribute must be a string, saw ${chalk.yellow(attr.ns)}`); } options.ns = attr.ns; } if (customHandler) { customHandler(transKey, options); return; } this.set(transKey, options); }; try { const ast = acorn.Parser.extend(acornStage3, optionalChaining, acornJsx()) .parse(content, { ...defaults.trans.acorn, ...acornOptions }); jsxwalk(ast, { JSXElement: parseJSXElement }); } catch (err) { if (transformOptions.filepath) { this.error(`Unable to parse ${chalk.blue(component)} component from ${chalk.yellow(JSON.stringify(transformOptions.filepath))}`); console.error(' ' + err); } else { this.error(`Unable to parse ${chalk.blue(component)} component:`); console.error(content); console.error(' ' + err); } } return this; } // Parses translation keys from `data-i18n` attribute in HTML // <div data-i18n="[attr]ns:foo.bar;[attr]ns:foo.baz"> // </div> parseAttrFromString(content, opts = {}, customHandler = null) { let setter = this.set.bind(this); if (_.isFunction(opts)) { setter = opts; opts = {}; } else if (_.isFunction(customHandler)) { setter = customHandler; } const attrs = (opts.list !== undefined) ? ensureArray(opts.list) : ensureArray(this.options.attr.list); if (attrs.length === 0) { return this; } const ast = parse5.parse(content); const parseAttributeValue = (key) => { key = _.trim(key); if (key.length === 0) { return; } if (key.indexOf('[') === 0) { const parts = key.split(']'); key = parts[1]; } if (key.indexOf(';') === (key.length - 1)) { key = key.substr(0, key.length - 2); } setter(key); }; const walk = (nodes) => { nodes.forEach(node => { if (node.attrs) { node.attrs.forEach(attr => { if (attrs.indexOf(attr.name) !== -1) { const values = attr.value.split(';'); values.forEach(parseAttributeValue); } }); } if (node.childNodes) { walk(node.childNodes); } if (node.content && node.content.childNodes) { walk(node.content.childNodes); } }); }; walk(ast.childNodes); return this; } // Get the value of a translation key or the whole resource store containing translation information // @param {string} [key] The translation key // @param {object} [opts] The opts object // @param {boolean} [opts.sort] True to sort object by key // @param {boolean} [opts.lng] The language to use // @return {object} get(key, opts = {}) { if (_.isPlainObject(key)) { opts = key; key = undefined; } let resStore = {}; if (this.options.removeUnusedKeys) { // Merge two objects `resStore` and `resScan` deeply, returning a new merged object with the elements from both `resStore` and `resScan`. const resMerged = deepMerge(this.resStore, this.resScan); Object.keys(this.resStore).forEach((lng) => { Object.keys(this.resStore[lng]).forEach((ns) => { const resStoreKeys = flattenObjectKeys(_.get(this.resStore, [lng, ns], {})); const resScanKeys = flattenObjectKeys(_.get(this.resScan, [lng, ns], {})); const unusedKeys = _.differenceWith(resStoreKeys, resScanKeys, _.isEqual); for (let i = 0; i < unusedKeys.length; ++i) { _.unset(resMerged[lng][ns], unusedKeys[i]); this.log(`Removed an unused translation key { ${chalk.red(JSON.stringify(unusedKeys[i]))} from ${chalk.red(JSON.stringify(this.formatResourceLoadPath(lng, ns)))}`); } // Omit empty object resMerged[lng][ns] = omitEmptyObject(resMerged[lng][ns]); }); }); resStore = resMerged; } else { resStore = cloneDeep(this.resStore); } if (opts.sort) { Object.keys(resStore).forEach((lng) => { const namespaces = resStore[lng]; Object.keys(namespaces).forEach((ns) => { // Deeply sort an object by its keys without mangling any arrays inside of it resStore[lng][ns] = sortObject(namespaces[ns]); }); }); } if (!_.isUndefined(key)) { let ns = this.options.defaultNs; // http://i18next.com/translate/keyBasedFallback/ // Set nsSeparator and keySeparator to false if you prefer // having keys as the fallback for translation. // i18next.init({ // nsSeparator: false, // keySeparator: false // }) if (_.isString(this.options.nsSeparator) && (key.indexOf(this.options.nsSeparator) > -1)) { const parts = key.split(this.options.nsSeparator); ns = parts[0]; key = parts[1]; } const keys = _.isString(this.options.keySeparator) ? key.split(this.options.keySeparator) : [key]; const lng = opts.lng ? opts.lng : this.options.fallbackLng; const namespaces = resStore[lng] || {}; let value = namespaces[ns]; let x = 0; while (keys[x]) { value = value && value[keys[x]]; x++; } return value; } return resStore; } // Set translation key with an optional defaultValue to i18n resource store // @param {string} key The translation key // @param {object} [options] The options object // @param {boolean|function} [options.fallbackKey] When the key is missing, pass `true` to return `options.defaultValue` as key, or pass a function to return user-defined key. // @param {string} [options.defaultValue] defaultValue to return if translation not found // @param {number} [options.count] count value used for plurals // @param {string} [options.context] used for contexts (eg. male) // @param {object} [options.contextList] used for informing 18next-scanner of all correct contexts // @param {string} [options.ns] namespace for the translation // @param {string|boolean} [options.nsSeparator] The value used to override this.options.nsSeparator // @param {string|boolean} [options.keySeparator] The value used to override this.options.keySeparator set(key, options = {}) { // Backward compatibility if (_.isString(options)) { const defaultValue = options; options = { defaultValue: defaultValue }; } const nsSeparator = (options.nsSeparator !== undefined) ? options.nsSeparator : this.options.nsSeparator; const keySeparator = (options.keySeparator !== undefined) ? options.keySeparator : this.options.keySeparator; let ns = options.ns || this.options.defaultNs; console.assert(_.isString(ns) && !!ns.length, 'ns is not a valid string', ns); // http://i18next.com/translate/keyBasedFallback/ // Set nsSeparator and keySeparator to false if you prefer // having keys as the fallback for translation. // i18next.init({ // nsSeparator: false, // keySeparator: false // }) if (_.isString(nsSeparator) && (key.indexOf(nsSeparator) > -1)) { const parts = key.split(nsSeparator); ns = parts[0]; key = parts[1]; } let keys = []; if (key) { keys = _.isString(keySeparator) ? key.split(keySeparator) : [key]; } else { // fallback key if (options.fallbackKey === true) { key = options.defaultValue; } if (typeof options.fallbackKey === 'function') { key = options.fallbackKey(ns, options.defaultValue); } if (!key) { // Ignore empty key return; } keys = [key]; } const { lngs, context, contextFallback, contextSeparator, contextDefaultValues, contextList, plural, pluralFallback, pluralSeparator, defaultLng, defaultValue } = this.options; lngs.forEach((lng) => { let resLoad = this.resStore[lng] && this.resStore[lng][ns]; let resScan = this.resScan[lng] && this.resScan[lng][ns]; if (!_.isPlainObject(resLoad)) { // Skip undefined namespace this.error(`${chalk.yellow(JSON.stringify(ns))} does not exist in the namespaces (${chalk.yellow(JSON.stringify(this.options.ns))}): key=${chalk.yellow(JSON.stringify(key))}, options=${chalk.yellow(JSON.stringify(options))}`); return; } Object.keys(keys).forEach((index) => { const key = keys[index]; if (index < (keys.length - 1)) { resLoad[key] = resLoad[key] || {}; resLoad = resLoad[key]; resScan[key] = resScan[key] || {}; resScan = resScan[key]; return; // continue } // Context & Plural // http://i18next.com/translate/context/ // http://i18next.com/translate/pluralSimple/ // // Format: // "<key>[[{{contextSeparator}}<context>]{{pluralSeparator}}<plural>]" // // Example: // { // "translation": { // "friend": "A friend", // "friend_male": "A boyfriend", // "friend_female": "A girlfriend", // "friend_male_plural": "{{count}} boyfriends", // "friend_female_plural": "{{count}} girlfriends" // } // } const resKeys = []; // http://i18next.com/translate/context/ const containsContext = (() => { if (ensureArray(contextList?.[options.contextList]?.list)?.length > 0) { return true; } if (!context) { return false; } if (_.isUndefined(options.context)) { return false; } return _.isFunction(context) ? context(lng, ns, key, options) : !!context; })(); // http://i18next.com/translate/pluralSimple/ const containsPlural = (() => { if (!plural) { return false; } if (_.isUndefined(options.count)) { return false; } return _.isFunction(plural) ? plural(lng, ns, key, options) : !!plural; })(); const contextValues = (() => { if (ensureArray(contextList?.[options.contextList]?.list)?.length > 0) { return ensureArray(contextList[options.contextList]?.list); } if (options.context !== '') { return [options.context]; } if (ensureArray(contextDefaultValues).length > 0) { return ensureArray(contextDefaultValues); } return []; })(); const validContextList = contextList?.[options.contextList] const contextListSeparator = validContextList?.separator ?? contextSeparator ? contextSeparator : ''; const contextListFallback = validContextList?.fallback ?? contextFallback; if (containsPlural) { let suffixes = pluralFallback ? this.pluralSuffixes[lng] : this.pluralSuffixes[lng].slice(1); suffixes.forEach((pluralSuffix) => { resKeys.push(`${key}${pluralSuffix}`); }); if (containsContext && containsPlural) { suffixes.forEach((pluralSuffix) => { contextValues.forEach(contextValue => { resKeys.push(`${key}${contextListSeparator}${contextValue}${pluralSuffix}`); }); }); } } else { if (!containsContext || (containsContext && (contextListFallback))) { resKeys.push(key); } if (containsContext) { contextValues.forEach(contextValue => { resKeys.push(`${key}${contextListSeparator}${contextValue}`); }); } } resKeys.forEach((resKey) => { if (resLoad[resKey] === undefined) { if (options.defaultValue_plural !== undefined && resKey.endsWith(`${pluralSeparator}plural`)) { resLoad[resKey] = options.defaultValue_plural; } else { // Fallback to `defaultValue` resLoad[resKey] = _.isFunction(defaultValue) ? defaultValue(lng, ns, key, options) : (options.defaultValue || defaultValue); } this.log(`Added a new translation key { ${chalk.yellow(JSON.stringify(resKey))}: ${chalk.yellow(JSON.stringify(resLoad[resKey]))} } to ${chalk.yellow(JSON.stringify(this.formatResourceLoadPath(lng, ns)))}`); } else if (options.defaultValue && (!options.defaultValue_plural || !resKey.endsWith(`${pluralSeparator}plural`))) { if (!resLoad[resKey]) { // Use `options.defaultValue` if specified resLoad[resKey] = options.defaultValue; } else if ((resLoad[resKey] !== options.defaultValue) && (lng === defaultLng)) { // A default value has provided but it's different with the expected default this.log(`The translation key ${chalk.yellow(JSON.stringify(resKey))} has a different default value, you may need to check the translation key of default language (${defaultLng})`); } } else if (options.defaultValue_plural && resKey.endsWith(`${pluralSeparator}plural`)) { if (!resLoad[resKey]) { // Use `options.defaultValue_plural` if specified resLoad[resKey] = options.defaultValue_plural; } else if ((resLoad[resKey] !== options.defaultValue_plural) && (lng === defaultLng)) { // A default value has provided but it's different with the expected default this.log(`The translation key ${chalk.yellow(JSON.stringify(resKey))} has a different default value, you may need to check the translation key of default language (${defaultLng})`); } } resScan[resKey] = resLoad[resKey]; }); }); }); } // Returns a JSON string containing translation information // @param {object} [options] The options object // @param {boolean} [options.sort] True to sort object by key // @param {function|string[]|number[]} [options.replacer] The same as the JSON.stringify() // @param {string|number} [options.space] The same as the JSON.stringify() method // @return {string} toJSON(options = {}) { const { replacer, space, ...others } = options; return JSON.stringify(this.get(others), replacer, space); } }
JavaScript
class Layer extends AnimatedObject { /** * @param {Model} model * @param {ModelViewer.parser.mdlx.Layer} layer * @param {number} layerId * @param {number} priorityPlane */ constructor(model, layer, layerId, priorityPlane) { let filterMode = layer.filterMode; let textureAnimationId = layer.textureAnimationId; let gl = model.viewer.gl; super(model, layer); this.index = layerId; this.priorityPlane = priorityPlane; this.filterMode = filterMode; this.textureId = layer.textureId; this.coordId = layer.coordId; this.alpha = layer.alpha; let flags = layer.flags; this.unshaded = flags & 0x1; this.sphereEnvironmentMap = flags & 0x2; this.twoSided = flags & 0x10; this.unfogged = flags & 0x20; this.noDepthTest = flags & 0x40; this.noDepthSet = flags & 0x80; this.depthMaskValue = (filterMode === 0 || filterMode === 1) ? 1 : 0; this.blendSrc = 0; this.blendDst = 0; this.blended = (filterMode > 1) ? true : false; if (this.blended) { [this.blendSrc, this.blendDst] = layerFilterMode(filterMode, gl); } this.uvDivisor = new Float32Array([1, 1]); if (textureAnimationId !== -1) { let textureAnimation = model.textureAnimations[textureAnimationId]; if (textureAnimation) { this.textureAnimation = textureAnimation; } } let variants = { alpha: [], slot: [], translation: [], rotation: [], scale: [], }; let hasSlotAnim = false; let hasTranslationAnim = false; let hasRotationAnim = false; let hasScaleAnim = false; for (let i = 0, l = model.sequences.length; i < l; i++) { let alpha = this.isAlphaVariant(i); let slot = this.isTextureIdVariant(i); let translation = this.isTranslationVariant(i); let rotation = this.isRotationVariant(i); let scale = this.isScaleVariant(i); variants.alpha[i] = alpha; variants.slot[i] = slot; variants.translation[i] = translation; variants.rotation[i] = rotation; variants.scale[i] = scale; hasSlotAnim = hasSlotAnim || slot; hasTranslationAnim = hasTranslationAnim || translation; hasRotationAnim = hasRotationAnim || rotation; hasScaleAnim = hasScaleAnim || scale; } this.variants = variants; this.hasSlotAnim = hasSlotAnim; this.hasTranslationAnim = hasTranslationAnim; this.hasRotationAnim = hasRotationAnim; this.hasScaleAnim = hasScaleAnim; // Handle sprite animations if (this.animations.KMTF) { // Get all unique texture IDs used by this layer let textureIds = unique(this.animations.KMTF.getValues().map((array) => array[0])); if (textureIds.length > 1) { let hash = stringHash(textureIds.join('')); let textures = []; // Grab all of the textures for (let i = 0, l = textureIds.length; i < l; i++) { textures[i] = model.textures[textureIds[i]]; } let atlas = model.viewer.loadTextureAtlas(hash, textures); atlas.whenLoaded() .then(() => { atlas.wrapMode(gl.REPEAT, gl.REPEAT); model.textures.push(atlas); this.textureId = model.textures.length - 1; this.uvDivisor.set([atlas.columns, atlas.rows]); }); } } } /** * @param {ShaderProgram} shader */ bind(shader) { let gl = this.model.viewer.gl; // gl.uniform1f(shader.uniforms.u_unshaded, this.unshaded); gl.uniform1f(shader.uniforms.u_filterMode, this.filterMode); if (this.blended) { gl.enable(gl.BLEND); gl.blendFunc(this.blendSrc, this.blendDst); } else { gl.disable(gl.BLEND); } if (this.twoSided) { gl.disable(gl.CULL_FACE); } else { gl.enable(gl.CULL_FACE); } if (this.noDepthTest) { gl.disable(gl.DEPTH_TEST); } else { gl.enable(gl.DEPTH_TEST); } if (this.noDepthSet) { gl.depthMask(0); } else { gl.depthMask(this.depthMaskValue); } } /** * @param {Float32Array} out * @param {ModelInstance} instance * @return {number} */ getAlpha(out, instance) { return this.getFloatValue(out, 'KMTA', instance, this.alpha); } /** * @param {Uint32Array} out * @param {ModelInstance} instance * @return {number} */ getTextureId(out, instance) { let keyframe = this.getUintValue(out, 'KMTF', instance, this.textureId); // If this layer is using a texture atlas, remap the texture ID to that of the texture atlas. if (this.texutreAtlasMapping) { out[0] = this.texutreAtlasMapping[out[0]]; } return keyframe; } /** * @param {vec3} out * @param {ModelInstance} instance * @return {number} */ getTranslation(out, instance) { if (this.textureAnimation) { return this.textureAnimation.getTranslation(out, instance); } vec3.copy(out, VEC3_ZERO); return -1; } /** * @param {quat} out * @param {ModelInstance} instance * @return {number} */ getRotation(out, instance) { if (this.textureAnimation) { return this.textureAnimation.getRotation(out, instance); } quat.copy(out, QUAT_DEFAULT); return -1; } /** * @param {vec3} out * @param {ModelInstance} instance * @return {number} */ getScale(out, instance) { if (this.textureAnimation) { return this.textureAnimation.getScale(out, instance); } vec3.copy(out, VEC3_ONE); return -1; } /** * @param {number} sequence * @return {boolean} */ isAlphaVariant(sequence) { return this.isVariant('KMTA', sequence); } /** * @param {number} sequence * @return {boolean} */ isTextureIdVariant(sequence) { return this.isVariant('KMTF', sequence); } /** * @param {number} sequence * @return {boolean} */ isTranslationVariant(sequence) { return this.textureAnimation && this.textureAnimation.isTranslationVariant(sequence); } /** * @param {number} sequence * @return {boolean} */ isRotationVariant(sequence) { return this.textureAnimation && this.textureAnimation.isRotationVariant(sequence); } /** * @param {number} sequence * @return {boolean} */ isScaleVariant(sequence) { return this.textureAnimation && this.textureAnimation.isScaleVariant(sequence); } }
JavaScript
class BlockClient extends Client { /** * @param {MessageTransport} transport */ constructor (transport) { super('block', ['put', 'get', 'rm', 'stat'], transport) } }
JavaScript
class ThemedOmnibox extends MultiCheckAudit { /** * @return {!AuditMeta} */ static get meta() { return { category: 'PWA', name: 'themed-omnibox', description: 'Address bar matches brand colors', helpText: 'The browser address bar can be themed to match your site. A `theme-color` [meta tag](https://developers.google.com/web/updates/2014/11/Support-for-theme-color-in-Chrome-39-for-Android) will upgrade the address bar when a user browses the site, and the [manifest theme-color](https://developers.google.com/web/updates/2015/08/using-manifest-to-set-sitewide-theme-color) will apply the same theme site-wide once it\'s been added to homescreen.', requiredArtifacts: ['Manifest', 'ThemeColor'] }; } static assessMetaThemecolor(themeColorMeta, failures) { if (themeColorMeta === null) { failures.push('No `<meta name="theme-color">` tag found'); } else if (!validColor(themeColorMeta)) { failures.push('The theme-color meta tag did not contain a valid CSS color'); } } static assessManifest(manifestValues, failures) { if (manifestValues.isParseFailure) { failures.push(manifestValues.parseFailureReason); return; } const themeColorCheck = manifestValues.allChecks.find(i => i.id === 'hasThemeColor'); if (!themeColorCheck.passing) { failures.push(themeColorCheck.failureText); } } static audit_(artifacts) { const failures = []; return artifacts.requestManifestValues(artifacts.Manifest).then(manifestValues => { ThemedOmnibox.assessManifest(manifestValues, failures); ThemedOmnibox.assessMetaThemecolor(artifacts.ThemeColor, failures); return { failures, manifestValues, themeColor: artifacts.ThemeColor }; }); } }
JavaScript
class Spreadsheet { /** * @param {*=} value - contents of the cell * @param {string=} style - cell formatting */ static create_cell(value,style) { return { "value": value, "style": style || "" }; } /** * @param {Object} associated - object to synchronise the spreadsheet with * @param {SpreadsheetRules} rules - rules to convert between objects and spreadsheets * @param {boolean=} convert_times_to_dates - guess the dates associated with times * * <p>The spreadsheet rules can include a <tt>formats</tt> member, * specifying how numbers will be formatted in the associated * member. Each value can be <tt>null</tt> (no special formatting), an * Excel number format code, or <tt>number</tt>/<tt>time</tt>/<tt>duration</tt> * (aliases for common formats).</p> * * @example * let spreadsheet = new Spreadsheet( * associated, * [ * { * sheet: "...", // name of a sheet in the spreadsheet (e.g. "records") * member: "...", // name of an array in the diary object (default: same as "sheet") * //type: "dictionary", // indicates the member is an object containing key/value pairs * cells: [ // cells in the associated sheet * * // most cells can be defined with the high-level format: * { * "member": "...", // required - name of the member (e.g. 'start') * "type": "text", // optional - can also be "number", "time" or "duration" * "regexp": /^[0-9]$/, // optional - values must match this pattern * //"optional": true, // allow this value to be missing * }, * * // sometimes you might need to use the low-level format: * { * "members": [ "foo", "bar" ], // names of members that will be returned by the read * "formats": [ null , "duration" ], // how numbers are formatted in this member (see above) * "export": (array_element,row,offset) => { // append cells to the current row * row[offset ] = Spreadsheet.create_cell(array_element["foo"]); * row[offset+1] = Spreadsheet.create_cell(array_element["foo"]+array_element["bar"]); * return false; // indicates this value cannot be serialised * }, * "import": (array_element,row,offset) => { * array_element["foo"] = row[offset]["value"]; * array_element["bar"] = row[offset+1]["value"] - row[offset]["value"]; * return false; // indicates this value cannot be parsed * }, * }, * * ... * * ] * }, * * ... * * ] * ); */ constructor(associated,rules,convert_times_to_dates) { const debug = false; function exporter(cell) { const create_cell = Spreadsheet.create_cell; const member = cell["member"]; let ret; switch ( cell["type"] ) { case "time" : ret = (elem,row,offset) => row[offset] = Spreadsheet.create_cell( ( elem[member] === undefined ) ? undefined : new Date( elem[member] )); break; case "duration": ret = (elem,row,offset) => row[offset] = Spreadsheet.create_cell( ( elem[member] === undefined ) ? undefined : elem[member] / (1000*60*60*24) ); break; default : ret = (elem,row,offset) => row[offset] = Spreadsheet.create_cell(elem[member]); } if ( cell["optional"] ) { const inner = ret; ret = (elem,row,offset) => ( elem[member] === undefined ) || inner(elem,row,offset); } if ( debug ) { // debugging use only const inner = ret; ret = (elem,row,offset) => { const result = inner(elem,row,offset); console.info(cell,row[offset],elem[member],result); return result; }; } return ret; } function importer(cell,self) { const member = cell["member"]; let ret; switch ( cell["type"] ) { case "time" : ret = ( convert_times_to_dates ? (elem,row,offset) => !isNaN( elem[member] = row[offset]. dated_timestamp ) : (elem,row,offset) => !isNaN( elem[member] = row[offset].parsed_timestamp ) ); break; case "duration": ret = (elem,row,offset) => !isNaN( elem[member] = row[offset]["value"].getTime() + self["epoch_offset"] ); break; case "number" : ret = (elem,row,offset) => !isNaN( elem[member] = parseFloat(row[offset]["value"]) ); break; case "boolean" : ret = (elem,row,offset) => !isNaN( elem[member] = !!row[offset]["value"] ); break; default: ret = (elem,row,offset) => { elem[member] = row[offset]["value"]; return true; }; } if ( cell["regexp"] ) { const inner = ret; ret = (elem,row,offset) => cell["regexp"].test(row[offset]["value"]) && inner(elem,row,offset); } if ( cell["optional"] ) { const inner = ret; ret = (elem,row,offset) => ( !row[offset] || row[offset]["value"] == null || inner(elem,row,offset) || row[offset]["value"] == "" ); } if ( debug ) { const inner = ret; ret = (elem,row,offset) => { const result = inner(elem,row,offset); if ( result ) { console.info(result,cell,elem[member]); } else { console.error(result,cell,elem[member],row[offset]?row[offset]["value"]:"(no cell at this offset)"); } return result; }; } return ret; } /** * Low-level spreadsheet library object. * @type (Object|null) * @private */ this.raw = null; /** * Object associated with this spreadsheet */ this.associated = associated; /** * Spreadsheet rules * @private */ this.rules = rules.map( rule => ({ "sheet" : rule["sheet"] || rule["member"], "member" : rule["member"] || rule["sheet"], "type" : rule["type"] || "list", "optional": !!rule["optional"], // convert high-level definitions to low-level definitions: "cells": rule["cells"].map( cell => { if ( cell["members"] ) { cell["formats"] = ( cell["formats"] || [] ).map( format => SpreadsheetNumberFormats[format] || format ); while ( cell["formats"].length < cell["members"].length ) { cell["formats"].push("General"); } return cell; } else { return { "members": [ cell["member"] ], "regexp": cell["regexp"] || new RegExp(""), "formats": [ SpreadsheetNumberFormats[ cell["type"] ] || "General" ], "export": exporter(cell), "import": importer(cell,this), } } }), })); /* * Epoch used by dates created in this spreadsheet, * in milliseconds relative to the Unix epoch */ this["epoch_offset"] = 0; /** * Array of sheets */ this["sheets"] = []; } ["get_sheet"](name,headers,number_formats) { const expected = headers.join("\0"); const sheets = this["sheets"].filter( sheet => sheet["cells"][0] && sheet["cells"][0].map( cell => cell["value"] ).join("\0") == expected ); if ( sheets.length ) { return [ false, sheets.find( sheet => sheet["name"] == name ) || sheets[0] ]; } else { const ret = { "name": name, "number_formats": number_formats.map( type => type ? SpreadsheetNumberFormats[ type ] || type : "General" ), "cells": [ headers.map( header => Spreadsheet.create_cell(header,"#FFEEEEEE,#FFEEEEEE") ) ], }; return [ true, ret ]; } } /** * Convert a cell to a Unix timestamp * @param {Object} value - cell or value to analyse * @param {Object=} raw_spreadsheet - raw spreadsheet object from which the value was taken * @return {number} Unix timestamp (if parseable) */ static parse_timestamp(value,raw_spreadsheet) { return DiaryBase.parse_timestamp( (value||{}).hasOwnProperty("value") ? value["value"] : value, raw_spreadsheet ? ( ( raw_spreadsheet["properties"] || {} ) ["date1904"] ? 2082844800000 : 2209161600000 ) : 0 ); } /** * Calculate timestamps for all cells in a worksheet * @param {Array} sheet - sheet to process * @param {Object=} raw_spreadsheet - raw spreadsheet object from which the value was taken */ static parse_all_timestamps(sheet,raw_spreadsheet) { let prev_date = 0; sheet.forEach( row => row.forEach( cell => { let timestamp = cell.parsed_timestamp = Spreadsheet.parse_timestamp(cell,raw_spreadsheet), dated_timestamp = cell.dated_timestamp = ( isNaN(timestamp) || timestamp < 0 || timestamp > 86400000 ) ? timestamp : timestamp + prev_date - (prev_date%86400000) ; if ( dated_timestamp < prev_date ) { cell.dated_timestamp = dated_timestamp += 86400000; } prev_date = dated_timestamp; })); } /** * Read data from a buffer (e.g. a file input) */ static buffer_to_spreadsheet(buffer) { function encode_style(style) { if ( style.hasOwnProperty("argb" ) ) return '#' + style["argb"]; else if ( style.hasOwnProperty("indexed") ) return 'i' + style["indexed"]; else if ( style.hasOwnProperty("theme" ) ) return 't' + style["theme"]; return ''; } let spreadsheet; try { spreadsheet = new self["ExcelJS"]["Workbook"](); } catch (e) { spreadsheet = new ( require("exceljs")["Workbook"] )(); } return spreadsheet["xlsx"]["load"](buffer).then( () => { if ( spreadsheet["_worksheets"].length ) { let sheets = []; spreadsheet["eachSheet"]( (raw_worksheet, sheetId) => { let sheet = { "name": raw_worksheet["name"], "cells": [] }; sheets.push(sheet); raw_worksheet["eachRow"]( { "includeEmpty": true }, (raw_row, row_number) => { let row = sheet["cells"][row_number-1] = []; raw_row["eachCell"]({ "includeEmpty": true }, function(cell, col_number) { let style = ""; if ( cell["style"] && cell["style"]["fill"] ) { style = ( encode_style(cell["style"]["fill"]["bgColor"]||{}) + ',' + encode_style(cell["style"]["fill"]["fgColor"]||{}) ); } if ( style.length == 1 ) style = ""; // check for floating point errors: if ( (cell["value"]||{}).getTime ) { const time = cell["value"].getTime(); if ( ( time % 1000 ) == 1 || ( time % 1000 ) == -999 ) { cell["value"] = new Date( time-1 ); } if ( ( time % 1000 ) == -1 || ( time % 1000 ) == 999 ) { cell["value"] = new Date( time+1 ); } } row[col_number-1] = Spreadsheet.create_cell(cell["value"],style); }) }); }); sheets.forEach( sheet => Spreadsheet.parse_all_timestamps( sheet["cells"], spreadsheet ) ); return { "file_format": "spreadsheet", "spreadsheet": spreadsheet, "sheets": sheets, } } else { throw Error( "empty spreadsheet" ); } } ); } /** * Copy data from the parameter into this.sheets and this.associated * * @param {string} contents - CSV file to load from * @return {Object|undefined} spreadsheet information */ static parse_csv(contents) { const value = "([^\",\\r\\n]*|\"([^\"]|\"\")*\")"; // Excel requires a byte order mark, which we ignore: if ( contents[0] == "\u{FEFF}" ) contents = contents.substr(1); // reduce the complexity of the regexps by guaranteeing a trailing newline: if ( contents.search(/[\r\n]$/) == -1 ) contents += "\n"; // does this look like a valid CSV file? if ( contents.search(new RegExp(`^(${value}(,${value})*(?:\r\n|\r|\n))*$`) ) ) return; let spreadsheet; try { spreadsheet = new self["ExcelJS"]["Workbook"](); } catch (e) { spreadsheet = new ( require("exceljs")["Workbook"] )(); } let raw_records = spreadsheet["addWorksheet"]("Records"), raw_settings = spreadsheet["addWorksheet"]("Settings"), records = [], row_number=0, settings = [ [ Spreadsheet.create_cell("Setting"), Spreadsheet.create_cell("Value") ] ] ; // CSV can start with key=value lines... while ( !contents.search(/^([A-Za-z_][A-Za-z0-9_]*)=[^,]*\n/) ) { contents = contents.replace( /([^=]*?)=(.*)\n/, (_,key,value) => { settings.push([key,value].map( v => Spreadsheet.create_cell(v) )); raw_settings["addRow"]([ key, value ]); return ''; } ); } contents.replace( new RegExp(`${value}(,${value})*(?:\r\n|\r|\n)`, 'g'), line_str => { let raw_row = raw_records["getRow"](++row_number), row = [], n=0 ; records.push(row); line_str .replace( new RegExp(value+'[,\r\n]','g'), value => { let raw_cell = raw_row["getCell"](++n); if ( value[0] == '"' ) { raw_cell["value"] = value.substr(1,value.length-3).replace( /""/g, '"' ); } else { raw_cell["value"] = value.substr(0,value.length-1); } row.push(Spreadsheet.create_cell(raw_cell["value"])); }); } ); Spreadsheet.parse_all_timestamps(records); return { "spreadsheet": spreadsheet, "sheets": [ { "name": "Records" , "cells": records }, { "name": "Settings", "cells": settings } ], } } static escape_csv_component( value ) { return ( ( value === undefined ) ? '' : ( value["getTime"] ) ? DiaryBase.date(value.getTime())["format"]("yyyy-MM-ddTHH:mm:ss.SSS")+'Z' : ( value.toString().search(/[",\n]/) == -1 ) ? value : '"'+value.replace(/"/g, '""')+'"' ); } /** * Copy data from the parameter into this.sheets and this.associated * * @param {Object} spreadsheet - spreadsheet to load from * @return {boolean} whether the operation was successful */ ["load"](spreadsheet) { const sheets = spreadsheet["sheets"]; if ( !sheets ) return false; const old_offset = this["epoch_offset"]; this["epoch_offset"] = ( ( spreadsheet["spreadsheet"]["properties"] || {} ) ["date1904"] ? 2082844800000 : 2209161600000 ); if ( !this.rules.every( sheet_rule => sheets.some( sheet => { const cells = sheet["cells"]; const is_dictionary = sheet_rule["type"] == "dictionary"; if ( !cells.length || ( is_dictionary && cells.length != 2 ) ) { return false; } // ensure that all headers are present: const header_row = cells[0].slice(0); if ( !sheet_rule["cells"].every( cell => cell["members"].every( member => member == (header_row.shift()||{"value":NaN})["value"] ) ) ) { return false; } // calculate array and check the values actually match: let array = []; if ( !cells.slice(1).every( row => { if ( !row.length ) return true; let offset = 0; let array_element = {}; array.push(array_element); return sheet_rule["cells"].every( cell => cell["import"]( array_element, row, ( offset += cell["members"].length ) - cell["members"].length ) ); }) ) { return false; } const member = sheet_rule["member"]; if ( is_dictionary ) { this.associated[member] = Object.assign( array[0], this.associated[member]||{} ); } else { if ( !this.associated[member] ) this.associated[member] = []; let data = this.associated[member]; if ( data.length >= cells.length ) data.splice( 0, cells.length - 1 ); array.forEach( (array_element,n) => data[n] = Object.assign( array_element, data[n] ) ); } let number_formats = []; sheet_rule["cells"].forEach( cell => number_formats = number_formats.concat( cell["formats"] ) ); sheet["number_formats"] = number_formats; return true; }) ) ) { this["epoch_offset"] = old_offset; return false; } this.raw = spreadsheet["spreadsheet"]; this["sheets"] = sheets; return true; } /** * Copy data from this.associated to this.sheets * @return {boolean} */ ["synchronise"]() { return this.rules.every( sheet_rule => { const is_dictionary = sheet_rule["type"] == "dictionary"; let headers = []; let number_formats = []; sheet_rule["cells"].forEach( cell => { headers = headers.concat( cell["members"] ) number_formats = number_formats.concat( cell["formats"] ); }); const added_sheet = this["get_sheet"](sheet_rule["sheet"],headers,number_formats); const added = added_sheet[0]; const sheet = added_sheet[1]; let cells = sheet["cells"] = [ headers.map(header => Spreadsheet.create_cell(header,"#FFEEEEEE,#FFEEEEEE")) ]; const associated = this.associated[sheet_rule["member"] || sheet_rule["sheet"]]; function process_row(array_element) { let row = [], offset = 0; cells.push(row); return sheet_rule["cells"].every( cell => cell["export"]( array_element, row, ( offset += cell["members"].length ) - cell["members"].length ) ); } if ( is_dictionary ) { if ( !process_row(associated) ) return false; } else { if ( !associated.every(process_row) ) return false; } if ( added ) this["sheets"].push(sheet); return true; }); } /** * Generate a spreadsheet based on this.sheets * @return {Promise} */ ["serialise"]() { function decode_style(style) { switch ( style[0] ) { case '#': return { "argb" : style.slice(1) }; case 'i': return { "indexed": parseInt(style.slice(1),10) }; case 't': return { "theme" : parseInt(style.slice(1),10) }; default : return {}; } } const fix_timestamps = !this.raw; if ( !this.raw ) { try { this.raw = new self["ExcelJS"]["Workbook"](); } catch (e) { this.raw = new ( require("exceljs")["Workbook"] )(); } this["epoch_offset"] = ( ( this.raw["properties"] || {} ) ["date1904"] ? 2082844800000 : 2209161600000 ); } const epoch_offset = this["epoch_offset"]; // Remove deleted worksheets: let raw_sheets = {}; this["sheets"].forEach( sheet => raw_sheets[sheet["name"]] = 0 ); this.raw["eachSheet"]( (worksheet, sheetId) => { if ( raw_sheets.hasOwnProperty(worksheet["name"]) ) { raw_sheets[worksheet["name"]] = worksheet; } else { this.raw.removeWorksheet(sheetId); } }); // Add/update worksheets: this["sheets"].forEach( sheet => { let raw_sheet = raw_sheets[sheet["name"]] || this.raw["addWorksheet"](sheet["name"],sheet["options"]); // Remove deleted cells: raw_sheet["eachRow"]( { "includeEmpty": true }, (raw_row, row_number) => { let row = sheet["cells"][row_number-1] || []; raw_row["eachCell"]({ "includeEmpty": true }, (raw_cell, col_number) => { if ( !row[col_number] ) { raw_cell["value"] = null; raw_cell["style"] = {}; } }) }); // Add/update cells: sheet["cells"].forEach( (row,n) => { let raw_row = raw_sheet["getRow"](n+1); row.forEach( (cell,n) => { let raw_cell = raw_row["getCell"](n+1); if ( fix_timestamps && (cell["value"]||{}).getTime && cell["value"].getTime() >= 0 && cell["value"].getTime() < 24 * 60 * 60 * 1000 ) { // reset times relative to the new epoch raw_cell["value"] = new Date( cell["value"].getTime() - epoch_offset ); } else { raw_cell["value"] = cell["value"]; } let style = cell["style"].split(','), raw_style = raw_cell["style"] = raw_cell["style"] || {}, column_font = ((sheet["styles"]||[])[n]||{})["font"] ; if ( style[0] || style[1] || style[2] ) { // Note: we remove any existing style, in case it interacts with the style we add: raw_style["fill"] = raw_style["fill"] || {}; raw_style["fill"]["type"] = "pattern"; raw_style["fill"]["pattern"] = "solid"; if ( style[0] ) { raw_style["fill"]["bgColor"] = decode_style(style[0]); } else { delete raw_style["fill"]["bgColor"]; } if ( style[1] ) { raw_style["fill"]["fgColor"] = decode_style(style[1]); } else { delete raw_style["fill"]["fgColor"]; } if ( style[2] ) { raw_style["font"] = raw_style["font"] || {}; raw_style["font"]["color"] = decode_style(style[2]); } else { delete raw_style["font"]; } } else { if ( raw_style && raw_style["fill"] ) { delete raw_style["fill"]["bgColor"]; delete raw_style["fill"]["fgColor"]; } } /* * Cell styles override column styles, so we need to copy them in. * "font" is the only property we actually use right now. */ if ( column_font ) { Object.assign( raw_style["font"] = raw_style["font"] || {}, column_font ); } }); raw_row["commit"](); }); if ( sheet["widths"] ) { sheet["widths"].forEach( (w,n) => raw_sheet["columns"][n]["width"] = w ); } else { raw_sheet["columns"].forEach( col => col["width"] = 18 ); } if ( sheet["styles"] ) { sheet["styles"].forEach( (s,n) => raw_sheet["columns"][n]["style"] = s ); } (sheet["number_formats"]||[]).forEach ( (format,n) => raw_sheet["getColumn"](n+1)["numFmt"] = format ); }); return this.raw["xlsx"]["writeBuffer"](); } output_csv() { const sheet_rule = this.rules[0]; return ( // Settings: (this.associated["settings"]||[]) .map( row => row["Setting"] + "=" + row["Value"] + "\n" ) .concat( // header: [sheet_rule["cells"].map( cell => cell["members"].join(',') ).join(',') + "\n"], // Records: this.associated[sheet_rule["member"]].map( r => { let row = [], offset = 0; sheet_rule["cells"].forEach( cell => cell["export"]( r, row, ( offset += cell["members"].length ) - cell["members"].length ) ); return row.map( v => Spreadsheet.escape_csv_component( v["value"] )).join(',') + "\n" } ) ).join("") ); } ["file_format"]() { return "Spreadsheet"; } }
JavaScript
class GvHeader extends withResizeObserver(ItemResource(LitElement)) { static get properties () { return { breadcrumbs: { type: Array }, sticky: { type: Boolean, reflect: true }, _breadcrumbs: { type: Array, attribute: false }, canSubscribe: { type: Boolean, attribute: 'can-subscribe' }, }; } static get styles () { return [ ...super.styles, // language=CSS css` :host { --img-w: 120px; --img-h: 120px; --gv-button--fz: var(--gv-header-button--fz, var(--gv-theme-font-size-l, 16px)); --gv-button--p: var(--gv-header-button--p, 10px 24px); --gv-link--bgc: transparent; --gv-link-active-bgc: transparent; --c: var(--gv-header--c, var(--gv-theme-font-color-dark, #262626)); --gv-link--c: var(--c); --gv-link-active--c: var(--c); --gv-link-a--ph: 5px; --gv-link--td: underline; --bgc: var(--gv-header--bgc, var(--gv-theme-color-light, #86c3d0)); box-sizing: border-box; display: block; } :host([w-lt-768]) { --img--w: calc(var(--img-w) / 2); --img--h: calc(var(--img-h) / 2); --gv-button--fz: var(--gv-theme-font-size-s, 12px); font-size: var(--gv-theme-font-size-s, 12px); } :host([w-lt-580]) { --gv-button--p: 3px 9px; --gv-link-a--ph: 0px; } :host([w-lt-580]) .actions { display: flex; flex-direction: column; } :host([w-lt-580]) .version { font-size: var(--gv-theme-font-size-s, 12px); line-height: var(--gv-theme-font-size-s, 12px); } :host([w-lt-580]) .image gv-image { top: -5px; } :host([w-lt-580]) h1 { font-size: calc(var(--gv-theme-font-size-xl, 26px) - 4px); line-height: calc(var(--gv-theme-font-size-xl, 26px) - 4px); } :host([w-lt-400]) h1 { font-size: calc(var(--gv-theme-font-size-xl, 26px) - 8px); } .header { display: flex; background-color: var(--bgc); flex-direction: row; color: var(--c); transition: all 350ms ease-in-out; padding: 0.5rem var(--gv-theme-layout--pr, 4rem) 0.5rem var(--gv-theme-layout--pl, 4rem); position: relative; } .title { flex: 1; margin: 0.5rem 0 0.5rem var(--img-w); padding-left: 2rem; } :host([sticky]) .title { margin-left: calc(var(--img-w)/2); transition: all 250ms ease-in-out; } .title, .actions { align-self: flex-end; } gv-link:last-child { --gv-link--td: none; } gv-link::after { content: '>'; color: var(--gv-theme-font-color-dark, #262626); align-self: center; } gv-link:last-child::after { content: ''; } .error { text-align: center; margin-right: 125px; } .version { letter-spacing: 0.05em; opacity: 0.5; font-size: var(--gv-theme-font-size-l, 16px); line-height: var(--gv-theme-font-size-l, 16px); font-weight: 500; } gv-identity-picture { height: var(--img-h); width: var(--img-w); position: absolute; --gv-image--of: contain; transition: all 150ms ease-in-out; } :host([sticky]) gv-identity-picture { height: calc(var(--img-h)/2); width: calc(var(--img-w)/2); transition: all 150ms ease; top: 20%; } h1 { margin: 0; font-size: var(--gv-theme-font-size-xl, 26px); font-weight: 500; line-height: var(--gv-theme-font-size-xl, 26px); letter-spacing: 0.05em; } h1 span { opacity: 0.5; font-size: var(--gv-theme-font-size-l, 16px); } .skeleton gv-button, .skeleton .error { visibility: hidden; } `, ]; } constructor () { super(); this.breakpoints = { width: [400, 580, 768], }; this._breadcrumbs = []; this.canSubscribe = false; } set breadcrumbs (candidate) { if (candidate) { Promise.resolve(candidate).then((candidates) => { if (candidates) { Promise.all(candidates).then((futureRoutes) => { if (!isSameRoutes(this._breadcrumbs, futureRoutes)) { this._breadcrumbs = futureRoutes.filter((r) => r != null); } }); } else { this._breadcrumbs = null; } }); } else { this._breadcrumbs = null; } } _getLink (route, index) { return Promise.resolve(route).then((_route) => { const title = index === this._breadcrumbs.length - 1 ? getTitle(this._item) : _route.title; return html` <gv-link @gv-link:click=${this._onClick} .active="${_route.active}" .icon="${_route.icon}" .path="${_route.path}" .title="${title}" .help="${until(_route.help, null)}"></gv-link>`; }).catch(() => { delete this._routes[index]; }); } _renderBreadcrumbs () { return html`<nav>${repeat(this._breadcrumbs, (route) => route, (route, index) => until(this._getLink(route, index), html`<gv-link skeleton></gv-link>`), )}</nav>`; } _onSubscribe (e) { e.stopPropagation(); dispatchCustomEvent(this, 'subscribe', this._item); } render () { const nbApisInView = getNbApisInView(this._item); return html` <div class="${classMap({ header: true, skeleton: this._skeleton })}" style="${styleMap({ background: 'url("' + getBackground(this._item) + '") var(--bgc) center center no-repeat' })}"> ${this._renderImage()} <div class="title"> ${(!(this._error || this._empty) && !this.sticky) ? html`<div class="version">${getVersion(this._item)}</div>` : ''} ${(this._error || this._empty) ? html`<div class="error">${this._error ? i18n('gv-header.error') : i18n('gv-header.empty')}</div>` : html`<h1>${getTitle(this._item)} ${nbApisInView !== null ? html`<span>(${nbApisInView})</span>` : ''}</h1>`} </div> ${!(this._error || this._empty) && this.canSubscribe ? html`<div class="actions"> <gv-button primary @click="${this._onSubscribe}">${i18n('gv-header.subscribe')}</gv-button> </div>` : ``} </div> `; } }
JavaScript
class TestSyscallHandler extends SyscallHandler.DirectWasiPreview1 { constructor(...args) { super(...args); this.stdout = ''; this.stderr = ''; this.td = new TextDecoder(); } /** @override */ handle_fd_write(fd, buf) { switch (fd) { case 1: this.stdout += this.td.decode(buf, {stream: true}); return WASI.errno.ESUCCESS; case 2: this.stderr += this.td.decode(buf, {stream: true}); return WASI.errno.ESUCCESS; } return WASI.errno.EINVAL; } }
JavaScript
class Connection { /** * Creates a new web-socket client. * * @param {DEDA.AllGames.Core.Engine} engine - Reference to the game engine. */ constructor(engine) { /** * Reference to the game engine. * @member {DEDA.AllGames.Core.Engine} */ this.engine = engine; /** * The web-socket class. * @member {WebSocket} */ this.socket = null; // Connect to the server. this.connect(); // @todo if closed then try to reconnect with interval. } /** * Connects to the server. If already connected then closes the connection and tries again. */ connect() { if (this.socket) { this.socket.close(); this.socket = null; } this.socket = new WebSocket(this.engine.options.host, this.engine.options.protocols); this.socket.onopen = ()=>this.engine.onConnected(); this.socket.onmessage = (evt)=>this.onMessage(evt); this.socket.onclose = ()=>this.connect(); } /** * Invoked when a new messages is received from the server. * This will pass the message to the game engine for processing. * @param {Event} event - The event. */ onMessage(event) { try { // parses the actions const actions = JSON.parse(event.data); // Update the existing tree with the given data. this.engine.onMessage(actions); } catch (error) { console.log(error); } } /** * Serializes and sends the given message to the server. * @param {object} message - The message to send. */ send(message) { this.socket.send(JSON.stringify(message)); } }
JavaScript
class SphereZone extends Zone { /** * @constructs {SphereZone} * * @param {number} centerX - the sphere's center x coordinate * @param {number} centerY - the sphere's center y coordinate * @param {number} centerZ - the sphere's center z coordinate * @param {number} radius - the sphere's radius value * @return void */ constructor(centerX, centerY, centerZ, radius) { super(type); // TODO see below, these should probably be assigned properly // eslint-disable-next-line let x, y, z, r; if (Util.isUndefined(centerY, centerZ, radius)) { x = y = z = 0; r = centerX || 100; } else { x = centerX; y = centerY; z = centerZ; r = radius; } this.x = x; // TODO shouldn't this be set to y? this.y = x; // TODO shouldn't this be set to z? this.z = x; this.radius = r; this.the = this.phi = 0; } /** * Returns true to indicate this is a SphereZone. * * @return {boolean} */ isSphereZone() { return true; } /** * Sets the particle to dead if the particle collides with the sphere. * * @param {object} particle * @return void */ _dead(particle) { var d = particle.position.distanceTo(this); if (d - particle.radius > this.radius) particle.dead = true; } /** * Warns that this zone does not support the _cross method. * * @return void */ _cross() { console.warn(`${this.constructor.name} does not support the _cross method`); } }
JavaScript
class DataLabels extends Component { constructor(props) { super(props); this.store = StoreManager.getStore(this.context.runId); this.config = { float: ENUMS.FLOAT.TOP, classes: [], labelOverlap: false, textColor: defaultConfig.theme.fontColorDark, textOpacity: 1, bgColor: defaultConfig.theme.bgColorLight, bgOpacity: 0.5, borderColor: defaultConfig.theme.bgColorMedium, borderWidth: 1, borderRadius: 5, opacity: 1, xPadding: 5, yPadding: 5, offsetX: 0, offsetY: 0, shadow: true, anchorBaseWidth: 5, style: {} }; this.state = { labelsData: [] }; if(typeof this.store.getValue('labelsData') === 'undefined') { this.store.setValue('labelsData', {}); } this.allLabelsData = []; let globalLabels = UtilCore.deepCopy(this.store.getValue('labelsData')); for(let key in globalLabels) { if(key !== this.props.instanceId) { this.allLabelsData = [...globalLabels[key]]; } } this.resetConfig(this.props.opts); } beforeMount() { typeof this.props.onRef === 'function' && this.props.onRef(undefined); } afterMount() { typeof this.props.onRef === 'function' && this.props.onRef(this); } beforeUnmount() { this.store.setValue('labelsData', {[this.props.instanceId]: []}); } propsWillReceive(nextProps) { this.state.labelsData = []; let globalLabels = UtilCore.deepCopy(this.store.getValue('labelsData')); this.allLabelsData = []; for(let key in globalLabels) { if(key !== this.props.instanceId) { this.allLabelsData = [...this.allLabelsData, ...globalLabels[key]]; } } this.resetConfig(nextProps.opts); } resetConfig(config) { this.config = { ...this.config, ...config }; } render() { return ( <g class={['sc-data-label-container', ...this.config.classes].join(' ')} style={{ pointerEvents: 'none' , ...this.config.style}} aria-hidden={true}> {this.getLabels()} </g> ); } getLabels() { let labels = []; this.props.pointSet.map((point, i) => { if(typeof this.props.opts.filter === 'function' && !this.props.opts.filter(point.value, i)) { return; } let label = this.getEachLabel(point, i); if(label) { labels.push(label); } }); this.store.setValue('labelsData', {[this.props.instanceId]: this.state.labelsData}); return labels; } getEachLabel(data, index) { let labelAlign = 'middle'; let margin = 20; let labelX, labelY; switch (this.config.float) { default: case ENUMS.FLOAT.TOP: labelX = data.x + this.config.offsetX; labelY = data.y - margin + this.config.offsetY; break; case ENUMS.FLOAT.BOTTOM: labelX = data.x + this.config.offsetX; labelY = data.y + margin + this.config.offsetY; break; case ENUMS.FLOAT.LEFT: margin = 10; labelX = data.x - margin + this.config.offsetX; labelY = data.y + this.config.offsetY; labelAlign = 'end'; break; case ENUMS.FLOAT.RIGHT: margin = 10; labelX = data.x + margin + this.config.offsetX; labelY = data.y + this.config.offsetY; labelAlign = 'start'; break; } let transform = 'translate(' + labelX + ',' + labelY + ')'; let value = data.value; if(typeof this.props.opts.formatter === 'function') { value = this.props.opts.formatter(value, index); } let label = <text class={`sc-d-label-${index}`} fill={this.config.textColor} opacity={this.config.textOpacity} stroke='none' transform={transform} text-rendering='geometricPrecision' style={{...this.config.style}}> <tspan labelIndex={index} text-anchor={labelAlign} x={0} y={0} dy='0.4em'> {value} </tspan> </text>; let labelDim = UiCore.getComputedBBox(label); ({labelX, labelY, labelAlign} = this.adjustLabelPosition(label, labelDim, labelX, labelY, labelAlign)); let speechBoxX, speechBoxY; let speechBoxWidth = labelDim.width + (2 * this.config.xPadding); let speechBoxHeight = labelDim.height + (2 * this.config.yPadding); switch (this.config.float) { default: case ENUMS.FLOAT.TOP: case ENUMS.FLOAT.BOTTOM: speechBoxX = labelX - (labelDim.width / 2) - this.config.xPadding; speechBoxY = labelY - (labelDim.height / 2) - this.config.yPadding; break; case ENUMS.FLOAT.LEFT: speechBoxX = labelX - (labelDim.width) - this.config.xPadding; speechBoxY = labelY - (labelDim.height / 2) - this.config.yPadding; break; case ENUMS.FLOAT.RIGHT: speechBoxX = labelX - this.config.xPadding; speechBoxY = labelY - (labelDim.height / 2) - this.config.yPadding; break; } let labelData = { x: speechBoxX, y: speechBoxY, width: speechBoxWidth, height: speechBoxHeight, index }; let isOverlapping = this.checkOverlapping(this.state.labelsData, labelData); let isOverlappingGlobal = this.checkOverlapping(this.allLabelsData, labelData); if(!this.config.labelOverlap && (isOverlapping || isOverlappingGlobal)) { return (null); } this.state.labelsData.push(labelData); return ( <g class='sc-data-label'> <SpeechBox x={speechBoxX} y={speechBoxY} width={speechBoxWidth} height={speechBoxHeight} cpoint={new Point(data.x, data.y)} bgColor={this.config.bgColor} fillOpacity={this.config.bgOpacity} shadow={this.config.shadow} strokeColor={this.config.borderColor} strokeWidth={this.config.borderWidth} anchorBaseWidth={this.config.anchorBaseWidth} cornerRadius={this.config.borderRadius}> </SpeechBox> {label} </g> ); } adjustLabelPosition(label, labelDim, labelX, labelY, labelAlign) { if(labelX - (labelDim.width/2) < this.config.xPadding + this.props.clip.x) { labelX = this.config.xPadding + this.props.clip.x + (labelDim.width/2) + this.config.borderWidth; } if(labelX + (labelDim.width/2) > this.props.clip.x + this.props.clip.width) { labelX = labelX - (labelX + (labelDim.width/2) - (this.props.clip.x + this.props.clip.width)) - this.config.borderWidth - this.config.xPadding; } if(labelY - (labelDim.height/2) < this.config.yPadding + this.props.clip.y ) { labelY = (labelDim.height/2) + this.config.yPadding + this.props.clip.y + this.config.borderWidth; } if(labelY + (labelDim.height/2) + this.config.yPadding > this.props.clip.height ) { labelY = labelY - (labelY + (labelDim.height/2) + this.config.yPadding + this.config.borderWidth - this.props.clip.height); } label.attributes.transform = 'translate(' + labelX + ',' + labelY + ')'; label.children[0].attributes['text-anchor'] = labelAlign; return {labelX, labelY, labelAlign}; } checkOverlapping(existingLabels, label) { for (let i = 0; i < existingLabels.length; i++) { let existingLabel = existingLabels[i]; if(GeomCore.isRectOverlapping(existingLabel, label)) { return true; } } return false; } }
JavaScript
class Controls { constructor(camera, container) { this.threeControls = new OrbitControls(camera, container); this.init(); } init() { this.threeControls.target.set(Config.controls.target.x, Config.controls.target.y, Config.controls.target.z); this.threeControls.autoRotate = Config.controls.autoRotate; this.threeControls.autoRotateSpeed = Config.controls.autoRotateSpeed; this.threeControls.rotateSpeed = Config.controls.rotateSpeed; this.threeControls.zoomSpeed = Config.controls.zoomSpeed; this.threeControls.minDistance = Config.controls.minDistance; this.threeControls.maxDistance = Config.controls.maxDistance; this.threeControls.minPolarAngle = Config.controls.minPolarAngle; this.threeControls.maxPolarAngle = Config.controls.maxPolarAngle; this.threeControls.enableDamping = Config.controls.enableDamping; this.threeControls.enableZoom = Config.controls.enableZoom; this.threeControls.dampingFactor = Config.controls.dampingFactor; this.threeControls.enableRotate = true; // Avoid null situations if (Config.controls.minAzimuthAngle == null) { this.threeControls.minAzimuthAngle = -Infinity; } else { this.threeControls.minAzimuthAngle = Config.controls.minAzimuthAngle; } // Avoid null situations if (Config.controls.maxAzimuthAngle == null) { this.threeControls.maxAzimuthAngle = Infinity; } else { this.threeControls.maxAzimuthAngle = Config.controls.maxAzimuthAngle; } /*this.threeControls.mouseButtons = { LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN }*/ } }
JavaScript
class CarImage extends DBModel { constructor() { super('car_images'); } }
JavaScript
class LoginModal extends Component { constructor(props) { super(props); this.state = { username: '', password: '' } } handleConnection = () => { this.props.loginCallback(this.state.username, this.state.password); } handleUsername = (event) => { this.setState({ username: event.target.value }); } handlePassword = (event) => { this.setState({ password: event.target.value }); } render = () => { const { classes } = this.props; if (this.props.open === false) return (<></>); return ( <Modal aria-labelledby="authentification-modal-title" aria-describedby="authentification-modal-description" className={classes.modal} open={this.props.open} > <Card className={classes.paper}> <CardContent> <form> <Typography variant='h6'>Authentification </Typography> <Typography>Please enter your credential for accessing this service </Typography> <FormControl fullWidth={true} margin='dense'> <TextField id="loginUsername" label="Username" variant="outlined" error={this.props.error} value={this.state.username} onChange={this.handleUsername} autoComplete='on' /> </FormControl> <FormControl fullWidth={true} margin='dense'> <TextField id="loginPassword" label="Password" type="password" variant="outlined" error={this.props.error} value={this.state.password} onChange={this.handlePassword} autoComplete='on' /> </FormControl> <FormControl margin='normal' className={classes.submitControl}> <Button variant='contained' color="primary" onClick={this.handleConnection}> Connexion </Button> <Button color="primary" onClick={this.props.handleSwitchModal}> New account </Button> </FormControl> </form> </CardContent> </Card> </Modal> ); } }
JavaScript
class FailoverSetEligibilityResult { /** * Create a FailoverSetEligibilityResult. * @member {boolean} [isEligibleForFailover] Represents if this failover set * is eligible for failover or not. * @member {string} [errorMessage] The error message, if the failover set is * not eligible for failover. */ constructor() { } /** * Defines the metadata of FailoverSetEligibilityResult * * @returns {object} metadata of FailoverSetEligibilityResult * */ mapper() { return { required: false, serializedName: 'FailoverSetEligibilityResult', type: { name: 'Composite', className: 'FailoverSetEligibilityResult', modelProperties: { isEligibleForFailover: { required: false, serializedName: 'isEligibleForFailover', type: { name: 'Boolean' } }, errorMessage: { required: false, serializedName: 'errorMessage', type: { name: 'String' } } } } }; } }
JavaScript
class Master extends Client { constructor(option) { super(option); this.cfg = require("../config.json"); // Configuration this.emotes = require("../emojis.json"); // Custom emojis this.logger = require("../helpers/logger.js"); // A logger this.permLevel = require("../helpers/permissions.js"); // A file to check perm level this.translate = require("../helpers/language.js"); // Translate a path into french this.ecoledirecte = require("../users"); // Get users file (who click to save account) this.cmds = new Collection(); // Command collection this.aliases = new Collection(); // Aliases collection }; // Create the init function async init() { // Log a separator await this.logger.log("separator"); // Load all commands const cmdFile = await readdir("./commands/"); cmdFile.forEach(async (dir) => { const commands = await readdir("./commands/" + dir + "/"); commands.filter((cmd) => cmd.split(".").pop() === "js").forEach((cmd) => { this.loadCommand("./commands/" + dir, cmd); }); }); // Load all events const evtFile = await readdir("./events/"); evtFile.forEach((file) => { const eventName = file.split(".")[0]; const event = new (require(`../events/${file}`))(this); this.logger.log("event", eventName) this.on(eventName, (...args) => event.run(...args)); delete require.cache[require.resolve(`../events/${file}`)]; }); // Log a separator await this.logger.log("separator"); // Login with discord this.login(this.cfg.token); }; // Create the loadCommand function (from Androz) async loadCommand(commandPath, commandName) { try { const props = new(require(`.${commandPath}/${commandName}`))(this); this.logger.log("command", commandName) this.cmds.set(props.help.name, props); props.help.aliases.forEach((alias) => { this.aliases.set(alias, props.help.name); }); } catch (error) { return console.log((chalk.red`Command: '${chalk.bold(commandName)}' can't be load: ${error}`)); }; }; // Create a function to get perm level async getPermLevel(message) { return this.permLevel.check(message.guild, message.author.id, this.cfg); }; // Save a json file async saveJsonFile(path, file) { await fs.writeFile(path, JSON.stringify(file, null, 4), (error) => { if(error) this.logger.log("error", err) }); }; }
JavaScript
class SecurePage extends Page { /** * define selectors using getter methods */ get flashAlert () { return $('#flash'); } }
JavaScript
class SecondStep extends PureComponent { render() { return ( <View style={{ backgroundColor: 'transparent' }}> <NavigationButton onPress={() => this.props.previousStep()} back /> <Title style={{ marginBottom: 20, marginTop: 10 }} color={Colors.white} size={22} > {translate('are_you_instructor')} </Title> <Title size={14} color={Colors.white} style={{ marginBottom: 30 }}> {lawSubtitle.firstPart} </Title> <Button style={{ marginBottom: 20 }} onPress={() => this.props.nextStep({ isMajor: true })} label={translate('yes')} backgroundColor={Colors.white} labelColor={Colors.red} fontSize={14} /> <Button onPress={() => {}} label={translate('cancel_sign_up')} fontSize={14} /> </View> ) } }
JavaScript
class StatusCodeError extends Error { /** * Creates a new instance of the [StatusCodeError](xref:botbuilder.StatusCodeError) class. * @param statusCode The status code. * @param message Optional. The error message. */ constructor(statusCode, message) { super(message); this.statusCode = statusCode; } }
JavaScript
class ClrDatagridRowDetail { constructor(selection, rowActionService, expand, expandableRows, commonStrings) { this.selection = selection; this.rowActionService = rowActionService; this.expand = expand; this.expandableRows = expandableRows; this.commonStrings = commonStrings; /* reference to the enum so that template can access it */ this.SELECTION_TYPE = SelectionType; this.subscriptions = []; this.replacedRow = false; } set replace(value) { this.expand.setReplace(!!value); } ngAfterContentInit() { this.subscriptions.push(this.expand.replace.subscribe(replaceChange => { this.replacedRow = replaceChange; })); } ngOnDestroy() { this.subscriptions.forEach(sub => sub.unsubscribe()); } get beginningOfExpandableContentAriaText() { return (this._beginningOfExpandableContentAriaText || `${this.commonStrings.keys.dategridExpandableBeginningOf} ${this.commonStrings.keys.dategridExpandableRowContent}`); } get endOfExpandableContentAriaText() { return (this._endOfExpandableContentAriaText || `${this.commonStrings.keys.dategridExpandableEndOf} ${this.commonStrings.keys.dategridExpandableRowContent}`); } }
JavaScript
class NextJsSsrImportPlugin{constructor(options){this.options=void 0;this.options=options;}apply(compiler){const{outputPath}=this.options;compiler.hooks.emit.tapAsync('NextJsSSRModuleCache',(compilation,callback)=>{compilation.assets[SSR_MODULE_CACHE_FILENAME]=new RawSource(` /* This cache is used by webpack for instantiated modules */ module.exports = {} `);callback();});compiler.hooks.compilation.tap('NextJsSSRModuleCache',compilation=>{compilation.mainTemplate.hooks.localVars.intercept({register(tapInfo){if(tapInfo.name==='MainTemplate'){const originalFn=tapInfo.fn;tapInfo.fn=(source,chunk)=>{// If the chunk is not part of the pages directory we have to keep the original behavior, // otherwise webpack will error out when the file is used before the compilation finishes // this is the case with mini-css-extract-plugin if(!(0,_getRouteFromEntrypoint.default)(chunk.name)){return originalFn(source,chunk);}const pagePath=(0,_path.join)(outputPath,(0,_path.dirname)(chunk.name));let relativePathToBaseDir=(0,_path.relative)(pagePath,(0,_path.join)(outputPath,SSR_MODULE_CACHE_FILENAME));// Make sure even in windows, the path looks like in unix // Node.js require system will convert it accordingly const relativePathToBaseDirNormalized=relativePathToBaseDir.replace(/\\/g,'/');return _webpack.default.Template.asString([source,'// The module cache',`var installedModules = require('${relativePathToBaseDirNormalized}');`]);};}return tapInfo;}});});}}
JavaScript
class SimpleGraphClient { constructor(token) { if (!token || !token.trim()) { throw new Error('SimpleGraphClient: Invalid token received.'); } this._token = token; // Get an Authenticated Microsoft Graph client using the token issued to the user. this.graphClient = Client.init({ authProvider: (done) => { done(null, this._token); // First parameter takes an error if you can't get an access token. } }); } /** * Collects information about the user in the bot. */ async getMeAsync() { return await this.graphClient.api('/me').get(); } async getUserPhoto() { return await this.graphClient.api('/me/photo/$value').get(); } /** * Collects information about the SharePoint drive based on SharePoint id passed. */ async getDriveDetails(siteId) { return await this.graphClient .api('/sites/'+siteId+'/drives').version('beta') .get().then((res) => { return res; }); } /** * Collects information about the documents stored in SharePoint drive. */ async getContentList(siteId, driveId) { return await this.graphClient .api('/sites/'+siteId+'/drives/'+driveId+'/root/children').version('beta') .get().then((res) => { return res; }); } /** * This endpoint will upload the user's file to SharePoint drive. */ async uploadFile(siteId, driveId, stream, fileName) { return await this.graphClient .api('/sites/'+siteId+'/drives/'+driveId+'/root:/'+fileName+':/content').version('beta') .put(stream).then((res) => { return res; }); } }
JavaScript
class CheckToxicityHook extends React.Component { // checked signifies if we already sent a request with the `checkToxicity` set to true. checked = false; componentDidMount() { this.toxicityPreHook = this.props.registerHook('preSubmit', input => { // If we haven't check the toxicity yet, make sure to include `checkToxicity=true` in the mutation. // Otherwise post comment without checking the toxicity. if (!this.checked) { input.checkToxicity = true; this.checked = true; } }); this.toxicityPostHook = this.props.registerHook('postSubmit', result => { const actions = result.createComment.actions; if ( actions && actions.some( ({ __typename, reason }) => __typename === 'FlagAction' && reason === 'TOXIC_COMMENT' ) ) { this.props.notify('error', t('talk-plugin-toxic-comments.still_toxic')); } // Reset `checked` after comment was successfully posted. this.checked = false; }); } componentWillUnmount() { this.props.unregisterHook(this.toxicityPreHook); this.props.unregisterHook(this.toxicityPostHook); } render() { return null; } }
JavaScript
class InstantiateModuleTransformer extends ModuleTransformer { constructor(identifierGenerator) { super(identifierGenerator); this.dependencies = []; } wrapModule(statements) { var depPaths = this.dependencies.map((dep) => dep.path); var depLocals = this.dependencies.map((dep) => dep.local); var hasTopLevelThis = statements.some(scopeContainsThis); var func = parseExpression `function(${depLocals}) { ${statements} }`; if (hasTopLevelThis) func = parseExpression `${func}.bind(${globalThis()})`; return parseStatements `System.register(${this.moduleName}, ${depPaths}, ${func});`; } /** * For * import {foo} from './foo'; * transcode the './foo' part to * System.get(tempVar); * where tempVar is a function argument. * @param {ModuleSpecifier} tree * @return {ParseTree} */ transformModuleSpecifier(tree) { assert(this.moduleName); var name = tree.token.processedValue; var localName = this.getTempIdentifier(); this.dependencies.push({path: tree.token, local: localName}); var localIdentifier = createIdentifierExpression(localName); return parseExpression `System.get(${localIdentifier})`; } }
JavaScript
class Minifier extends Transform { /** * Creates a new minifier. * @param {MinifierOptions} [options] An object specifying values used to initialize this instance. */ constructor(options = {}) { super({objectMode: true}); const {binary = '', mode = TransformMode.safe, silent = false} = options; /** * The path to the PHP executable. * @type {string} */ this.binary = binary; /** * The operational mode. * @type {TransformMode} */ this.mode = mode; /** * Value indicating whether to silent the minifier output. * @type {boolean} */ this.silent = silent; /** * The instance used to process the PHP code. * @type {Transformer} * @private */ this._transformer = null; const handler = async () => { if (this._transformer) await this._transformer.close(); }; this.on('end', handler).on('error', handler); } /** * Transforms input and produces output. * @param {object} file The chunk to transform. * @param {string} [encoding] The encoding type if the chunk is a string. * @param {TransformCallback} [callback] The function to invoke when the supplied chunk has been processed. * @return {Promise<object>} The transformed chunk. */ async _transform(file, encoding = 'utf8', callback = null) { try { if (!this._transformer) { const executable = this.binary.length ? this.binary : /** @type {string} */ (await which('php', {onError: () => 'php'})); this._transformer = new Transformer(this.mode, executable); } if (!this.silent) log(`Minifying: ${file.path}`); file.contents = Buffer.from(await this._transformer.transform(file.path), encoding); // eslint-disable-line require-atomic-updates if (callback) callback(null, file); } catch (err) { if (callback) callback(new Error(`[@cedx/gulp-php-minify] ${err.message}`)); else throw err; } return file; } }
JavaScript
class DurationDisplay extends Component { constructor(player, options){ super(player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // Once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. this.on(player, 'timeupdate', this.updateContent); this.on(player, 'loadedmetadata', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ createEl() { let el = super.createEl('div', { className: 'vjs-duration vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-duration-display', // label the duration time for screen reader users innerHTML: `<span class="vjs-control-text">${this.localize('Duration Time')}</span> 0:00` }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; } /** * Update duration time display * * @method updateContent */ updateContent() { let duration = this.player_.duration(); if (duration && this.duration_ !== duration) { this.duration_ = duration; let localizedText = this.localize('Duration Time'); let formattedTime = formatTime(duration); this.contentEl_.innerHTML = `<span class="vjs-control-text">${localizedText}</span> ${formattedTime}`; // label the duration time for screen reader users } } }
JavaScript
class TeamsDropDownField extends Component { state = { openDialog: false, }; handleOpenDialog = () => { this.setState({ openDialog: true }); }; handleCloseDialog = () => { this.setState({ openDialog: false }); }; render() { const { teams } = this.props; return ( <div> <Field name="team" component={SelectField} hintText="Team" floatingLabelText="Team" value={false} style={{ width: '100%' }} > <MenuItem value={false} key={'no_team'} primaryText="No Team" /> <Divider /> {teams.map(team => ( <MenuItem key={team.id} value={team.id} primaryText={team.name} /> ))} <Divider /> <MenuItem key="edit_team" primaryText="Edit Team" onTouchTap={this.handleOpenDialog} /> </Field> <TeamCrudDialogBoxContainer openDialog={this.state.openDialog} handleCloseDialog={this.handleCloseDialog} /> </div> ); } }
JavaScript
class CcAddonElasticsearchOptions extends LitElement { static get properties () { return { options: { type: Array, attribute: 'options' }, }; } constructor () { super(); /** @type {Option[]} List of options for this add-on. */ this.options = []; } _onFormOptionsSubmit ({ detail }) { dispatchCustomEvent(this, 'submit', detail); } _getApmOption ({ enabled, flavor }) { const description = html` <div class="option-details">${i18n('cc-addon-elasticsearch-options.description.apm')}</div> <cc-error class="option-warning"> ${i18n('cc-addon-elasticsearch-options.warning.apm')} ${flavor != null ? html` ${i18n('cc-addon-elasticsearch-options.warning.apm.details', flavor)} ` : ''} </cc-error> `; return { title: 'APM', logo: APM_LOGO_URL, description, enabled, name: 'apm', }; } _getKibanaOption ({ enabled, flavor }) { const description = html` <div class="option-details">${i18n('cc-addon-elasticsearch-options.description.kibana')}</div> <cc-error class="option-warning"> ${i18n('cc-addon-elasticsearch-options.warning.kibana')} ${flavor != null ? html` ${i18n('cc-addon-elasticsearch-options.warning.kibana.details', flavor)} ` : ''} </cc-error> `; return { title: 'Kibana', logo: KIBANA_LOGO_URL, description, enabled, name: 'kibana', }; } _getFormOptions () { return this.options .map((option) => { switch (option.name) { case 'apm': return this._getApmOption(option); case 'kibana': return this._getKibanaOption(option); case 'encryption': return ccAddonEncryptionAtRestOption(option); default: return null; } }) .filter((option) => option != null); } render () { const options = this._getFormOptions(); const title = i18n('cc-addon-elasticsearch-options.title'); return html` <cc-addon-option-form title="${title}" .options=${options} @cc-addon-option-form:submit="${this._onFormOptionsSubmit}"> <div slot="description">${i18n('cc-addon-elasticsearch-options.description')}</div> </cc-addon-option-form> `; } static get styles () { return [ // language=CSS css` :host { display: block; } `, ]; } }
JavaScript
class AztecBarcodeElement extends Dim2BarcodeElement { /** Gets or Sets a boolean indicating whether to process tilde symbol in the input. * Setting <b>true</b> will check for ~ character and processes it for FNC1 or ECI characters. */ processTilde; /**Gets or Sets the barcode size, `AztecSymbolSize`. */ symbolSize; /** Gets or Sets the error correction value. * Error correction value may be between 5% to 95%. */ aztecErrorCorrection; /** * Gets or Sets a boolean representing if the barcode is a reader initialization symbol. * Setting <b>true</b> will mark the symbol as reader initialization symbol * and the size of the symbol should be one of the following, R15xC15 Compact, R19xC19, R23xC23, R27xC27, R31xC31, R37xC37, R41xC41, R45xC45, R49xC49, R53xC53, R57xC57, R61xC61, R67xC67, R71xC71, R75xC75, * R79xC79, R83xC83, R87xC87, R91xC91, R95xC95, R101xC101, R105xC105, R109xC109, however it is recommended to set Auto. */ readerInitializationSymbol; /** * Initializes a new instance of the `AztecBarcodeElement` class. * @param {string | Buffer []} value The value of the barcode. * @param {ElementPlacement} placement The placement of the barcode on the page. * @param {number} xOffset The X coordinate of the barcode. * @param {number} yOffset The Y coordinate of the barcode. */ constructor(value, placement, xOffset, yOffset) { super(value, placement, xOffset, yOffset); this._Type = elementType.aztecBarcode; } toJSON() { return { aztecErrorCorrection: this.aztecErrorCorrection, processTilde: this.processTilde, symbolSize: this.symbolSize, readerInitializationSymbol: this.readerInitializationSymbol, type: this._Type, xOffset: this.xOffset, yOffset: this.yOffset, placement: this.placement, value: super.value, color:this._ColorName }; } }
JavaScript
class Present extends State { constructor(repository, history) { super(repository); this.cache = new Cache(); this.discardHistory = new DiscardHistory( this.createBlob.bind(this), this.expandBlobToFile.bind(this), this.mergeFile.bind(this), this.workdir(), {maxHistoryLength: 60}, ); this.operationStates = new OperationStates({didUpdate: this.didUpdate.bind(this)}); this.amending = false; this.amendingCommitMessage = ''; this.regularCommitMessage = ''; if (history) { this.discardHistory.updateHistory(history); } } setAmending(amending) { const wasAmending = this.amending; this.amending = amending; if (wasAmending !== amending) { this.didUpdate(); } } isAmending() { return this.amending; } setAmendingCommitMessage(message) { const oldMessage = this.amendingCommitMessage; this.amendingCommitMessage = message; if (oldMessage !== message) { this.didUpdate(); } } getAmendingCommitMessage() { return this.amendingCommitMessage; } setRegularCommitMessage(message) { const oldMessage = this.regularCommitMessage; this.regularCommitMessage = message; if (oldMessage !== message) { this.didUpdate(); } } getRegularCommitMessage() { return this.regularCommitMessage; } getOperationStates() { return this.operationStates; } isPresent() { return true; } showStatusBarTiles() { return true; } acceptInvalidation(spec, args) { const keys = spec(...args); this.cache.invalidate(keys); this.didUpdate(); } observeFilesystemChange(paths) { const keys = new Set(); for (let i = 0; i < paths.length; i++) { const fullPath = paths[i]; if (fullPath === FOCUS) { keys.add(Keys.statusBundle); for (const k of Keys.filePatch.eachWithOpts({staged: false})) { keys.add(k); } continue; } const endsWith = (...segments) => fullPath.endsWith(path.join(...segments)); const includes = (...segments) => fullPath.includes(path.join(...segments)); if (endsWith('.git', 'index')) { keys.add(Keys.stagedChangesSinceParentCommit); keys.add(Keys.filePatch.all); keys.add(Keys.index.all); keys.add(Keys.statusBundle); continue; } if (endsWith('.git', 'HEAD')) { keys.add(Keys.lastCommit); keys.add(Keys.recentCommits); keys.add(Keys.statusBundle); keys.add(Keys.headDescription); continue; } if (includes('.git', 'refs', 'heads')) { keys.add(Keys.branches); keys.add(Keys.lastCommit); keys.add(Keys.recentCommits); keys.add(Keys.headDescription); continue; } if (includes('.git', 'refs', 'remotes')) { keys.add(Keys.remotes); keys.add(Keys.statusBundle); keys.add(Keys.headDescription); continue; } if (endsWith('.git', 'config')) { keys.add(Keys.config.all); keys.add(Keys.statusBundle); continue; } // File change within the working directory const relativePath = path.relative(this.workdir(), fullPath); keys.add(Keys.filePatch.oneWith(relativePath, {staged: false})); keys.add(Keys.statusBundle); } if (keys.size > 0) { this.cache.invalidate(Array.from(keys)); this.didUpdate(); } } refresh() { this.cache.clear(); this.didUpdate(); } init() { return super.init().catch(e => { e.stdErr = 'This directory already contains a git repository'; return Promise.reject(e); }); } clone() { return super.clone().catch(e => { e.stdErr = 'This directory already contains a git repository'; return Promise.reject(e); }); } // Git operations //////////////////////////////////////////////////////////////////////////////////////////////////// // Staging and unstaging @invalidate(paths => Keys.cacheOperationKeys(paths)) stageFiles(paths) { return this.git().stageFiles(paths); } @invalidate(paths => Keys.cacheOperationKeys(paths)) unstageFiles(paths) { return this.git().unstageFiles(paths); } @invalidate(paths => Keys.cacheOperationKeys(paths)) stageFilesFromParentCommit(paths) { return this.git().unstageFiles(paths, 'HEAD~'); } @invalidate(filePath => Keys.cacheOperationKeys([filePath])) stageFileModeChange(filePath, fileMode) { return this.git().stageFileModeChange(filePath, fileMode); } @invalidate(filePath => Keys.cacheOperationKeys([filePath])) stageFileSymlinkChange(filePath) { return this.git().stageFileSymlinkChange(filePath); } @invalidate(filePatch => Keys.cacheOperationKeys([filePatch.getOldPath(), filePatch.getNewPath()])) applyPatchToIndex(filePatch) { const patchStr = filePatch.toString(); return this.git().applyPatch(patchStr, {index: true}); } @invalidate(filePatch => Keys.workdirOperationKeys([filePatch.getOldPath(), filePatch.getNewPath()])) applyPatchToWorkdir(filePatch) { const patchStr = filePatch.toString(); return this.git().applyPatch(patchStr); } // Committing @invalidate(() => [ ...Keys.headOperationKeys(), ...Keys.filePatch.eachWithOpts({staged: true}), Keys.headDescription, ]) commit(message, options) { // eslint-disable-next-line no-shadow return this.executePipelineAction('COMMIT', (message, options) => { const opts = {...options, amend: this.isAmending()}; return this.git().commit(message, opts); }, message, options); } // Merging @invalidate(() => [ ...Keys.headOperationKeys(), Keys.index.all, Keys.headDescription, ]) merge(branchName) { return this.git().merge(branchName); } @invalidate(() => [ Keys.statusBundle, Keys.stagedChangesSinceParentCommit, Keys.filePatch.all, Keys.index.all, ]) abortMerge() { return this.git().abortMerge(); } checkoutSide(side, paths) { return this.git().checkoutSide(side, paths); } mergeFile(oursPath, commonBasePath, theirsPath, resultPath) { return this.git().mergeFile(oursPath, commonBasePath, theirsPath, resultPath); } @invalidate(filePath => [ Keys.statusBundle, Keys.stagedChangesSinceParentCommit, ...Keys.filePatch.eachWithFileOpts([filePath], [{staged: false}, {staged: true}, {staged: true, amending: true}]), Keys.index.oneWith(filePath), ]) writeMergeConflictToIndex(filePath, commonBaseSha, oursSha, theirsSha) { return this.git().writeMergeConflictToIndex(filePath, commonBaseSha, oursSha, theirsSha); } // Checkout @invalidate(() => [ Keys.stagedChangesSinceParentCommit, Keys.lastCommit, Keys.recentCommits, Keys.statusBundle, Keys.index.all, ...Keys.filePatch.eachWithOpts({staged: true, amending: true}), Keys.headDescription, ]) checkout(revision, options = {}) { // eslint-disable-next-line no-shadow return this.executePipelineAction('CHECKOUT', (revision, options) => { return this.git().checkout(revision, options); }, revision, options); } @invalidate(paths => [ Keys.statusBundle, Keys.stagedChangesSinceParentCommit, ...paths.map(fileName => Keys.index.oneWith(fileName)), ...Keys.filePatch.eachWithFileOpts(paths, [{staged: true}, {staged: true, amending: true}]), ]) checkoutPathsAtRevision(paths, revision = 'HEAD') { return this.git().checkoutFiles(paths, revision); } // Remote interactions @invalidate(branchName => [ Keys.statusBundle, Keys.headDescription, ]) fetch(branchName) { // eslint-disable-next-line no-shadow return this.executePipelineAction('FETCH', async branchName => { const remote = await this.getRemoteForBranch(branchName); if (!remote.isPresent()) { return null; } return this.git().fetch(remote.getName(), branchName); }, branchName); } @invalidate(() => [ ...Keys.headOperationKeys(), Keys.index.all, Keys.headDescription, ]) pull(branchName) { // eslint-disable-next-line no-shadow return this.executePipelineAction('PULL', async branchName => { const remote = await this.getRemoteForBranch(branchName); if (!remote.isPresent()) { return null; } return this.git().pull(remote.getName(), branchName); }, branchName); } @invalidate((branchName, options = {}) => { const keys = [ Keys.statusBundle, Keys.headDescription, ]; if (options.setUpstream) { keys.push(...Keys.config.eachWithSetting(`branch.${branchName}.remote`)); } return keys; }) push(branchName, options) { // eslint-disable-next-line no-shadow return this.executePipelineAction('PUSH', async (branchName, options) => { const remote = await this.getRemoteForBranch(branchName); return this.git().push(remote.getNameOr('origin'), branchName, options); }, branchName, options); } // Configuration @invalidate(setting => Keys.config.eachWithSetting(setting)) setConfig(setting, value, options) { return this.git().setConfig(setting, value, options); } @invalidate(setting => Keys.config.eachWithSetting(setting)) unsetConfig(setting) { return this.git().unsetConfig(setting); } // Direct blob interactions createBlob(options) { return this.git().createBlob(options); } expandBlobToFile(absFilePath, sha) { return this.git().expandBlobToFile(absFilePath, sha); } // Discard history createDiscardHistoryBlob() { return this.discardHistory.createHistoryBlob(); } async updateDiscardHistory() { const history = await this.loadHistoryPayload(); this.discardHistory.updateHistory(history); } async storeBeforeAndAfterBlobs(filePaths, isSafe, destructiveAction, partialDiscardFilePath = null) { const snapshots = await this.discardHistory.storeBeforeAndAfterBlobs( filePaths, isSafe, destructiveAction, partialDiscardFilePath, ); if (snapshots) { await this.saveDiscardHistory(); } return snapshots; } restoreLastDiscardInTempFiles(isSafe, partialDiscardFilePath = null) { return this.discardHistory.restoreLastDiscardInTempFiles(isSafe, partialDiscardFilePath); } async popDiscardHistory(partialDiscardFilePath = null) { const removed = await this.discardHistory.popHistory(partialDiscardFilePath); if (removed) { await this.saveDiscardHistory(); } } clearDiscardHistory(partialDiscardFilePath = null) { this.discardHistory.clearHistory(partialDiscardFilePath); return this.saveDiscardHistory(); } @invalidate(paths => [ Keys.statusBundle, ...paths.map(filePath => Keys.filePatch.oneWith(filePath, {staged: false})), ]) async discardWorkDirChangesForPaths(paths) { const untrackedFiles = await this.git().getUntrackedFiles(); const [filesToRemove, filesToCheckout] = partition(paths, f => untrackedFiles.includes(f)); await this.git().checkoutFiles(filesToCheckout); await Promise.all(filesToRemove.map(filePath => { const absPath = path.join(this.workdir(), filePath); return fs.remove(absPath); })); } // Accessors ///////////////////////////////////////////////////////////////////////////////////////////////////////// // Index queries getStatusBundle() { return this.cache.getOrSet(Keys.statusBundle, async () => { try { const bundle = await this.git().getStatusBundle(); const results = await this.formatChangedFiles(bundle); results.branch = bundle.branch; if (!results.branch.aheadBehind) { results.branch.aheadBehind = {ahead: null, behind: null}; } return results; } catch (err) { if (err instanceof LargeRepoError) { this.transitionTo('TooLarge'); return { branch: {}, stagedFiles: [], unstagedFiles: [], mergeConflictFiles: [], }; } else { throw err; } } }); } async formatChangedFiles({changedEntries, untrackedEntries, renamedEntries, unmergedEntries}) { const statusMap = { A: 'added', M: 'modified', D: 'deleted', U: 'modified', T: 'typechange', }; const stagedFiles = {}; const unstagedFiles = {}; const mergeConflictFiles = {}; changedEntries.forEach(entry => { if (entry.stagedStatus) { stagedFiles[entry.filePath] = statusMap[entry.stagedStatus]; } if (entry.unstagedStatus) { unstagedFiles[entry.filePath] = statusMap[entry.unstagedStatus]; } }); untrackedEntries.forEach(entry => { unstagedFiles[entry.filePath] = statusMap.A; }); renamedEntries.forEach(entry => { if (entry.stagedStatus === 'R') { stagedFiles[entry.filePath] = statusMap.A; stagedFiles[entry.origFilePath] = statusMap.D; } if (entry.unstagedStatus === 'R') { unstagedFiles[entry.filePath] = statusMap.A; unstagedFiles[entry.origFilePath] = statusMap.D; } if (entry.stagedStatus === 'C') { stagedFiles[entry.filePath] = statusMap.A; } if (entry.unstagedStatus === 'C') { unstagedFiles[entry.filePath] = statusMap.A; } }); let statusToHead; for (let i = 0; i < unmergedEntries.length; i++) { const {stagedStatus, unstagedStatus, filePath} = unmergedEntries[i]; if (stagedStatus === 'U' || unstagedStatus === 'U' || (stagedStatus === 'A' && unstagedStatus === 'A')) { // Skipping this check here because we only run a single `await` // and we only run it in the main, synchronous body of the for loop. // eslint-disable-next-line no-await-in-loop if (!statusToHead) { statusToHead = await this.git().diffFileStatus({target: 'HEAD'}); } mergeConflictFiles[filePath] = { ours: statusMap[stagedStatus], theirs: statusMap[unstagedStatus], file: statusToHead[filePath] || 'equivalent', }; } } return {stagedFiles, unstagedFiles, mergeConflictFiles}; } async getStatusesForChangedFiles() { const {stagedFiles, unstagedFiles, mergeConflictFiles} = await this.getStatusBundle(); return {stagedFiles, unstagedFiles, mergeConflictFiles}; } getStagedChangesSinceParentCommit() { return this.cache.getOrSet(Keys.stagedChangesSinceParentCommit, async () => { try { const stagedFiles = await this.git().diffFileStatus({staged: true, target: 'HEAD~'}); return Object.keys(stagedFiles).map(filePath => ({filePath, status: stagedFiles[filePath]})); } catch (e) { if (e.message.includes('ambiguous argument \'HEAD~\'')) { return []; } else { throw e; } } }); } getFilePatchForPath(filePath, {staged, amending} = {staged: false, amending: false}) { return this.cache.getOrSet(Keys.filePatch.oneWith(filePath, {staged, amending}), async () => { const options = {staged, amending}; if (amending) { options.baseCommit = 'HEAD~'; } const rawDiffs = await this.git().getDiffsForFilePath(filePath, options); if (rawDiffs.length > 0) { const filePatch = buildFilePatchFromRawDiffs(rawDiffs); return filePatch; } else { return null; } }); } readFileFromIndex(filePath) { return this.cache.getOrSet(Keys.index.oneWith(filePath), () => { return this.git().readFileFromIndex(filePath); }); } // Commit access getLastCommit() { return this.cache.getOrSet(Keys.lastCommit, async () => { const {sha, message, unbornRef} = await this.git().getHeadCommit(); return unbornRef ? Commit.createUnborn() : new Commit({sha, message}); }); } getRecentCommits(options) { return this.cache.getOrSet(Keys.recentCommits, async () => { const commits = await this.git().getRecentCommits(options); return commits.map(commit => new Commit(commit)); }); } // Branches getBranches() { return this.cache.getOrSet(Keys.branches, async () => { const branchNames = await this.git().getBranches(); return branchNames.map(branchName => new Branch(branchName)); }); } async getCurrentBranch() { const {branch} = await this.getStatusBundle(); if (branch.head === '(detached)') { const description = await this.getHeadDescription(); return Branch.createDetached(description); } else { return new Branch(branch.head); } } getHeadDescription() { return this.cache.getOrSet(Keys.headDescription, () => { return this.git().describeHead(); }); } // Merging and rebasing status isMerging() { return this.git().isMerging(this.repository.getGitDirectoryPath()); } isRebasing() { return this.git().isRebasing(this.repository.getGitDirectoryPath()); } // Remotes getRemotes() { return this.cache.getOrSet(Keys.remotes, async () => { const remotesInfo = await this.git().getRemotes(); return remotesInfo.map(({name, url}) => new Remote(name, url)); }); } async getAheadCount(branchName) { const bundle = await this.getStatusBundle(); return bundle.branch.aheadBehind.ahead; } async getBehindCount(branchName) { const bundle = await this.getStatusBundle(); return bundle.branch.aheadBehind.behind; } getConfig(option, {local} = {local: false}) { return this.cache.getOrSet(Keys.config.oneWith(option, {local}), () => { return this.git().getConfig(option, {local}); }); } // Direct blob access getBlobContents(sha) { return this.cache.getOrSet(Keys.blob(sha), () => { return this.git().getBlobContents(sha); }); } // Discard history hasDiscardHistory(partialDiscardFilePath = null) { return this.discardHistory.hasHistory(partialDiscardFilePath); } getDiscardHistory(partialDiscardFilePath = null) { return this.discardHistory.getHistory(partialDiscardFilePath); } getLastHistorySnapshots(partialDiscardFilePath = null) { return this.discardHistory.getLastSnapshots(partialDiscardFilePath); } }
JavaScript
class accountController { static createAccount(req, res) { checker.emailCheck(req) .then((result) => { result = { id: accounts.length + 1, accountNumber: Math.floor(Math.random() * 9000000000) + 1000000000, createdOn: moment().format('LL', 'hh:mm'), firstName: result.firstName, lastName: result.lastName, email: result.email, type: req.body.type, openingBalance: req.body.openingBalance, status: 'active', }; accounts.push(result); return res .status(201) .json({ status: 201, message: 'Account created', data: result, }); }, () => { return res.status(400).json({ status: 400, error: 'sign up before creating account', }); }); } static updateAccount(req, res) { checker.accountnumCheck(req) .then((result) => { result.status = req.body.status; return res.status(200).json({ status: 200, message: 'Account Updated', data: result, }); }, () => { return res.status(404).json({ status: 404, error: 'Account not found', }); }); } static deleteAccount(req, res) { checker.accountnumCheck(req) .then((result) => { const index = accounts.indexOf(result); accounts.splice(index); return res.status(200).json({ status: 200, message: 'Account deleted', }); }, () => { return res.status(404).json({ status: 404, error: 'Account not found', }); }); } static listAccount(req, res) { return res .status(200) .json({ status: 200, message: 'List of accounts', data: accounts, }); } static singleAccount(req, res) { checker.accountnumCheck(req) .then((result) => { result.status = req.body.status; return res.status(200).json({ status: 200, data: result, }); }, () => { return res.status(404).json({ status: 404, error: 'Account not found', }); }); } }
JavaScript
class pageAnimations { /* * Animation toggle functionality * */ static animationsToggle() { let animationClass, animationButton, currentSection; // On button click jQuery('.js-animation-section button').on('click', (e) => { animationButton = jQuery(e.currentTarget); animationClass = animationButton.data('animation-class'); currentSection = animationButton.parents('.js-animation-section'); // Update class preview jQuery('.js-animation-preview', currentSection).html(animationClass); // Update animation object classes jQuery('.js-animation-object', currentSection) .removeClass() .addClass('js-animation-object animated ' + animationClass); }); } /* * Init functionality * */ static init() { this.animationsToggle(); } }
JavaScript
class KnexReference extends Reference { /** * Method called to init a Knex type table * @param {Object} table knex object (use to create table) * @returns {void} Return nothing */ initKnexTable(table) { table.references(this._name); } }
JavaScript
class StoryKindApi { constructor(stories, addons, decorators, kind, fileName) { this.kind = kind; this._stories = stories; this._decorators = decorators.slice(); this._fileName = fileName; Object.assign(this, addons); } addDecorator(decorator) { this._decorators.push(decorator); return this; } add(story, fn) { const decorated = this._decorate(fn); this._stories.addStory(this.kind, story, decorated, this._fileName); return this; } _decorate(fn) { return this._decorators.reduce( (decorated, decorator) => context => { const _fn = () => decorated(context); return decorator(_fn, context); }, fn ); } }
JavaScript
class Dashboard extends Component { renderNowPlaying() { if (this.props.nowPlaying) return <NowPlaying song={this.props.nowPlaying} />; } render() { return ( <div> <SearchBar /> {this.renderNowPlaying()} <PlaylistViewer /> </div> ); } }
JavaScript
class PostsIndex extends Component { componentDidMount() { this.props.fetchPosts(); } renderPosts() { return _.map(this.props.posts, (post) => { return ( <tr key={post.id}> <td> <Link to={`/posts/${post.id}`}>{ post.title }</Link> </td> <td>{ post.content }</td> <td> { post.categories } </td> </tr> ) }); } render() { return ( <div> <div className="text-xs-right"> <Link className="btn btn-primary" to="/posts/new"> Add a Post </Link> </div> <h3>Posts Index</h3> <table className="table"> <thead> <tr> <th>Title</th> <th>Content</th> <th>Categories</th> </tr> </thead> <tbody> {this.renderPosts()} </tbody> </table> </div> ) } }
JavaScript
class Simple extends Component { render() { return ( <View style={styles.container}> <BackgroundColoredComponent /> <ContainerComponent /> <ExampleComponent /> </View> ); } }
JavaScript
class DLCSSearchForm extends React.Component { state = { string1: '', string2: '', string3: '', number1: 0, number2: 0, number3: 0, }; searchFormChange = ev => { this.setState({ [ev.target.name]: ev.target.value, }); }; static fieldHasValue = (name, value) => (name.startsWith('string') && value !== '') || (name.startsWith('number') && value !== 0); onSearch = ev => { ev.preventDefault(); const queryString = Object.entries(this.state || {}) .reduce((acc, [name, value]) => { if (DLCSSearchForm.fieldHasValue(name, value)) { acc.push(encodeURIComponent(name) + '=' + encodeURIComponent(value)); } return acc; }, []) .join('&'); if (this.props.callback) { this.props.callback(queryString); } }; render() { const { string1, string2, string3, number1, number2, number3 } = this.state; const { style, classes } = this.props; return ( <div style={style || {}} className={classes.root}> <div className={classes.searchFields}> <TextField label="String1" type="text" name="string1" value={string1} onChange={this.searchFormChange} variant="outlined" margin="dense" InputLabelProps={{ focused: true, shrink: true }} className={classes.textField} /> <TextField label="String2" type="text" name="string2" value={string2} onChange={this.searchFormChange} variant="outlined" margin="dense" InputLabelProps={{ focused: true, shrink: true }} className={classes.textField} /> <TextField label="String3" type="text" name="string3" value={string3} onChange={this.searchFormChange} variant="outlined" margin="dense" InputLabelProps={{ focused: true, shrink: true }} className={classes.textField} /> </div> <div className={classes.searchFields}> <TextField label="Number1" type="number" name="number1" value={number1} onChange={this.searchFormChange} variant="outlined" margin="dense" InputLabelProps={{ focused: true, shrink: true }} className={classes.textField} /> <TextField label="Number2" type="number" name="number2" value={number2} onChange={this.searchFormChange} variant="outlined" margin="dense" InputLabelProps={{ focused: true, shrink: true }} className={classes.textField} /> <TextField label="Number3" type="number" name="number3" value={number3} onChange={this.searchFormChange} variant="outlined" margin="dense" InputLabelProps={{ focused: true, shrink: true }} className={classes.textField} /> </div> <div className={classes.buttonBar}> <Button onClick={this.onSearch}>Search</Button> </div> </div> ); } }
JavaScript
class Word { constructor(word) { // word.split - splits word into array of letters // .map - instantiate a new `Letter` for each character and return an array // referred to with the instance variable, `letters` this.letters = word.split("").map(char => new Letter(char)); } getSolution() { return this.letters // iterate over each letter and return the solution for each // to form an array of solved letters .map(letter => letter.getSolution()) .join(""); // create a string from the array of solved letters } // setting `toString()` as a method lets us concatenate it like we would a string! toString() { return this.letters.join(" "); // see Letter.prototype.toString in Letter.js } guessLetter(char) { // Checks to see if any of the letters in the array match the user's guess and updates `foundLetter` let foundLetter = false; this.letters.forEach(letter => { if (letter.guess(char)) { foundLetter = true; } }); // Print the word guessed so far--because we set the method for toString, // JavaScript will automatically concatenate this even if we don't call toString console.log("\n" + this + "\n"); // return whether we found a letter return foundLetter; } // Returns true if all letters in the word have been guessed guessedCorrectly() { // The `every` method returns true if the callback function returns true for every element in the array return this.letters.every(letter => letter.visible); } }
JavaScript
class Server { /** * @param {string} configPath - Location of resource configs */ constructor(configPath) { if (!configPath) throw new Error('Master must be called with a configPath parameter'); this.api = null; this.log = null; this._httpServer = null; this._staticHandler = null; this._configPath = require.resolve(configPath); this._clusterWorker = null; this._plugins = {}; } /** * Run the worker process. * * Initializes a new instance of {@link Api} by resolving the configPath supplied * in the constructor. Attaches to a @florajs/cluster worker (if we are in a cluster) * and creates a new {@link https://nodejs.org/api/http.html#http_class_http_server|HTTP server}. * * @returns {Promise} */ async run() { // eslint-disable-next-line global-require const config = require(this._configPath); this._clusterWorker = new ClusterWorker({ shutdownTimeout: config.shutdownTimeout, log: config.log }); this.api = new Api(); this.api.clusterWorker = this._clusterWorker; try { await this.api.init(config); } catch (err) { if (this.api.log) this.api.log.fatal(err, 'Error initializing Flora'); this._clusterWorker.shutdown(); throw err; } this.log = this.api.log; Object.keys(this._plugins).forEach((name) => { const [plugin, options] = this._plugins[name]; this.log.debug(`Registering plugin "${name}"`); this.api.register(name, plugin, options); }); if (config.staticPath) { this._staticHandler = serveStatic(config.staticPath); } if (!config.port) { this.log.warn('No port in configuration, not starting HTTP server'); return null; } this._httpServer = http.createServer(this._handleRequest.bind(this)); this._clusterWorker.on('close', () => this.close()); this._clusterWorker.attach(this._httpServer); return new Promise((resolve) => { this._httpServer.listen(config.port, () => { this._clusterWorker.ready(); this.log.info('Flora server running on port %d', config.port); resolve(); }); }); } /** * Gracefully shutdown the server. * * @returns {Promise} */ async close() { if (!this.api) throw new Error('Not running'); if (this._httpServer) { this.log.info('Closing HTTP server'); // TODO: Callback will get the error from httpServer#close, // regardless what Api#close returns.); return new Promise((resolve) => this._httpServer.close(() => resolve(this.api.close()))); } return this.api.close(); } /** * Register a plugin. * * The plugin has to be a function, which is called with parameters (api, options). * * @param {string} name - Plugin name * @param {Object} function - Plugin function * @param {Object} [options] - Configuration options that are passed to the function */ register(name, plugin, options) { if (this._plugins[name]) throw new Error(`Plugin "${name}" already registered.`); this._plugins[name] = [plugin, options]; if (this.api) this.api.register(name, plugin, options); } /** * Handle a HTTP request. * * Parse the request path and parameters, search for the required resource * and execute the resource, build and send the response. * * @param {http.IncomingMessage} httpRequest * @param {http.ServerResponse} httpResponse * @returns {Promise} * @fires Api#httpRequest * @private */ async _handleRequest(httpRequest, httpResponse) { try { await this.api.emit('httpRequest', { httpRequest, httpResponse }); if (httpRequest.method === 'OPTIONS') { // Abort execution of OPTIONS requests here, send 200 for now httpResponse.writeHead(200); return httpResponse.end(); } const floraRequest = await httpToFloraRequest(httpRequest, { postTimeout: this.api.config.postTimeout }); if (!floraRequest) { if (this._staticHandler) { return this._staticHandler(httpRequest, httpResponse, () => { this._sendError( new NotFoundError(`URL "${httpRequest.url}" not found (not a valid resource url)`), httpRequest, httpResponse ); }); } return this._sendError( new NotFoundError(`URL "${httpRequest.url}" not found (not a valid resource url)`), httpRequest, httpResponse ); } if (!this.api.getResource(floraRequest.resource) && this._staticHandler) { return this._staticHandler(httpRequest, httpResponse, () => { this._sendError( new NotFoundError(`Resource "${floraRequest.resource}" not found`), httpRequest, httpResponse ); }); } const response = await this.api.execute(floraRequest); return this._sendResponse(response, httpRequest, httpResponse); } catch (err) { this._sendError(err, httpRequest, httpResponse); } return null; } /** * @param {FloraError} err * @param {http.Request} httpRequest * @param {http.Response} httpResponse * @private */ _sendError(err, httpRequest, httpResponse) { const response = new Response(); if (err.data) response.data = err.data; if (err.meta) Object.assign(response.meta, err.meta); response.meta.statusCode = err.httpStatusCode || new errors.FloraError().httpStatusCode; response.error = errors.format(err, { exposeErrors: this.api.config.exposeErrors }); this._sendResponse(response, httpRequest, httpResponse); } /** * @param {Object} response * @param {http.Request} httpRequest * @param {http.Response} httpResponse * @private */ _sendResponse(response, httpRequest, httpResponse) { const headers = response.meta.headers; let stream = httpResponse; const acceptEncoding = httpRequest.headers['accept-encoding'] || ''; if (!headers['Content-Type']) headers['Content-Type'] = 'application/json; charset=utf-8'; if (acceptEncoding.match(/\bgzip\b/)) { headers['Content-Encoding'] = 'gzip'; stream = zlib.createGzip(); stream.pipe(httpResponse); } else if (acceptEncoding.match(/\bdeflate\b/)) { headers['Content-Encoding'] = 'deflate'; stream = zlib.createDeflate(); stream.pipe(httpResponse); } try { let json = null; if (!(response.data instanceof Stream.Readable) && !(response.data instanceof Buffer)) { json = JSON.stringify({ meta: response.meta, cursor: response.cursor, error: response.error, data: response.data }); } // measure duration as late as possible - after JSON.stringify, right before writeHead: if (httpRequest.flora && httpRequest.flora.startTime) { const hrtime = process.hrtime(httpRequest.flora.startTime); headers['X-Response-Time'] = Math.round((hrtime[0] * 1000 + hrtime[1] / 1000000) * 1000) / 1000; } httpResponse.writeHead(response.meta.statusCode, headers); if (response.data instanceof Stream.Readable) { response.data.pipe(stream); return; } stream.end(json || response.data); } catch (e) { this.log.warn(e, 'Error while sending response'); } } }
JavaScript
class Workflowview{ constructor(container, wf){ this.wf = wf; this.container = container; this.graph; this.tagBarDiv; this.nodeBarDiv; this.weekSelect; this.bracketBarDiv; this.tagSelect; this.legend; this.editbar; this.titleNode; this.authorNode; this.descriptionNode; this.weekWidth=0; this.colFloat } nameUpdated(){ this.graph.getModel().setValue(this.titleNode,this.wf.name); } authorUpdated(){ this.graph.getModel().setValue(this.authorNode,this.wf.author); } descriptionUpdated(){ this.graph.getModel().setValue(this.descriptionNode,this.wf.description); } makeConnectionsFromIds(){ for(var i=0;i<this.wf.weeks.length;i++){ for(var j=0;j<this.wf.weeks[i].nodes.length;j++){ var node = this.wf.weeks[i].nodes[j]; if(node.autoLinkOut)node.autoLinkOut.redraw(); for(var k=0;k<this.wf.weeks[i].nodes[j].fixedLinksOut.length;k++){ var link = this.wf.weeks[i].nodes[j].fixedLinksOut[k]; node.view.fixedLinkAdded(link,null); } } } } makeActive(){ this.initializeGraph(); var graph = this.graph; var parent = graph.getDefaultParent(); var minimap = document.getElementById('outlineContainer'); this.toolbar = new WFToolbar(this.wf.project,document.getElementById('nbContainer'),"right","nodebar"); this.toolbar.container.classList.add("nodebar"); //create views for the tags for(var i=0;i<this.wf.tagSets.length;i++){ this.wf.tagSets[i].view = new Tagview(this.graph,this.wf.tagSets[i],this.wf); } //Add the first cells // Adds cells to the model in a single step graph.getModel().beginUpdate(); try{ //Create the title boxes this.createTitleNode(); this.createLegend(); this.createAuthorNode(); this.createDescriptionNode(); this.createSpanner(); this.drawGraph(); this.createLegendVertex(); } finally{ // Updates the display graph.getModel().endUpdate(); } this.generateToolbars(); this.generateColumnFloat(); var wfview = this; // Installs a popupmenu handler. if(!this.wf.project.readOnly)graph.popupMenuHandler.factoryMethod = function(menu, cell, evt){ if(evt.shiftKey)return; return wfview.createPopupMenu(menu, cell, evt); }; this.container.contextItem={dummyObject:true}; document.body.contextItem = this.wf; console.log(this.wf.settings.settingsKey.validation); if(this.wf.settings.settingsKey.validation.value){$("#validateviewbar").removeClass("disabled");} $("#expand").removeClass("disabled"); $("#collapse").removeClass("disabled"); $("#expandviewbar").removeClass("disabled"); $("#collapseviewbar").removeClass("disabled"); $("#print").removeClass("disabled"); $("#showlegend").removeClass("disabled"); } drawGraph(){ var columns = this.wf.columns; var weeks = this.wf.weeks; var comments = this.wf.comments; var brackets = this.wf.brackets; for(var i=0;i<columns.length;i++){ columns[i].view = new Columnview(this.graph,columns[i]); columns[i].view.createVertex(); } this.positionColumns(); for(var i=0;i<weeks.length;i++){ var week = weeks[i]; if(week instanceof WFArea)week.view = new WFAreaview(this.graph,week); else if(week instanceof Term)week.view = new Termview(this.graph,week); else week.view = new Weekview(this.graph,week); var y; if(i==0)y=columns[0].view.vertex.b()+cellSpacing; else y = weeks[i-1].view.vertex.b(); week.view.createVertex(cellSpacing,y,this.weekWidth); week.view.fillNodes(); } this.wf.updateWeekIndices(); for(var i=0;i<brackets.length;i++){ brackets[i].view = new Bracketview(this.graph,brackets[i]); brackets[i].view.createVertex(); brackets[i].view.updateHorizontal(); brackets[i].view.updateVertical(); } for(var i=0;i<comments.length;i++){ comments[i].view = new Commentview(this.graph,comments[i]); comments[i].view.createVertex(); } this.bringCommentsToFront(); this.makeConnectionsFromIds(); } makeInactive(){ this.toolbar.container.style.display="none"; this.descriptionNode.parentElement.removeChild(this.descriptionNode); this.graph.stopEditing(false); $(".mxPopupMenu").remove(); this.graph.clearSelection(); for(var i=0;i<this.wf.tagSets.length;i++){ if(this.wf.tagSets[i].view)this.wf.tagSets[i].view.clearViews(); } if(this.colFloat)this.colFloat.parentElement.parentElement.removeChild(this.colFloat.parentElement); if(this.graph!=null)this.graph.destroy(); this.container.contextItem=null; this.container.innerHTML=""; document.body.contextItem = this.wf.project; $("#validateviewbar").addClass("disabled"); $("#expand").addClass("disabled"); $("#collapse").addClass("disabled"); $("#expandviewbar").addClass("disabled"); $("#collapseviewbar").addClass("disabled"); $("#print").addClass("disabled"); $("#showlegend").addClass("disabled"); } createTitleNode(){ var wf = this.wf; var title = "["+LANGUAGE_TEXT.workflow.inserttitle[USER_LANGUAGE]+"]"; if(wf.name&&wf.name!=wf.getDefaultName())title = wf.name; this.titleNode = this.graph.insertVertex(this.graph.getDefaultParent(),null,title,wfStartX,wfStartY,400,24,defaultTitleStyle); this.titleNode.isTitle=true; this.titleNode.wf=wf; this.titleNode.valueChanged = function(value){ var value1 = wf.setNameSilent(value); if(value1!=value)wf.view.graph.getModel().setValue(wf.view.titleNode,value1); else mxCell.prototype.valueChanged.apply(this,arguments); } } createAuthorNode(){ var wf = this.wf; var title = "["+LANGUAGE_TEXT.workflow.insertauthor[USER_LANGUAGE]+"]"; if(wf.author)title = wf.author; this.authorNode = this.graph.insertVertex(this.graph.getDefaultParent(),null,title,wfStartX,wfStartY+40,400,20,defaultTitleStyle+"fontSize=14;fontStyle=3;"); this.authorNode.isTitle=true; this.authorNode.wf=wf; this.authorNode.valueChanged = function(value){ var value1 = wf.setAuthorSilent(value); if(value1!=value)wf.view.graph.getModel().setValue(wf.view.authorNode,value1); else mxCell.prototype.valueChanged.apply(this,arguments); } } createDescriptionNode(){ var wf = this.wf; var title = "["+LANGUAGE_TEXT.workflow.insertdescription[USER_LANGUAGE]+"]"; if(wf.description)title = wf.description; this.descriptionHeaderNode = this.graph.insertVertex(this.graph.getDefaultParent(),null,LANGUAGE_TEXT.workflow.description[USER_LANGUAGE]+":",wfStartX,wfStartY+90,800,16,defaultTitleStyle+"fontSize=14;verticalAlign=top;editable=0;selectable=0;"); this.descriptionHeaderNode.noSelect=true; this.descriptionNode = document.createElement('div'); var descriptionNode = this.descriptionNode; var quilldiv = document.createElement('div'); this.descriptionNode.appendChild(quilldiv); this.descriptionNode.style.width = "800px"; this.descriptionNode.style.height = "80px"; this.descriptionNode.className = "descriptionnode"; this.descriptionNode.style.left = (wfStartX+cellSpacing+100)+"px"; this.descriptionNode.style.top = (wfStartY+70+40)+"px"; this.descriptionNode.style.position="absolute"; this.container.parentElement.appendChild(this.descriptionNode); var toolbarOptions = [['bold','italic','underline'],[{'script':'sub'},{'script':'super'}],[{'list':'bullet'},{'list':'ordered'}],['link'],['formula']]; var quill = new Quill(quilldiv,{ theme: 'snow', modules: { toolbar: toolbarOptions }, placeholder:LANGUAGE_TEXT.editbar.insertdescription[USER_LANGUAGE] }); quill.on('text-change', function(delta, oldDelta, source) { if (source == 'user') { if(wf){ wf.setDescriptionSilent(quilldiv.childNodes[0].innerHTML.replace(/\<p\>\<br\>\<\/p\>\<ul\>/g,"\<ul\>")); } } }); var allowedattrs = ['link','bold','italic','underline','script','list']; quill.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => { for(var i=0;i<delta.ops.length;i++){ var op = delta.ops[i]; if(op.attributes){ for(var attr in op.attributes){ if(allowedattrs.indexOf(attr)<0)op.attributes[attr]=null; } } } return delta; }); var readOnly = wf.project.readOnly; var toolbar = quill.getModule('toolbar'); toolbar.defaultLinkFunction=toolbar.handlers['link']; toolbar.addHandler("link",function customLinkFunction(value){ var select = quill.getSelection(); if(value&&select['length']==0&&!readOnly){ quill.insertText(select['index'],'link'); quill.setSelection(select['index'],4); } this.defaultLinkFunction(value); }); this.descriptionNode.edit = function(){quilldiv.firstElementChild.contentEditable=true;quilldiv.firstElementChild.focus();descriptionNode.classList.add('active');} if(wf.description!=null)quill.clipboard.dangerouslyPasteHTML(wf.description,"silent"); else quill.clipboard.dangerouslyPasteHTML("","silent"); quilldiv.firstElementChild.contentEditable=false; quilldiv.firstElementChild.ondblclick = function(){if(readOnly)return;quilldiv.firstElementChild.contentEditable=true;quilldiv.firstElementChild.focus();descriptionNode.classList.add('active');} descriptionNode.firstElementChild.onmousedown = function(evt){evt.preventDefault();} quilldiv.addEventListener("focusout",function(evt){ //check if related target is within the quillified div var target = evt.relatedTarget; if(target == null)target = evt.explicitOriginalTarget; while(target!=null){ if(target.parentElement==quilldiv)return; else(target = target.parentElement); } quilldiv.firstElementChild.contentEditable=false; descriptionNode.classList.remove('active'); }); quilldiv.firstElementChild.blur(); var wfv = this; descriptionNode.oncontextmenu = function(evt){ mxEvent.redirectMouseEvents(descriptionNode,wfv.graph,null) evt.preventDefault(); evt.stopPropagation(); /*var evt2 = new evt.constructor(evt.type,evt); wfv.container.firstElementChild.firstElementChild.dispatchEvent(evt);*/ } } nodeAddedFromXML(node){ node.view = new Nodeview(this.graph,node); node.view.createVertex(0,0); node.view.columnUpdated(); } bracketAddedFromXML(bracket){ bracket.view = new Bracketview(this.graph,bracket); bracket.view.createVertex(); bracket.view.updateHorizontal(); bracket.view.updateVertical(); } finishedAddingNodesFromXML(week,endIndex){ week.view.pushNodesFast(endIndex); this.bringCommentsToFront(); } positionColumns(){ var columns = this.wf.columns; for(var i=0;i<columns.length;i++){ //columns[i].view = new Columnview(this.graph,columns[i]); //columns[i].view.createVertex(); columns[i].view.pos = wfStartX+cellSpacing+defaultCellWidth/2+i*(defaultCellWidth-2*cellSpacing); columns[i].view.updatePosition(); } this.updateWeekWidths(); } columnAdded(col){ var i = this.wf.columns.length-1; col.view = new Columnview(this.graph,col); col.view.pos = wfStartX+cellSpacing+defaultCellWidth/2+i*(defaultCellWidth-2*cellSpacing); col.view.createVertex(); col.view.updatePosition(); if(this.nodeBarDiv!=null&&col.name.substr(0,3)=='CUS')this.populateNodeBar(); this.updateWeekWidths(); } columnRemoved(col){ this.positionColumns(); for(var i=0;i<this.wf.brackets.length;i++){ var bv = this.wf.brackets[i].view; if(bv)bv.updateHorizontal(); } } findNearestColumn(x){ var dist = 99999; var tdist = 0; var name = null; var columns = this.wf.columns; for(var i=0;i<columns.length;i++){ tdist = Math.abs(columns[i].view.pos-x); if(tdist<dist){ dist=tdist; name = columns[i].name; } } if(name!=null)return name; else return columns[0].name; } getColPos(name){ for(var i=0;i<this.wf.columns.length;i++){ if(this.wf.columns[i].name==name)return this.wf.columns[i].view.pos; } return this.wf.columns[this.wf.columns.length-1].view.pos; } weekAdded(week){ //if(week instanceof Term) week.view = new Termview(this.graph,week); //else week.view = new Weekview(this.graph,week); //week.view.createVertex(cellSpacing,0,this.weekWidth); //week.view.makeFlushWithAbove(this.wf.weeks.indexOf(week)); this.populateWeekBar(); } weekDeleted(){} pushWeeks(startIndex){ var weeks = this.wf.weeks; //this should never start at 0, the top week should not be moved if(startIndex==0) {weeks[0].view.makeFlushWithAbove(0);startIndex++} if(startIndex>weeks.length-1)return; var dy=weeks[startIndex-1].view.vertex.b()-weeks[startIndex].view.vertex.y(); for(var i=startIndex;i<weeks.length;i++){ weeks[i].view.moveWeek(dy); } } updateWeekWidths(){ var oldWidth= this.weekWidth; var weeks = this.wf.weeks; if(this.wf.columns.length==0)return; this.weekWidth=this.wf.columns[this.wf.columns.length-1].view.pos+defaultCellWidth/2+cellSpacing-wfStartX; for(var i = 0;i<weeks.length;i++){ if(weeks[i].view)weeks[i].view.vertex.resize(this.graph,this.weekWidth-oldWidth,0); } //if(weeks[0].view)this.graph.moveCells([this.authorNode],weeks[0].view.vertex.r()-this.authorNode.r()); for(var i=0;i<this.wf.brackets.length;i++){ if(this.wf.brackets[i].view)this.wf.brackets[i].view.updateHorizontal(); } this.spanner.resize(this.graph,this.weekWidth-oldWidth,0); //this.graph.moveCells([this.spanner],2*cellSpacing+this.weekWidth-this.spanner.x(),0); } weekIndexUpdated(week){ if(week.collapsed){ this.graph.setCellStyles("fontColor","#777777;",[week.view.vertex]); this.graph.setCellStyles("fillColor","#bbbbbb;",[week.view.vertex]); } else{ this.graph.setCellStyles("fillColor","#"+(0xe0e0e0+(week.index%2)*0x0F0F0F).toString(16)+";",[week.view.vertex]); this.graph.setCellStyles("fontColor","#000000;",[week.view.vertex]); } } weeksSwapped(week,week2,direction){ week.view.moveWeek(week2.view.vertex.h()*direction); week2.view.moveWeek(-week.view.vertex.h()*direction); this.populateWeekBar(); } //A significantly faster version of this function, which first computes what must be moved, then moves it all at once in a single call to moveCells pushWeeksFast(startIndex,dy=null){ var weeks = this.wf.weeks; //this should never start at 0, the top week should not be moved if(startIndex==0) {weeks[0].view.makeFlushWithAbove(0);startIndex++} if(startIndex>weeks.length-1)return; if(dy==null)dy=weeks[startIndex-1].view.vertex.b()-weeks[startIndex].view.vertex.y(); var vertices=[]; var brackets=[]; for(var i=startIndex;i<weeks.length;i++){ vertices.push(weeks[i].view.vertex); for(var j=0;j<weeks[i].nodes.length;j++){ vertices.push(weeks[i].nodes[j].view.vertex); for(var k=0;k<weeks[i].nodes[j].brackets.length;k++){ var bracket = weeks[i].nodes[j].brackets[k]; if(brackets.indexOf(bracket)<0)brackets.push(bracket); } } } this.graph.moveCells(vertices,0,dy); for(i=0;i<brackets.length;i++)brackets[i].view.updateVertical(); } bracketAdded(bracket){ bracket.view = new Bracketview(this.graph,bracket); bracket.view.createVertex(); bracket.view.updateHorizontal(); bracket.view.updateVertical(); } bringCommentsToFront(){ if(this.wf.comments.length==0)return; var com = []; for(var i=0;i<this.wf.comments.length;i++){ com.push(this.wf.comments[i].view.vertex); } this.graph.orderCells(false,com); } createLegend(){ this.legend = new Legend(this.wf,this.graph); } createLegendVertex(){ this.legend.createVertex(); } columnsSwitched(in1,in2){ var columns = this.wf.columns; var weeks = this.wf.weeks; [columns[in1].view.pos,columns[in2].view.pos]=[columns[in2].view.pos,columns[in1].view.pos]; columns[in1].view.updatePosition(); columns[in2].view.updatePosition(); for(var i=0;i<weeks.length;i++){ for(var j=0;j<weeks[i].nodes.length;j++){ weeks[i].nodes[j].view.columnUpdated(); } } } showLegend(){ if(this.legend!=null&&this.legend.vertex!=null){ this.legend.createDisplay(); this.graph.cellsToggled([this.legend.vertex],!this.graph.isCellVisible(this.legend.vertex)); } } legendUpdate(category,newval,oldval){ if(this.legend!=null)this.legend.update(category,newval,oldval); } scrollToWeek(week){ if(week.view&&week.view.vertex)this.scrollToVertex(week.view.vertex); } scrollToVertex(vertex){ var newy = vertex.y(); $(".bodywrapper")[0].scrollTo(0,newy); } //Executed when we generate all the toolbars generateToolbars(){ var toolbar = this.toolbar; if(this.wf.project.readOnly)toolbar.container.style.display="none"; else toolbar.container.style.display="inline"; this.generateNodeBar(); if(this.wf instanceof Courseflow || this.wf instanceof Programflow)this.generateWeekBar(); this.generateBracketBar(); this.generateTagBar(); this.toolbar.show(); this.toolbar.toggleShow(); this.toolbar.toggled=true; } generateNodeBar(){ this.nodeBarDiv = this.toolbar.addBlock(LANGUAGE_TEXT.workflowview.nodeheader[USER_LANGUAGE],null,"nodebarh3"); this.populateNodeBar(); } generateWeekBar(){ var weekDiv = this.toolbar.addBlock(LANGUAGE_TEXT.workflowview.jumpto[USER_LANGUAGE]); this.weekSelect = document.createElement('select'); weekDiv.appendChild(this.weekSelect); var wfv = this; var weekSelect = this.weekSelect; this.weekSelect.onchange = function(){ if(weekSelect.value!=""){ var index = int(weekSelect.value); if(wfv.wf.weeks.length>index)wfv.scrollToWeek(wfv.wf.weeks[index]); weekSelect.selectedIndex=0; } } this.populateWeekBar(); } generateBracketBar(){ if(this.wf.getBracketList()==null)return; this.bracketBarDiv = this.toolbar.addBlock(LANGUAGE_TEXT.workflowview.strategiesheader[USER_LANGUAGE],null,"nodebarh3"); this.populateBracketBar(); } generateTagBar(){ if(this.wf.getTagDepth()<0)return; var wf = this.wf; var p=wf.project; this.tagBarDiv = this.toolbar.addBlock(LANGUAGE_TEXT.workflowview.outcomesheader[USER_LANGUAGE],null,"nodebarh3"); var compSelect = document.createElement('select'); this.tagSelect=compSelect; this.populateTagSelect(p.workflows["outcome"],this.wf.getTagDepth()); var addButton = document.createElement('button'); addButton.innerHTML = LANGUAGE_TEXT.workflowview.assignoutcome[USER_LANGUAGE]; addButton.onclick=function(){ var value = compSelect.value; if(value!=""){ var comp = p.getTagByID(value); wf.addTagSet(comp); var removalIDs = comp.getAllID([]); for(var i=0;i<compSelect.options.length;i++)if(removalIDs.indexOf(compSelect.options[i].value)>=0){ compSelect.remove(i); i--; } } } this.tagBarDiv.parentElement.appendChild(compSelect); this.tagBarDiv.parentElement.appendChild(addButton); this.populateTagBar(); } populateNodeBar(){ if(this.nodeBarDiv==null)return; this.nodeBarDiv.innerHTML = ""; var nodebar = new mxToolbar(this.nodeBarDiv); nodebar.enabled = false; // Function that is executed when the image is dropped on // the graph. The cell argument points to the cell under // the mousepointer if there is one. var makeDropFunction=function(col,workflow){ var dropfunction = function(graph, evt, filler, x, y) { var wf = workflow; var column=col; var cell = graph.getCellAt(x,y); graph.stopEditing(false); if(cell!=null && cell.isWeek){ var startIndex = cell.week.view.getNextIndexFromPoint(y,column); var node=wf.createNodeOfType(column); node.view = new Nodeview(graph,node); node.view.createVertex(x,y); node.setColumn(column); node.setWeek(cell.week); cell.week.addNode(node,0,startIndex); wf.view.bringCommentsToFront(); wf.updated("Add Node",node); } this.lastCell=null; } return dropfunction; } var allColumns = this.wf.getPossibleColumns(); for(var i=0;i<allColumns.length;i++){ var button = this.addNodebarItem(this.nodeBarDiv,allColumns[i].nodetext,iconpath+allColumns[i].image+'.svg',makeDropFunction(allColumns[i].name,this.wf),null,function(cellToValidate){return (cellToValidate!=null&&cellToValidate.isWeek);}); button.style.borderColor=allColumns[i].colour; button.style.borderWidth='3px'; } } populateWeekBar(){ if(this.weekSelect==null)return; while(this.weekSelect.length>0)this.weekSelect.remove(0); var opt = document.createElement('option'); opt.text=LANGUAGE_TEXT.workflowview.jumpto[USER_LANGUAGE]+"..."; opt.value=""; this.weekSelect.appendChild(opt); for(var i=0;i<this.wf.weeks.length;i++){ var week = this.wf.weeks[i]; var opt = document.createElement('option'); if(week.name)opt.text=week.name; else opt.text=week.getDefaultName(); opt.value=i; this.weekSelect.appendChild(opt); } } populateBracketBar(){ this.bracketBarDiv.innerHTML = ""; var bracketList = this.wf.getBracketList(); var bracketbar = new mxToolbar(this.tagBarDiv); bracketbar.enabled = false; var makeDropFunction=function(strat,workflow){ var dropfunction = function(graph, evt, filler, x, y) { var wf = workflow; var strategy=strat['value']; var cell = graph.getCellAt(x,y); graph.stopEditing(false); if(cell!=null&&graph.isPart(cell))cell=graph.getModel().getParent(cell); if(cell!=null && cell.isNode){ gaEvent('Bracket','Add to Node',wf.name,wf.brackets.length); wf.addBracket(strategy,cell.node); wf.updated("Add Bracket",strategy); } if(cell!=null&&cell.isWeek){ gaEvent('Bracket','Add to Week',wf.name,wf.brackets.length); var xml = findStrategyXML(strategy); var startIndex = cell.week.view.getNextIndexFromPoint(y); makeLoad(function(){ wf.addNodesFromXML(cell.week,startIndex,xml); wf.updated("Add Strategy",strategy); }); } this.lastCell=null; } return dropfunction; } for(var i=0;i<bracketList.length;i++){ this.addNodebarItem(this.bracketBarDiv,bracketList[i].text[USER_LANGUAGE],iconpath+bracketList[i]['value']+'.svg',makeDropFunction(bracketList[i],this.wf),null,function(cellToValidate){return (cellToValidate!=null&&(cellToValidate.isNode||cellToValidate.isWeek));}); } } generateColumnFloat(){ var colFloatContainer = document.createElement('div'); var colFloat = document.createElement('div'); colFloatContainer.className = "columnfloatcontainer"; colFloat.className="columnfloat"; this.container.parentElement.insertBefore(colFloatContainer,this.container); colFloatContainer.appendChild(colFloat); this.colFloat = colFloat; this.fillColumnFloat(); } fillColumnFloat(){ if(!this.colFloat)return; this.colFloat.innerHTML = ""; for(var i=0;i<this.wf.columns.length;i++){ var col = this.wf.columns[i]; var title = document.createElement('div'); title.className = "columnfloatheader"; this.colFloat.appendChild(title); title.innerHTML=col.text.replace(/\n/g,"<br>"); if(col.view)title.style.left = (col.view.pos-100)+"px"; } } showColFloat(show){ if(show)this.colFloat.classList.remove("hidden"); else this.colFloat.classList.add("hidden"); } tagSetAdded(tag){ if(tag.view==null)tag.view = new Tagview(this.graph,tag,this.wf); } tagSetRemoved(tag){ if(tag.view)this.removeAllHighlights(tag); this.populateTagBar(); this.populateTagSelect(this.wf.project.workflows["outcome"],this.wf.getTagDepth()); } removeAllHighlights(tag){ tag.view.highlight(false); for(var i=0;i<tag.children.length;i++){ this.removeAllHighlights(tag.children[i]); } } populateTagBar(){ var tagSets = this.wf.tagSets; this.tagBarDiv.innerHTML=""; for(var i=0;i<tagSets.length;i++){ var tagDiv = document.createElement('div'); this.tagBarDiv.appendChild(tagDiv); tagDiv.layout=this; this.populateTagDiv(tagDiv,tagSets[i]); } if(tagSets.length==0){ this.tagBarDiv.classList.add("emptytext"); this.tagBarDiv.innerHTML="<b>"+LANGUAGE_TEXT.workflowview.nooutcomes[USER_LANGUAGE]+"</b>" }else this.tagBarDiv.classList.remove("emptytext"); } populateTagDiv(container,tag){ var button = new Layoutbutton(tag,container); button.b.onclick=null; //Creates the function that is called when you drop it on something var makeDropFunction=function(addedtag,workflow){ var dropfunction = function(graph, evt, filler, x, y) { var wf = workflow; var thistag =addedtag; var cell = graph.getCellAt(x,y); graph.stopEditing(false); while(cell!=null&&graph.isPart(cell)){cell=graph.getModel().getParent(cell);} if(cell!=null && cell.isNode){ cell.node.addTag(thistag,true,cell.node.wf instanceof Programflow); wf.updated("Add Tag",cell.node); }else if(cell!=null && wf.settings.settingsKey.linktagging.value && cell.isLink){ cell.link.addTag(thistag,true,cell.link.wf instanceof Programflow); wf.updated("Add Tag",cell.link); } this.lastCell=null; } return dropfunction; } console.log(tag.getIcon()); this.addNodebarItem(button.bwrap,tag.name,iconpath+tag.getIcon()+".svg",makeDropFunction(tag,this.wf),button,function(cellToValidate){return (cellToValidate!=null&&(cellToValidate.isNode||(cellToValidate.isLink&&cellToValidate.link.node.wf.settings.settingsKey.linktagging.value)));}); tag.view.addDrop(button); if(tag.depth<=this.wf.getTagDepth())button.makeEditable(false,false,true,this.wf); button.makeExpandable(); button.makeNodeIndicators(); button.layout.view.updateDrops(); if(tag.depth<=this.wf.getTagDepth())for(var i=0;i<tag.children.length;i++){ this.populateTagDiv(button.childdiv,tag.children[i]); } return button; } populateTagSelect(list,depth=0){ var compSelect=this.tagSelect; while(compSelect.length>0)compSelect.remove(0); var currentIndices = []; for(i=0;i<this.wf.tagSets.length;i++){ currentIndices = this.wf.tagSets[i].getAllID(currentIndices,depth); } var allTags=[]; for(i=0;i<list.length;i++){ allTags = list[i].getAllTags(allTags,depth,currentIndices); } var opt = document.createElement('option'); opt.text = LANGUAGE_TEXT.workflowview.selectset[USER_LANGUAGE]; opt.value = ""; compSelect.add(opt); for(var i=0;i<allTags.length;i++){ opt = document.createElement('option'); opt.innerHTML = "&nbsp;".repeat(allTags[i].depth*4)+allTags[i].getNameType()[0]+" - "+allTags[i].name; opt.value = allTags[i].id; compSelect.add(opt); } } //Adds a drag and drop. If button is null, it creates one, if it is passed an existing button it simply makes it draggable. addNodebarItem(container,name,image, dropfunction,button=null,validtargetfunction=function(cellToValidate){return false;}) { var wf = this.wf; var graph = this.graph; var line; var img; var namediv; if(button==null){ line = document.createElement("button"); img = document.createElement("img"); namediv = document.createElement("div"); img.setAttribute('src',image); img.style.width="24px"; namediv.innerText = name; line.appendChild(img); line.appendChild(namediv); container.appendChild(line); }else { img=button.icon; line=button.b; namediv=button.namediv; } // Creates the image which is used as the drag icon (preview) var dragimg = img.cloneNode(true); dragimg.style.width="24px"; console.log(dragimg); var draggable = mxUtils.makeDraggable(line, graph, dropfunction,dragimg,-12,-16); var defaultMouseMove = draggable.mouseMove; draggable.mouseMove = function(evt){ var boundRect = $("#graphContainer")[0].getBoundingClientRect(); var leftPos = boundRect.x; var topPos = boundRect.y; var cell = this.getDropTarget(graph,evt.pageX-leftPos,evt.pageY-topPos,evt); while(cell!=null&&graph.isPart(cell)){cell=graph.getModel().getParent(cell);} if(draggable.lastCell!=null&&cell!=draggable.lastCell){graph.view.getState(draggable.lastCell).shape.node.firstChild.classList.remove("validdrop");draggable.lastCell=null;} if(draggable.lastCell==null){ if(validtargetfunction(cell)){ this.dragElement.style.outline="2px solid lightgreen"; var g = graph.view.getState(cell).shape.node; if(g.firstChild!=null){ g.firstChild.classList.add("validdrop"); var hlRemove = function(){g.firstChild.classList.remove("validdrop");} document.addEventListener("mouseup",hlRemove,{once:true}); draggable.lastCell = cell; } }else{ this.dragElement.style.outline="2px solid red"; } } return defaultMouseMove.apply(this,arguments); } return line; } //This creates an invisible box that spans the width of our workflow. It's useful to have the graph area automatically resize in the y direction, but we want to maintain a minimum width in the x direction so that the user can always see the right hand side even when the editbar is up, and so they can click the seemingly empty space to the right of the graph to deselect items, and this is sort of cheesy way around that. createSpanner(){ this.spanner = this.graph.insertVertex(this.graph.getDefaultParent(),null,'',wfStartX+cellSpacing,this.descriptionHeaderNode.b()+120,this.weekWidth+250,1,invisibleStyle+"strokeColor=#DDDDDD;editable=0;constituent=0;"); this.spanner.noSelect=true; } createPopupMenu(menu,cell,evt){ var graph = this.graph; var wf = this.wf; var model = graph.getModel(); if (cell != null){ while (graph.isPart(cell)){cell=cell.getParent();} } menu.addItem(LANGUAGE_TEXT.workflowview.addcomment[USER_LANGUAGE],iconpath+'comment.svg',function(){ var comparent =null; if(cell)if(cell.isNode)comparent=cell.node; else if(cell.isBracket)comparent=cell.bracket; else if(cell.isHead)comparent=cell.column; else if(cell.isWeek)comparent=cell.week; var boundRect = $("#graphContainer")[0].getBoundingClientRect(); var leftPos = boundRect.x; var topPos = boundRect.y; var x = evt.pageX-leftPos; var y = evt.pageY-topPos; if(x<wfStartX)x=wfStartX; if(y<wf.weeks[0].view.vertex.y()-10)y=wf.weeks[0].view.vertex.y()-10; var com = new WFComment(wf,x,y,comparent); com.view = new Commentview(graph,com); com.view.createVertex(); wf.addComment(com); }); if(cell!=null){ if(cell.isNode)cell.node.view.populateMenu(menu); else if(cell.isWeek)cell.week.view.populateMenu(menu); else if (cell.isHead)cell.column.view.populateMenu(menu); else if (cell.isComment)cell.comment.view.populateMenu(menu); else if (cell.isBracket)cell.bracket.view.populateMenu(menu); else if (cell.isLink)cell.link.view.populateMenu(menu); else this.populateMenu(menu); }else this.populateMenu(menu); /*menu.addItem(LANGUAGE_TEXT.workflowview.whatsthis[USER_LANGUAGE],iconpath+'/info.svg',function(){ if(cell==null){ if(wf instanceof Activityflow)wf.project.showHelp("activityhelp.html"); else if (wf instanceof Courseflow)wf.project.showHelp("coursehelp.html"); else if (wf instanceof Programflow)wf.project.showHelp("programhelp.html"); else wf.project.showHelp("help.html"); }else if(cell.isNode){ wf.project.showHelp("nodehelp.html"); }else if(cell.isComment){ wf.project.showHelp("commenthelp.html"); }else if(cell.isBracket){ wf.project.showHelp("strategyhelp.html"); }else if(cell.isWeek){ if(wf instanceof Activityflow)wf.project.showHelp("activityhelp.html"); else if (wf instanceof Courseflow)wf.project.showHelp("weekhelp.html"); else if (wf instanceof Programflow)wf.project.showHelp("programhelp.html"); }else if(cell.isHead){ wf.project.showHelp("columnhelp.html"); }else{ wf.project.showHelp("help.html"); } });*/ } populateMenu(menu){ var wfv = this; var graph = this.graph; menu.addItem(LANGUAGE_TEXT.workflowview.edittitle[USER_LANGUAGE],iconpath+'text.svg',function(){ graph.startEditingAtCell(wfv.titleNode); }); menu.addItem(LANGUAGE_TEXT.workflowview.editauthor[USER_LANGUAGE],iconpath+'text.svg',function(){ graph.startEditingAtCell(wfv.authorNode); }); menu.addItem(LANGUAGE_TEXT.workflowview.editdescription[USER_LANGUAGE],iconpath+'text.svg',function(){ wfv.descriptionNode.edit(); }); this.wf.populateMenu(menu); } expandAllNodes(expand=true){ this.makeInactive(); var wf = this.wf; for(var i=0;i<wf.weeks.length;i++){ var week = wf.weeks[i]; if(week.collapsed && expand) week.collapsed = false; for(var j=0;j<week.nodes.length;j++){ var node = week.nodes[j]; node.isDropped=expand; } } /*for(var i=0;i<wf.weeks.length;i++){ var week=wf.weeks[i]; if(expand&&week.collapsed==expand)week.toggleCollapse(); for(var j=0;j<week.nodes.length;j++){ var node = week.nodes[j]; if(node.isDropped!=expand)node.toggleDropDown(); } }*/ this.makeActive(); } settingsChanged(){ this.wf.project.changeActive(this.wf); } clearGraph(){ while(this.wf.brackets.length>0){ this.brackets[0].deleteSelf(); } while(this.comments.length>0){ this.comments[0].deleteSelf(); } while(this.weeks.length>1){ this.weeks[this.weeks.length-1].deleteSelf(); } this.weeks[0].deleteSelf(); while(this.wf.columns.length>0){ this.wf.columns[this.wf.columns.length-1].deleteSelf(); } this.legend.deleteSelf(); } initializeGraph(){ var container = this.container; // Creates the mxgraph instance inside the given container var graph = new mxGraph(container); var p = this.wf.project; var wfv = this; //create minimap var minimap = document.getElementById('outlineContainer'); var outln = new mxOutline(graph, minimap); var ebContainer = document.getElementById('ebWrapper'); if(ebContainer.nextElementSibling==null||!ebContainer.nextElementSibling.classList.contains("panelresizehandle"))makeResizable(ebContainer.parentElement,"left"); //ebContainer.style.top = int(minimap.style.top)+int(minimap.style.height)+6+"px"; ebContainer.parentElement.style.zIndex='5'; ebContainer.parentElement.style.width = '400px'; var editbar = new EditBar(ebContainer,this.wf); editbar.disable(); this.editbar=editbar; //graph.panningHandler.useLeftButtonForPanning = true; if(p.readOnly){ if(!p.nodesMovable)graph.cellsMovable=false; graph.cellsEditable=false; graph.cellsResizable=false; graph.isCellConnectable = function(){return false;} } //graph.cellsDisconnectable=false; graph.setAllowDanglingEdges(false); graph.connectionHandler.select = false; //graph.view.setTranslate(20, 20); graph.setHtmlLabels(true); graph.foldingEnabled = false; graph.setTooltips(true); graph.setGridSize(10); graph.setBorder(20); graph.constrainChildren = false; graph.extendParents = false; graph.resizeContainer=true; mxConstants.HANDLE_FILLCOLOR="#DDDDFF"; //display a popup menu when user right clicks on cell, but do not select the cell graph.panningHandler.popupMenuHandler = false; //expand menus on hover graph.popupMenuHandler.autoExpand = true; //disable regular popup //mxEvent.disableContextMenu(this.container); //Disable cell movement associated with user events graph.moveCells = function (cells, dx,dy,clone,target,evt,mapping){ if(cells.length==1&&(cells[0].isComment||cells[0].isLegend)){ var comment = cells[0].comment; if(comment==null)comment=cells[0].legend; var wf = comment.wf; var x = comment.x+dx; var y = comment.y+dy; if(x<wfStartX)dx=wfStartX-comment.x; if(y<wf.weeks[0].view.vertex.y()-10)dy=wf.weeks[0].view.vertex.y()-10-comment.y; if(x>wf.weeks[wf.weeks.length-1].view.vertex.r()+200)dx=wf.weeks[wf.weeks.length-1].view.vertex.r()+200-comment.x; if(y>wf.weeks[wf.weeks.length-1].view.vertex.b()+200)dy=wf.weeks[wf.weeks.length-1].view.vertex.b()+200-comment.y; comment.x+=dx; comment.y+=dy; var parent = cells[0].parent; return mxGraph.prototype.moveCells.apply(this,[cells,dx,dy,clone,parent,evt,mapping]); } if(evt!=null && (evt.type=='mouseup' || evt.type=='pointerup' || evt.type=='ontouchend')){ dx=0;dy=0; } return mxGraph.prototype.moveCells.apply(this,[cells,dx,dy,clone,target,evt,mapping]); } //Flag for layout being changed, don't update while true graph.ffL=false; //This overwrites the preview functionality when moving nodes so that nodes are automatically //snapped into place and moved while the preview is active. graph.graphHandler.updatePreviewShape = function(){ if(this.shape!=null&&!graph.ffL){ graph.ffL=true; //creates a new variable for the initial bounds, //otherwise once the node moves the preview will be //drawn relative to the NEW position but with the OLD //displacement, leading to a huge offset. if(this.shape.initboundx==null){this.shape.initboundx=this.pBounds.x;this.shape.offsetx=this.shape.initboundx-this.cells[0].getGeometry().x;} if(this.shape.initboundy==null){this.shape.initboundy=this.pBounds.y;this.shape.offsety=this.shape.initboundy-this.cells[0].getGeometry().y;} //redraw the bounds. This is the same as the original function we are overriding, however //initboundx has taken the place of pBound.x this.shape.bounds = new mxRectangle(Math.round(this.shape.initboundx + this.currentDx - this.graph.panDx), Math.round(this.shape.initboundy + this.currentDy - this.graph.panDy), this.pBounds.width, this.pBounds.height); this.shape.redraw(); //Get the selected cells var cells = this.cells; var preview = this.shape.bounds.getPoint(); //Unfortunately, the preview uses the position relative to the current panned window, whereas everything else uses the real positions. So we figure out the offset between these //at the start of the drag. var newx = preview.x-this.shape.offsetx; var newy = preview.y-this.shape.offsety; //for single WFNodes, we will snap during the preview if(cells.length==1 && cells[0].isNode) { var cell = cells[0]; var wf = cell.node.wf; var columns=cell.node.wf.columns; var weeks = cell.node.wf.weeks; //It's more intuitive if we go from the center of the cells, especially since the column positions are measured relative to the center, so we do a quick redefinition of the position. newx=newx+cell.w()/2; newy=newy+cell.h()/2; //Start by checking whether we need to move in the x direction var colIndex=wf.getColIndex(cell.node.column); var newColName = wf.view.findNearestColumn(newx); if(newColName!=cell.node.column&&(!wf.project.readOnly)){ var oldColName=cell.node.column; cell.node.setColumn(newColName); cell.node.week.columnUpdated(cell.node,oldColName); cell.node.wf.updated("Node Moved",cell.node); } //Check the y //First we check whether we are inside a new week; if we are then it hardly matters where we are relative to the nodes within the old week. var node = cell.node; var week = node.week; var weekChange=week.view.relativePos(newy); if(weekChange==0){//proceed to determine whether or not the node must move within the week var index = week.getIndexOf(node); var newIndex = week.view.getNearestNode(newy,node.column); if(index!=newIndex){ week.shiftNode(index,newIndex,node.column); node.wf.updated("Node Moved",node); } }else{ node.changeWeek(weekChange,graph); node.wf.updated("Node Moved",node); } }else if(cells.length==1 && cells[0].isHead){ //as above but with only the horizontal movement var cell = cells[0]; var wf = cell.column.wf; var columns=wf.columns; //start from center of this cell newx=newx+cell.w()/2; //column index var colIndex=wf.columns.indexOf(cell.column); if(colIndex>0 && Math.abs(columns[colIndex].view.pos-newx)>Math.abs(columns[colIndex-1].view.pos-newx)){ //swap this column with that to the left wf.swapColumns(colIndex,colIndex-1); wf.updated("Column Moved"); } if(colIndex<columns.length-1 && Math.abs(columns[colIndex].view.pos-newx)>Math.abs(columns[colIndex+1].view.pos-newx)){ //swap this column with that to the right wf.swapColumns(colIndex,colIndex+1); wf.updated("Column Moved"); } } graph.ffL=false; } } //Alters the way the drawPreview function is handled on resize, so that the brackets can snap as they are resized. Also disables horizontal resizing. mxVertexHandler.prototype.drawPreview = function(){ var cell = this.state.cell; if(this.selectionBorder.offsetx==null){this.selectionBorder.offsetx=this.bounds.x-cell.x();this.selectionBorder.offsety=this.bounds.y-cell.y();} if(cell.isNode||cell.isBracket){ this.bounds.width = this.state.cell.w(); this.bounds.x = this.state.cell.x()+this.selectionBorder.offsetx; } if(this.state.cell!=null&&!graph.ffL){ if(cell.isBracket){ graph.ffL=true; var br = cell.bracket; var wf = br.wf; var bounds = this.bounds; if(Math.abs(bounds.height-cell.h())>minCellHeight/2+cellSpacing){ var dy = bounds.y-cell.y()-this.selectionBorder.offsety; var db = (bounds.height+bounds.y)-cell.b()-this.selectionBorder.offsety; var dh = bounds.height-cell.h(); var isTop = (dy!=0); var next = wf.findNextNodeOfSameType(br.getNode(isTop),int((dy+db)/Math.abs(dy+db))); if(next!=null){ if(Math.abs(dh)>cellSpacing+next.view.vertex.h()/2){ var delta = (next.view.vertex.y()-cell.y())*(isTop) + (next.view.vertex.b()-cell.b())*(!isTop); br.changeNode(next,isTop); //Required because of the way in which mxvertex handler tracks rescales. I don't think this breaks anything else. this.startY = this.startY +delta; } } } graph.ffL=false; } } drawPreviewPrototype.apply(this,arguments); } //disable cell resize for the bracket var resizeCellPrototype = mxVertexHandler.prototype.resizeCell; mxVertexHandler.prototype.resizeCell = function(cell,dx,dy,index,gridEnabled,constrained,recurse){ if(cell.isBracket)return; else return resizeCellPrototype.apply(this,arguments); } //Disable horizontal resize graph.resizeCell = function (cell, bounds, recurse){ if(cell.isNode) { if(bounds.height<minCellHeight)bounds.height=minCellHeight; bounds.y=cell.y(); bounds.x=cell.x(); bounds.width=cell.w(); var dy = bounds.height - cell.h(); var returnval = mxGraph.prototype.resizeCell.apply(this,arguments); cell.node.resizeBy(dy); return returnval; } if(cell.isBracket){bounds.width=cell.w();bounds.x=cell.x();} return mxGraph.prototype.resizeCell.apply(this,arguments); } //handle the changing of the toolbar upon selection graph.selectCellForEvent = function(cell,evt){ if(cell.noSelect){graph.clearSelection();return;} if(cell.isWeek){graph.clearSelection();return;} if(cell.isHead){wfv.showColFloat(false);} mxGraph.prototype.selectCellForEvent.apply(this,arguments); } graph.clearSelection = function(){ this.stopEditing(false); if(editbar.node&&editbar.node.view)editbar.node.view.deselected(); editbar.disable(); wfv.showColFloat(true); $("body>.mxPopupMenu").remove(); mxGraph.prototype.clearSelection.apply(this,arguments); } //function that checks if it is a constituent graph.isPart = function(cell){ var state = this.view.getState(cell); var style = (state != null) ? state.style : this.getCellStyle(cell); return style['constituent']=='1'; } //Redirect clicks and drags to parent var graphHandlerGetInitialCellForEvent = mxGraphHandler.prototype.getInitialCellForEvent; mxGraphHandler.prototype.getInitialCellForEvent = function(me){ var cell = graphHandlerGetInitialCellForEvent.apply(this, arguments); while (this.graph.isPart(cell)){ cell = this.graph.getModel().getParent(cell); } return cell; }; //Adds an event listener to handle the drop down collapse/expand of nodes graph.addListener(mxEvent.CLICK,function(sender,evt){ container.focus(); }); //Add an event listener to handle double clicks to nodes, which, if they have a linked wf, will change the active wf graph.addListener(mxEvent.DOUBLE_CLICK,function(sender,evt){ var cell = evt.getProperty('cell'); if(cell!=null){ while (graph.isPart(cell)){cell = graph.getModel().getParent(cell);} if(cell.isNode){ var node = cell.node; node.openLinkedWF(); } } }); //These will be used to distinguish between clicks and drags var downx=0; var downy=0; graph.addMouseListener( { mouseDown: function(sender,me){downx=me.graphX;downy=me.graphY;}, mouseUp: function(sender,me){ var cell = me.getCell(); if(cell!=null&&me.evt.button==0){ //check if this was a click, rather than a drag if(Math.sqrt(Math.pow(downx-me.graphX,2)+Math.pow(downy-me.graphY,2))<2){ if(cell.isDrop){ cell.node.toggleDropDown(); }else if(cell.isComment){ cell.comment.view.show(); }else{ while (graph.isPart(cell)){cell = graph.getModel().getParent(cell);} //check if this was a click, rather than a drag if(cell.isNode){ if(editbar.node&&editbar.node.view)editbar.node.view.deselected(); editbar.enable(cell.node); cell.node.view.selected(); } } } } }, mouseMove: function(sender,me){ var cell=me.getCell(); if(cell==null)return; while (graph.isPart(cell)){if(cell.cellOverlays!=null)break;cell = graph.getModel().getParent(cell);} if(cell.cellOverlays!=null){ if(graph.getCellOverlays(cell)==null){ //check if you are in bounds, if so create overlays. Because of a weird offset between the graph view and the graph itself, we have to use the cell's view state instead of its own bounds var mouserect = new mxRectangle(me.getGraphX()-exitPadding/2,me.getGraphY()-exitPadding/2,exitPadding,exitPadding); if(mxUtils.intersects(mouserect,graph.view.getState(cell))){ //Add link highlighting if(cell.isNode&&cell.node.view)cell.node.view.mouseIn(); if(cell.isLink&&cell.link.view)cell.link.view.mouseIn(); //Add the overlays if(!p.readOnly)for(var i=0;i<cell.cellOverlays.length;i++){ graph.addCellOverlay(cell,cell.cellOverlays[i]); } //if it's a node with tags, also show those var timeoutvar; if(cell.isTagPreview&&cell.node.tags.length>0)timeoutvar = setTimeout(function(){if(cell.node.wf.view==wfv)cell.node.view.toggleTags(true);},200); //add the listener that will remove these once the mouse exits graph.addMouseListener({ mouseDown: function(sender,me){}, mouseUp: function(sender,me){}, mouseMove: function(sender,me){ if(graph.view.getState(cell)==null){graph.removeMouseListener(this);return;} var exitrect = new mxRectangle(me.getGraphX()-exitPadding,me.getGraphY()-exitPadding,exitPadding*2,exitPadding*2); if(!mxUtils.intersects(exitrect,graph.view.getState(cell))){ /*if(cell.isNode&&graph.view.getState(cell.node.view.tagBox)!=null&&mxUtils.intersects(exitrect,graph.view.getState(cell.node.view.tagBox))){ return; }*/ //remove link highlighting if(cell.isNode&&cell.node.view)cell.node.view.mouseOut(); if(cell.isLink&&cell.link.view)cell.link.view.mouseOut(); graph.removeCellOverlay(cell); if(cell.isTagPreview||cell.isNode){cell.node.view.toggleTags(false);clearTimeout(timeoutvar);} if(cell.isLink){cell.link.view.toggleTags(false);clearTimeout(timeoutvar);} graph.removeMouseListener(this); } } }); } } } } } ); //Change default graph behaviour to make vertices not connectable graph.insertVertex = function(par,id,value,x,y,width,height,style,relative){ var vertex = mxGraph.prototype.insertVertex.apply(this,arguments); vertex.setConnectable(false); return vertex; } //Setting up ports for the cell connections graph.setConnectable(true); // Replaces the port image graph.setPortsEnabled(false); mxConstraintHandler.prototype.pointImage = new mxImage(iconpath+'port.svg', 10, 10); var ports = new Array(); ports['OUTw'] = {x: 0, y: 0.6, perimeter: true, constraint: 'west'}; ports['OUTe'] = {x: 1, y: 0.6, perimeter: true, constraint: 'east'}; ports['OUTs'] = {x: 0.5, y: 1, perimeter: true, constraint: 'south'}; ports['HIDDENs'] = {x: 0.5, y: 1, perimeter: true, constraint: 'south'}; ports['INw'] = {x: 0, y: 0.4, perimeter: true, constraint: 'west'}; ports['INe'] = {x: 1, y: 0.4, perimeter: true, constraint: 'east'}; ports['INn'] = {x: 0.5, y: 0, perimeter: true, constraint: 'north'}; // Extends shapes classes to return their ports mxShape.prototype.getPorts = function() { return ports; }; // Disables floating connections (only connections via ports allowed) graph.connectionHandler.isConnectableCell = function(cell) { return false; }; mxEdgeHandler.prototype.isConnectableCell = function(cell) { return graph.connectionHandler.isConnectableCell(cell); }; // Disables existing port functionality graph.view.getTerminalPort = function(state, terminal, source) { return terminal; }; // Returns all possible ports for a given terminal graph.getAllConnectionConstraints = function(terminal, source) { if (terminal != null && this.model.isVertex(terminal.cell)) { if (terminal.shape != null) { var ports = terminal.shape.getPorts(); var cstrs = new Array(); for (var id in ports) { if(id.indexOf("HIDDEN")>=0)continue; if((id.indexOf("IN")>=0&&source)||id.indexOf("OUT")>=0&&!source)continue; var port = ports[id]; var cstr = new mxConnectionConstraint(new mxPoint(port.x, port.y), port.perimeter); cstr.id = id; cstrs.push(cstr); } return cstrs; } } return null; }; // Sets the port for the given connection graph.setConnectionConstraint = function(edge, terminal, source, constraint) { if (constraint != null) { var key = (source) ? mxConstants.STYLE_SOURCE_PORT : mxConstants.STYLE_TARGET_PORT; if (constraint == null || constraint.id == null) { this.setCellStyles(key, null, [edge]); } else if (constraint.id != null) { this.setCellStyles(key, constraint.id, [edge]); } } }; // Returns the port for the given connection graph.getConnectionConstraint = function(edge, terminal, source) { var key = (source) ? mxConstants.STYLE_SOURCE_PORT : mxConstants.STYLE_TARGET_PORT; var id = edge.style[key]; if (id != null) { var c = new mxConnectionConstraint(null, null); c.id = id; return c; } return null; }; initializeConnectionPointForGraph(graph); //make the non-default connections through our own functions, so that we can keep track of what is linked to what. The prototype is saved in Constants, so that we don't keep overwriting it. mxConnectionHandler.prototype.insertEdge = function(parent,id,value,source,target,style){ if(source.isNode&&target.isNode){ for(var i=0;i<source.node.fixedLinksOut.length;i++){ if(source.node.fixedLinksOut[i].targetNode==target.node)return null; } } var edge = insertEdgePrototype.apply(this,arguments); if(source.isNode && target.isNode){ graph.setCellStyle(defaultEdgeStyle,[edge]); source.node.addFixedLinkOut(target.node,edge); } return edge; } //Handle changing the edge's target or source mxEdgeHandler.prototype.connect = function(edge,terminal,isSource,isClone,me){ var link = edge.link; if(!link||link instanceof WFAutolink)return; var newSource; var newTarget; if(isSource){newSource=terminal.node;newTarget=edge.link.targetNode;} else {newSource=edge.link.node;newTarget=terminal.node;} if(newSource&&newTarget)for(var i=0;i<newSource.fixedLinksOut.length;i++){ if(newSource.fixedLinksOut[i].targetNode==newTarget)return; } var returnval = edgeConnectPrototype.apply(this,arguments); console.log(edge); console.log(link); try{ var originalNode = link.node; if(isSource){ originalNode.fixedLinksOut.splice(originalNode.fixedLinksOut.indexOf(link),1); link.node = terminal.node; terminal.node.fixedLinksOut.push(link); }else{ link.targetNode.linksIn.splice(link.targetNode.linksIn.indexOf(link),1); link.targetNode = terminal.node; link.targetNode.linksIn.push(link); link.id = link.targetNode.id; } var ps = link.view.getPortStyle(); if(ps)link.portStyle = ps; }catch(err){console.log("there was a problem changing the edge");} console.log(returnval); return returnval; } this.graph = graph; } //Scale such that there is no horizontal overflow, vertical can break over pages print(){ var graph = this.graph; if(graph==null)return; var des = graph.insertVertex(graph.getDefaultParent(),null,this.wf.description,(wfStartX+cellSpacing+20),(wfStartY+70+40),800,80,defaultTextStyle+"strokeColor=none;"); var x = graph.getGraphBounds().width; var x0 = mxConstants.PAGE_FORMAT_A4_PORTRAIT.width; var scale = 0.95; if(x>x0)scale=scale*x0/x; var preview = new mxPrintPreview(graph, scale,mxConstants.PAGE_FORMAT_A4_PORTRAIT); preview.open(); graph.removeCells([des]) } }
JavaScript
class __SyntheticTypes { // __findTypeTable(): // // Finds a type table for the given path and module (if one has already been read) // __findTypeTable(path, boundModule) { var mod = __getModuleFor(boundModule); for (var typeTable of __typeTables) { if (mod.Name == typeTable.Module.Name && mod.BaseAddress == typeTable.Module.BaseAddress) { // // We've found a type table bound to the same module. Is it the same header read? // if (typeTable.__headerPath !== undefined && typeTable.__headerPath == path) { return typeTable; } } } return null; } // ReadHeader(): // // Performs a limited understanding read of a C header file and generates synthetic types // based on that understanding. The return value is a type table. // ReadHeader(path, boundModule, attributes) { if (boundModule === undefined) { throw new Error("ReadHeader() requires a module to bind type names to"); } var macros; if (attributes && attributes.Macros) { macros = attributes.Macros; } // // If we already have a type table, just return it. Don't bother to reread the // table. This will prevent things like DML links from repeatedly rereading the // header and creating duplicate tables! // var typeTable = this.__findTypeTable(path, boundModule); if (typeTable) { return typeTable; } var file = __getAPI().FileSystem.OpenFile(path); var capturedException; try { var reader = __getAPI().FileSystem.CreateTextReader(file); var parser = new __CParser(reader, macros); typeTable = parser.readTypeTable(boundModule, path, macros); __typeTables.push(typeTable); } catch(exc) { capturedException = exc; if (__diag) { host.diagnostics.debugLog("We hit an exception: '", exc, "'!\n"); } } file.Close(); // // If the header failed to read: pass the error back. Do not give the user an invalid or // partial type table. // if (capturedException) { throw capturedException; } return typeTable; } // CreateInstance(): // // Creates an instance of a given type. // CreateInstance(typeName, addrObj) { var name = typeName; var alias = __typeAliases[name]; if (alias !== undefined) { name = alias; } var def = __syntheticTypes[name]; if (def === undefined) { throw new Error("Unrecognized type name"); } var ctor = def.classObject; return new ctor(addrObj, def.containingTable.Module); } // TypeTables(): // // Returns the type tables we have read. // get TypeTables() { return __typeTables; } get [Symbol.metadataDescriptor]() { return { ReadHeader: { PreferShow: true, Help: "ReadHeader(headerPath, module, [attributes])- Reads a header at the file and defines synthetic constructors for all structs and unions in the header referencing existing types in the given module. Attributes is a set of key value pairs. Presently, it may contain Macros (another set of key/value pairs)" }, CreateInstance: {PreferShow: true, Help: "CreateInstance(typeName, addrObj) - Creates an instance of a synthetic type and returns it. The type must have been read from a header or defined through other APIs here" }, TypeTables: {Help: "The set of type tables create from prior calls to read headers or define tables"} }; } }
JavaScript
class MP4VideoPlayer extends PolymerElement { static get template() { return html` ${playerStyles} <div id="video_container" class="container"> <div class="title"> <h3 id="video_title">[[title]]</h3> </div> <div id="region_left" class="tap-region tap-left" on-touchstart="_handleDblTap"> </div> <div id="region_right" class="tap-region tap-right" on-touchstart="_handleDblTap"> </div> <div id="replay_pulse" class="pulse-icon icon-left"> <iron-icon icon="player-icons:replay-5"></iron-icon> </div> <div id="forward_pulse" class="pulse-icon icon-right"> <iron-icon icon="player-icons:forward-5"></iron-icon> </div> <div class="large-btn" on-click="play"> <iron-icon icon="player-icons:play-arrow"></iron-icon> </div> <video id="video_player" playsinline on-dblclick="_toggleFullscreen" preload="metadata" src$="[[src]]" autoplay$="[[autoPlay]]" loop$="[[loop]]" poster$="[[poster]]" on-play="_firePlayEvent" on-pause="_firePauseEvent" on-ended="_fireEndedEvent" on-loadedmetadata="_metadetaLoaded" on-timeupdate="_handleTimeUpdate"> <source src$="{{videoFilePath}}" type="video/mp4"> </video> <div class="video-controls"> <template is="dom-if" if={{timelinePreview}}> <div id="time_preview" class="preview">[[previewTime]]</div> </template> <div id="menu" class="dropdown-menu" hidden> <button type="button" class="menu-item"> <iron-icon icon="player-icons:closed-caption"></iron-icon> <span>CAPTION</span> </button> <template is="dom-if" if="{{_enablePIP}}"> <button type="button" class="menu-item" on-click="_togglePictureInPicture"> <iron-icon icon="player-icons:picture-in-picture"></iron-icon> <span>PICTURE-IN-PICTURE</span> </button> </template> <button type="button" class="menu-item"> <a href$="{{videoFilePath}}" download> <iron-icon icon="player-icons:file-download"></iron-icon> </a> <span>DOWNLOAD</span> </button> </div> <div class="track" on-mouseenter="_togglePreview" on-mousemove="_updatePreviewPosition" on-mouseleave="_togglePreview" on-mousedown="_handleDown" on-touchstart="_handleDown"> <div id="track_slider" class="slider"> <div id="track_thumb" class="thumb"></div> </div> <div id="track_fill" class="fill"></div> </div> <div class="lower-controls"> <div class="left"> <div id="play_icons" class="control-icons" on-click="_togglePlay"> <template is="dom-if" if={{!playing}}> <template is="dom-if" if={{ended}}> <iron-icon icon="player-icons:replay"></iron-icon> </template> <template is="dom-if" if={{!ended}}> <iron-icon icon="player-icons:play-arrow"></iron-icon> </template> </template> <template is="dom-if" if={{playing}}> <iron-icon icon="player-icons:pause"></iron-icon> </template> <span class="tooltip">[[_tooltipCaptions.playButton]]</span> </div> <div id="time" class="time-elapsed"> <span id="current_time" tabindex="-1">[[_formattedCurrentTime]]</span> &nbsp;/&nbsp; <span id="total_duration" tabindex="-1">[[_formattedDuration]]</span> </div> </div> <div class="right"> <template is="dom-if" if={{!touchDevice}}> <div id="volume_icons" class="control-icons" tabindex="0" on-click="_toggleMute"> <template is="dom-if" if={{muted}}> <iron-icon icon="player-icons:volume-off"></iron-icon> </template> <template is="dom-if" if={{!muted}}> <iron-icon icon="player-icons:volume-up"></iron-icon> </template> <span class="tooltip">[[_tooltipCaptions.volumeButton]]</span> </div> <div id="volume_track" class="track volume" on-mousedown="_handleDown" on-touchstart="_handleDown"> <div id="volume_track_slider" class="slider volume"> <div id="volume_track_thumb" class="thumb volume"></div> <div id="volume_track_fill" class="fill volume"></div> </div> </div> </template> <div id="fullscreen_icons" class="control-icons" on-click="_toggleFullscreen"> <template is="dom-if" if={{!fullscreen}}> <iron-icon icon="player-icons:fullscreen"></iron-icon> </template> <template is="dom-if" if={{fullscreen}}> <iron-icon icon="player-icons:fullscreen-exit"></iron-icon> </template> <span class="tooltip">[[_tooltipCaptions.fullscreenButton]]</span> </div> <div id="settings_icon" class="control-icons" on-click="_toggleMenu"> <iron-icon icon="player-icons:more-vert"></iron-icon> <span class="tooltip">[[_tooltipCaptions.optionButton]]</span> </div> </div> </div> </div> </div> `; } static get properties() { return { /* The title displayed on the top of video player */ title: String, /* Path to .mp4 video */ src: String, /* File path to poster image. It can be a relative or absolute URL */ poster: String, /* Whether the video should start playing as soon as it is loaded */ autoPlay: Boolean, /* Whether the video should start over again, every time it is finished */ loop: Boolean, /* Duration of the video */ duration: { type: Number, readOnly: true }, /* If the video is currently playing */ playing: { type: Boolean, value: false, readOnly: true, reflectToAttribute: true }, ended: { type: Boolean, value: false, readOnly: true, reflectToAttribute: true }, /* If the audio is currently muted */ muted: { type: Boolean, computed: '_isMuted(volume)' }, /* If the player is in fullscreen mode */ fullscreen: { type: Boolean, value: false, readOnly: true, reflectToAttribute: true }, /* Determines if the timeline preview above the track appears when hovering */ timelinePreview: { type: Boolean, value: true, reflectToAttribute: true }, /* The volume scaled from 0-1 */ volume: { type: Number, value: 0.5 }, /* Current time of video playback */ time: { type: Number, value: 0 }, /* Skip ahead or behind the current time based on the right or left arrow keys respectively */ skipBy: { type: Number, value: 5 }, /* The formatted current position of the video playback in m:ss */ _formattedCurrentTime: { type: String, value: '0:00' }, /* The formatted total duration of the video playback in m:ss */ _formattedDuration: { type: String, value: '0:00' }, /* Used the populate the tooltip captions based on the current state of the player */ _tooltipCaptions: { type: Object, computed: '_computeTooltipCaptions(playing, muted, fullscreen, ended)' }, /* Toggle the Picture-in-Picture feature based on browser compatibility */ _enablePIP: { type: Boolean, value: () => document.pictureInPictureEnabled, readOnly: true }, /* If operating on a touch device */ touchDevice: { type: Boolean, value: false, readOnly: true, reflectToAttribute: true } }; } constructor() { super(); this.tabIndex = 0; this.min = 0; this.step = 0.01; this.toFixed = 8; this.dragging = { volume: false, track: false }; this.fullscreenChangeEvent = this._prefix === 'ms' ? 'MSFullscreenchange' : `${this._prefix}fullscreenchange`; this.parser = new UAParser(); } ready() { super.ready(); this.addEventListener(this.fullscreenChangeEvent, this._handleFullscreenChange.bind(this)); this._setTouchDevice(this._isTouchDevice()); this._createPropertyObserver('volume', '_volumeChanged', true); this._createPropertyObserver('time', '_timeChanged', true); window.addEventListener('resize', () => { const { currentTime, duration } = this._getShadowElementById('video_player'); this._setTrackPosition(currentTime, duration); }); window.addEventListener('keydown', this._handleKeyCode.bind(this)); } /** * Determine if the browser is operating on a touch * device based on operating system. * @return {boolean} if operating on touch device */ _isTouchDevice() { const { name } = this.parser.getOS(); return name === 'iOS' || name === 'Android'; } /** * Determine if variable/property is truly a function. * @param {*} func function variable * @return {boolean} if variable is function. * @private */ _isFunction(func) { return typeof func === 'function'; } /** * Retrieve vender prefix for handling fullscreen * functionality * @private * @return {string} vendor prefix */ get _prefix() { if (document.exitFullscreen) { return ''; // no prefix Edge } const prefixes = ['webkit', 'ms', 'moz']; return prefixes.find((prefix) => { const exitFunction = document[`${prefix}ExitFullscreen`]; // Chrome, Safari, IE const mozExitFunction = document[`${prefix}CancelFullscreen`]; // Firefox return this._isFunction(exitFunction) || this._isFunction(mozExitFunction); }); } get _SPACE_BAR_KEY() { return 32; } get _P_KEY() { return 80; } get _M_KEY() { return 77; } get _F_KEY() { return 70; } get _LEFT_ARROW() { return 37; } get _UP_ARROW() { return 38; } get _RIGHT_ARROW() { return 39; } get _DOWN_ARROW() { return 40; } /** * Computes the value of the `muted` prop based on the current volume. * @param {number} volume current volume * @return {boolean} if the current volume is 0 * @private */ _isMuted(volume) { return volume === 0; } /** * Compute the tooltip caption text based on the current * state of the video player. * @param {boolean} playing if video is playing * @param {boolean} muted if volume is muted * @param {boolean} fullscreen if player is in fullscreen mode * @return {Object} captions for lower track controls * @private */ _computeTooltipCaptions(playing, muted, fullscreen, ended) { const captions = { playButton: 'Play', volumeButton: 'Volume', fullscreenButton: 'Fullscreen', optionButton: 'Options' }; if (playing) { captions.playButton = 'Pause'; } if (muted) { captions.volumeButton = 'Mute'; } if (fullscreen) { captions.fullscreenButton = 'Exit Fullscreen'; } if (!playing) { if (ended) { captions.playButton = 'Replay'; } } return captions; } /** * Find element with an id within the Shadow DOM * of the video player. * @param {string} id id of element * @return {Element | undefined} element * @private */ _getShadowElementById(id) { const element = this.$[id]; if (element) { return element; } return this.shadowRoot.querySelector(`#${id}`); } /** * Toggle thumbnail previews event handler * @param {MouseEvent} event mouse-enter/leave event * @private */ _togglePreview(event) { if (this.timelinePreview) { const thumbnail = this._getShadowElementById('time_preview'); const { type } = event; let toggle = false; if (type === 'mouseenter') { toggle = true; } thumbnail.classList.toggle('appear', toggle); } } /** * Toggle Picture-in-Picture mode * @private */ _togglePictureInPicture() { const video = this._getShadowElementById('video_player'); if (!document.pictureInPictureElement) { video.requestPictureInPicture() .catch(() => { console.log('Failed to enter Picture-in-Picture mode'); }); } else { document.exitPictureInPicture() .catch(() => { console.log('Failed to leave Picture-in-Picture mode'); }); } } /** * Toggle settings menu * @private */ _toggleMenu() { const menu = this._getShadowElementById('menu'); menu.hidden = !menu.hidden; } /** * Update preview position on track * @param {MouseEvent} event mouse-move event * @private */ _updatePreviewPosition(event) { if (this.timelinePreview) { const video = this._getShadowElementById('video_player'); const thumbnail = this._getShadowElementById('time_preview'); const container = this._getShadowElementById('video_container'); const containerRec = container.getBoundingClientRect(); const thumbnailRec = thumbnail.getBoundingClientRect(); const progressBarRec = event.currentTarget.getBoundingClientRect(); const thumbnailWidth = thumbnailRec.width; const minVal = containerRec.left - progressBarRec.left + 10; const maxVal = containerRec.right - progressBarRec.left - thumbnailWidth - 10; const mousePosX = event.pageX; const relativePosX = mousePosX - progressBarRec.left; let previewPos = relativePosX - thumbnailWidth / 2; if (previewPos < minVal) { previewPos = minVal; } if (previewPos > maxVal) { previewPos = maxVal; } thumbnail.style.left = `${previewPos + 5}px`; // TODO: very hacky. This is because of the 5px padding.. this.previewTime = this._formatTime(video.duration * (relativePosX / event.currentTarget.offsetWidth)); } } /** * Calculate and set the track thumb position & track fill. * @param {*} value current value on track * @param {*} maxValue maximum value on track * @param {*} sliderIdPrefix id prefix of the slider that is being targeted (volume or otherwise) * @private */ _setTrackPosition(value, maxValue, sliderIdPrefix = '') { const thumb = this._getShadowElementById(`${sliderIdPrefix}track_thumb`); const slider = this._getShadowElementById(`${sliderIdPrefix}track_slider`); const maxHandlePos = slider.offsetWidth - thumb.offsetWidth; this.grabX = thumb.offsetWidth / 2; const position = this._getPositionFromValue(value, maxHandlePos, maxValue); this._setPosition(position, sliderIdPrefix); } /** * When video metadata is completely loaded * total duration is then formatted onto the player * @param {Event} event when the video has loaded metadeta * @private */ _metadetaLoaded(event) { const { duration } = event.currentTarget; this._fireLoadedmetadata(); this._setDuration(duration); this._formattedDuration = this._formatTime(duration); } /** * Format the elasped time to minutes and seconds * @private */ _formatElapsedTime() { const { currentTime } = this._getShadowElementById('video_player'); this._formattedCurrentTime = this._formatTime(currentTime); } /** * Format the current time * @param {number} time current time * @return {string} formatted time * @private */ _formatTime(time) { let mins = Math.floor(time / 60); let secs = Math.round(time - mins * 60); if (secs === 60) { mins += 1; secs = 0; } if (secs < 10) { secs = `0${secs}`; } return `${mins}:${secs}`; } _createEvent(eventName, detail) { return new CustomEvent(eventName, { bubbles: true, detail }); } /** * Fire the appropriate event based on event type */ fireEvent(type) { switch (type) { case 'loaded': this._fireLoadedmetadata(); break; case 'play': this._firePlayEvent(); break; case 'pause': this._firePauseEvent(); break; case 'ended': this._fireEndedEvent(); break; case 'enterFullscreen': this._fireEnterFullscreenEvent(); break; case 'exitFullscreen': this._fireExitFullscreenEvent(); break; case 'timeUpdated': this._fireTimeUpdatedEvent(); break; case 'volumeChange': this._fireVolumeChangeEvent(); break; default: break; } } /** * When the video has paused */ _fireLoadedmetadata() { const { duration } = this._getShadowElementById('video_player'); this.dispatchEvent(this._createEvent('loadedmetadata', { duration })); } /** * When the video has started to play */ _firePlayEvent() { const { currentTime } = this._getShadowElementById('video_player'); if (this.autoPlay) { this._setPlaying(true); // change the state of the track controls when initially playing.. } this.dispatchEvent(this._createEvent('play', { currentTime })); } /** * When the video has paused */ _firePauseEvent() { const { currentTime } = this._getShadowElementById('video_player'); this.dispatchEvent(this._createEvent('pause', { currentTime })); } /** * When the video has ended */ _fireEndedEvent() { this._setPlaying(false); this._setEnded(true); const { currentTime } = this._getShadowElementById('video_player'); this.dispatchEvent(this._createEvent('ended', { currentTime })); } /** * When the video has enter fullscreen */ _fireEnterFullscreenEvent() { const { currentTime } = this._getShadowElementById('video_player'); this.dispatchEvent(this._createEvent('enterFullscreen', { currentTime })); } /** * When the video has exited fullscreen */ _fireExitFullscreenEvent() { const { currentTime } = this._getShadowElementById('video_player'); this.dispatchEvent(this._createEvent('exitFullscreen', { currentTime })); } /** * When the video has exited fullscreen */ _fireTimeUpdatedEvent() { const { currentTime } = this._getShadowElementById('video_player'); this.dispatchEvent(this._createEvent('timeUpdated', { currentTime })); } /** * When the video has changed volume */ _fireVolumeChangeEvent() { const { volume } = this._getShadowElementById('video_player'); this.dispatchEvent(this._createEvent('volumeChange', { volume })); } /** * Update the track positioning when the * current video curentTime property updates * @param {Event} event * @private */ _handleTimeUpdate() { if ((this.playing) && !this.dragging.track) { const { currentTime, duration } = this._getShadowElementById('video_player'); this._setTrackPosition(currentTime, duration); } this._formatElapsedTime(); } /** * Update the current time of the video * @param {number} progress current progress * @private */ _updateCurrentTime(progress) { const video = this._getShadowElementById('video_player'); this._fireTimeUpdatedEvent(); video.currentTime = progress; } /** * Update the volume of the video player * @param {number} volume current volume * @private */ _updateCurrentVolume(volume) { this.volume = volume; } _matches(element, selector) { const matchMethod = element.matches || element.webwebkitMatchesSelector || element.msMatchesSelector || element.mozMatchesSelector; return matchMethod.call(element, selector); } /** * Skip forward or replay the current time of the video * @param {Boolean} forward whether or not to skip forward */ _skip(forward) { const idPrefix = forward ? 'forward' : 'replay'; const skipBy = forward ? this.skipBy : -this.skipBy; const { currentTime } = this._getShadowElementById('video_player'); const pulse = this._getShadowElementById(`${idPrefix}_pulse`); this._updateCurrentTime(currentTime + skipBy); pulse.classList.remove('on'); // eslint-disable-next-line no-unused-expressions pulse.offsetWidth; // trigger reflow.. pulse.classList.add('on'); } /** * Handle double tap events on video container * @param {TouchEvent} e touch event */ _handleDblTap(e) { const { currentTarget: { id } } = e; const time = new Date().getTime(); const tapLength = time - this.lastTap; let skipForward = true; e.preventDefault(); clearTimeout(this.timeout); if (tapLength < 500 && tapLength > 0) { if (id === 'region_left') { skipForward = false; } this._skip(skipForward); } else { this.timeout = setTimeout(() => { clearTimeout(this.timeout); }, 500); } this.lastTap = time; } /** * Handle keycode video playback shortcuts * @param {KeyboardEvent} event key-up event * @private */ _handleKeyCode(event) { const { keyCode } = event; const { activeElement } = document; const preventableCodes = [this._UP_ARROW, this._DOWN_ARROW, this._SPACE_BAR_KEY]; const editableSelectors = 'input, select, textarea'; if (activeElement instanceof Element) { if (this._matches(activeElement, editableSelectors)) return; } if (preventableCodes.includes(keyCode)) { event.preventDefault(); } const maxVol = 1; const minVol = 0; const { volume } = this._getShadowElementById('video_player'); switch (event.keyCode) { case this._SPACE_BAR_KEY: case this._P_KEY: this._togglePlay(); break; case this._M_KEY: this._toggleMute(); break; case this._F_KEY: this._toggleFullscreen(); break; case this._LEFT_ARROW: { this._skip(false); break; } case this._RIGHT_ARROW: { this._skip(true); break; } case this._UP_ARROW: { const newVolume = this._between(volume + 0.05, minVol, maxVol); this._updateCurrentVolume(newVolume); break; } case this._DOWN_ARROW: { const newVolume = this._between(volume - 0.05, minVol, maxVol); this._updateCurrentVolume(newVolume); break; } default: break; } } /** * Handle changes when toggling between * fullscreen mode * @private */ _handleFullscreenChange() { const isFullscreen = !!document.fullscreenElement; if (isFullscreen) { this._fireEnterFullscreenEvent(); } else { this._fireExitFullscreenEvent(); } this._setFullscreen(isFullscreen); } /** * Play the video */ play() { const aPromise = this._getShadowElementById('video_player').play(); if (aPromise !== undefined) { aPromise.then(() => { this._setPlaying(true); this.focus(); }).catch(() => { console.log('Problem Playing Audio!'); }); } } /** * Pause the video */ pause() { this._getShadowElementById('video_player').pause(); this._setPlaying(false); } /** * Mute the audio */ mute() { this.volume = 0; } /** * Toggle play the player * @private */ _togglePlay() { this._setEnded(false); this._setPlaying(!this.playing); if (this.playing) { this.play(); } else { this.pause(); } } /** * Request to enter fullscreen mode * @private */ _enterFullscreen() { if (!this._prefix) { this.requestFullscreen(); } else { this[`${this._prefix}RequestFullscreen`](); } } /** * Exit fullscreen mode * @private */ _exitFullscreen() { if (!this._prefix) { document.exitFullscreen(); } else { const action = this._prefix === 'moz' ? 'Cancel' : 'Exit'; document[`${this._prefix}${action}Fullscreen`](); } } /** * Toggle fullscreen mode * @private */ _toggleFullscreen() { this._setFullscreen(!this.fullscreen); if (this.fullscreen) { this._enterFullscreen(); } else { this._exitFullscreen(); } } _timeChanged(newTime) { const video = this._getShadowElementById('video_player'); const { duration } = video; this._setTrackPosition(newTime, duration); if (!this.dragging.track) { video.currentTime = 0; } } /** * Change the volume of the video * @param {Number} newVolume new volume level * @param {Number} oldVolume current volume level * @private */ _volumeChanged(newVolume, oldVolume) { const maxVolume = 1; this.prevVolume = oldVolume; this._setTrackPosition(newVolume, maxVolume, 'volume_'); this._getShadowElementById('video_player').volume = newVolume; this._fireVolumeChangeEvent(); } /** * Toggle mute the player * @private */ _toggleMute() { if (this.volume !== 0) { this.mute(); } else { this.volume = this.prevVolume; } } /** * Calculate video playback, slider thumb & slider fill positioning * when the user has begun pressing or tapping within a region of the slider (volume or otherwise) * @param {TouchEvent| MouseEvent} e touchstart or mousedown event * @private */ _handleDown(e) { if (e.cancelable) e.preventDefault(); const { button, touches, currentTarget } = e; if (touches === undefined && button !== 0) return; const eventPrefix = e.type === 'touchstart' ? 'touch' : 'mouse'; const eventReleasePrefix = e.type === 'touchstart' ? 'end' : 'up'; const sliderIdPrefix = currentTarget.classList.contains('volume') ? 'volume_' : ''; const thumb = this._getShadowElementById(`${sliderIdPrefix}track_thumb`); const slider = this._getShadowElementById(`${sliderIdPrefix}track_slider`); const posX = this._getRelativePosition(e, sliderIdPrefix); const maxHandlePos = slider.offsetWidth - thumb.offsetWidth; this.dragging.track = !currentTarget.classList.contains('volume'); this.dragging.volume = currentTarget.classList.contains('volume'); this.grabX = thumb.offsetWidth / 2; this._boundMouseMove = (event) => this._handleMove(event, sliderIdPrefix); this._boundMouseUp = (event) => this._handleRelease(event, sliderIdPrefix); if (sliderIdPrefix === '') { this.prevPlaying = this.playing; if (this.playing) this.pause(); this.time = this._getValueFromPosition(this._between(posX - this.grabX, 0, maxHandlePos), maxHandlePos, this.duration); } else { const maxVolume = 1; this.volume = this._getValueFromPosition(this._between(posX - this.grabX, 0, maxHandlePos), maxHandlePos, maxVolume); } document.addEventListener(`${eventPrefix}move`, this._boundMouseMove); document.addEventListener(`${eventPrefix + eventReleasePrefix}`, this._boundMouseUp); } /** * Calculate video playback, slider thumb & slider fill positioning * when the user begins dragging within of the document (volume or otherwise) * whilst still pressing down. * @param {TouchEvent| MouseEvent} e mousemove or touchmove event * @param {string} sliderIdPrefix id prefix of the slider being targeted * @private */ _handleMove(e, sliderIdPrefix) { if (e.cancelable) e.preventDefault(); if (this.dragging.track || this.dragging.volume) { const thumb = this._getShadowElementById(`${sliderIdPrefix}track_thumb`); const slider = this._getShadowElementById(`${sliderIdPrefix}track_slider`); const posX = this._getRelativePosition(e, sliderIdPrefix); const maxHandlePos = slider.offsetWidth - thumb.offsetWidth; const pos = posX - this.grabX; if (sliderIdPrefix === '') { this.time = this._getValueFromPosition(this._between(pos, 0, maxHandlePos), maxHandlePos, this.duration); } else { const maxVolume = 1; this.volume = this._getValueFromPosition(this._between(pos, 0, maxHandlePos), maxHandlePos, maxVolume); } } } /** * @param {TouchEvent| MouseEvent} e mouseup or touchend event * @param {string} sliderIdPrefix id prefix of the slider being targeted * @private */ _handleRelease(e, sliderIdPrefix) { if (e.cancelable) e.preventDefault(); const eventPrefix = e.type === 'touchend' ? 'touch' : 'mouse'; const eventReleasePrefix = e.type === 'touchend' ? 'end' : 'up'; const draggableItem = sliderIdPrefix === '' ? 'track' : 'volume'; this.dragging[draggableItem] = false; document.removeEventListener(`${eventPrefix}move`, this._boundMouseMove); document.removeEventListener(`${eventPrefix + eventReleasePrefix}`, this._boundMouseUp); if (sliderIdPrefix === '') { if (this.prevPlaying) this.play(); } } /** * Derive the positioning on a slider based on a value * @param {number} value current value * @param {number} maxHandlePos maximum handle position of slider * @param {number} maxValue maximum value * @return {number} position in pixels * @private */ _getPositionFromValue(value, maxHandlePos, maxValue) { const percentage = (value - this.min) / (maxValue - this.min); const pos = percentage * maxHandlePos; // eslint-disable-next-line no-restricted-globals return isNaN(pos) ? 0 : pos; } /** * Derive the value on a slider based on the current position * @param {number} pos current position in pixels * @param {number} maxHandlePos maximum handle position of slider * @param {number} maxValue maximum value * @return {number} value * @private */ _getValueFromPosition(pos, maxHandlePos, maxValue) { const percentage = ((pos) / (maxHandlePos || 1)); const value = this.step * Math.round((percentage * (maxValue - this.min)) / this.step) + this.min; return Number((value).toFixed(this.toFixed)); } /** * Retreive the relative positioning on a slider when a user presses or taps * within its region. * @param {TouchEvent| MouseEvent} e * @param {string} sliderIdPrefix id prefix of the slider being targeted * @return {number} relative position in pixels * @private */ _getRelativePosition(e, sliderIdPrefix) { const slider = this._getShadowElementById(`${sliderIdPrefix}track_slider`); const boundingClientRect = slider.getBoundingClientRect(); // Get the offset relative to the viewport const rangeSize = boundingClientRect.left; let pageOffset = 0; const pagePositionProperty = this.vertical ? 'pageY' : 'pageX'; if (typeof e[pagePositionProperty] !== 'undefined') { pageOffset = (e.touches && e.touches.length) ? e.touches[0][pagePositionProperty] : e[pagePositionProperty]; } else if (typeof e.originalEvent !== 'undefined') { if (typeof e.originalEvent[pagePositionProperty] !== 'undefined') { pageOffset = e.originalEvent[pagePositionProperty]; } else if (e.originalEvent.touches && e.originalEvent.touches[0] && typeof e.originalEvent.touches[0][pagePositionProperty] !== 'undefined') { pageOffset = e.originalEvent.touches[0][pagePositionProperty]; } } else if (e.touches && e.touches[0] && typeof e.touches[0][pagePositionProperty] !== 'undefined') { pageOffset = e.touches[0][pagePositionProperty]; } else if (e.currentPoint && (typeof e.currentPoint.x !== 'undefined' || typeof e.currentPoint.y !== 'undefined')) { pageOffset = this.vertical ? e.currentPoint.y : e.currentPoint.x; } return this.vertical ? rangeSize - pageOffset : pageOffset - rangeSize; } /** * Return the same position if it is within the maximum and minimum values. * Otherwise set to maximum and minimum values if the position is greater than or less * than respectively. * @param {number} pos current position * @param {number} min minimum position * @param {number} max maximum position * @return position * @private */ _between(pos, min, max) { if (pos < min) { return min; } if (pos > max) { return max; } return pos; } /** * Position a slider's elements appropriately * @param {number} pos current position * @param {string} sliderIdPrefix id prefix of the slider that is being targeted * @private */ _setPosition(pos, sliderIdPrefix = '') { const slider = this._getShadowElementById(`${sliderIdPrefix}track_slider`); const thumb = this._getShadowElementById(`${sliderIdPrefix}track_thumb`); const fill = this._getShadowElementById(`${sliderIdPrefix}track_fill`); const maxHandlePos = slider.offsetWidth - thumb.offsetWidth; const max = sliderIdPrefix === 'volume_' ? 1 : this.duration; const value = this._getValueFromPosition(this._between(pos, 0, maxHandlePos), maxHandlePos, max); const newPos = this._getPositionFromValue(value, maxHandlePos, max); fill.style.width = `${newPos + this.grabX}px`; thumb.style.left = `${newPos}px`; if (sliderIdPrefix === 'volume_' && this.dragging.volume) { // dragging volume this._updateCurrentVolume(value); } if (sliderIdPrefix !== 'volume_' && this.dragging.track) { // dragging timeline this._updateCurrentTime(value); } } }