text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import AssetsPlugin from 'assets-webpack-plugin' import { version as cacheLoaderVersion } from 'cache-loader/package.json' import chalk from 'chalk' import CleanPlugin from 'clean-webpack-plugin' import CopyPlugin from 'copy-webpack-plugin' import TsCheckerPlugin from 'fork-ts-checker-webpack-plugin' import fse from 'fs-extra' import HtmlWebpackPlugin from 'html-webpack-plugin' import _, { pick } from 'lodash' import MiniCssExtractPlugin from 'mini-css-extract-plugin' import path from 'path' import { Configuration, DllReferencePlugin, EnvironmentPlugin, ProvidePlugin } from 'webpack' import * as constants from '../constants' import { BuildCliOptions, DevCliOptions, Props } from '../types' import { mergeWebpackConfig, globalStore, getModulePath, fetchFile, getDllHostDir, getDllManifestFile, } from '../utils' import * as amis from './amis' import { getBabelConfig } from './babel' import HtmlHooksPlugin from './plugins/html_hooks_plugin' import LogPlugin from './plugins/log_plugin' import MonacoWebpackPlugin from './plugins/monaco_editor_plugin' const { libVer, libName, generatedDirName, staticDirName, tsConfFileName, tsLintConfFileName, webpackConfFileName, dllVendorFileName, staticLibDirPath, esLintFileName, cssAssetsFile, dllFileKeys, srcDirName, stylesDirName, winConst, dllVer, } = constants type BaseConfigOptions = Props & Partial<DevCliOptions> & Partial<BuildCliOptions> export async function createBaseConfig(options: BaseConfigOptions): Promise<Configuration> { const { outDir, srcDir, genDir, siteDir, publicPath, env, bundleAnalyzer, mock, siteConfig, dll = true, scssUpdate = false, } = options const { envModes, ui, styledConfig, appKey } = siteConfig const { assetJson, manifestFile, hostDir: dllFilesHostDir, withCdnDll = false, } = await loadDllManifest(options) // "envModes" must contains "env" if (envModes && env && !envModes.includes(env)) { throw new Error( `env: "${env}" is not allowed. The "env" must be one of "envModes": ${envModes}.` ) } const isProd = globalStore('get', 'isProd') || false const cacheLoader = { loader: 'cache-loader', options: { cacheIdentifier: `cache-loader:${cacheLoaderVersion}`, }, } const babelLoader = { loader: 'babel-loader', options: getBabelConfig({ siteDir, styledConfig }), } const useTs = fse.existsSync(`${siteDir}/${tsConfFileName}`) const baseConfig = { mode: process.env.NODE_ENV, entry: getAppEntries({ siteDir, hot: options.hot }), output: { // Use future version of asset emitting logic, which allows freeing memory of assets after emitting. publicPath, futureEmitAssets: true, pathinfo: false, path: outDir, filename: isProd ? '[name]_[contenthash:6].js' : '[name].js', chunkFilename: isProd ? 'chunks/[name]_[contenthash:6].js' : 'chunks/[name].js', }, // throw warning when asset created is over 2.5 M performance: { // TODO: add to config maxEntrypointSize: 2500 * 1024, // 2.5 MB maxAssetSize: 2000 * 1024, // 2MB assetFilter: (filePath) => { // Filter genDir or theme files const isLibFiles = /static[\\/]ovine/.test(filePath) const isThemeStyles = /themes[\\/].*\.css/.test(filePath) return !isLibFiles && !isThemeStyles }, }, // Omit not necessary stats log stats: { chunkModules: false, assets: false, }, // Source map help for trick bugs devtool: bundleAnalyzer ? false : isProd ? 'nosources-source-map' : 'cheap-module-eval-source-map', resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'], symlinks: true, alias: { '~': srcDir, '@generated': genDir, '@core': '@ovine/core/lib', 'react-dom': '@hot-loader/react-dom', }, // This allows you to set a fallback for where Webpack should look for modules. modules: [ 'node_modules', path.resolve(__dirname, '../../node_modules'), path.resolve(fse.realpathSync(process.cwd()), 'node_modules'), ], }, optimization: { runtimeChunk: { // https://github.com/webpack/webpack/issues/7875 name: ({ name }) => `runtime_${name}`, }, removeAvailableModules: false, // Only minimize client bundle in production because server bundle is only used for static site generation minimize: isProd, splitChunks: { // Since the chunk name includes all origin chunk names it’s recommended for production builds with long term caching to NOT include [name] in the filenames automaticNameDelimiter: '_', minSize: 0, chunks: 'all', cacheGroups: { default: false, // disabled default configuration vendors: false, // disabled splitChunks vendors configuration ...siteConfig.cacheGroups, // append user cacheGroups config appVendor: { chunks: 'all', name: 'app_vendor', test: /[\\/]node_modules[\\/]/, priority: 20, minChunks: 1, reuseExistingChunk: true, }, appCommon: { chunks: 'all', test: /[\\/]src[\\/]((?!pages).*)/, name: 'app_common', priority: 19, minChunks: 2, reuseExistingChunk: true, }, pages: { chunks: 'async', test: /[\\/]src[\\/]pages[\\/]((?!preset).*)/, priority: 18, minChunks: 1, enforce: true, // test: (mod: any) => { // const isPages = /[\\/]src[\\/]pages[\\/]((?!preset).*)/.test(mod.context) // return isPages // }, // reuseExistingChunk: true, name: (mod: any) => { const resolvedPath = mod.context.match(/[\\/]src[\\/]pages[\\/](.*)$/) const commonName = 'pages_common' const { splitRoutes } = siteConfig let modPath = commonName // resolvedPath[1] is not with ".ext", value is `pages/${resolvedPath[1]}` if (resolvedPath && _.isArray(splitRoutes)) { splitRoutes.some(({ test, name }) => { if (!(test instanceof RegExp) || !name || !test.test(resolvedPath[1])) { return false } modPath = name // `p_${resolvedPath[1].replace(/[\\/]/g, '_')}` return true }) } return modPath }, }, }, }, }, module: { rules: [ !mock && { test: /[\\/]mock\.[t|j]sx?$/, use: 'null-loader', exclude: /node_modules/, }, { test: /\.jsx?$/, exclude: excludeJS, use: [cacheLoader, babelLoader], }, ...getFixLibLoaders({ dll, publicPath, babelLoader }), useTs && { test: /\.tsx?$/, exclude: excludeJS, use: [ cacheLoader, { loader: 'thread-loader' }, babelLoader, { loader: 'ts-loader', options: { happyPackMode: true, transpileOnly: true, }, }, ], }, { test: /\.css$/, use: (isProd ? [MiniCssExtractPlugin.loader] : [cacheLoader, 'style-loader']).concat([ 'css-loader', ]), exclude: scssUpdate ? undefined : /\.ovine[\\/]styles[\\/]themes/, }, !scssUpdate && { test: /\.ovine[\\/]styles[\\/]themes[\\/].*\.css$/, use: [ { loader: 'file-loader', options: { publicPath, limit: 1, // always use url, instate of base64 name: `${staticDirName}/${libName}/${stylesDirName}/themes/[name]_[contenthash:6].css`, }, }, require.resolve('./loaders/extract_loader'), 'css-loader', ], }, { test: /\.svg$/, // svg loader for tsx/jsx files issuer: /\.[t|j]sx$/, use: ['@svgr/webpack'], }, { test: /\.svg$/, // svg loader for ts/js/css styled files issuer: [/\.css$/, /\.[t|j]s$/], use: [ { loader: 'url-loader', options: { publicPath, limit: 2000, esModule: false, name: !isProd ? '[path][name].[ext]' : 'assets/svgs/[name]_[contenthash:6].[ext]', }, }, ], }, { test: new RegExp( `\\.${`(gif,png,jpg,ttf,ico,woff,woff2,eot${ !siteConfig.staticFileExts ? '' : `,${siteConfig.staticFileExts}` }`.replace(/,/gi, '|')})$` ), exclude: [/[\\/]qs[\\/]/], use: [ { loader: 'url-loader', options: { publicPath, limit: 2000, // less than 2kb files use base64 url name: !isProd ? '[path][name].[ext]' : (modulePath) => { const pathAr = modulePath .split('/') .filter((i) => i !== 'assets') .slice(-2) return `assets/${path.dirname(pathAr.join('/'))}/[name]_[contenthash:6].[ext]` }, }, }, ], }, ].filter(Boolean) as any[], }, plugins: [ new LogPlugin({ name: `${libName}-${isProd ? 'Build' : 'Dev'}`, }), new CleanPlugin(), !dll && new MonacoWebpackPlugin({ publicPath, }), getCopyPlugin(siteDir, outDir, { withCdnDll }), new EnvironmentPlugin({ PUBLIC_PATH: publicPath, NODE_ENV: process.env.NODE_ENV, APP_KEY: appKey, INIT_THEME: ui.appTheme || ui.defaultTheme, HOT: options.hot || false, MOCK: mock, ENV: env, }), new ProvidePlugin({ $: 'jquery', jQuery: 'jquery', }), useTs && new TsCheckerPlugin({ tsconfig: `${siteDir}/${tsConfFileName}`, eslint: fse.existsSync(`${siteDir}/${esLintFileName}`), eslintOptions: fse.existsSync(`${siteDir}/${esLintFileName}`) && require(`${siteDir}/${esLintFileName}`), tslint: !fse.existsSync(`${siteDir}/${tsLintConfFileName}`) ? undefined : `${siteDir}/${tsLintConfFileName}`, reportFiles: ['src/**/*.{ts,tsx}', 'typings/**/*.{ts,tsx}'], silent: true, }), dll && new DllReferencePlugin({ context: siteDir, manifest: manifestFile, }), new MiniCssExtractPlugin({ filename: isProd ? '[name]_[contenthash:6].css' : '[name].css', chunkFilename: isProd ? 'chunks/[name]_[contenthash:6].css' : 'chunks/[name].css', // remove css order warnings if css imports are not sorted alphabetically // see https://github.com/webpack-contrib/mini-css-extract-plugin/pull/422 for more reasoning ignoreOrder: true, }), !scssUpdate && new AssetsPlugin({ manifestFirst: true, keepInMemory: !isProd, includeAllFileTypes: false, fileTypes: ['css'], filename: cssAssetsFile.split('/')[1], fullPath: false, path: `${siteDir}/${cssAssetsFile.split('/')[0]}`, }), !scssUpdate && new HtmlHooksPlugin({ scssUpdate, isProd, indexHtml: `${outDir}/index.html`, getThemeTpl: (opts: any) => { const themeOpts = { publicPath, siteDir, appKey, defaultTheme: ui.defaultTheme, appTheme: ui.appTheme, ...opts, } return getThemeTpl(themeOpts) }, }), new HtmlWebpackPlugin({ ..._.pick(siteConfig.template, ['head', 'preBody', 'postBody']), isProd, libVer, publicPath, title: siteConfig.title, favIcon: siteConfig.favicon, // TODO: 将图标图片 拷贝到项目根目录! withIconfont: siteConfig.ui?.withIconfont, withoutPace: siteConfig.ui?.withoutPace, staticLibPath: `${publicPath}${staticLibDirPath}/`, template: siteConfig.template?.path || path.resolve(__dirname, './template.ejs'), filename: `${outDir}/index.html`, dllVendorCss: getDllDistFile(dllFilesHostDir, assetJson, dllVendorFileName, 'css'), dllVendorJs: dll && dllFileKeys .map((fileKey) => getDllDistFile(dllFilesHostDir, assetJson, fileKey, 'js')) .join(','), }), ].filter(Boolean) as any[], } const config = mergeWebpackConfig(baseConfig, `${siteDir}/${webpackConfFileName}`) return config } function excludeJS(modulePath: string) { // exclude fixed amis file const regs = ['editorFileReg', 'factoryFileReg', 'froalaEditorReg', 'chartFileReg', 'apiUtilReg'] if (Object.values(pick(amis, regs)).some((reg: any) => reg.test(modulePath))) { return true } // Don't transpile node_modules except any @ovine npm package const isNodeModules = /node_modules/.test(modulePath) const isLibModules = /node_modules[\\/]@ovine[\\/].*\.[j|t]sx?$/.test(modulePath) // if (/editor\.min\.js$/.test(modulePath)) { // console.log('@+++?', modulePath) // return true // } return isLibModules ? false : isNodeModules } function getAppEntries(option: any) { const { siteDir, hot } = option const entries: any[] = hot ? ['react-hot-loader/patch'] : [] const siteSrcDir = `${siteDir}/${srcDirName}/` const extArr = ['js', 'jsx', 'ts', 'tsx'] const getLibFile = (fileName: string) => getModulePath(siteDir, `lib/core/lib/app/${fileName}`, true) const isAutoEntry = extArr .map((ext) => `app.auto.${ext}`) .map((file) => fse.existsSync(`${siteSrcDir}${file}`)) .filter(Boolean).length === 1 // use app.config for entry if (isAutoEntry) { entries.push(getLibFile('entry_auto.js')) return entries } const isCustomEntry = extArr .map((ext) => `app.custom.${ext}`) .map((file) => fse.existsSync(`${siteSrcDir}${file}`)) .filter(Boolean).length === 1 // use app.custom for entry if (isCustomEntry) { entries.push(getLibFile('entry_custom.js')) return entries } // use app for entry -----> ovineCore would not anything. All give to developer! const appEntryExtIdx = extArr .map((ext) => `app.${ext}`) .map((file) => fse.existsSync(`${siteSrcDir}${file}`)) .findIndex((i) => i) if (appEntryExtIdx > -1) { entries.push(`${siteSrcDir}app.${extArr[appEntryExtIdx]}`) return entries } throw new Error('no app entry!! please add entry file.') } function getFixLibLoaders(option: any) { const { dll, babelLoader } = option const loaders = [ { test: amis.editorFileReg, use: [babelLoader, amis.fixEditorLoader()], }, { test: amis.factoryFileReg, use: [babelLoader, amis.fixFactoryLoader()], }, { test: amis.froalaEditorReg, use: [babelLoader, amis.fixFroalaLoader()], }, { test: amis.chartFileReg, use: [babelLoader, amis.fixChartLoader()], }, { test: amis.apiUtilReg, use: [babelLoader, amis.fixApiUtilLoader()], }, ] return dll ? [] : loaders } function getDllDistFile( dllFilesHostDir: string, assetJson: any, fileKey: string = dllVendorFileName, type: string = 'js' ) { return `${dllFilesHostDir}${_.get(assetJson, `${fileKey}.${type}`)}` } function getCopyPlugin(siteDir: string, outDir: string, option: { withCdnDll: boolean }) { const { withCdnDll } = option const generatedStaticDir = `${siteDir}/${generatedDirName}/${staticDirName}` const generatedStylesDir = `${siteDir}/${generatedDirName}/${stylesDirName}` const siteStaticDir = `${siteDir}/${staticDirName}` const outStaticDir = `${outDir}/${staticDirName}` const outLibDir = `${outDir}/${staticLibDirPath}` const copyFiles: any = [ { from: generatedStaticDir, to: outLibDir, ignore: withCdnDll ? ['dll/**/*'] : undefined, }, ] if (fse.pathExistsSync(siteStaticDir)) { copyFiles.unshift({ from: siteStaticDir, to: outStaticDir, }) } // copy static theme files if (fse.pathExistsSync(`${generatedStylesDir}/themes/cxd.css`)) { copyFiles.unshift({ from: generatedStylesDir, to: `${outLibDir}/${stylesDirName}`, }) } const coreStatic = getModulePath(siteDir, 'lib/core/static') if (coreStatic) { copyFiles.unshift({ from: coreStatic, to: `${outLibDir}/core`, }) } return new CopyPlugin(copyFiles) } function getThemeTpl(options: any) { const { siteDir, localFs, defaultTheme, publicPath, appTheme, appKey } = options const cssAssetsJson = JSON.parse(localFs.readFileSync(`${siteDir}/${cssAssetsFile}`, 'utf8')) const cssAssets = _.get(cssAssetsJson, '.css') || [] const tpl = { link: '', script: '', } if (!cssAssets || !cssAssets.map) { return tpl } const themesArr = cssAssets.filter((i) => /themes\/[a-z]*_\w{6}\.css/.test(i)) const themes = (themesArr.length ? themesArr : cssAssets.filter((i) => /themes\/.*\.css$/.test(i)) ).map((i) => `${publicPath}${i}`) if (!themes.length) { return tpl } const checkTheme = (t: string) => t && themes.some((theme) => theme.indexOf(t) > -1) const presetTheme = checkTheme(defaultTheme) ? defaultTheme : 'cxd' if (appTheme === 'false') { return tpl } const themeKey = `${appKey ? `${appKey}_` : ''}libAppThemeStore` if (checkTheme(appTheme)) { const link = themes.find((t) => t.indexOf(appTheme) > -1) tpl.link = `<link rel="stylesheet" href="${link}" />` tpl.script = `localStorage.setItem('${themeKey}', '"${appTheme}"');` return tpl } // TODO: 优化主题处理逻辑 tpl.script = ` (function() { var isLoad = false; var themes = "${themes}".split(','); var themeName = (localStorage.getItem('${themeKey}') || '').replace(/"/g, '') || '${presetTheme}'; var linkHref = themes.find(function(t){ return t.indexOf(themeName) > -1 }); var head = document.head || document.getElementsByTagName('head')[0]; var link = document.createElement('link'); head.appendChild(link); link.rel = 'stylesheet'; link.type = 'text/css'; link.dataset.theme = themeName; link.href= linkHref; var hideApp = function() { var $app = document.getElementById('app-root'); if ($app) { $app.style.display = 'none'; } }; var showApp = function() { isLoad = true; var $app = document.getElementById('app-root'); if ($app) { $app.style.display = 'block'; } }; setTimeout(function(){ if(!isLoad){ hideApp() } },50); link.onload = showApp; link.onerror = showApp; })(); ` return tpl } type ManifestInfo = { hostDir: string assetsFile: string manifestFile: string assetJson: any withCdnDll?: boolean } export async function loadDllManifest(options: Props & Partial<BuildCliOptions>) { const { siteDir } = options const [hostDir, backHostDir] = getDllHostDir(options.siteConfig) const files = getDllManifestFile(siteDir) const { assetsFile, manifestFile } = files const backFiles = { ...files, hostDir: backHostDir, } const cacheDir = `${siteDir}/${generatedDirName}/cache` const dllHostDirKey = 'DLL_HOST_DIR' const assetsFileName = path.basename(assetsFile) const manifestFileName = path.basename(manifestFile) const cacheAssetsFile = `${cacheDir}/${assetsFileName}` const cacheManifestFile = `${cacheDir}/${manifestFileName}` const cachedFiles = { hostDir, withCdnDll: true, assetsFile: cacheAssetsFile, manifestFile: cacheManifestFile, } function getManifest(filesData: any) { try { const assetJson = require(filesData.assetsFile) return { assetJson, hostDir, ...filesData, } } catch (err) { console.log(chalk.red(`\nload assetsFile: ${filesData.assetsFile} with error. \n`, err)) throw err } } const fetchManifest = async () => { // check cache files if exits if ([cacheAssetsFile, cacheManifestFile].every((filePath) => fse.existsSync(filePath))) { const assetJson = await fse.readJSON(cacheAssetsFile) // check the cache if valid if (assetJson[winConst.dllVersion] === dllVer && assetJson[dllHostDirKey] === hostDir) { // already cached return getManifest(cachedFiles) } } const httpAssetFile = `${hostDir}${assetsFileName}` const httpManifestFile = `${hostDir}${manifestFileName}` // download manifest files to cache await Promise.all( [httpAssetFile, httpManifestFile].map((httpFile) => { return fetchFile(httpFile).then((fileRes) => { if (fileRes.headers['content-type'].indexOf('application/json') === -1) { throw new Error(`apply ${httpFile} with error.`) } const cachePath = `${cacheDir}/${path.basename(httpFile)}` let jsonBody = fileRes.body if (httpFile === httpAssetFile) { const assetJson = JSON.parse(jsonBody) assetJson[dllHostDirKey] = hostDir jsonBody = JSON.stringify(assetJson) } fse.ensureFileSync(cachePath) fse.writeFileSync(cachePath, jsonBody, { encoding: 'utf-8', }) }) }) ) return getManifest(cachedFiles) } let manifestInfo: any = {} if (hostDir.startsWith('http') && hostDir !== backHostDir) { try { manifestInfo = await fetchManifest() } catch (err) { manifestInfo = getManifest(backFiles) // console.log(`load host dll manifest files.`, err) // print log when needed } } else { manifestInfo = getManifest(backFiles) } return manifestInfo as ManifestInfo }
the_stack
'use strict'; import { errors, SharedAccessSignature, ConnectionString, httpCallbackToPromise, encodeUriComponentStrict } from 'azure-iot-common'; import { RestApiClient } from 'azure-iot-http-base'; import { QuerySpecification, Query, QueryResult } from './query'; // tslint seems to think AttestationMechanism isn't used on the next import statement so disabling this warning. // tslint:disable-next-line:no-unused-variable import { IndividualEnrollment, EnrollmentGroup, DeviceRegistrationState, BulkEnrollmentOperation, BulkEnrollmentOperationResult, AttestationMechanism } from './interfaces'; import { ErrorCallback, errorCallbackToPromise, HttpResponseCallback, ResultWithHttpResponse } from 'azure-iot-common'; import { TokenCredential } from '@azure/core-http'; // tslint:disable-next-line:no-var-requires const packageJson = require('../package.json'); const ArgumentError = errors.ArgumentError; export class ProvisioningServiceClient { private readonly _enrollmentGroupsPrefix: string = '/enrollmentGroups/'; private readonly _enrollmentsPrefix: string = '/enrollments/'; private readonly _registrationsPrefix: string = '/registrations/'; private _restApiClient: RestApiClient; constructor(config: RestApiClient.TransportConfig, restApiClient?: RestApiClient) { if (!config) { /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_001: [The `ProvisioningServiceClient` construction shall throw a `ReferenceError` if the `config` object is falsy.] */ throw new ReferenceError('The \'config\' parameter cannot be \'' + config + '\''); } else if (!config.host) { throw new ArgumentError('The \'config\' argument is missing the host property'); } else if (!config.sharedAccessSignature && !config.tokenCredential) { throw new ArgumentError('The \'config\' argument must define either the sharedAccessSignature or tokenCredential property'); } else if (config.tokenCredential && !config.tokenScope) { throw new ArgumentError('The \'config\' argument must define the tokenScope property if it defines the tokenCredential property'); } /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_003: [The `ProvisioningServiceClient` constructor shall use the `restApiClient` provided as a second argument if it is provided.] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_004: [The `ProvisioningServiceClient` constructor shall use `azure-iot-http-base.RestApiClient` if no `restApiClient` argument is provided.] */ this._restApiClient = restApiClient || new RestApiClient(config, packageJson.name + '/' + packageJson.version); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#createOrUpdateIndividualEnrollment * @description Create or update a device enrollment record. * @param {object} enrollment The device enrollment record. * @param {function} [callback] Invoked upon completion of the operation. * @returns {Promise<ResultWithHttpResponse<IndividualEnrollment>> | void} Promise if no callback function was passed, void otherwise. */ public createOrUpdateIndividualEnrollment(enrollment: IndividualEnrollment, callback: HttpResponseCallback<IndividualEnrollment>): void; public createOrUpdateIndividualEnrollment(enrollment: IndividualEnrollment): Promise<ResultWithHttpResponse<IndividualEnrollment>>; public createOrUpdateIndividualEnrollment(enrollment: IndividualEnrollment, callback?: HttpResponseCallback<IndividualEnrollment>): Promise<ResultWithHttpResponse<IndividualEnrollment>> | void { return httpCallbackToPromise((_callback) => { this._createOrUpdate(this._enrollmentsPrefix, enrollment, _callback); }, callback); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#deleteIndividualEnrollment * @description Delete a device enrollment record. * @param {string | object} enrollmentOrId An IndividualEnrollment object or a string containing the registration id. * @param {string | function} etagOrCallback In the case of the first argument being a string this could be an etag (or the callback). * @param {function} [deleteCallback] Invoked upon completion of the operation. * @returns {Promise<void> | void} Promise if no callback function was passed, void otherwise. */ public deleteIndividualEnrollment(enrollmentOrId: string | IndividualEnrollment, etag: string, deleteCallback: ErrorCallback): void; public deleteIndividualEnrollment(enrollmentOrId: string | IndividualEnrollment, deleteCallback: ErrorCallback): void; public deleteIndividualEnrollment(enrollmentOrId: string | IndividualEnrollment, etag: string): Promise<void>; public deleteIndividualEnrollment(enrollmentOrId: string | IndividualEnrollment): Promise<void>; public deleteIndividualEnrollment(enrollmentOrId: string | IndividualEnrollment, etagOrCallback?: string | ErrorCallback, deleteCallback?: ErrorCallback): Promise<void> | void { if (deleteCallback && !(typeof deleteCallback === 'function')) { throw new ArgumentError('Callback has to be a Function'); } if (!deleteCallback && (typeof etagOrCallback === 'function')) { deleteCallback = etagOrCallback as ErrorCallback; etagOrCallback = undefined; } return errorCallbackToPromise((_callback) => { this._delete(this._enrollmentsPrefix, enrollmentOrId, etagOrCallback, _callback); }, deleteCallback); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#getIndividualEnrollment * @description Get a device enrollment record. * @param {string} id Registration ID. * @param {function} [getCallback] Invoked upon completion of the operation. * @returns {Promise<ResultWithHttpResponse<IndividualEnrollment>> | void} Promise if no callback function was passed, void otherwise. */ public getIndividualEnrollment(id: string, getCallback: HttpResponseCallback<IndividualEnrollment>): void; public getIndividualEnrollment(id: string): Promise<ResultWithHttpResponse<IndividualEnrollment>>; public getIndividualEnrollment(id: string, getCallback?: HttpResponseCallback<IndividualEnrollment>): Promise<ResultWithHttpResponse<IndividualEnrollment>> | void { return httpCallbackToPromise((_callback) => { this._get(this._enrollmentsPrefix, id, _callback); }, getCallback); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#createIndividualEnrollmentQuery * @description Creates a query that can be used to return pages of existing enrollments. * @param {object} querySpecification The query specification. * @param {number} pageSize The maximum number of elements to return per page. */ createIndividualEnrollmentQuery(querySpecification: QuerySpecification, pageSize?: number): Query { return new Query(this._getEnrollFunc(this._enrollmentsPrefix, querySpecification, pageSize)); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#getDeviceRegistrationState * @description Gets the device registration status. * @param {string} id Registration ID. * @param {function} [callback] Invoked upon completion of the operation. * @returns {Promise<ResultWithHttpResponse<DeviceRegistrationState>> | void} Promise if no callback function was passed, void otherwise. */ public getDeviceRegistrationState(id: string, callback: HttpResponseCallback<DeviceRegistrationState>): void; public getDeviceRegistrationState(id: string): Promise<ResultWithHttpResponse<DeviceRegistrationState>>; public getDeviceRegistrationState(id: string, callback?: HttpResponseCallback<DeviceRegistrationState>): Promise<ResultWithHttpResponse<DeviceRegistrationState>> | void { return httpCallbackToPromise((_callback) => { this._get(this._registrationsPrefix, id, _callback); }, callback); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#createOrUpdateEnrollmentGroup * @description Create or update a device enrollment group. * @param {object} enrollmentGroup The device enrollment group. * @param {function} [callback] Invoked upon completion of the operation. * @returns {Promise<ResultWithHttpResponse<DeviceRegistrationState>> | void} Promise if no callback function was passed, void otherwise. */ public createOrUpdateEnrollmentGroup(enrollmentGroup: EnrollmentGroup, callback: HttpResponseCallback<EnrollmentGroup>): void; public createOrUpdateEnrollmentGroup(enrollmentGroup: EnrollmentGroup): Promise<ResultWithHttpResponse<EnrollmentGroup>>; public createOrUpdateEnrollmentGroup(enrollmentGroup: EnrollmentGroup, callback?: HttpResponseCallback<EnrollmentGroup>): Promise<ResultWithHttpResponse<EnrollmentGroup>> | void { return httpCallbackToPromise((_callback) => { this._createOrUpdate(this._enrollmentGroupsPrefix, enrollmentGroup, _callback); }, callback); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#deleteEnrollmentGroup * @description Delete a device enrollment group. * @param {object | string} enrollmentGroupOrId EnrollmentGroup object or a string containing the enrollment Group Id. * @param {string | function} [etagOrCallback] In the case of the first argument being a string this could be an etag (or the callback). * @param {function} [deleteCallback] Invoked upon completion of the operation. * @returns {Promise<void> | void} Promise if no callback function was passed, void otherwise. */ public deleteEnrollmentGroup(enrollmentGroupOrId: string | EnrollmentGroup, etag: string, deleteCallback: ErrorCallback): void; public deleteEnrollmentGroup(enrollmentGroupOrId: string | EnrollmentGroup, deleteCallback: ErrorCallback): void; public deleteEnrollmentGroup(enrollmentGroupOrId: string | EnrollmentGroup, etag: string): Promise<void>; public deleteEnrollmentGroup(enrollmentGroupOrId: string | EnrollmentGroup): Promise<void>; public deleteEnrollmentGroup(enrollmentGroupOrId: string | EnrollmentGroup, etagOrCallback?: string | ErrorCallback, deleteCallback?: ErrorCallback): Promise<void> | void { if (deleteCallback && !(typeof deleteCallback === 'function')) { throw new ArgumentError('Callback has to be a Function'); } if (typeof etagOrCallback === 'function') { deleteCallback = etagOrCallback as ErrorCallback; etagOrCallback = undefined; } return errorCallbackToPromise((_callback) => { this._delete(this._enrollmentGroupsPrefix, enrollmentGroupOrId, etagOrCallback, _callback); }, deleteCallback); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#getEnrollmentGroup * @description Get a device enrollment group. * @param {string} id IndividualEnrollment group ID. * @param {function} [getCallback] Invoked upon completion of the operation. * @returns {ResultWithHttpResponse<EnrollmentGroup> | void} Promise if no callback function was passed, void otherwise. */ public getEnrollmentGroup(id: string, getCallback: HttpResponseCallback<EnrollmentGroup>): void; public getEnrollmentGroup(id: string): Promise<ResultWithHttpResponse<EnrollmentGroup>>; public getEnrollmentGroup(id: string, getCallback?: HttpResponseCallback<EnrollmentGroup>): Promise<ResultWithHttpResponse<EnrollmentGroup>> | void { return httpCallbackToPromise((_callback) => { this._get(this._enrollmentGroupsPrefix, id, _callback); }, getCallback); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#createEnrollmentGroupQuery * @description Creates a query that can be used to return pages of existing enrollment groups. * @param {object} querySpecification The query specification. * @param {number} pageSize The maximum number of elements to return per page. */ createEnrollmentGroupQuery(querySpecification: QuerySpecification, pageSize?: number): Query { return new Query(this._getEnrollFunc(this._enrollmentGroupsPrefix, querySpecification, pageSize)); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#createEnrollmentGroupDeviceRegistrationStateQuery * @description Creates a query that can be used to return, for a specific EnrollmentGroup, pages of existing device registration status. * @param {object} querySpecification The query specification. * @param {string} enrollmentGroupId The EnrollmentGroup id that provides the scope for the query. * @param {number} pageSize The maximum number of elements to return per page. */ createEnrollmentGroupDeviceRegistrationStateQuery(querySpecification: QuerySpecification, enrollmentGroupId: string, pageSize?: number): Query { if (!enrollmentGroupId) { throw new ReferenceError('Required enrollmentGroupId parameter was falsy.'); } return new Query(this._getEnrollFunc(this._registrationsPrefix + encodeURIComponent(enrollmentGroupId) + '/', querySpecification, pageSize)); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#runBulkEnrollmentOperation * @description Runs a number CRUD operations on an array of enrollment records. * @param {object} bulkEnrollmentOperation An object that specifies the single kind of CRUD operations on the array of IndividualEnrollment objects that are also part of the object. * @param {function} callback Invoked upon completion of the operation. */ public runBulkEnrollmentOperation(bulkEnrollmentOperation: BulkEnrollmentOperation, callback: HttpResponseCallback<BulkEnrollmentOperationResult>): void; public runBulkEnrollmentOperation(bulkEnrollmentOperation: BulkEnrollmentOperation): Promise<ResultWithHttpResponse<BulkEnrollmentOperationResult>>; public runBulkEnrollmentOperation(bulkEnrollmentOperation: BulkEnrollmentOperation, callback?: HttpResponseCallback<BulkEnrollmentOperationResult>): Promise<ResultWithHttpResponse<BulkEnrollmentOperationResult>> | void { return httpCallbackToPromise((_callback) => { /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_038: [The `runBulkEnrollmentOperation` method shall throw `ReferenceError` if the `bulkEnrollmentOperation` argument is falsy.] */ if (!bulkEnrollmentOperation) { throw new ReferenceError('Required bulkEnrollmentOperation parameter was falsy when calling runBulkEnrollmentOperation.'); } const path = this._enrollmentsPrefix + this._versionQueryString(); const httpHeaders = { 'Accept': 'application/json', 'Content-Type': 'application/json; charset=utf-8' }; /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_039: [** The `runBulkEnrollmentOperation` method shall construct an HTTP request using information supplied by the caller as follows: POST /enrollments?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> Accept: application/json Content-Type: application/json; charset=utf-8 <stringified json string of the bulkEnrollmentOperation argument> ] */ this._restApiClient.executeApiCall('POST', path, httpHeaders, bulkEnrollmentOperation, (err, bulkEnrollmentOperationResult, httpResponse) => { if (callback) { if (err) { _callback(err); } else { _callback(null, bulkEnrollmentOperationResult, httpResponse); } } }); }, callback); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#deleteDeviceRegistrationState * @description Delete a device registration status. * @param {object | string} idOrRegistrationState A string containing the registration id OR an actual DeviceRegistrationState. * @param {string | function} etagOrCallback In the case of the first argument being a string this could be an etag (or the callback). * @param {function} [deleteCallback] Invoked upon completion of the operation. * @returns {Promise<void> | void} Promise if no callback function was passed, void otherwise. */ public deleteDeviceRegistrationState(idOrRegistrationState: string | DeviceRegistrationState, etag: string, deleteCallback: ErrorCallback): void; public deleteDeviceRegistrationState(idOrRegistrationState: string | DeviceRegistrationState, deleteCallback: ErrorCallback): void; public deleteDeviceRegistrationState(idOrRegistrationState: string | DeviceRegistrationState, etag: string): Promise<void>; public deleteDeviceRegistrationState(idOrRegistrationState: string | DeviceRegistrationState): Promise<void>; public deleteDeviceRegistrationState(idOrRegistrationState: string | DeviceRegistrationState, etagOrCallback?: string | ErrorCallback, deleteCallback?: ErrorCallback): Promise<void> | void { if (deleteCallback && !(typeof deleteCallback === 'function')) { throw new ArgumentError('Callback has to be a Function'); } if (typeof etagOrCallback === 'function') { deleteCallback = etagOrCallback as ErrorCallback; etagOrCallback = undefined; } return errorCallbackToPromise((_callback) => { this._delete(this._registrationsPrefix, idOrRegistrationState, etagOrCallback, _callback); }, deleteCallback); } /** * Gets the attestation mechanism for an IndividualEnrollment record. * @param enrollementId Unique identifier of the enrollment. * @param callback Function called when the request is completed, either with an error or with an AttestationMechanism object. * @returns {Promise<ResultWithHttpResponse<AttestationMechanism>> | void} Promise if no callback function was passed, void otherwise. */ public getIndividualEnrollmentAttestationMechanism(enrollementId: string, callback: HttpResponseCallback<AttestationMechanism>): void; public getIndividualEnrollmentAttestationMechanism(enrollementId: string): Promise<ResultWithHttpResponse<AttestationMechanism>>; public getIndividualEnrollmentAttestationMechanism(enrollementId: string, callback?: HttpResponseCallback<AttestationMechanism>): Promise<ResultWithHttpResponse<AttestationMechanism>> | void { /*SRS_NODE_PROVISIONING_SERVICE_CLIENT_16_001: [The `getIndividualEnrollmentAttestationMechanism` method shall throw a `ReferenceError` if the `enrollmentId` parameter is falsy.]*/ if (!enrollementId) { throw new ReferenceError('enrollmentId cannot be \'' + enrollementId + '\''); } /*SRS_NODE_PROVISIONING_SERVICE_CLIENT_16_002: [The `getIndividualEnrollmentAttestationMechanism` shall construct an HTTP request using information supplied by the caller as follows: ``` POST /enrollments/<encodeUriComponentStrict(enrollmentId)>/attestationmechanism?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> ```]*/ const path = '/enrollments/' + encodeUriComponentStrict(enrollementId) + '/attestationmechanism' + this._versionQueryString(); const headers = {}; return httpCallbackToPromise((_callback) => { // for some reason we have to specify types in this callback to avoid the typescript compiler complaining about not using AttestationMechanism (even if it's in the method signature) this._restApiClient.executeApiCall('POST', path, headers, undefined, _callback); }, callback); } /** * Gets the attestation mechanism for an EnrollmentGroup record. * @param enrollementGroupId Unique identifier of the EnrollmentGroup. * @param callback Function called when the request is completed, either with an error or with an AttestationMechanism object. * @returns {Promise<ResultWithHttpResponse<AttestationMechanism>> | void} Promise if no callback function was passed, void otherwise. */ public getEnrollmentGroupAttestationMechanism(enrollmentGroupId: string, callback: HttpResponseCallback<AttestationMechanism>): void; public getEnrollmentGroupAttestationMechanism(enrollmentGroupId: string): Promise<ResultWithHttpResponse<AttestationMechanism>>; public getEnrollmentGroupAttestationMechanism(enrollmentGroupId: string, callback?: HttpResponseCallback<AttestationMechanism>): Promise<ResultWithHttpResponse<AttestationMechanism>> | void { /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_16_003: [The `getEnrollmentGroupAttestationMechanism` method shall throw a `ReferenceError` if the `enrollementGroupId` parameter is falsy.]*/ if (!enrollmentGroupId) { throw new ReferenceError('enrollmentGroupId cannot be \'' + enrollmentGroupId + '\''); } /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_16_004: [The `getEnrollmentGroupAttestationMechanism` shall construct an HTTP request using information supplied by the caller as follows: ``` POST /enrollmentgroups/<encodeUriComponentStrict(enrollmentGroupId)>/attestationmechanism?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> ```]*/ const path = '/enrollmentgroups/' + encodeUriComponentStrict(enrollmentGroupId) + '/attestationmechanism' + this._versionQueryString(); const headers = {}; return httpCallbackToPromise((_callback) => { // for some reason we have to specify types in this callback to avoid the typescript compiler complaining about not using AttestationMechanism (even if it's in the method signature) this._restApiClient.executeApiCall('POST', path, headers, undefined, _callback); }, callback); } private _getEnrollFunc(prefix: string, querySpecification: QuerySpecification, pageSize: number): (continuationToken: string, done: HttpResponseCallback<QueryResult>) => void { return (continuationToken, done) => { const path = prefix + 'query' + this._versionQueryString(); let headers = { 'Accept': 'application/json', 'Content-Type': 'application/json; charset=utf-8' }; if (continuationToken) { headers['x-ms-continuation'] = continuationToken; } if (pageSize) { headers['x-ms-max-item-count'] = pageSize; } this._restApiClient.executeApiCall('POST', path, headers, querySpecification, done); }; } private _versionQueryString(): string { return '?api-version=2021-10-01'; } private _createOrUpdate(endpointPrefix: string, enrollment: any, callback?: (err: Error, enrollmentResponse?: any, response?: any) => void): void { /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_009: [The `createOrUpdateIndividualEnrollment` method shall throw `ReferenceError` if the `IndividualEnrollment` argument is falsy.]*/ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_012: [The `createOrUpdateEnrollmentGroup` method shall throw `ReferenceError` if the `EnrollmentGroup` argument is falsy.] */ if (!enrollment) { throw new ReferenceError('Required parameter enrollment was null or undefined when calling createOrUpdate.'); } let id: string; if (endpointPrefix === this._enrollmentGroupsPrefix) { id = enrollment.enrollmentGroupId; } else { id = enrollment.registrationId; } /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_011: [The `createOrUpdateIndividualEnrollment` method shall throw `ArgumentError` if the `enrollment.registrationId` property is falsy.] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_013: [`createOrUpdateEnrollmentGroup` method shall throw `ArgumentError` if the `enrollmentGroup.enrollmentGroupsId` property is falsy.] */ if (!id) { throw new ArgumentError('Required id property was null or undefined when calling createOrUpdate.'); } const path = endpointPrefix + encodeURIComponent(id) + this._versionQueryString(); const httpHeaders = { 'Accept': 'application/json', 'Content-Type': 'application/json; charset=utf-8' }; /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_055: [If the `enrollmentGroup` object contains an `etag` property it will be added as the value of the `If-Match` header of the http request.] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_056: [If the `enrollment` object contains an `etag` property it will be added as the value of the `If-Match` header of the http request.] */ if (enrollment.etag) { httpHeaders['If-Match'] = enrollment.etag; } /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_010: [The `createOrUpdateIndividualEnrollment` method shall construct an HTTP request using information supplied by the caller, as follows: PUT /enrollments/<uri-encoded-enrollment.registrationId>?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> Accept: application/json Content-Type: application/json; charset=utf-8 <stringified json string of the enrollment argument>]*/ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_014: [The `createOrUpdateEnrollmentGroup` method shall construct an HTTP request using information supplied by the caller, as follows: PUT /enrollmentGroups/<uri-encoded-enrollmentGroup.enrollmentGroupsId>?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> Accept: application/json Content-Type: application/json; charset=utf-8 <stringified json string of the enrollmentGroup argument> ] */ this._restApiClient.executeApiCall('PUT', path, httpHeaders, enrollment, (err, enrollmentResponse, httpResponse) => { if (callback) { if (err) { callback(err); } else { callback(null, enrollmentResponse, httpResponse); } } }); } private _delete(endpointPrefix: string, enrollmentOrIdOrRegistration: string | any, etagOrCallback?: string | ErrorCallback, deleteCallback?: ErrorCallback): void { let ifMatch: string; let suppliedCallback: ErrorCallback | undefined; let id: string; suppliedCallback = deleteCallback || ((typeof etagOrCallback === 'function') ? etagOrCallback as ErrorCallback : undefined); if (!suppliedCallback) { throw new ArgumentError('No callback was passed.'); } /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_015: [The `deleteIndividualEnrollment` method shall throw `ReferenceError` if the `enrollmentOrId` argument is falsy.] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_016: [The `deleteEnrollmentGroup` method shall throw `ReferenceError` if the `enrollmentGroupOrId` argument is falsy.] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_025: [The `deleteDeviceRegistrationState` method shall throw `ReferenceError` if the `idOrRegistrationState` argument is falsy.] */ if (!enrollmentOrIdOrRegistration) { throw new ReferenceError('Required parameter \'' + enrollmentOrIdOrRegistration + '\' was null or undefined when calling delete.'); } if (typeof enrollmentOrIdOrRegistration === 'string') { id = enrollmentOrIdOrRegistration; /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_040: [The `deleteIndividualEnrollment` method, if the first argument is a string, the second argument if present, must be a string or a callback, otherwise shall throw `ArgumentError`. .] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_045: [The `deleteEnrollmentGroup` method, if the first argument is a string, the second argument if present, must be a string or a callback, otherwise shall throw `ArgumentError`.] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_050: [The `deleteDeviceRegistrationState` method, if the first argument is a string, the second argument if present, must be a string or a callback, otherwise shall throw `ArgumentError`.] */ if (!etagOrCallback) { ifMatch = undefined; } else if (typeof etagOrCallback === 'string') { /*Codes_**SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_044: [** The `deleteIndividualEnrollment` method, if the first argument is a string, and the second argument is a string, shall construct an HTTP request using information supplied by the caller as follows: DELETE /enrollments/<uri-encoded-enrollmentOrId>?api-version=<version> HTTP/1.1 If-Match: <second argument> Authorization: <sharedAccessSignature> */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_049: [** The `deleteEnrollmentGroup` method, if the first argument is a string, and the second argument is a string, shall construct an HTTP request using information supplied by the caller as follows: DELETE /enrollmentGroups/<uri-encoded-enrollmentGroupOrId>?api-version=<version> HTTP/1.1 If-Match: <second argument> Authorization: <sharedAccessSignature> ] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_054: [** The `deleteDeviceRegistrationState` method, if the first argument is a string, and the second argument is a string, shall construct an HTTP request using information supplied by the caller as follows: DELETE /registrations/<uri-encoded-idOrRegistrationState>?api-version=<version> HTTP/1.1 If-Match: <second argument> Authorization: <sharedAccessSignature> ] */ ifMatch = etagOrCallback; } else if (typeof etagOrCallback === 'function') { /*Codes_**SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_043: [** The `deleteIndividualEnrollment` method, if the first argument is a string, and the second argument is NOT a string, shall construct an HTTP request using information supplied by the caller as follows: DELETE /enrollments/<uri-encoded-enrollmentOrId>?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_048: [** The `deleteEnrollmentGroup` method, if the first argument is a string, and the second argument is NOT a string, shall construct an HTTP request using information supplied by the caller as follows: DELETE /enrollmentGroups/<uri-encoded-enrollmentGroupOrId>?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> ] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_053: [** The `deleteDeviceRegistrationState` method, if the first argument is a string, and the second argument is NOT a string, shall construct an HTTP request using information supplied by the caller as follows: DELETE /registrations/<uri-encoded-idOrRegistrationState>?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> ] */ ifMatch = undefined; suppliedCallback = etagOrCallback; } else { throw new ArgumentError('Second argument of this delete method must be a string or function.'); } } else { if (endpointPrefix === this._enrollmentsPrefix) { if (!enrollmentOrIdOrRegistration.registrationId) { /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_017: [The `deleteIndividualEnrollment` method, if the first argument is an `IndividualEnrollment` object, shall throw an `ArgumentError`, if the `registrationId` property is falsy.] */ throw new ArgumentError('Required property \'registrationId\' was null or undefined when calling delete.'); } id = enrollmentOrIdOrRegistration.registrationId; } else if (endpointPrefix === this._enrollmentGroupsPrefix) { if (!enrollmentOrIdOrRegistration.enrollmentGroupId) { /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_018: [The `deleteEnrollmentGroup` method, if the first argument is an `EnrollmentGroup` object, shall throw an `ArgumentError`, if the `enrollmentGroupId' property is falsy.] */ throw new ArgumentError('Required property \'enrollmentGroupId\' was null or undefined when calling delete.'); } id = enrollmentOrIdOrRegistration.enrollmentGroupId; } else if (endpointPrefix === this._registrationsPrefix) { if (!enrollmentOrIdOrRegistration.registrationId) { /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_026: [The `deleteDeviceRegistrationState` method, if the first argument is a `DeviceRegistrationState` object, shall throw an `ArgumentError`, if the `registrationId' property is falsy.] */ throw new ArgumentError('Required property \'registrationId\' was null or undefined when calling delete.'); } id = enrollmentOrIdOrRegistration.registrationId; } else { throw new ArgumentError('Invalid path specified for delete operation.'); } if (enrollmentOrIdOrRegistration.etag) { /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_021: [The `deleteIndividualEnrollment` method, if the first argument is an `IndividualEnrollment` object, with a non-falsy `etag` property, shall construct an HTTP request using information supplied by the caller as follows: DELETE /enrollments/<uri-encoded-enrollmentOrIdOrRegistration.registrationId>?api-version=<version> HTTP/1.1 If-Match: enrollmentOrIdOrRegistration.etag Authorization: <sharedAccessSignature> ] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_022: [The `deleteEnrollmentGroup` method, if the first argument is an `EnrollmentGroup` object, with a non-falsy `etag` property, shall construct an HTTP request using information supplied by the caller as follows: DELETE /enrollmentGroups/<uri-encoded-enrollmentGroupOrId.enrollmentGroupId>?api-version=<version> HTTP/1.1 If-Match: enrollmentParameter.etag Authorization: <sharedAccessSignature> ] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_028: [** The `deleteDeviceRegistrationState` method, if the first argument is a `DeviceRegistrationState` object, with a non-falsy `etag` property, shall construct an HTTP request using information supplied by the caller as follows: DELETE /registrations/<uri-encoded-idOrRegistrationState.registrationId>?api-version=<version> HTTP/1.1 If-Match: idOrRegistrationState.etag Authorization: <sharedAccessSignature> ] */ ifMatch = enrollmentOrIdOrRegistration.etag; } else { /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_023: [The `deleteEnrollmentGroup` method, if the first argument is an `EnrollmentGroup` object, with a falsy `etag` property, shall construct an HTTP request using information supplied by the caller as follows: DELETE /enrollmentGroups/<uri-encoded-enrollmentGroupOrId.enrollmentGroupId>?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> ] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_024: [The `deleteIndividualEnrollment` method, if the first argument is an `enrollment` object, with a falsy `etag` property, shall construct an HTTP request using information supplied by the caller as follows: DELETE /enrollments/<uri-encoded-enrollmentParameter.registrationId>?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> ] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_029: [** The `deleteDeviceRegistrationState` method, if the first argument is a `DeviceRegistrationState` object, with a falsy `etag` property, shall construct an HTTP request using information supplied by the caller as follows: DELETE /registrations/<uri-encoded-idOrRegistrationState.registrationId>?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> ] */ ifMatch = undefined; } } const path = endpointPrefix + encodeURIComponent(id) + this._versionQueryString(); let httpHeaders = {}; if (ifMatch) { httpHeaders['If-Match'] = ifMatch; } this._restApiClient.executeApiCall('DELETE', path, httpHeaders, null, (err) => { if (suppliedCallback) { if (err) { suppliedCallback(err); } else { suppliedCallback(null); } } }); } private _get(endpointPrefix: string, id: string, getCallback: HttpResponseCallback<DeviceRegistrationState> | HttpResponseCallback<IndividualEnrollment> | HttpResponseCallback<EnrollmentGroup>): void { /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_030: [The `getIndividualEnrollment` method shall throw `ReferenceError` if the `id` argument is falsy.] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_031: [The `getEnrollmentGroup` method shall throw `ReferenceError` if the `id` argument is falsy.] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_032: [The `getDeviceRegistrationState` method shall throw `ReferenceError` if the `id` argument is falsy.] */ if (!id) { throw new ReferenceError('Required parameter \'' + id + '\' was null or undefined when calling get.'); } const path = endpointPrefix + encodeURIComponent(id) + this._versionQueryString(); const httpHeaders = { 'Accept': 'application/json' }; /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_033: [** The `getIndividualEnrollment` method shall construct an HTTP request using information supplied by the caller as follows: GET /enrollments/<uri-encoded-id>?api-version=<version> HTTP/1.1 Accept: application/json Authorization: <sharedAccessSignature> ] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_034: [** The `getEnrollmentGroup` method shall construct an HTTP request using information supplied by the caller as follows: GET /enrollmentGroups/<uri-encoded-id>?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> ] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_035: [** The `getDeviceRegistrationState` method shall construct an HTTP request using information supplied by the caller as follows: GET /registrations/<uri-encoded-id>?api-version=<version> HTTP/1.1 Authorization: <sharedAccessSignature> ] */ this._restApiClient.executeApiCall('GET', path, httpHeaders, null, (err?: Error, enrollmentOrRegistrationState?: DeviceRegistrationState | IndividualEnrollment | EnrollmentGroup, httpResponse?: any) => { const callback = (getCallback as HttpResponseCallback<DeviceRegistrationState | IndividualEnrollment | EnrollmentGroup>); if (err) { callback(err); } else { callback(null, enrollmentOrRegistrationState, httpResponse); } }); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#fromConnectionString * @description Constructs a ProvisioningServiceClient object from the given connection * string using the default transport * ({@link module:azure-iothub.Http|Http}). * @param {String} value A connection string which encapsulates the * appropriate (read and/or write) ProvisioningServiceClient * permissions. * @returns {module:azure-iot-provisioning-service.ProvisioningServiceClient} */ static fromConnectionString(value: string): ProvisioningServiceClient { /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_005: [The `fromConnectionString` method shall throw `ReferenceError` if the `value` argument is falsy.]*/ if (!value) throw new ReferenceError('value is \'' + value + '\''); const cn = ConnectionString.parse(value); const config: RestApiClient.TransportConfig = { host: cn.HostName, sharedAccessSignature: SharedAccessSignature.create(cn.HostName, cn.SharedAccessKeyName, cn.SharedAccessKey, Date.now()), tokenCredential: undefined }; /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_006: [`fromConnectionString` method shall derive and transform the needed parts from the connection string in order to create a `config` object for the constructor (see `SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_002`).] */ /*Codes_SRS_NODE_PROVISIONING_SERVICE_CLIENT_06_007: [The `fromConnectionString` method shall return a new instance of the `ProvisioningServiceClient` object.] */ return new ProvisioningServiceClient(config); } /** * @method module:azure-iot-provisioning-service.ProvisioningServiceClient#fromTokenCredential * @description Constructs a ProvisioningServiceClient object from the given Azure TokenCredential * using the default transport * ({@link module:azure-iothub.Http|Http}). * @param {String} hostName Host name of the Azure service. * @param {String} tokenCredential An Azure TokenCredential used to authenticate * with the Azure service * @returns {module:azure-iot-provisioning-service.ProvisioningServiceClient} */ static fromTokenCredential(hostName: string, tokenCredential: TokenCredential): ProvisioningServiceClient { const config: RestApiClient.TransportConfig = { host: hostName, tokenCredential, tokenScope: 'https://azure-devices-provisioning.net/.default' }; return new ProvisioningServiceClient(config); } } export type _tsLintWorkaround = { query: QueryResult, results: BulkEnrollmentOperationResult };
the_stack
import { inspect } from "util"; import ono, { Ono } from "../../esm"; class EmptyClass {} class CustomClass { // eslint-disable-next-line @typescript-eslint/no-parameter-properties public constructor(public code: number, public message: string) {} } class CustomErrorClass extends Error { // eslint-disable-next-line @typescript-eslint/no-parameter-properties public constructor(public isValid: boolean) { super("Onoes!"); } } const err = new Error(); const errPOJO = { message: "this is an error message" }; const emptyClass = new EmptyClass(); const customClass = new CustomClass(404, "ENOTFOUND"); const customError = new CustomErrorClass(false); const props = { id: "NOT_FOUND", statusCode: 404 }; const message = "This message has parameters: %s %s"; const param1 = "foo"; const param2 = "bar"; export function testExtendedProperties() { let error = ono({ foo: 123, bar: true }); // Error props error.name = "string"; error.message = "string"; error.stack = "string"; // OnoError props error.toJSON(); error[inspect.custom](); // Extended props error.foo = 123; error.bar = true; error.toJSON().foo = 123; error.toJSON().bar = true; error[inspect.custom]().foo = 123; error[inspect.custom]().bar = true; } export function testExtendedPropertiesWithOriginalError() { let error = ono(customError, { foo: 123, bar: true }); // Error props error.name = "string"; error.message = "string"; error.stack = "string"; // customError props error.isValid = true; // OnoError props error.toJSON(); error[inspect.custom](); // Extended props error.foo = 123; error.bar = true; error.toJSON().foo = 123; error.toJSON().bar = true; error[inspect.custom]().foo = 123; error[inspect.custom]().bar = true; } export function testExtendedPropertiesWithCustomOno() { let customOno = new Ono(CustomErrorClass); let error = customOno({ foo: 123, bar: true }); // Error props error.name = "string"; error.message = "string"; error.stack = "string"; // CustomErrorClass props error.isValid = true; // OnoError props error.toJSON(); error[inspect.custom](); // Extended props error.foo = 123; error.bar = true; error.toJSON().foo = 123; error.toJSON().bar = true; error[inspect.custom]().foo = 123; error[inspect.custom]().bar = true; } export function testOnoConstructorWithoutNew() { // eslint-disable-next-line new-cap let customOno = Ono(CustomErrorClass); let error = customOno(message, param1, param2); // Error props error.name = "string"; error.message = "string"; error.stack = "string"; // OnoError props error.toJSON(); error[inspect.custom](); // CustomErrorClass props error.isValid = true; error.toJSON().isValid = true; error[inspect.custom]().isValid = true; } export function testOnoConstructorWithNew() { let customOno = new Ono(CustomErrorClass); let error = customOno(message, param1, param2); // Error props error.name = "string"; error.message = "string"; error.stack = "string"; // OnoError props error.toJSON(); error[inspect.custom](); // CustomErrorClass props error.isValid = true; error.toJSON().isValid = true; error[inspect.custom]().isValid = true; } export function testOnoConstructorWithNonErrorClass() { let customOno = new Ono(CustomClass); let error = customOno(message, param1, param2); // Error props error.name = "string"; error.message = "string"; error.stack = "string"; // OnoError props error.toJSON(); error[inspect.custom](); // CustomClass props error.code = 12345; error.toJSON().code = 12345; error[inspect.custom]().code = 12345; } export function testOnoToJSON() { let pojo = Ono.toJSON(err); // ErrorPOJO props pojo.name = "string"; pojo.message = "string"; pojo.stack = "string"; let pojo2 = Ono.toJSON(errPOJO); // ErrorPOJO props pojo2.name = "string"; pojo2.message = "string"; pojo2.stack = "string"; } export function testOnoSignatures() { ono(message); ono(message, param1, param2); ono(props); ono(props, message); ono(props, message, param1, param2); ono(err); ono(errPOJO); ono(emptyClass); ono(customClass); ono(customError); ono(err, props); ono(errPOJO, props); ono(emptyClass, props); ono(customClass, props); ono(customError, props); ono(err, message); ono(errPOJO, message); ono(emptyClass, message); ono(customClass, message); ono(customError, message); ono(err, message, param1, param2); ono(errPOJO, message, param1, param2); ono(emptyClass, message, param1, param2); ono(customClass, message, param1, param2); ono(customError, message, param1, param2); ono(err, props, message); ono(errPOJO, props, message); ono(emptyClass, props, message); ono(customClass, props, message); ono(customError, props, message); ono(err, props, message, param1, param2); ono(errPOJO, props, message, param1, param2); ono(emptyClass, props, message, param1, param2); ono(customClass, props, message, param1, param2); ono(customError, props, message, param1, param2); } export function testErrorSignatures() { ono.error(message); ono.error(message, param1, param2); ono.error(props); ono.error(props, message); ono.error(props, message, param1, param2); ono.error(err); ono.error(errPOJO); ono.error(emptyClass); ono.error(customClass); ono.error(customError); ono.error(err, props); ono.error(errPOJO, props); ono.error(emptyClass, props); ono.error(customClass, props); ono.error(customError, props); ono.error(err, message); ono.error(errPOJO, message); ono.error(emptyClass, message); ono.error(customClass, message); ono.error(customError, message); ono.error(err, message, param1, param2); ono.error(errPOJO, message, param1, param2); ono.error(emptyClass, message, param1, param2); ono.error(customClass, message, param1, param2); ono.error(customError, message, param1, param2); ono.error(err, props, message); ono.error(errPOJO, props, message); ono.error(emptyClass, props, message); ono.error(customClass, props, message); ono.error(customError, props, message); ono.error(err, props, message, param1, param2); ono.error(errPOJO, props, message, param1, param2); ono.error(emptyClass, props, message, param1, param2); ono.error(customClass, props, message, param1, param2); ono.error(customError, props, message, param1, param2); } export function testEvalSignatures() { ono.eval(message); ono.eval(message, param1, param2); ono.eval(props); ono.eval(props, message); ono.eval(props, message, param1, param2); ono.eval(err); ono.eval(errPOJO); ono.eval(emptyClass); ono.eval(customClass); ono.eval(customError); ono.eval(err, props); ono.eval(errPOJO, props); ono.eval(emptyClass, props); ono.eval(customClass, props); ono.eval(customError, props); ono.eval(err, message); ono.eval(errPOJO, message); ono.eval(emptyClass, message); ono.eval(customClass, message); ono.eval(customError, message); ono.eval(err, message, param1, param2); ono.eval(errPOJO, message, param1, param2); ono.eval(emptyClass, message, param1, param2); ono.eval(customClass, message, param1, param2); ono.eval(customError, message, param1, param2); ono.eval(err, props, message); ono.eval(errPOJO, props, message); ono.eval(emptyClass, props, message); ono.eval(customClass, props, message); ono.eval(customError, props, message); ono.eval(err, props, message, param1, param2); ono.eval(errPOJO, props, message, param1, param2); ono.eval(emptyClass, props, message, param1, param2); ono.eval(customClass, props, message, param1, param2); ono.eval(customError, props, message, param1, param2); } export function testRangeSignatures() { ono.range(message); ono.range(message, param1, param2); ono.range(props); ono.range(props, message); ono.range(props, message, param1, param2); ono.range(err); ono.range(errPOJO); ono.range(emptyClass); ono.range(customClass); ono.range(customError); ono.range(err, props); ono.range(errPOJO, props); ono.range(emptyClass, props); ono.range(customClass, props); ono.range(customError, props); ono.range(err, message); ono.range(errPOJO, message); ono.range(emptyClass, message); ono.range(customClass, message); ono.range(customError, message); ono.range(err, message, param1, param2); ono.range(errPOJO, message, param1, param2); ono.range(emptyClass, message, param1, param2); ono.range(customClass, message, param1, param2); ono.range(customError, message, param1, param2); ono.range(err, props, message); ono.range(errPOJO, props, message); ono.range(emptyClass, props, message); ono.range(customClass, props, message); ono.range(customError, props, message); ono.range(err, props, message, param1, param2); ono.range(errPOJO, props, message, param1, param2); ono.range(emptyClass, props, message, param1, param2); ono.range(customClass, props, message, param1, param2); ono.range(customError, props, message, param1, param2); } export function testReferenceSignatures() { ono.reference(message); ono.reference(message, param1, param2); ono.reference(props); ono.reference(props, message); ono.reference(props, message, param1, param2); ono.reference(err); ono.reference(errPOJO); ono.reference(emptyClass); ono.reference(customClass); ono.reference(customError); ono.reference(err, props); ono.reference(errPOJO, props); ono.reference(emptyClass, props); ono.reference(customClass, props); ono.reference(customError, props); ono.reference(err, message); ono.reference(errPOJO, message); ono.reference(emptyClass, message); ono.reference(customClass, message); ono.reference(customError, message); ono.reference(err, message, param1, param2); ono.reference(errPOJO, message, param1, param2); ono.reference(emptyClass, message, param1, param2); ono.reference(customClass, message, param1, param2); ono.reference(customError, message, param1, param2); ono.reference(err, props, message); ono.reference(errPOJO, props, message); ono.reference(emptyClass, props, message); ono.reference(customClass, props, message); ono.reference(customError, props, message); ono.reference(err, props, message, param1, param2); ono.reference(errPOJO, props, message, param1, param2); ono.reference(emptyClass, props, message, param1, param2); ono.reference(customClass, props, message, param1, param2); ono.reference(customError, props, message, param1, param2); } export function testSyntaxSignatures() { ono.syntax(message); ono.syntax(message, param1, param2); ono.syntax(props); ono.syntax(props, message); ono.syntax(props, message, param1, param2); ono.syntax(err); ono.syntax(errPOJO); ono.syntax(emptyClass); ono.syntax(customClass); ono.syntax(customError); ono.syntax(err, props); ono.syntax(errPOJO, props); ono.syntax(emptyClass, props); ono.syntax(customClass, props); ono.syntax(customError, props); ono.syntax(err, message); ono.syntax(errPOJO, message); ono.syntax(emptyClass, message); ono.syntax(customClass, message); ono.syntax(customError, message); ono.syntax(err, message, param1, param2); ono.syntax(errPOJO, message, param1, param2); ono.syntax(emptyClass, message, param1, param2); ono.syntax(customClass, message, param1, param2); ono.syntax(customError, message, param1, param2); ono.syntax(err, props, message); ono.syntax(errPOJO, props, message); ono.syntax(emptyClass, props, message); ono.syntax(customClass, props, message); ono.syntax(customError, props, message); ono.syntax(err, props, message, param1, param2); ono.syntax(errPOJO, props, message, param1, param2); ono.syntax(emptyClass, props, message, param1, param2); ono.syntax(customClass, props, message, param1, param2); ono.syntax(customError, props, message, param1, param2); } export function testTypeSignatures() { ono.type(message); ono.type(message, param1, param2); ono.type(props); ono.type(props, message); ono.type(props, message, param1, param2); ono.type(err); ono.type(errPOJO); ono.type(emptyClass); ono.type(customClass); ono.type(customError); ono.type(err, props); ono.type(errPOJO, props); ono.type(emptyClass, props); ono.type(customClass, props); ono.type(customError, props); ono.type(err, message); ono.type(errPOJO, message); ono.type(emptyClass, message); ono.type(customClass, message); ono.type(customError, message); ono.type(err, message, param1, param2); ono.type(errPOJO, message, param1, param2); ono.type(emptyClass, message, param1, param2); ono.type(customClass, message, param1, param2); ono.type(customError, message, param1, param2); ono.type(err, props, message); ono.type(errPOJO, props, message); ono.type(emptyClass, props, message); ono.type(customClass, props, message); ono.type(customError, props, message); ono.type(err, props, message, param1, param2); ono.type(errPOJO, props, message, param1, param2); ono.type(emptyClass, props, message, param1, param2); ono.type(customClass, props, message, param1, param2); ono.type(customError, props, message, param1, param2); } export function testURISignatures() { ono.uri(message); ono.uri(message, param1, param2); ono.uri(props); ono.uri(props, message); ono.uri(props, message, param1, param2); ono.uri(err); ono.uri(errPOJO); ono.uri(emptyClass); ono.uri(customClass); ono.uri(customError); ono.uri(err, props); ono.uri(errPOJO, props); ono.uri(emptyClass, props); ono.uri(customClass, props); ono.uri(customError, props); ono.uri(err, message); ono.uri(errPOJO, message); ono.uri(emptyClass, message); ono.uri(customClass, message); ono.uri(customError, message); ono.uri(err, message, param1, param2); ono.uri(errPOJO, message, param1, param2); ono.uri(emptyClass, message, param1, param2); ono.uri(customClass, message, param1, param2); ono.uri(customError, message, param1, param2); ono.uri(err, props, message); ono.uri(errPOJO, props, message); ono.uri(emptyClass, props, message); ono.uri(customClass, props, message); ono.uri(customError, props, message); ono.uri(err, props, message, param1, param2); ono.uri(errPOJO, props, message, param1, param2); ono.uri(emptyClass, props, message, param1, param2); ono.uri(customClass, props, message, param1, param2); ono.uri(customError, props, message, param1, param2); } export function testCustomSignatures() { // eslint-disable-next-line new-cap let customOno = Ono(CustomErrorClass); customOno(message); customOno(message, param1, param2); customOno(props); customOno(props, message); customOno(props, message, param1, param2); customOno(err); customOno(errPOJO); customOno(emptyClass); customOno(customClass); customOno(customError); customOno(err, props); customOno(errPOJO, props); customOno(emptyClass, props); customOno(customClass, props); customOno(customError, props); customOno(err, message); customOno(errPOJO, message); customOno(emptyClass, message); customOno(customClass, message); customOno(customError, message); customOno(err, message, param1, param2); customOno(errPOJO, message, param1, param2); customOno(emptyClass, message, param1, param2); customOno(customClass, message, param1, param2); customOno(customError, message, param1, param2); customOno(err, props, message); customOno(errPOJO, props, message); customOno(emptyClass, props, message); customOno(customClass, props, message); customOno(customError, props, message); customOno(err, props, message, param1, param2); customOno(errPOJO, props, message, param1, param2); customOno(emptyClass, props, message, param1, param2); customOno(customClass, props, message, param1, param2); customOno(customError, props, message, param1, param2); }
the_stack
import { Utility } from "@hpcc-js/common"; const TIMEOUT_DEFAULT = 60; function espValFix(val) { if (val === undefined || val === null) { return null; } if (!val.trim) { if (val.Row) { return espRowFix(val.Row); } return val; } const retVal = val.trim(); if (retVal !== "" && !isNaN(retVal)) { if (retVal.length <= 1 || retVal[0] !== "0" || retVal[1] === ".") { return Number(retVal); } } return retVal; } function espRowFix(row) { for (const key in row) { row[key] = espValFix(row[key]); } return row; } export class ESPUrl { protected _protocol = "http:"; protected _hostname = "localhost"; protected _url; protected _port; protected _search; protected _pathname; protected _params; protected _hash; protected _host; constructor() { } url(_: string): this; url(): string; url(_?): string | this { if (!arguments.length) return this._url; this._url = _; const parser = document.createElement("a"); parser.href = this._url; // eslint-disable-next-line no-self-assign parser.href = parser.href; // This fixes an IE9/IE10 DOM value issue const params = {}; if (parser.search.length) { let tmp: any = parser.search; if (tmp[0] === "?") { tmp = tmp.substring(1); } tmp = tmp.split("&"); tmp.map(function (item) { const tmpItem = item.split("="); params[decodeURIComponent(tmpItem[0])] = decodeURIComponent(tmpItem[1]); }); } this._protocol = parser.protocol; this._hostname = parser.hostname; this._port = parser.port; this._pathname = parser.pathname; while (this._pathname.length && this._pathname[0] === "/") { this._pathname = this._pathname.substring(1); } this._search = parser.search; this._params = params; this._hash = parser.hash; this._host = parser.host; return this; } protocol(_: string): this; protocol(): string; protocol(_?: string): string | this { if (!arguments.length) return this._protocol; this._protocol = _; return this; } hostname(_: string): this; hostname(): string; hostname(_?: string): string | this { if (!arguments.length) return this._hostname; this._hostname = _; return this; } port(_: string): this; port(): string; port(_?: string) { if (!arguments.length) return this._port; this._port = _; return this; } search(_: string): this; search(): string; search(_?: string) { if (!arguments.length) return this._search; this._search = _; return this; } pathname(_: string): this; pathname(): string; pathname(_?: string) { if (!arguments.length) return this._pathname; this._pathname = _; return this; } hash(_: string): this; hash(): string; hash(_?: string) { if (!arguments.length) return this._hash; this._hash = _; return this; } host(_: string): this; host(): string; host(_?: string) { if (!arguments.length) return this._host; this._host = _; return this; } params(_: string): this; params(): string; params(_?: string) { if (!arguments.length) return this._params; this._params = _; return this; } param(key: string) { return this._params[key]; } isWsWorkunits() { return this._pathname.toLowerCase().indexOf("wsworkunits") >= 0 || this._params["Wuid"]; } isWorkunitResult() { return this.isWsWorkunits() && (this._params["Sequence"] || this._params["ResultName"]); } isWsEcl() { return this._pathname.toLowerCase().indexOf("wsecl") >= 0 || (this._params["QuerySetId"] && this._params["Id"]); } isWsWorkunits_GetStats() { return this._pathname.toLowerCase().indexOf("wsworkunits/wugetstats") >= 0 && this._params["WUID"]; } getUrl(overrides) { overrides = overrides || {}; return (overrides.protocol !== undefined ? overrides.protocol : this._protocol) + "//" + (overrides.hostname !== undefined ? overrides.hostname : this._hostname) + ":" + (overrides.port !== undefined ? overrides.port : this._port) + "/" + (overrides.pathname !== undefined ? overrides.pathname : this._pathname); } } export function ESPMappings(mappings) { this._mappings = mappings; this._reverseMappings = {}; for (const resultName in this._mappings) { this._reverseMappings[resultName] = {}; for (const key in this._mappings[resultName]) { this._reverseMappings[resultName][this._mappings[resultName][key]] = key; } } } ESPMappings.prototype.contains = function (resultName, origField) { return Utility.exists(resultName + "." + origField, this._mappings); }; ESPMappings.prototype.mapResult = function (response, resultName) { const mapping = this._mappings[resultName]; if (mapping) { response[resultName] = response[resultName].map(function (item) { let row = []; if (mapping.x && mapping.x instanceof Array) { // LINE Mapping --- row = []; for (let i = 0; i < mapping.x.length; ++i) { row.push(item[mapping.y[i]]); } } else { // Regular Mapping --- for (const key in mapping) { if (mapping[key] === "label") { row[0] = item[key]; } else if (mapping[key] === "weight") { row[1] = item[key]; } } } return row; }, this); } }; ESPMappings.prototype.mapResponse = function (response) { for (const key in response) { this.mapResult(response, key); } }; const serialize = function (obj) { const str = []; for (const key in obj) { if (obj.hasOwnProperty(key)) { const val = obj[key]; if (val !== undefined && val !== null) { str.push(encodeURIComponent(key) + "=" + encodeURIComponent(val)); } } } return str.join("&"); }; let jsonp = function (url, request, timeout) { return new Promise(function (resolve, reject) { let respondedTimeout = timeout * 1000; const respondedTick = 5000; const callbackName = "jsonp_callback_" + Math.round(Math.random() * 999999); window[callbackName] = function (response) { respondedTimeout = 0; doCallback(); resolve(response); }; const script = document.createElement("script"); script.src = url + (url.indexOf("?") >= 0 ? "&" : "?") + "jsonp=" + callbackName + "&" + serialize(request); document.body.appendChild(script); const progress = setInterval(function () { if (respondedTimeout <= 0) { clearInterval(progress); } else { respondedTimeout -= respondedTick; if (respondedTimeout <= 0) { clearInterval(progress); console.log("Request timeout: " + script.src); doCallback(); reject(Error("Request timeout: " + script.src)); } else { console.log("Request pending (" + respondedTimeout / 1000 + " sec): " + script.src); } } }, respondedTick); function doCallback() { delete window[callbackName]; document.body.removeChild(script); } }); }; export class Comms extends ESPUrl { protected _proxyMappings; protected _mappings; protected _timeout; protected _hipieResults; protected _hipieResultsLength; constructor() { super(); this._proxyMappings = {}; this._mappings = new ESPMappings({}); this._timeout = TIMEOUT_DEFAULT; this._hipieResults = {}; } hipieResults(_) { if (!arguments.length) return this._hipieResults; this._hipieResultsLength = 0; this._hipieResults = {}; const context = this; _.forEach(function (item) { context._hipieResultsLength++; context._hipieResults[item.id] = item; }); return this; } jsonp(url, request) { for (const key in this._proxyMappings) { const newUrlParts = url.split(key); const newUrl = newUrlParts[0]; if (newUrlParts.length > 1) { const espUrl = new ESPUrl() .url(url) ; url = newUrl + this._proxyMappings[key]; request.IP = espUrl.hostname(); request.PORT = espUrl.port(); if (newUrlParts.length > 0) { request.PATH = newUrlParts[1]; } break; } } return jsonp(url, request, this.timeout()); } ajax(method, url, request?) { return new Promise(function (resolve, reject) { let uri = url; if (method === "GET" && request) { uri += "?" + serialize(request); } const xhr: any = new XMLHttpRequest(); xhr.onload = function (e) { if (this.status >= 200 && this.status < 300) { resolve(JSON.parse(this.response)); } else { reject(Error(this.statusText)); } }; xhr.onerror = function () { reject(Error(this.statusText)); }; xhr.open(method, uri); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); if (method === "GET") { xhr.send(); } else { xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(serialize(request)); } }); } get(url, request?) { return this.ajax("GET", url, request); } post(url, request) { return this.ajax("POST", url, request); } mappings(_?) { if (!arguments.length) return this._mappings; this._mappings = new ESPMappings(_); return this; } proxyMappings(_?) { if (!arguments.length) return this._proxyMappings; this._proxyMappings = _; return this; } timeout(_?) { if (!arguments.length) return this._timeout; this._timeout = _ || TIMEOUT_DEFAULT; return this; } } export class Basic extends Comms { protected _cacheCalls; constructor() { super(); } cacheCalls(_?) { if (!arguments.length) return this._cacheCalls; this._cacheCalls = _; return this; } call(request, callback) { const url = this._url + (this._url.indexOf("?") >= 0 ? "&" : "?") + serialize(request); if (this._cacheCalls) { const context = this; return new Promise(function (resolve, reject) { const response = JSON.parse(localStorage.getItem("hpcc.viz." + url)); if (!response) { throw Error("not cached"); } if (callback) { console.log("Deprecated: callback, use promise (Basic.prototype.call)"); callback(response); } resolve(response); }).catch(function (response) { return context.get(url).then(function (response2) { localStorage.setItem("hpcc.viz." + url, JSON.stringify(response2)); if (callback) { console.log("Deprecated: callback, use promise (Basic.prototype.call)"); callback(response2); } return response2; }); }); } else { localStorage.removeItem("hpcc.viz." + url); return this.get(url).then(function (response) { if (callback) { console.log("Deprecated: callback, use promise (Basic.prototype.call)"); callback(response); } return response; }); } } } function locateRoxieResponse(response): object { // v5 and v6 compatible --- for (const key in response) { if (response[key].Row && response[key].Row instanceof Array) { return response; } let retVal; if (typeof (response[key]) !== "string") { retVal = locateRoxieResponse(response[key]); } if (retVal) { return retVal; } } return null; } function locateRoxieException(response) { for (const key in response) { if (response[key].Exception && response[key].Exception instanceof Array) { return response[key]; } const retVal = locateRoxieException(response[key]); if (retVal) { return retVal; } } return null; } export class WsECL extends Comms { protected _target; protected _query; constructor() { super(); this._port = "8002"; this._target = ""; this._query = ""; } url(_?) { const retVal = super.url.apply(this, arguments); if (arguments.length) { // http://localhost:8010/esp/files/stub.htm?QuerySetId=roxie&Id=stock.3&Widget=QuerySetDetailsWidget this._port = this._port === "8010" ? "8002" : this._port; // Need a better way --- for (const key in this._params) { switch (key) { case "QuerySetId": this.target(this._params[key]); break; case "Id": this.query(this._params[key]); break; } } let pathParts; let queryParts; if (!this._target || !this._query) { // http://localhost:8002/WsEcl/forms/default/query/roxie/wecare pathParts = this._pathname.split("/query/"); if (pathParts.length >= 2) { queryParts = pathParts[1].split("/"); if (queryParts.length >= 2) { this.target(queryParts[0]); this.query(queryParts[1]); } } } } return retVal; } target(_?) { if (!arguments.length) return this._target; this._target = _; return this; } query(_?) { if (!arguments.length) return this._query; this._query = _; return this; } constructUrl() { return Comms.prototype.getUrl.call(this, { pathname: "WsEcl/submit/query/" + this._target + "/" + this._query + "/json" }); } call(target, request, callback) { target = target || {}; target.target = target.target || this._target; target.query = target.query || this._query; const context = this; const url = this.getUrl({ pathname: "WsEcl/submit/query/" + target.target + "/" + target.query + "/json" }); return this.jsonp(url, request).then(function (response: any) { let _response = locateRoxieResponse(response); if (!_response) { _response = locateRoxieException(response); } response = _response; // Check for exceptions if (response.Exception) { throw Error(response.Exception.reduce(function (previousValue, exception, index, array) { if (previousValue.length) { previousValue += "\n"; } return previousValue + exception.Source + " " + exception.Code + ": " + exception.Message; }, "")); } // Remove "response.result.Row" for (const key in response) { if (response[key].Row) { response[key] = response[key].Row.map(espRowFix); } } context._mappings.mapResponse(response); if (callback) { console.log("Deprecated: callback, use promise (WsECL.prototype.call)"); callback(response); } return response; }); } send(request, callback) { return this.call({ target: this._target, query: this._query }, request, callback); } } export class WsWorkunits extends Comms { protected _wuid = ""; protected _jobname = ""; protected _sequence = null; protected _resultName = null; protected _fetchResultNamesPromise = null; protected _fetchResultPromise = {}; protected _resultNameCache = {}; protected _resultNameCacheCount = 0; protected _total; constructor() { super(); this._port = "8010"; } url(_?) { const retVal = Comms.prototype.url.apply(this, arguments); if (arguments.length) { // http://localhost:8010/WsWorkunit/WuResult?Wuid=xxx&ResultName=yyy for (const key in this._params) { switch (key) { case "Wuid": this.wuid(this._params[key]); break; case "ResultName": this.resultName(this._params[key]); break; case "Sequence": this.sequence(this._params[key]); break; } } if (!this._wuid) { // http://localhost:8010/WsWorkunits/res/W20140922-213329/c:/temp/index.html const urlParts = this._url.split("/res/"); if (urlParts.length >= 2) { const urlParts2 = urlParts[1].split("/"); this.wuid(urlParts2[0]); } } } return retVal; } wuid(_?) { if (!arguments.length) return this._wuid; this._wuid = _; return this; } jobname(_?) { if (!arguments.length) return this._jobname; this._jobname = _; return this; } sequence(_?) { if (!arguments.length) return this._sequence; this._sequence = _; return this; } resultName(_?) { if (!arguments.length) return this._resultName; this._resultName = _; return this; } appendParam(label, value, params) { if (value) { if (params) { params += "&"; } return params + label + "=" + value; } return params; } constructUrl() { const url = Comms.prototype.getUrl.call(this, { pathname: "WsWorkunits/res/" + this._wuid + "/" }); let params = ""; params = this.appendParam("ResultName", this._resultName, params); return url + (params ? "?" + params : ""); } _fetchResult(target, callback, skipMapping) { target = target || {}; if (!this._fetchResultPromise[target.resultname]) { target._start = target._start || 0; target._count = target._count || -1; const url = this.getUrl({ pathname: "WsWorkunits/WUResult.json" }); const request = { Wuid: target.wuid, ResultName: target.resultname, SuppressXmlSchema: true, Start: target._start, Count: target._count }; this._resultNameCache[target.resultname] = {}; const context = this; this._fetchResultPromise[target.resultname] = this.jsonp(url, request).then(function (response: any) { // Remove "xxxResponse.Result" for (const key in response) { if (!response[key].Result) { throw new Error("No result found."); } context._total = response[key].Total; response = response[key].Result; for (const responseKey in response) { response = response[responseKey].Row.map(espRowFix); break; } break; } context._resultNameCache[target.resultname] = response; if (!skipMapping) { context._mappings.mapResult(context._resultNameCache, target.resultname); } if (callback) { console.log("Deprecated: callback, use promise (WsWorkunits.prototype._fetchResult)"); callback(context._resultNameCache[target.resultname]); } return context._resultNameCache[target.resultname]; }); } return this._fetchResultPromise[target.resultname]; } fetchResult(target, callback, skipMapping) { if (target.wuid) { return this._fetchResult(target, callback, skipMapping); } else if (target.jobname) { const context = this; return this.WUQuery(target, function (response) { target.wuid = response[0].Wuid; return context._fetchResult(target, callback, skipMapping); }); } } WUQuery(_request, callback) { const url = this.getUrl({ pathname: "WsWorkunits/WUQuery.json" }); const request = { Jobname: _request.jobname, Count: 1 }; this._resultNameCache = {}; this._resultNameCacheCount = 0; return this.jsonp(url, request).then(function (response: any) { if (!Utility.exists("WUQueryResponse.Workunits.ECLWorkunit", response)) { throw Error("No workunit found."); } response = response.WUQueryResponse.Workunits.ECLWorkunit; if (callback) { console.log("Deprecated: callback, use promise (WsWorkunits.prototype.WUQuery)"); callback(response); } return response; }); } fetchResultNames(callback?) { if (!this._fetchResultNamesPromise) { const url = this.getUrl({ pathname: "WsWorkunits/WUInfo.json" }); const request = { Wuid: this._wuid, TruncateEclTo64k: true, IncludeExceptions: false, IncludeGraphs: false, IncludeSourceFiles: false, IncludeResults: true, IncludeResultsViewNames: false, IncludeVariables: false, IncludeTimers: false, IncludeResourceURLs: false, IncludeDebugValues: false, IncludeApplicationValues: false, IncludeWorkflows: false, IncludeXmlSchemas: false, SuppressResultSchemas: true }; this._resultNameCache = {}; this._resultNameCacheCount = 0; const context = this; this._fetchResultNamesPromise = this.jsonp(url, request).then(function (response: any) { if (Utility.exists("WUInfoResponse.Workunit.Archived", response) && response.WUInfoResponse.Workunit.Archived) { console.log("WU is archived: " + url + " " + JSON.stringify(request)); } if (Utility.exists("WUInfoResponse.Workunit.Results.ECLResult", response)) { response.WUInfoResponse.Workunit.Results.ECLResult.map(function (item) { context._resultNameCache[item.Name] = []; ++context._resultNameCacheCount; }); } if (callback) { console.log("Deprecated: callback, use promise (WsWorkunits.prototype.fetchResultNames)"); callback(context._resultNameCache); } return context._resultNameCache; }); } return this._fetchResultNamesPromise; } fetchResults(callback, skipMapping) { const context = this; return this.fetchResultNames().then(function (response) { const fetchArray = []; for (const key in context._resultNameCache) { fetchArray.push(context.fetchResult({ wuid: context._wuid, resultname: key }, null, skipMapping)); } return Promise.all(fetchArray).then(function (responseArray) { if (callback) { console.log("Deprecated: callback, use promise (WsWorkunits.prototype.fetchResults)"); callback(context._resultNameCache); } return context._resultNameCache; }); }); } postFilter(request, response) { const retVal = {}; for (const key in response) { retVal[key] = response[key].filter(function (row, idx) { for (const request_key in request) { if (row[request_key] !== undefined && request[request_key] !== undefined && row[request_key] != request[request_key]) { return false; } } return true; }); } this._mappings.mapResponse(retVal); return retVal; } send(request, callback) { const context = this; if (!this._resultNameCacheCount) { this.fetchResults(function (response) { callback(context.postFilter(request, response)); }, true); } else { callback(context.postFilter(request, this._resultNameCache)); } } } function WsWorkunits_GetStats() { Comms.call(this); this._port = "8010"; this._wuid = null; } WsWorkunits_GetStats.prototype = Object.create(Comms.prototype); WsWorkunits_GetStats.prototype.url = function (_) { const retVal = Comms.prototype.url.apply(this, arguments); if (arguments.length) { // http://localhost:8010/WsWorkunits/WUGetStats?WUID="xxx" for (const key in this._params) { switch (key) { case "WUID": this.wuid(this._params[key]); break; } } } return retVal; }; WsWorkunits_GetStats.prototype.wuid = function (_) { if (!arguments.length) return this._wuid; this._wuid = _; return this; }; WsWorkunits_GetStats.prototype.constructUrl = function () { return Comms.prototype.getUrl.call(this, { pathname: "WsWorkunits/WUGetStats?WUID=" + this._wuid }); }; WsWorkunits_GetStats.prototype.send = function (request, callback) { const url = this.getUrl({ pathname: "WsWorkunits/WUGetStats.json?WUID=" + this._wuid }); return this.jsonp(url, request).then(function (response) { if (Utility.exists("WUGetStatsResponse.Statistics.WUStatisticItem", response)) { if (callback) { console.log("Deprecated: callback, use promise (WsWorkunits_GetStats.prototype.send)"); callback(response.WUGetStatsResponse.Statistics.WUStatisticItem); } return response.WUGetStatsResponse.Statistics.WUStatisticItem; } else { if (callback) { console.log("Deprecated: callback, use promise (WsWorkunits_GetStats.prototype.send)"); callback([]); } return []; } }); }; // HIPIERoxie --- function HIPIERoxie() { Comms.call(this); } HIPIERoxie.prototype = Object.create(Comms.prototype); HIPIERoxie.prototype.fetchResults = function (request, callback) { const url = this.getUrl({}); this._resultNameCache = {}; this._resultNameCacheCount = 0; const context = this; return this.jsonp(url, request).then(function (response) { let _response = locateRoxieResponse(response); if (!_response) { _response = locateRoxieException(response); } response = _response; // Check for exceptions if (response.Exception) { throw Error(response.Exception.reduce(function (previousValue, exception, index, array) { if (previousValue.length) { previousValue += "\n"; } return previousValue + exception.Source + " " + exception.Code + ": " + exception.Message; }, "")); } // Remove "response.result.Row" for (const key in response) { if (response[key].Row) { context._resultNameCache[key] = response[key].Row.map(espRowFix); ++context._resultNameCacheCount; } } if (callback) { console.log("Deprecated: callback, use promise (HIPIERoxie.prototype.fetchResults)"); callback(context._resultNameCache); } return context._resultNameCache; }); }; HIPIERoxie.prototype.fetchResult = function (name, callback) { const context = this; return new Promise(function (resolve, reject) { if (callback) { console.log("Deprecated: callback, use promise (HIPIERoxie.prototype.fetchResult)"); callback(context._resultNameCache[name]); } resolve(context._resultNameCache[name]); }); }; HIPIERoxie.prototype.call = function (request, callback) { const context = this; return this.fetchResults(request, callback).then(function (response) { const retVal = {}; for (const hipieKey in context._hipieResults) { const item = context._hipieResults[hipieKey]; retVal[item.id] = response[item.from]; } return retVal; }); }; // HIPIEWorkunit --- function HIPIEWorkunit() { WsWorkunits.call(this); } HIPIEWorkunit.prototype = Object.create(WsWorkunits.prototype); HIPIEWorkunit.prototype.fetchResults = function (callback) { const context = this; return WsWorkunits.prototype.fetchResultNames.call(this).then(function (response) { const fetchArray = []; for (const key in context._hipieResults) { const item = context._hipieResults[key]; fetchArray.push(context.fetchResult(item.from)); } return Promise.all(fetchArray).then(function (response2) { if (callback) { console.log("Deprecated: callback, use promise (HIPIEWorkunit.prototype.fetchResults)"); callback(context._resultNameCache); } return context._resultNameCache; }); }); }; HIPIEWorkunit.prototype.fetchResult = function (name, callback) { return WsWorkunits.prototype.fetchResult.call(this, { wuid: this._wuid, resultname: name }).then(function (response) { if (callback) { console.log("Deprecated: callback, use promise (HIPIEWorkunit.prototype.fetchResult)"); callback(response); } return response; }); }; HIPIEWorkunit.prototype.call = function (request, callback) { const context = this; if (request.refresh || !this._resultNameCache || !this._resultNameCacheCount) { return this.fetchResults(callback).then(function (response) { return filterResults(request); }); } else { return new Promise(function (resolve, reject) { resolve(filterResults(request)); }); } function filterResults(request2) { const changedFilter = {}; for (const key in request2) { if (request2[key + "_changed"] !== undefined) { changedFilter[key] = { value: request2[key] }; } } const retVal = {}; for (const hipieKey in context._hipieResults) { const hipieResult = context._hipieResults[hipieKey]; const outputFilter = {}; for (let i = 0; i < hipieResult.filters.length; ++i) { const filter = hipieResult.filters[i]; if (!filter.isRange()) { outputFilter[filter.fieldid] = changedFilter[filter.fieldid] || { value: undefined }; outputFilter[filter.fieldid].filter = filter; } } retVal[hipieResult.id] = context._resultNameCache[hipieResult.from].filter(function (row) { for (const key2 in outputFilter) { if (!outputFilter[key2].filter.matches(row, outputFilter[key2].value)) { return false; } } return true; }); } return retVal; } }; // HIPIEDatabomb --- function HIPIEDatabomb() { HIPIEWorkunit.call(this); } HIPIEDatabomb.prototype = Object.create(HIPIEWorkunit.prototype); HIPIEDatabomb.prototype.databomb = function (_) { if (!arguments.length) return this._databomb; this._databomb = _; return this; }; HIPIEDatabomb.prototype.databombOutput = function (from, id) { if (!arguments.length) return undefined; this._resultNameCacheCount++; if (this._databomb instanceof Array) { this._resultNameCache[from] = this._databomb.map(espRowFix); } else { this._resultNameCache[from] = this._databomb[from].map(espRowFix); } return this; }; HIPIEDatabomb.prototype.fetchResults = function (callback) { const context = this; return new Promise(function (resolve, reject) { if (callback) { console.log("Deprecated: callback, use promise (HIPIEDatabomb.prototype.fetchResults)"); callback(context._resultNameCache); } resolve(context._resultNameCache); }); }; export function createESPConnection(url) { url = url || document.URL; const testURL = new ESPUrl() .url(url) ; if (testURL.isWsWorkunits_GetStats()) { return new WsWorkunits_GetStats() .url(url) ; } if (testURL.isWsWorkunits()) { return new WsWorkunits() .url(url) ; } if (testURL.isWsEcl()) { return new WsECL() .url(url) ; } return null; } export function hookJsonp(func) { jsonp = func; } export { HIPIEWorkunit, HIPIERoxie, HIPIEDatabomb };
the_stack
describe("unittests:: services:: PreProcessFile:", () => { function test(sourceText: string, readImportFile: boolean, detectJavaScriptImports: boolean, expectedPreProcess: ts.PreProcessedFileInfo): void { const resultPreProcess = ts.preProcessFile(sourceText, readImportFile, detectJavaScriptImports); assert.equal(resultPreProcess.isLibFile, expectedPreProcess.isLibFile, "Pre-processed file has different value for isLibFile. Expected: " + expectedPreProcess.isLibFile + ". Actual: " + resultPreProcess.isLibFile); checkFileReferenceList("Imported files", expectedPreProcess.importedFiles, resultPreProcess.importedFiles); checkFileReferenceList("Referenced files", expectedPreProcess.referencedFiles, resultPreProcess.referencedFiles); checkFileReferenceList("Type reference directives", expectedPreProcess.typeReferenceDirectives, resultPreProcess.typeReferenceDirectives); checkFileReferenceList("Lib reference directives", expectedPreProcess.libReferenceDirectives, resultPreProcess.libReferenceDirectives); assert.deepEqual(resultPreProcess.ambientExternalModules, expectedPreProcess.ambientExternalModules); } function checkFileReferenceList(kind: string, expected: ts.FileReference[], actual: ts.FileReference[]) { if (expected === actual) { return; } assert.deepEqual(actual, expected, `Expected [${kind}] ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`); } describe("Test preProcessFiles,", () => { it("Correctly return referenced files from triple slash", () => { test("///<reference path = \"refFile1.ts\" />" + "\n" + "///<reference path =\"refFile2.ts\"/>" + "\n" + "///<reference path=\"refFile3.ts\" />" + "\n" + "///<reference path= \"..\\refFile4d.ts\" />", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [{ fileName: "refFile1.ts", pos: 22, end: 33 }, { fileName: "refFile2.ts", pos: 59, end: 70 }, { fileName: "refFile3.ts", pos: 94, end: 105 }, { fileName: "..\\refFile4d.ts", pos: 131, end: 146 }], importedFiles: [] as ts.FileReference[], typeReferenceDirectives: [], libReferenceDirectives: [], ambientExternalModules: undefined, isLibFile: false }); }); it("Do not return reference path because of invalid triple-slash syntax", () => { test("///<reference path\"refFile1.ts\" />" + "\n" + "///<reference path =\"refFile2.ts\">" + "\n" + "///<referencepath=\"refFile3.ts\" />" + "\n" + "///<reference pat= \"refFile4d.ts\" />", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [] as ts.FileReference[], importedFiles: [] as ts.FileReference[], typeReferenceDirectives: [], libReferenceDirectives: [], ambientExternalModules: undefined, isLibFile: false }); }); it("Do not return reference path of non-imports", () => { test("Quill.import('delta');", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [] as ts.FileReference[], importedFiles: [] as ts.FileReference[], typeReferenceDirectives: [], libReferenceDirectives: [], ambientExternalModules: undefined, isLibFile: false }); }); it("Do not return reference path of nested non-imports", () => { test("a.b.import('c');", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [] as ts.FileReference[], importedFiles: [] as ts.FileReference[], typeReferenceDirectives: [], libReferenceDirectives: [], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly return imported files", () => { test("import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\"); import i3= require(\"r3.ts\"); import i4=require(\"r4.ts\"); import i5 = require (\"r5.ts\");", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [] as ts.FileReference[], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [{ fileName: "r1.ts", pos: 20, end: 25 }, { fileName: "r2.ts", pos: 49, end: 54 }, { fileName: "r3.ts", pos: 78, end: 83 }, { fileName: "r4.ts", pos: 106, end: 111 }, { fileName: "r5.ts", pos: 138, end: 143 }], ambientExternalModules: undefined, isLibFile: false }); }); it("Do not return imported files if readImportFiles argument is false", () => { test("import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\"); import i3= require(\"r3.ts\"); import i4=require(\"r4.ts\"); import i5 = require (\"r5.ts\");", /*readImportFile*/ false, /*detectJavaScriptImports*/ false, { referencedFiles: [] as ts.FileReference[], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [] as ts.FileReference[], ambientExternalModules: undefined, isLibFile: false }); }); it("Do not return import path because of invalid import syntax", () => { test("import i1 require(\"r1.ts\"); import = require(\"r2.ts\") import i3= require(\"r3.ts\"); import i5", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [] as ts.FileReference[], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [{ fileName: "r3.ts", pos: 73, end: 78 }], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly return referenced files and import files", () => { test("///<reference path=\"refFile1.ts\" />" + "\n" + "///<reference path =\"refFile2.ts\"/>" + "\n" + "import i1 = require(\"r1.ts\"); import i2 =require(\"r2.ts\");", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [{ fileName: "refFile1.ts", pos: 20, end: 31 }, { fileName: "refFile2.ts", pos: 57, end: 68 }], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [{ fileName: "r1.ts", pos: 92, end: 97 }, { fileName: "r2.ts", pos: 121, end: 126 }], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly return referenced files and import files even with some invalid syntax", () => { test("///<reference path=\"refFile1.ts\" />" + "\n" + "///<reference path \"refFile2.ts\"/>" + "\n" + "import i1 = require(\"r1.ts\"); import = require(\"r2.ts\"); import i2 = require(\"r3.ts\");", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [{ fileName: "refFile1.ts", pos: 20, end: 31 }], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [{ fileName: "r1.ts", pos: 91, end: 96 }, { fileName: "r3.ts", pos: 148, end: 153 }], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly return ES6 imports", () => { test("import * as ns from \"m1\";" + "\n" + "import def, * as ns from \"m2\";" + "\n" + "import def from \"m3\";" + "\n" + "import {a} from \"m4\";" + "\n" + "import {a as A} from \"m5\";" + "\n" + "import {a as A, b, c as C} from \"m6\";" + "\n" + "import def , {a, b, c as C} from \"m7\";" + "\n", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "m1", pos: 20, end: 22 }, { fileName: "m2", pos: 51, end: 53 }, { fileName: "m3", pos: 73, end: 75 }, { fileName: "m4", pos: 95, end: 97 }, { fileName: "m5", pos: 122, end: 124 }, { fileName: "m6", pos: 160, end: 162 }, { fileName: "m7", pos: 199, end: 201 } ], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly return ES6 exports", () => { test("export * from \"m1\";" + "\n" + "export {a} from \"m2\";" + "\n" + "export {a as A} from \"m3\";" + "\n" + "export {a as A, b, c as C} from \"m4\";" + "\n", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "m1", pos: 14, end: 16 }, { fileName: "m2", pos: 36, end: 38 }, { fileName: "m3", pos: 63, end: 65 }, { fileName: "m4", pos: 101, end: 103 }, ], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly handles import types", () => { test("import type * as ns from \"m1\";" + "\n" + "import type def, * as ns from \"m2\";" + "\n" + "import type def from \"m3\";" + "\n" + "import type {a} from \"m4\";" + "\n" + "import type {a as A} from \"m5\";" + "\n" + "import type {a as A, b, c as C} from \"m6\";" + "\n" + "import type def , {a, b, c as C} from \"m7\";" + "\n" + "import type from \"m8\";" + "\n" + "import type T = require(\"m9\");" + "\n" + "import type = require(\"m10\");" + "\n" + "export import type T = require(\"m11\");" + "\n" + "export import type = require(\"m12\");" + "\n", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [] as ts.FileReference[], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "m1", pos: 25, end: 27 }, { fileName: "m2", pos: 61, end: 63 }, { fileName: "m3", pos: 88, end: 90 }, { fileName: "m4", pos: 115, end: 117 }, { fileName: "m5", pos: 147, end: 149 }, { fileName: "m6", pos: 190, end: 192 }, { fileName: "m7", pos: 234, end: 236 }, { fileName: "m8", pos: 257, end: 259 }, { fileName: "m9", pos: 287, end: 289 }, { fileName: "m10", pos: 316, end: 319 }, { fileName: "m11", pos: 355, end: 358 }, { fileName: "m12", pos: 392, end: 395 }, ], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly handles export types", () => { test("export type * from \"m1\";" + "\n" + "export type {a} from \"m2\";" + "\n" + "export type {a as A} from \"m3\";" + "\n" + "export type {a as A, b, c as C} from \"m4\";" + "\n", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [] as ts.FileReference[], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "m1", pos: 19, end: 21 }, { fileName: "m2", pos: 46, end: 48 }, { fileName: "m3", pos: 78, end: 80 }, { fileName: "m4", pos: 121, end: 123 }, ], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly handles import type node", () => { test("const x: import(\"m1\") = { x: 0, y: 0 };" + "\n" + "let y: import(\"m2\").Bar.I = { a: \"\", b: 0 };" + "\n" + "let shim: typeof import(\"m3\") = { Bar: Bar2 };" + "\n", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "m1", pos: 16, end: 18 }, { fileName: "m2", pos: 54, end: 56 }, { fileName: "m3", pos: 109, end: 111 }, ], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly return ambient external modules", () => { test(` declare module A {} declare module "B" {} function foo() { } `, /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [], ambientExternalModules: ["B"], isLibFile: false }); }); it("Correctly handles export import declarations", () => { test("export import a = require(\"m1\");", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "m1", pos: 26, end: 28 } ], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly handles export require calls in JavaScript files", () => { test(` export import a = require("m1"); var x = require('m2'); foo(require('m3')); var z = { f: require('m4') } `, /*readImportFile*/ true, /*detectJavaScriptImports*/ true, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "m1", pos: 39, end: 41 }, { fileName: "m2", pos: 74, end: 76 }, { fileName: "m3", pos: 105, end: 107 }, { fileName: "m4", pos: 146, end: 148 }, ], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly handles dependency lists in define([deplist]) calls in JavaScript files", () => { test(` define(["mod1", "mod2"], (m1, m2) => { }); `, /*readImportFile*/ true, /*detectJavaScriptImports*/ true, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "mod1", pos: 21, end: 25 }, { fileName: "mod2", pos: 29, end: 33 }, ], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly handles dependency lists in define(modName, [deplist]) calls in JavaScript files", () => { test(` define("mod", ["mod1", "mod2"], (m1, m2) => { }); `, /*readImportFile*/ true, /*detectJavaScriptImports*/ true, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "mod1", pos: 28, end: 32 }, { fileName: "mod2", pos: 36, end: 40 }, ], ambientExternalModules: undefined, isLibFile: false }); }); it("correctly handles augmentations in external modules - 1", () => { test(` declare module "../Observable" { interface I {} } export {} `, /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "../Observable", pos: 28, end: 41 } ], ambientExternalModules: undefined, isLibFile: false }); }); it("correctly handles augmentations in external modules - 2", () => { test(` declare module "../Observable" { interface I {} } import * as x from "m"; `, /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "m", pos: 123, end: 124 }, { fileName: "../Observable", pos: 28, end: 41 } ], ambientExternalModules: undefined, isLibFile: false }); }); it("correctly handles augmentations in external modules - 3", () => { test(` declare module "../Observable" { interface I {} } import m = require("m"); `, /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "m", pos: 123, end: 124 }, { fileName: "../Observable", pos: 28, end: 41 } ], ambientExternalModules: undefined, isLibFile: false }); }); it("correctly handles augmentations in external modules - 4", () => { test(` declare module "../Observable" { interface I {} } namespace N {} export = N; `, /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "../Observable", pos: 28, end: 41 } ], ambientExternalModules: undefined, isLibFile: false }); }); it("correctly handles augmentations in external modules - 5", () => { test(` declare module "../Observable" { interface I {} } namespace N {} export import IN = N; `, /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "../Observable", pos: 28, end: 41 } ], ambientExternalModules: undefined, isLibFile: false }); }); it("correctly handles augmentations in external modules - 6", () => { test(` declare module "../Observable" { interface I {} } export let x = 1; `, /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "../Observable", pos: 28, end: 41 } ], ambientExternalModules: undefined, isLibFile: false }); }); it ("correctly handles augmentations in ambient external modules - 1", () => { test(` declare module "m1" { export * from "m2"; declare module "augmentation" { interface I {} } } `, /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "m2", pos: 65, end: 67 }, { fileName: "augmentation", pos: 102, end: 114 } ], ambientExternalModules: ["m1"], isLibFile: false }); }); it ("correctly handles augmentations in ambient external modules - 2", () => { test(` namespace M { var x; } import IM = M; declare module "m1" { export * from "m2"; declare module "augmentation" { interface I {} } } `, /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "m2", pos: 127, end: 129 }, { fileName: "augmentation", pos: 164, end: 176 } ], ambientExternalModules: ["m1"], isLibFile: false }); }); it ("correctly recognizes type reference directives", () => { test(` /// <reference path="a"/> /// <reference types="a1"/> /// <reference path="a2"/> /// <reference types="a3"/> `, /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [ { pos: 34, end: 35, fileName: "a" }, { pos: 112, end: 114, fileName: "a2" } ], typeReferenceDirectives: [ { pos: 73, end: 75, fileName: "a1" }, { pos: 152, end: 154, fileName: "a3" } ], libReferenceDirectives: [], importedFiles: [], ambientExternalModules: undefined, isLibFile: false }); }); it ("correctly recognizes lib reference directives", () => { test(` /// <reference path="a"/> /// <reference lib="a1"/> /// <reference path="a2"/> /// <reference lib="a3"/> `, /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [ { pos: 34, end: 35, fileName: "a" }, { pos: 110, end: 112, fileName: "a2" } ], typeReferenceDirectives: [ ], libReferenceDirectives: [ { pos: 71, end: 73, fileName: "a1" }, { pos: 148, end: 150, fileName: "a3" } ], importedFiles: [], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly handles dynamic imports with template literals", () => { test("const m1 = import('mod1');" + "\n" + "const m2 = import(`mod2`);" + "\n" + "Promise.all([import('mod3'), import(`mod4`)]);" + "\n" + "import(/* webpackChunkName: 'module5' */ `mod5`);" + "\n", /*readImportFile*/ true, /*detectJavaScriptImports*/ false, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "mod1", pos: 18, end: 22 }, { fileName: "mod2", pos: 45, end: 49 }, { fileName: "mod3", pos: 74, end: 78 }, { fileName: "mod4", pos: 90, end: 94 }, { fileName: "mod5", pos: 142, end: 146 } ], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly handles require calls with template literals in JS files", () => { test("const m1 = require(`mod1`);" + "\n" + "f(require(`mod2`));" + "\n" + "const a = { x: require(`mod3`) };" + "\n", /*readImportFile*/ true, /*detectJavaScriptImports*/ true, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "mod1", pos: 19, end: 23 }, { fileName: "mod2", pos: 38, end: 42 }, { fileName: "mod3", pos: 71, end: 75 } ], ambientExternalModules: undefined, isLibFile: false }); }); it("Correctly handles dependency lists in define(modName, [deplist]) calls with template literals in JS files", () => { test("define(`mod`, [`mod1`, `mod2`], (m1, m2) => {});", /*readImportFile*/ true, /*detectJavaScriptImports*/ true, { referencedFiles: [], typeReferenceDirectives: [], libReferenceDirectives: [], importedFiles: [ { fileName: "mod1", pos: 15, end: 19 }, { fileName: "mod2", pos: 23, end: 27 }, ], ambientExternalModules: undefined, isLibFile: false }); }); }); });
the_stack
import React from 'react'; import { act } from 'react-dom/test-utils'; import { mount } from 'enzyme'; import Icon from '../../Icon'; import Layout from '../../Layout'; import Tooltip from '../../Tooltip'; import Menu from '../index'; import collapseMotion from '../../../utils/motion'; import mountTest from '../../../../tools/tests/mountTest'; const { SubMenu } = Menu; const noop = () => {}; const expectSubMenuBehavior = (menu, enter = noop, leave = noop) => { if (!menu.prop('openKeys') && !menu.prop('defaultOpenKeys')) { expect(menu.find('ul.fishd-menu-sub').length).toBe(0); } menu.update(); expect(menu.find('ul.fishd-menu-sub').length).toBe(0); const AnimationClassNames = { horizontal: 'slide-up-leave', inline: 'fishd-motion-collapse-leave', vertical: 'zoom-big-leave', }; const mode = menu.prop('mode') || 'horizontal'; act(() => { enter(); jest.runAllTimers(); menu.update(); }); function getSubMenu() { if (mode === 'inline') { return menu.find('ul.fishd-menu-sub.fishd-menu-inline').hostNodes().at(0); } return menu.find('div.fishd-menu-submenu-popup').hostNodes().at(0); } expect( getSubMenu().hasClass('fishd-menu-hidden') || getSubMenu().hasClass(AnimationClassNames[mode]), ).toBeFalsy(); act(() => { leave(); jest.runAllTimers(); menu.update(); if (getSubMenu().length) { expect( getSubMenu().hasClass('fishd-menu-submenu-hidden') || getSubMenu().hasClass('fishd-menu-hidden') || getSubMenu().hasClass(AnimationClassNames[mode]), ).toBeTruthy(); } }); }; describe('Menu', () => { window.requestAnimationFrame = callback => window.setTimeout(callback, 16); window.cancelAnimationFrame = window.clearTimeout; beforeEach(() => { jest.useFakeTimers(); }); afterEach(() => { jest.useRealTimers(); }); mountTest(() => ( <Menu> <Menu.Item /> <Menu.ItemGroup /> <Menu.SubMenu /> </Menu> )); mountTest(() => ( <Menu> <Menu.Item /> <> <Menu.ItemGroup /> <Menu.SubMenu /> {null} </> <> <Menu.Item /> </> {undefined} <> <> <Menu.Item /> </> </> </Menu> )); let div; beforeEach(() => { div = document.createElement('div'); document.body.appendChild(div); }); afterEach(() => { document.body.removeChild(div); }); it('If has select nested submenu item ,the menu items on the grandfather level should be highlight', () => { const wrapper = mount( <Menu defaultSelectedKeys={['1-3-2']} mode="vertical"> <SubMenu key="1" title="submenu1"> <Menu.Item key="1-1">Option 1</Menu.Item> <Menu.Item key="1-2">Option 2</Menu.Item> <SubMenu key="1-3" title="submenu1-3"> <Menu.Item key="1-3-1">Option 3</Menu.Item> <Menu.Item key="1-3-2">Option 4</Menu.Item> </SubMenu> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expect(wrapper.find('li.fishd-menu-submenu-selected').length).toBe(1); }); it('forceSubMenuRender', () => { const wrapper = mount( <Menu mode="horizontal"> <SubMenu key="1" title="submenu1"> <Menu.Item key="1-1"> <span className="bamboo" /> </Menu.Item> </SubMenu> </Menu>, ); expect(wrapper.find('.bamboo').hostNodes()).toHaveLength(0); wrapper.setProps({ forceSubMenuRender: true, getPopupContainer: node => node.parentNode as HTMLElement, }); wrapper.update(); expect(wrapper.find('.bamboo').hostNodes()).toHaveLength(1); }); it('should accept defaultOpenKeys in mode horizontal', () => { const wrapper = mount( <Menu defaultOpenKeys={['1']} mode="horizontal"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expect(wrapper.exists('.fishd-menu-sub')).toBeFalsy(); }); it('should accept defaultOpenKeys in mode inline', () => { const wrapper = mount( <Menu defaultOpenKeys={['1']} mode="inline"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expect(wrapper.find('.fishd-menu-sub').at(0).hasClass('fishd-menu-hidden')).not.toBe(true); }); it('should accept defaultOpenKeys in mode vertical', () => { const wrapper = mount( <Menu defaultOpenKeys={['1']} mode="vertical"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expect(wrapper.find('PopupTrigger').first().prop('visible')).toBeTruthy(); }); it('should accept openKeys in mode horizontal', () => { const wrapper = mount( <Menu openKeys={['1']} mode="horizontal"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expect(wrapper.find('PopupTrigger').first().prop('visible')).toBeTruthy(); }); it('should accept openKeys in mode inline', () => { const wrapper = mount( <Menu openKeys={['1']} mode="inline"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expect(wrapper.find('InlineSubMenuList').first().prop('open')).toBeTruthy(); }); it('should accept openKeys in mode vertical', () => { const wrapper = mount( <Menu openKeys={['1']} mode="vertical"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expect(wrapper.find('PopupTrigger').first().prop('visible')).toBeTruthy(); }); it('test submenu in mode horizontal', () => { const wrapper = mount( <Menu mode="horizontal"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expectSubMenuBehavior( wrapper, () => wrapper.setProps({ openKeys: ['1'] }), () => wrapper.setProps({ openKeys: [] }), ); }); it('test submenu in mode inline', () => { const wrapper = mount( <Menu mode="inline"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expectSubMenuBehavior( wrapper, () => wrapper.setProps({ openKeys: ['1'] }), () => wrapper.setProps({ openKeys: [] }), ); }); it('test submenu in mode vertical', () => { const wrapper = mount( <Menu mode="vertical"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expectSubMenuBehavior( wrapper, () => wrapper.setProps({ openKeys: ['1'] }), () => wrapper.setProps({ openKeys: [] }), ); }); // https://github.com/ant-design/ant-design/pulls/4677 // https://github.com/ant-design/ant-design/issues/4692 // TypeError: Cannot read property 'indexOf' of undefined it('pr #4677 and issue #4692', () => { const wrapper = mount( <Menu mode="horizontal"> <SubMenu title="submenu"> <Menu.Item key="1">menu1</Menu.Item> <Menu.Item key="2">menu2</Menu.Item> </SubMenu> </Menu>, ); wrapper.update(); // just expect no error emit }); it('should always follow openKeys when mode is switched', () => { const wrapper = mount( <Menu openKeys={['1']} mode="inline"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu11">Option 11</Menu.Item> <Menu.Item key="submenu22">Option 22</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expect(wrapper.find('ul.fishd-menu-sub').at(0).hasClass('fishd-menu-hidden')).toBe(false); wrapper.setProps({ mode: 'vertical' }); jest.runAllTimers(); wrapper.update(); expect(wrapper.find('ul.fishd-menu-sub').at(0).hasClass('fishd-menu-hidden')).toBe(false); wrapper.setProps({ mode: 'inline' }); jest.runAllTimers(); wrapper.update(); expect(wrapper.find('ul.fishd-menu-sub').at(0).hasClass('fishd-menu-hidden')).toBe(false); }); it('should always follow openKeys when inlineCollapsed is switched', () => { jest.useFakeTimers(); const wrapper = mount( <Menu defaultOpenKeys={['1']} mode="inline"> <Menu.Item key="menu1" icon={<Icon type="Settingx" />}> Option </Menu.Item> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option</Menu.Item> <Menu.Item key="submenu2">Option</Menu.Item> </SubMenu> </Menu>, ); expect(wrapper.find('InlineSubMenuList').prop('open')).toBeTruthy(); // inlineCollapsed wrapper.setProps({ inlineCollapsed: true }); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(wrapper.find('ul.fishd-menu-root').hasClass('fishd-menu-vertical')).toBeTruthy(); expect(wrapper.find('PopupTrigger').prop('visible')).toBeFalsy(); // !inlineCollapsed wrapper.setProps({ inlineCollapsed: false }); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(wrapper.find('ul.fishd-menu-sub').last().hasClass('fishd-menu-inline')).toBeTruthy(); expect(wrapper.find('InlineSubMenuList').prop('open')).toBeTruthy(); }); it('inlineCollapsed should works well when specify a not existed default openKeys', () => { const wrapper = mount( <Menu defaultOpenKeys={['not-existed']} mode="inline"> <Menu.Item key="menu1" icon={<Icon type="Settingx" />}> Option </Menu.Item> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option</Menu.Item> <Menu.Item key="submenu2">Option</Menu.Item> </SubMenu> </Menu>, ); expect(wrapper.find('.fishd-menu-sub').length).toBe(0); wrapper.setProps({ inlineCollapsed: true }); jest.runAllTimers(); wrapper.update(); wrapper.simulate('transitionEnd', { propertyName: 'width' }); act(() => { jest.runAllTimers(); wrapper.update(); }); wrapper.find('.fishd-menu-submenu-title').at(0).simulate('mouseEnter'); jest.runAllTimers(); wrapper.update(); expect(wrapper.find('.fishd-menu-submenu').at(0).hasClass('fishd-menu-submenu-vertical')).toBe( true, ); expect(wrapper.find('.fishd-menu-submenu').at(0).hasClass('fishd-menu-submenu-open')).toBe( true, ); expect(wrapper.find('ul.fishd-menu-sub').at(0).hasClass('fishd-menu-vertical')).toBe(true); expect(wrapper.find('ul.fishd-menu-sub').at(0).hasClass('fishd-menu-hidden')).toBe(false); }); it('inlineCollapsed Menu.Item Tooltip can be removed', () => { const wrapper = mount( <Menu defaultOpenKeys={['not-existed']} mode="inline" inlineCollapsed getPopupContainer={node => node.parentNode as HTMLElement} > <Menu.Item key="menu1">item</Menu.Item> <Menu.Item key="menu2" title="title"> item </Menu.Item> <Menu.Item key="menu3" title={undefined}> item </Menu.Item> <Menu.Item key="menu4" title={null}> item </Menu.Item> <Menu.Item key="menu5" title=""> item </Menu.Item> <Menu.Item key="menu6" title={false}> item </Menu.Item> </Menu>, ); expect(wrapper.find(Menu.Item).at(0).find(Tooltip).props().title).toBe('item'); expect(wrapper.find(Menu.Item).at(1).find(Tooltip).props().title).toBe('title'); expect(wrapper.find(Menu.Item).at(2).find(Tooltip).props().title).toBe('item'); expect(wrapper.find(Menu.Item).at(3).find(Tooltip).props().title).toBe(null); expect(wrapper.find(Menu.Item).at(4).find(Tooltip).props().title).toBe(''); expect(wrapper.find(Menu.Item).at(4).find(Tooltip).props().title).toBe(''); }); describe('open submenu when click submenu title', () => { beforeEach(() => { jest.useFakeTimers(); }); afterEach(() => { jest.useRealTimers(); }); const toggleMenu = (wrapper, index, event) => { wrapper.find('.fishd-menu-submenu-title').at(index).simulate(event); jest.runAllTimers(); wrapper.update(); }; it('inline', () => { const wrapper = mount( <Menu mode="inline"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expectSubMenuBehavior( wrapper, () => toggleMenu(wrapper, 0, 'click'), () => toggleMenu(wrapper, 0, 'click'), ); }); it('inline menu collapseMotion should be triggered', async () => { const cloneMotion = { ...collapseMotion, motionDeadline: 1, }; const onOpenChange = jest.fn(); // const onEnterEnd = jest.spyOn(cloneMotion, 'onEnterEnd'); const wrapper = mount( <Menu mode="inline" motion={cloneMotion} onOpenChange={onOpenChange}> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); wrapper.find('div.fishd-menu-submenu-title').simulate('click'); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(onOpenChange).toHaveBeenCalled(); // expect(onEnterEnd).toHaveBeenCalledTimes(1); }); it('vertical with hover(default)', () => { const wrapper = mount( <Menu mode="vertical"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expectSubMenuBehavior( wrapper, () => toggleMenu(wrapper, 0, 'mouseenter'), () => toggleMenu(wrapper, 0, 'mouseleave'), ); }); it('vertical with click', () => { const wrapper = mount( <Menu mode="vertical" triggerSubMenuAction="click"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expectSubMenuBehavior( wrapper, () => toggleMenu(wrapper, 0, 'click'), () => toggleMenu(wrapper, 0, 'click'), ); }); it('horizontal with hover(default)', () => { jest.useFakeTimers(); const wrapper = mount( <Menu mode="horizontal"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expectSubMenuBehavior( wrapper, () => toggleMenu(wrapper, 0, 'mouseenter'), () => toggleMenu(wrapper, 0, 'mouseleave'), ); }); it('horizontal with click', () => { jest.useFakeTimers(); const wrapper = mount( <Menu mode="horizontal" triggerSubMenuAction="click"> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expectSubMenuBehavior( wrapper, () => toggleMenu(wrapper, 0, 'click'), () => toggleMenu(wrapper, 0, 'click'), ); }); }); it('inline title', () => { jest.useFakeTimers(); const wrapper = mount( <Menu mode="inline" inlineCollapsed> <Menu.Item key="1" title="bamboo lucky" icon={<Icon type="Settingx" />}> Option 1 <img style={{ width: 20 }} alt="test" src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" /> </Menu.Item> </Menu>, ); wrapper.find('.fishd-menu-item').hostNodes().simulate('mouseenter'); act(() => { jest.runAllTimers(); }); wrapper.update(); const text = wrapper.find('.fishd-tooltip-inner').text(); expect(text).toBe('bamboo lucky'); jest.useRealTimers(); }); it('render correctly when using with Layout.Sider', () => { class Demo extends React.Component { state = { collapsed: false, }; onCollapse = collapsed => this.setState({ collapsed }); render() { const { collapsed } = this.state; return ( <Layout style={{ minHeight: '100vh' }}> <Layout.Sider collapsible collapsed={collapsed} onCollapse={this.onCollapse}> <div className="logo" /> <Menu theme="dark" defaultSelectedKeys={['1']} mode="inline"> <SubMenu key="sub1" icon={<Icon type="Settingx" />} title="User"> <Menu.Item key="3">Tom</Menu.Item> <Menu.Item key="4">Bill</Menu.Item> <Menu.Item key="5">Alex</Menu.Item> </SubMenu> </Menu> </Layout.Sider> </Layout> ); } } const wrapper = mount(<Demo />); expect(wrapper.find(Menu).at(0).getDOMNode().classList.contains('fishd-menu-inline')).toBe( true, ); wrapper.find('.fishd-menu-submenu-title').simulate('click'); wrapper.find('.fishd-layout-sider-trigger').simulate('click'); act(() => { jest.runAllTimers(); }); wrapper.update(); expect(wrapper.find(Menu).getDOMNode().classList.contains('fishd-menu-inline-collapsed')).toBe( true, ); wrapper.find(Menu).simulate('mouseenter'); expect(wrapper.find(Menu).getDOMNode().classList.contains('fishd-menu-inline')).toBe(false); expect(wrapper.find(Menu).getDOMNode().classList.contains('fishd-menu-vertical')).toBe(true); }); it('onMouseEnter should work', () => { const onMouseEnter = jest.fn(); const wrapper = mount( <Menu onMouseEnter={onMouseEnter} defaultSelectedKeys={['test1']}> <Menu.Item key="test1">Navigation One</Menu.Item> <Menu.Item key="test2">Navigation Two</Menu.Item> </Menu>, ); wrapper.find('ul.fishd-menu-root').simulate('mouseenter'); expect(onMouseEnter).toHaveBeenCalled(); }); it('MenuItem should not render Tooltip when inlineCollapsed is false', () => { const wrapper = mount( <Menu defaultSelectedKeys={['mail']} defaultOpenKeys={['mail']} mode="horizontal"> <Menu.Item key="mail" icon={<Icon type="Settingx" />}> Navigation One </Menu.Item> <Menu.Item key="app" icon={<Icon type="Settingx" />}> Navigation Two </Menu.Item> <Menu.Item key="alipay"> <a href="https://163.com" target="_blank" rel="noopener noreferrer"> Navigation Four - Link </a> </Menu.Item> </Menu>, { attachTo: div }, ); wrapper.find('li.fishd-menu-item').first().simulate('mouseenter'); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(wrapper.find('.fishd-tooltip-inner').length).toBe(0); }); it('MenuItem should render icon and icon should be the first child when icon exists', () => { const wrapper = mount( <Menu> <Menu.Item key="mail" icon={<Icon type="Settingx" />}> Navigation One </Menu.Item> </Menu>, ); expect(wrapper.find('.fishd-menu-item .fishdicon').hasClass('fishdicon-Settingx')).toBe(true); }); it('should controlled collapse work', () => { const wrapper = mount( <Menu mode="inline" inlineCollapsed={false}> <Menu.Item key="1" icon={<Icon type="Settingx" />}> Option 1 </Menu.Item> </Menu>, ); expect(wrapper.render()).toMatchSnapshot(); wrapper.setProps({ inlineCollapsed: true }); expect(wrapper.render()).toMatchSnapshot(); }); it('not title if not collapsed', () => { jest.useFakeTimers(); const wrapper = mount( <Menu mode="inline" inlineCollapsed={false}> <Menu.Item key="1" icon={<Icon type="Settingx" />}> Option 1 </Menu.Item> </Menu>, ); wrapper.find('.fishd-menu-item').hostNodes().simulate('mouseenter'); jest.runAllTimers(); wrapper.update(); expect(wrapper.find('.fishd-tooltip-inner').length).toBeFalsy(); jest.useRealTimers(); }); it('props#onOpen and props#onClose do not warn anymore', () => { const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); const onOpen = jest.fn(); const onClose = jest.fn(); mount( // @ts-ignore <Menu defaultOpenKeys={['1']} mode="inline" onOpen={onOpen} onClose={onClose}> <SubMenu key="1" title="submenu1"> <Menu.Item key="submenu1">Option 1</Menu.Item> <Menu.Item key="submenu2">Option 2</Menu.Item> </SubMenu> <Menu.Item key="2">menu2</Menu.Item> </Menu>, ); expect(errorSpy.mock.calls.length).toBe(1); expect(errorSpy.mock.calls[0][0]).not.toContain( '`onOpen` and `onClose` are removed, please use `onOpenChange` instead, see: https://u.ant.design/menu-on-open-change.', ); expect(onOpen).not.toHaveBeenCalled(); expect(onClose).not.toHaveBeenCalled(); }); // https://github.com/ant-design/ant-design/issues/18825 // https://github.com/ant-design/ant-design/issues/8587 it('should keep selectedKeys in state when collapsed to 0px', () => { jest.useFakeTimers(); const wrapper = mount( <Menu mode="inline" inlineCollapsed={false} defaultSelectedKeys={['1']} // @ts-ignore collapsedWidth={0} openKeys={['3']} > <Menu.Item key="1">Option 1</Menu.Item> <Menu.Item key="2">Option 2</Menu.Item> <Menu.SubMenu key="3" title="Option 3"> <Menu.Item key="4">Option 4</Menu.Item> </Menu.SubMenu> </Menu>, ); expect(wrapper.find('li.fishd-menu-item-selected').getDOMNode().textContent).toBe('Option 1'); wrapper.find('li.fishd-menu-item').at(1).simulate('click'); expect(wrapper.find('li.fishd-menu-item-selected').getDOMNode().textContent).toBe('Option 2'); wrapper.setProps({ inlineCollapsed: true }); act(() => { jest.runAllTimers(); wrapper.update(); }); expect( wrapper .find('PopupTrigger') .map(node => node.prop('popupVisible')) .findIndex(node => !!node), ).toBe(-1); wrapper.setProps({ inlineCollapsed: false }); expect(wrapper.find('li.fishd-menu-item-selected').getDOMNode().textContent).toBe('Option 2'); jest.useRealTimers(); }); it('Menu.Item with icon children auto wrap span', () => { const wrapper = mount( <Menu> <Menu.Item key="1" icon={<Icon type="Settingx" />}> Navigation One </Menu.Item> <Menu.Item key="2" icon={<Icon type="Settingx" />}> <span>Navigation One</span> </Menu.Item> <Menu.SubMenu key="3" icon={<Icon type="Settingx" />} title="Navigation One" /> <Menu.SubMenu key="4" icon={<Icon type="Settingx" />} title={<span>Navigation One</span>} /> </Menu>, ); expect(wrapper.render()).toMatchSnapshot(); }); // https://github.com/ant-design/ant-design/issues/23755 it('should trigger onOpenChange when collapse inline menu', () => { const onOpenChange = jest.fn(); function App() { const [inlineCollapsed, setInlineCollapsed] = React.useState(false); return ( <> <button type="button" onClick={() => { setInlineCollapsed(!inlineCollapsed); }} > collapse menu </button> <Menu mode="inline" onOpenChange={onOpenChange} inlineCollapsed={inlineCollapsed}> <Menu.SubMenu key="1" title="menu"> <Menu.Item key="1-1">menu</Menu.Item> <Menu.Item key="1-2">menu</Menu.Item> </Menu.SubMenu> </Menu> </> ); } const wrapper = mount(<App />); wrapper.find('button').simulate('click'); expect(onOpenChange).toHaveBeenCalledWith([]); }); it('Use first char as Icon when collapsed', () => { const wrapper = mount( <Menu mode="inline" inlineCollapsed> <Menu.SubMenu title="Light" /> <Menu.Item>Bamboo</Menu.Item> </Menu>, ); expect(wrapper.find('.fishd-menu-inline-collapsed-noicon').first().text()).toEqual('L'); expect(wrapper.find('.fishd-menu-inline-collapsed-noicon').last().text()).toEqual('B'); }); it('divider should show', () => { const wrapper = mount( <Menu mode="vertical"> <SubMenu key="sub1" title="Navigation One"> <Menu.Item key="1">Option 1</Menu.Item> </SubMenu> <Menu.Divider dashed /> <SubMenu key="sub2" title="Navigation Two"> <Menu.Item key="2">Option 2</Menu.Item> </SubMenu> <Menu.Divider /> <SubMenu key="sub4" title="Navigation Three"> <Menu.Item key="3">Option 3</Menu.Item> </SubMenu> </Menu>, ); expect(wrapper.find('li.fishd-menu-item-divider').length).toBe(2); expect(wrapper.find('li.fishd-menu-item-divider-dashed').length).toBe(1); }); });
the_stack
import fs from 'fs'; import { OnRequestFunction } from 'messaging-api-common'; export type ClientConfig = { accessToken: string; appId?: string; appSecret?: string; version?: string; origin?: string; onRequest?: OnRequestFunction; skipAppSecretProof?: boolean; }; /** * Page Scoped User ID (PSID) of the message recipient. */ export type RecipientWithID = { id: string; }; /** * Used for Customer Matching. (Closed Beta) */ export type RecipientWithPhoneNumber = { phoneNumber: string; name?: Record<string, any>; }; /** * Used for the checkbox plugin. */ export type RecipientWithUserRef = { userRef: string; }; /** * Used for Private Replies to reference the visitor post to reply to. */ export type RecipientWithPostId = { postId: string; }; /** * Used for Private Replies to reference the post comment to reply to. */ export type RecipientWithCommentId = { commentId: string; }; /** * Used for the Messenger Platform's One-Time Notification API. */ export type RecipientWithOneTimeNotifToken = { oneTimeNotifToken: string; }; /** * Description of the message recipient. All requests must include one to identify the recipient. */ export type Recipient = | RecipientWithID | RecipientWithPhoneNumber | RecipientWithUserRef | RecipientWithPostId | RecipientWithCommentId | RecipientWithOneTimeNotifToken; /** * Description of the message recipient. If a string is provided, it will be recognized as a psid. */ export type PsidOrRecipient = string | Recipient; export type UrlMediaAttachmentPayload = { url: string; isReusable?: boolean; }; export type AttachmentIdAttachmentPayload = { attachmentId: string; }; export type MediaAttachmentPayload = | UrlMediaAttachmentPayload | AttachmentIdAttachmentPayload; export type MediaAttachmentType = 'audio' | 'video' | 'image' | 'file'; export type FileDataAttachmentPayload = { isReusable?: boolean; }; export type FileDataMediaAttachment = { type: MediaAttachmentType; payload: FileDataAttachmentPayload; }; export type FileDataMediaAttachmentMessage = { attachment: FileDataMediaAttachment; quickReplies?: QuickReply[]; }; export type MediaAttachment = { type: MediaAttachmentType; payload: MediaAttachmentPayload; }; export type TemplateAttachmentPayload = { templateType: | 'button' | 'generic' | 'media' | 'receipt' | 'airline_boardingpass' | 'airline_checkin' | 'airline_itinerary' | 'airline_update' | 'one_time_notif_req'; [key: string]: any; // FIXME: list all of templates }; export type TemplateAttachment = { type: 'template'; payload: TemplateAttachmentPayload; }; export type Attachment = MediaAttachment | TemplateAttachment; export type TextQuickReply = { contentType: 'text'; title: string; payload: string; imageUrl?: string; }; export type UserPhoneNumberQuickReply = { contentType: 'user_phone_number'; }; export type UserEmailQuickReply = { contentType: 'user_email'; }; export type QuickReply = | TextQuickReply | UserPhoneNumberQuickReply | UserEmailQuickReply; export type TextMessage = { text?: string; quickReplies?: QuickReply[]; }; export type AttachmentMessage = { attachment?: Attachment; quickReplies?: QuickReply[]; }; export type Message = TextMessage | AttachmentMessage; export type MessagingType = | 'RESPONSE' | 'UPDATE' | 'MESSAGE_TAG' | 'NON_PROMOTIONAL_SUBSCRIPTION'; export type MessageTag = | 'CONFIRMED_EVENT_UPDATE' | 'POST_PURCHASE_UPDATE' | 'ACCOUNT_UPDATE' | 'HUMAN_AGENT'; export type InsightMetric = | 'page_messages_blocked_conversations_unique' | 'page_messages_reported_conversations_unique' | 'page_messages_total_messaging_connections' | 'page_messages_new_conversations_unique'; export type InsightOptions = { since?: number; until?: number; }; export type SendOption = { messagingType?: MessagingType; tag?: MessageTag; quickReplies?: QuickReply[]; personaId?: string; }; export type SenderActionOption = { personaId?: string; }; export type UploadOption = { filename?: string; isReusable?: boolean; }; export type TemplateButton = { type: string; title: string; url?: string; payload?: string; webviewHeightRatio?: 'compact' | 'tall' | 'full'; }; export type MenuItem = TemplateButton; export type TemplateElement = { title: string; imageUrl?: string; subtitle?: string; defaultAction?: { type: string; url: string; messengerExtensions?: boolean; webviewHeightRatio?: string; fallbackUrl?: string; }; buttons?: TemplateButton[]; }; export type MediaElement = { mediaType: 'image' | 'video'; attachmentId?: string; url?: string; buttons?: TemplateButton[]; }; export type Address = { street1: string; street2?: string; city: string; postalCode: string; state: string; country: string; }; export type Summary = { subtotal?: number; shippingCost?: number; totalTax?: number; totalCost: number; }; export type Adjustment = { name?: string; amount?: number; }; export type ReceiptElement = { title: string; subtitle?: string; quantity?: number; price: number; currency?: string; imageUrl: string; }; export type ReceiptAttributes = { recipientName: string; merchantName?: string; orderNumber: string; // must be unique currency: string; paymentMethod: string; timestamp?: string; orderUrl?: string; elements?: ReceiptElement[]; address?: Address; summary: Summary; adjustments?: Adjustment[]; }; export type Airport = { airportCode: string; city: string; terminal?: string; gate?: string; }; export type FlightSchedule = { boardingTime?: string; departureTime: string; arrivalTime?: string; }; export type FlightInfo = { connectionId: string; segmentId: string | PassengerSegmentInfo; flightNumber: string; aircraftType?: string; departureAirport: Airport; arrivalAirport: Airport; flightSchedule: FlightSchedule; travelClass: 'economy' | 'business' | 'first_class'; }; export type Field = { label: string; value: string; }; export type BoardingPass = { passengerName: string; pnrNumber: string; travelClass?: string; seat?: string; auxiliaryFields?: Field[]; secondaryFields?: Field[]; logoImageUrl: string; headerImageUrl?: string; headerTextField?: Field; qrCode?: string; // FIXME: qr_code or barcode_image_url barcodeImageUrl?: string; aboveBarCodeImageUrl: string; flightInfo: FlightInfo; }; export type AirlineBoardingPassAttributes = { introMessage: string; locale: string; boardingPass: BoardingPass[]; }; export type PassengerInfo = { passengerId: string; ticketNumber?: string; name: string; }; export type ProductInfo = { title: string; value: string; }; export type PassengerSegmentInfo = { segmentId: string; passengerId: string; seat: string; seatType: string; productInfo?: ProductInfo[]; }; export type PriceInfo = { title: string; amount: string; currency?: string; }; export type AirlineCheckinAttributes = { introMessage: string; locale: string; pnrNumber?: string; checkinUrl: string; flightInfo: FlightInfo[]; }; export type AirlineItineraryAttributes = { introMessage: string; locale: string; themeColor?: string; pnrNumber: string; passengerInfo: PassengerInfo[]; flightInfo: FlightInfo[]; passengerSegmentInfo: PassengerSegmentInfo[]; priceInfo?: PriceInfo[]; basePrice?: string; tax?: string; totalPrice: string; currency: string; }; export type UpdateFlightInfo = { flightNumber: string; departureAirport: Airport; arrivalAirport: Airport; flightSchedule: FlightSchedule; }; export type AirlineUpdateAttributes = { introMessage: string; themeColor?: string; updateType: 'delay' | 'gate_change' | 'cancellation'; locale: string; pnrNumber?: string; updateFlightInfo: UpdateFlightInfo; }; export type OneTimeNotifReqAttributes = { title: string; payload: string; }; export type SenderAction = 'mark_seen' | 'typing_on' | 'typing_off'; /** * Fields can be retrieved from a person's profile information */ export type UserProfileField = // Granted by default | 'id' | 'name' | 'first_name' | 'last_name' | 'profile_pic' // Needs approval by Facebook | 'locale' | 'timezone' | 'gender'; /** * The User Profile API allows you to use a Page-scoped ID (PSID) to retrieve user profile information in this format */ export type User = { id: string; name: string; firstName: string; lastName: string; profilePic: string; locale?: string; timezone?: number; gender?: string; }; export type PersistentMenuItem = { locale: string; composerInputDisabled: boolean; callToActions: MenuItem[]; }; export type PersistentMenu = PersistentMenuItem[]; export type GreetingConfig = { locale: string; text: string; }; export type IceBreaker = { question: string; payload: string; }; export type UserPersistentMenu = { userLevelPersistentMenu?: PersistentMenu; pageLevelPersistentMenu?: PersistentMenu; }; export type MessengerProfile = { getStarted?: { payload: string; }; persistentMenu?: PersistentMenu; greeting?: { locale: string; text: string; }[]; iceBreakers?: IceBreaker[]; whitelistedDomains?: string[]; accountLinkingUrl?: string; paymentSettings?: { privacyUrl?: string; publicKey?: string; testUsers?: string[]; }; homeUrl?: { url: string; webviewHeightRatio: 'tall'; webviewShareButton?: 'hide' | 'show'; inTest: boolean; }; }; export type MessengerProfileResponse = { data: MessengerProfile[]; }; export type MutationSuccessResponse = { result: string; }; export type SendMessageSuccessResponse = { recipientId: string; messageId: string; }; export type SendSenderActionResponse = { recipientId: string; }; export type MessageTagResponse = { tag: MessageTag; description: string; }[]; export type FileData = Buffer | fs.ReadStream; export type BatchRequestOptions = { name?: string; dependsOn?: string; omitResponseOnSuccess?: boolean; }; export type Model = | 'CUSTOM' | 'CHINESE' | 'CROATIAN' | 'DANISH' | 'DUTCH' | 'ENGLISH' | 'FRENCH_STANDARD' | 'GERMAN_STANDARD' | 'HEBREW' | 'HUNGARIAN' | 'IRISH' | 'ITALIAN_STANDARD' | 'KOREAN' | 'NORWEGIAN_BOKMAL' | 'POLISH' | 'PORTUGUESE' | 'ROMANIAN' | 'SPANISH' | 'SWEDISH' | 'VIETNAMESE'; export type MessengerNLPConfig = { nlpEnabled?: boolean; model?: Model; customToken?: string; verbose?: boolean; nBest?: number; }; export type PageInfo = { name: string; id: string; }; type Scope = string; export type TokenInfo = { appId: string; type: 'PAGE' | 'APP' | 'USER'; application: string; dataAccessExpiresAt: number; expiresAt: number; isValid: true; issuedAt?: number; profileId: string; scopes: Scope[]; userId: string; }; export type MessagingFeatureReview = { feature: string; status: 'pending' | 'rejected' | 'approved' | 'limited'; }; export type Persona = { name: string; profilePictureUrl: string; }; export type SubscriptionFields = { name: string; version: string; }; export type MessengerSubscription = { object: string; callbackUrl: string; active: boolean; fields: SubscriptionFields[]; }; export type BatchItem = { method: string; relativeUrl: string; name?: string; body?: Record<string, any>; responseAccessPath?: string; } & BatchRequestOptions;
the_stack
import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { Flow, IFlow } from 'app/shared/model/flow.model'; import { Endpoint, EndpointType } from 'app/shared/model/endpoint.model'; import { FlowService } from './flow.service'; import { EndpointService } from '../endpoint'; import { SecurityService } from '../security'; import { JhiEventManager } from 'ng-jhipster'; import { LoginModalService } from 'app/core'; import { NavigationEnd, Router } from '@angular/router'; import * as moment from 'moment'; import { forkJoin, Observable, Observer, Subscription } from 'rxjs'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { FlowDeleteDialogComponent } from 'app/entities/flow'; enum Status { active = 'active', paused = 'paused', inactive = 'inactive', inactiveError = 'inactiveError' } @Component({ selector: '[jhi-flow-row]', templateUrl: './flow-row.component.html' }) export class FlowRowComponent implements OnInit, OnDestroy { sslUrl: any; mySubscription: Subscription; @Input() flow: Flow; //@Input() fromEndpoints: Endpoint[]; @Input() isAdmin: boolean; endpoints: Array<Endpoint> = [new Endpoint()]; fromEndpoint: Array<Endpoint> = []; toEndpoints: Array<Endpoint> = []; errorEndpoint: Endpoint = new Endpoint(); responseEndpoints: Array<Endpoint> = []; public isFlowStarted: boolean; public isFlowRestarted: boolean; public isFlowPaused: boolean; public isFlowResumed: boolean; public isFlowStopped: boolean; public disableActionBtns: boolean; public flowDetails: string; public flowStatus: string; public flowStatusError: string; public isFlowStatusOK: boolean; public flowStatistic: string; public flowStatusButton: string; public flowStartTime: any; public clickButton = false; public flowAlerts: string; public flowAlertsButton: string; public numberOfAlerts: any; public showNumberOfItems: number; fromEndpointTooltips: Array<string> = []; toEndpointsTooltips: Array<string> = []; errorEndpointTooltip: string; responseEndpointTooltips: Array<string> = []; public statusFlow: Status; public previousState: string; public p = false; lastError: string; flowRowID: string; flowRowErrorEndpointID: string; statsTableRows: Array<string> = []; intervalTime: any; stompClient = null; subscriber = null; connection: Promise<any>; connectedPromise: any; listener: Observable<any>; listenerObserver: Observer<any>; alreadyConnectedOnce = false; private subscription: Subscription; modalRef: NgbModalRef | null; constructor( private flowService: FlowService, private endpointService: EndpointService, private securityService: SecurityService, private loginModalService: LoginModalService, private modalService: NgbModal, private router: Router, private eventManager: JhiEventManager ) { this.listener = this.createListener(); this.router.routeReuseStrategy.shouldReuseRoute = function() { return false; }; this.mySubscription = this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { // Trick the Router into believing it's last link wasn't previously loaded this.router.navigated = false; } }); } ngOnInit() { this.setFlowStatusDefaults(); this.getStatus(this.flow.id); this.endpoints = this.flow.endpoints; this.getEndpoints(); this.registerTriggeredAction(); } ngAfterViewInit() { this.connection = this.flowService.connectionStomp(); this.stompClient = this.flowService.client(); this.subscribe('alert'); this.subscribe('event'); this.receive().subscribe(data => { const data2 = data.split(':'); if (Array.isArray(data2) || data2.length) { if (data2[0] === 'event') { this.setFlowStatus(data2[1]); } else if (data2[0] === 'alert') { const alertId = Number(data2[1]); if (this.flow.id === alertId) { this.getFlowNumberOfAlerts(alertId); } } } }); } ngOnDestroy() { this.flowService.unsubscribe(); if (this.mySubscription) { this.mySubscription.unsubscribe(); } } getStatus(id: number) { this.clickButton = true; forkJoin(this.flowService.getFlowStatus(id), this.flowService.getFlowNumberOfAlerts(id)).subscribe( ([flowStatus, flowAlertsNumber]) => { if (flowStatus.body != 'unconfigured') { this.setFlowStatus(flowStatus.body); } this.setFlowNumberOfAlerts(flowAlertsNumber.body); } ); } setFlowStatusDefaults() { this.isFlowStatusOK = true; this.flowStatus = 'unconfigured'; this.lastError = ''; this.setFlowStatus(this.flowStatus); } getFlowStatus(id: number) { this.clickButton = true; this.flowService.getFlowStatus(id).subscribe(response => { this.setFlowStatus(response.body); }); } setFlowStatus(status: string): void { switch (status) { case 'unconfigured': this.statusFlow = Status.inactive; this.isFlowStarted = this.isFlowPaused = false; this.isFlowStopped = this.isFlowRestarted = this.isFlowResumed = true; this.flowStatusButton = ` Last action: - <br/> Status: Flow is stopped<br/> `; break; case 'started': this.statusFlow = Status.active; this.isFlowPaused = this.isFlowStopped = this.isFlowRestarted = false; this.isFlowStarted = this.isFlowResumed = true; this.flowStatusButton = ` Last action: Start <br/> Status: Started succesfullly `; break; case 'suspended': this.statusFlow = Status.paused; this.isFlowResumed = this.isFlowStopped = this.isFlowRestarted = false; this.isFlowPaused = this.isFlowStarted = true; this.flowStatusButton = ` Last action: Pause <br/> Status: Paused succesfully `; break; case 'restarted': this.statusFlow = Status.active; this.isFlowPaused = this.isFlowStopped = this.isFlowRestarted = false; this.isFlowResumed = this.isFlowStarted = true; this.flowStatusButton = ` Last action: Restart <br/> Status: Restarted succesfully `; break; case 'resumed': this.statusFlow = Status.active; this.isFlowPaused = this.isFlowStopped = this.isFlowRestarted = false; this.isFlowResumed = this.isFlowStarted = true; this.flowStatusButton = ` Last action: Resume <br/> Status: Resumed succesfully `; break; case 'stopped': this.statusFlow = Status.inactive; this.isFlowStarted = this.isFlowPaused = false; this.isFlowStopped = this.isFlowRestarted = this.isFlowResumed = true; this.flowStatusButton = ` Last action: Stop <br/> Status: Stopped succesfully `; break; default: this.flowStatusButton = ` Last action: ${this.flowStatus} <br/> Status: Stopped after error `; break; } } getFlowAlerts(id: number) { this.clickButton = true; this.flowService.getFlowAlerts(id).subscribe(response => { this.setFlowAlerts(response.body); }); } setFlowAlerts(flowAlertsItems: string): void { if (flowAlertsItems !== null) { let alertStartItem; let alertEndItem; let flowAlertsList = flowAlertsItems.split(','); if (flowAlertsList.length < 4) { this.showNumberOfItems = flowAlertsList.length; alertStartItem = flowAlertsList.length - 1; alertEndItem = 0; } else { this.showNumberOfItems = 3; alertStartItem = flowAlertsList.length - 1; alertEndItem = flowAlertsList.length - 3; } let i; let alertItems = ''; for (i = alertStartItem; i >= alertEndItem; i--) { alertItems += `<a class="list-group-item"><h5 class="mb-1">` + flowAlertsList[i] + `</h5></a>`; } this.flowAlertsButton = `<div class="list-group">` + alertItems + `</div>`; } else { this.flowAlertsButton = `Can't retrieve alert details`; } } getFlowNumberOfAlerts(id: number) { this.clickButton = true; this.flowService.getFlowNumberOfAlerts(id).subscribe(response => { this.setFlowNumberOfAlerts(response.body); }); } setFlowNumberOfAlerts(numberOfAlerts: string): void { let numberOfAlerts2 = parseInt(numberOfAlerts, 10); if (numberOfAlerts2 === 0) { this.flowAlerts = `false`; this.numberOfAlerts = `0`; this.showNumberOfItems = 3; } else { this.flowAlerts = `true`; this.numberOfAlerts = numberOfAlerts; if (numberOfAlerts2 < 4) { this.showNumberOfItems = numberOfAlerts.length; } else { this.showNumberOfItems = 3; } } } navigateToFlow(action: string) { switch (action) { case 'edit': this.isAdmin ? this.router.navigate(['../../flow/edit-all', this.flow.id, { mode: 'edit' }]) : this.router.navigate(['../flow', this.flow.id]); break; case 'clone': this.isAdmin ? this.router.navigate(['../../flow/edit-all', this.flow.id, { mode: 'clone' }]) : this.router.navigate(['../flow', this.flow.id]); break; case 'delete': if (this.isAdmin) { let modalRef = this.modalService.open(FlowDeleteDialogComponent as any); if (typeof FlowDeleteDialogComponent as Component) { modalRef.componentInstance.flow = this.flow; modalRef.result.then( result => { this.eventManager.broadcast({ name: 'flowDeleted', content: this.flow }); modalRef = null; }, reason => { this.eventManager.broadcast({ name: 'flowDeleted', content: this.flow }); modalRef = null; } ); } } else { this.router.navigate(['../flow', this.flow.id]); } //this.router.navigate([{ outlets: { popup: 'flow/' + this.flow.id + '/delete' } }], { replaceUrl: true, queryParamsHandling: 'merge' }) : //this.router.navigate(['../flow', this.flow.id]); break; default: break; } } navigateToEndpoint(endpoint: Endpoint) { this.isAdmin ? this.router.navigate(['../../flow/edit-all', this.flow.id], { queryParams: { mode: 'edit', endpointid: endpoint.id } }) : this.router.navigate(['../flow', this.flow.id]); } getFlowLastError(id: number, action: string, errMessage: string) { if (errMessage) { if (errMessage.startsWith('Full authentication is required to access this resource', 0)) { this.loginModalService.open(); } else { this.flowStatusButton = ` Last action: ${action} <br/> Status: Stopped after error <br/><br/> ${errMessage} `; this.statusFlow = Status.inactiveError; } } else { this.flowService.getFlowLastError(id).subscribe(response => { this.lastError = response === '0' ? '' : response.body; this.flowStatusButton = ` Last action: ${action} <br/> Status: Stopped after error <br/><br/> ${this.lastError} `; this.statusFlow = Status.inactiveError; }); } } getFlowStats(flow: IFlow) { this.startGetFlowStats(flow); //refresh every 5 seconds this.intervalTime = setInterval(() => { this.startGetFlowStats(flow); }, 5000); } startGetFlowStats(flow: IFlow) { this.flowStatistic = ``; this.statsTableRows = []; for (let endpoint of flow.endpoints) { if (endpoint.endpointType === EndpointType.FROM) { this.flowService.getFlowStats(flow.id, endpoint.id, flow.gatewayId).subscribe(res => { this.setFlowStatistic(res.body, endpoint.componentType.toString() + '://' + endpoint.uri); }); } } } stopGetFlowStats() { clearInterval(this.intervalTime); } getFlowDetails() { const createdFormatted = moment(this.flow.created).format('YYYY-MM-DD HH:mm:ss'); const lastModifiedFormatted = moment(this.flow.lastModified).format('YYYY-MM-DD HH:mm:ss'); this.flowDetails = ` <b>ID:</b> ${this.flow.id}<br/> <b>Name:</b> ${this.flow.name}<br/> <b>Version:</b> ${this.flow.version}<br/><br/> <b>Created:</b> ${createdFormatted}<br/> <b>Last modified:</b> ${lastModifiedFormatted}<br/><br/> <b>Autostart:</b> ${this.flow.autoStart}<br/> <b>Offloading:</b> ${this.flow.offLoading}<br/><br/> <b>Maximum Redeliveries:</b> ${this.flow.maximumRedeliveries}<br/> <b>Redelivery Delay:</b> ${this.flow.redeliveryDelay}<br/> <b>Log Level:</b> ${this.flow.logLevel}<br/> `; } setFlowStatistic(res, uri) { /* Example Available stats * * "maxProcessingTime": 1381, "lastProcessingTime": 1146, "meanProcessingTime": 1262, "lastExchangeFailureExchangeId": "", "firstExchangeFailureTimestamp": "1970-01-01T00:59:59.999+0100", "firstExchangeCompletedExchangeId": "ID-win81-1553585873482-0-1", "lastExchangeCompletedTimestamp": "2019-03-26T08:44:04.510+0100", "exchangesCompleted": 3, "deltaProcessingTime": -114, "firstExchangeCompletedTimestamp": "2019-03-26T08:44:01.955+0100", "externalRedeliveries": 0, "firstExchangeFailureExchangeId": "", "lastExchangeCompletedExchangeId": "ID-win81-1553585873482-0-9", "lastExchangeFailureTimestamp": "1970-01-01T00:59:59.999+0100", "exchangesFailed": 0, "redeliveries": 0, "minProcessingTime": 1146, "resetTimestamp": "2019-03-26T08:43:59.201+0100", "failuresHandled": 3, "totalProcessingTime": 3787, "startTimestamp": "2019-03-26T08:43:59.201+0100" */ if (res === 0) { this.flowStatistic = `Currently there are no statistics for this flow.`; } else { const now = moment(new Date()); const start = moment(res.stats.startTimestamp); const flowRuningTime = moment.duration(now.diff(start)); const hours = Math.floor(flowRuningTime.asHours()); const minutes = flowRuningTime.minutes(); const completed = res.stats.exchangesCompleted - res.stats.failuresHandled; const failures = res.stats.exchangesFailed + res.stats.failuresHandled; let processingTime = ``; if (this.statsTableRows.length === 0) { this.statsTableRows[0] = `<td>${uri}</td>`; this.statsTableRows[1] = `<td>${this.checkDate(res.stats.startTimestamp)}</td>`; this.statsTableRows[2] = `<td>${hours} hours ${minutes} ${minutes > 1 ? 'minutes' : 'minute'}</td>`; this.statsTableRows[3] = `<td>${this.checkDate(res.stats.firstExchangeCompletedTimestamp)}</td>`; this.statsTableRows[4] = `<td>${this.checkDate(res.stats.lastExchangeCompletedTimestamp)}</td>`; this.statsTableRows[5] = `<td>${completed}</td>`; this.statsTableRows[6] = `<td>${failures}</td>`; this.statsTableRows[7] = `<td>${res.stats.minProcessingTime} ms</td>`; this.statsTableRows[8] = `<td>${res.stats.maxProcessingTime} ms</td>`; this.statsTableRows[9] = `<td>${res.stats.meanProcessingTime} ms</td>`; } else { this.statsTableRows[0] = this.statsTableRows[0] + `<td>${uri}</td>`; this.statsTableRows[1] = this.statsTableRows[1] + `<td>${this.checkDate(res.stats.startTimestamp)}</td>`; this.statsTableRows[2] = this.statsTableRows[2] + `<td>${hours} hours ${minutes} ${minutes > 1 ? 'minutes' : 'minute'}</td>`; this.statsTableRows[3] = this.statsTableRows[3] + `<td>${this.checkDate(res.stats.firstExchangeCompletedTimestamp)}</td>`; this.statsTableRows[4] = this.statsTableRows[4] + `<td>${this.checkDate(res.stats.lastExchangeCompletedTimestamp)}</td>`; this.statsTableRows[5] = this.statsTableRows[5] + `<td>${completed}</td>`; this.statsTableRows[6] = this.statsTableRows[6] + `<td>${failures}</td>`; this.statsTableRows[7] = this.statsTableRows[7] + `<td>${res.stats.minProcessingTime} ms</td>`; this.statsTableRows[8] = this.statsTableRows[8] + `<td>${res.stats.maxProcessingTime} ms</td>`; this.statsTableRows[9] = this.statsTableRows[9] + `<td>${res.stats.meanProcessingTime} ms</td>`; } if (res.stats.lastProcessingTime > 0) { processingTime = `<tr> <th scope="row">Min</th> ${this.statsTableRows[7]} </tr> <tr> <th scope="row">Max</th> ${this.statsTableRows[8]} </tr> <tr> <th scope="row">Average</th> ${this.statsTableRows[9]} </tr>`; } this.flowStatistic = ` <div class="col-12"> <table class="table"> <tbody> <tr> <th scope="row">Endpoint</th> ${this.statsTableRows[0]} </tr> <tr> <th scope="row">Start time</th> ${this.statsTableRows[1]} </tr> <tr> <th scope="row">Running</th> ${this.statsTableRows[2]} </tr> <tr> <th scope="row">First Message</th> ${this.statsTableRows[3]} </tr> <tr> <th scope="row">Last Message</th> ${this.statsTableRows[4]} </tr>` + processingTime + ` <tr> <th scope="row">Completed</th> ${this.statsTableRows[5]} </tr> <tr> <th scope="row">Failed</th> ${this.statsTableRows[6]} </tr> </tbody> </table> <div> `; } } checkDate(r) { if (!!r) { return moment(r).format('YYYY-MM-DD HH:mm:ss'); } else { return '-'; } } flowConfigurationNotObtained(id) { this.isFlowStatusOK = false; this.flowStatusError = `Configuration for flow with id=${id} is not obtained.`; } getEndpoints() { this.endpoints.forEach(endpoint => { if (endpoint.endpointType.valueOf() === 'FROM') { this.fromEndpoint.push(endpoint); this.fromEndpointTooltips.push(this.endpointTooltip(endpoint.componentType, endpoint.uri, endpoint.options)); } else if (endpoint.endpointType.valueOf() === 'TO') { this.toEndpoints.push(endpoint); this.toEndpointsTooltips.push(this.endpointTooltip(endpoint.componentType, endpoint.uri, endpoint.options)); } else if (endpoint.endpointType.valueOf() === 'ERROR') { this.errorEndpoint = endpoint; this.errorEndpointTooltip = this.endpointTooltip(endpoint.componentType, endpoint.uri, endpoint.options); } else if (endpoint.endpointType.valueOf() === 'RESPONSE') { this.responseEndpoints.push(endpoint); this.responseEndpointTooltips.push(this.endpointTooltip(endpoint.componentType, endpoint.uri, endpoint.options)); } }); } getSSLUrl(type: String, uri: String, options: String) { var hostname; switch (type) { case 'FTPS': if (uri.includes('@')) { uri = uri.substring(uri.indexOf('@') + 1); } hostname = new URL('https://' + uri).hostname; this.sslUrl = 'https://' + hostname; break; case 'HTTPS': hostname = new URL('https://' + uri).hostname; this.sslUrl = 'https://' + hostname; break; case 'IMAPS': if (uri.includes('@')) { uri = uri.substring(uri.indexOf('@') + 1); } hostname = new URL('https://' + uri).hostname; this.sslUrl = 'https://' + hostname; break; case 'KAFKA': if (options.includes(',')) { options = options.substring(options.lastIndexOf('brokers=') + 1, options.lastIndexOf(',')); } else { options = options.substring(uri.indexOf(',') + 1); } hostname = new URL('https://' + options).hostname; this.sslUrl = 'https://' + hostname; break; case 'NETTY4': hostname = new URL('https://' + uri).hostname; this.sslUrl = 'https://' + hostname; break; case 'SMTPS': if (uri.includes('@')) { uri = uri.substring(uri.indexOf('@') + 1); } hostname = new URL('https://' + uri).hostname; this.sslUrl = 'https://' + hostname; break; default: this.sslUrl = `0`; break; } return this.sslUrl; } endpointTooltip(type, uri, options): string { if (type === null) { return; } const opt = options === '' ? '' : `?${options}`; return `${type.toLowerCase()}://${uri}${opt}`; } curentDateTime(): string { return moment().format('YYYY-MM-DD HH:mm:ss'); } registerTriggeredAction() { this.eventManager.subscribe('trigerAction', response => { switch (response.content) { case 'start': if (this.statusFlow === Status.inactive) { this.start(); } break; case 'stop': if (this.statusFlow === Status.active || this.statusFlow === Status.paused) { this.stop(); } break; case 'pause': if (this.statusFlow === Status.active) { this.pause(); } break; case 'restart': if (this.statusFlow === Status.active) { this.restart(); } break; case 'resume': if (this.statusFlow === Status.paused) { this.resume(); } break; default: break; } }); } start() { this.flowStatus = 'Starting'; this.isFlowStatusOK = true; this.disableActionBtns = true; this.flowService.getConfiguration(this.flow.id).subscribe( data => { this.flowService.setConfiguration(this.flow.id, data.body, 'true').subscribe(data2 => { this.flowService.start(this.flow.id).subscribe( response => { if (response.status === 200) { //this.setFlowStatus('started'); } this.disableActionBtns = false; }, err => { this.getFlowLastError(this.flow.id, 'Start', err.error); this.isFlowStatusOK = false; this.flowStatusError = `Flow with id=${this.flow.id} is not started.`; this.disableActionBtns = false; } ); }); }, err => { this.getFlowLastError(this.flow.id, 'Start', err.error); this.isFlowStatusOK = false; this.flowStatusError = `Flow with id=${this.flow.id} is not started.`; this.flowConfigurationNotObtained(this.flow.id); this.disableActionBtns = false; } ); } pause() { this.flowStatus = 'Pausing'; this.isFlowStatusOK = true; this.disableActionBtns = true; this.flowService.pause(this.flow.id).subscribe( response => { if (response.status === 200) { // this.setFlowStatus('suspended'); } this.disableActionBtns = false; }, err => { this.getFlowLastError(this.flow.id, 'Pause', err.error); this.isFlowStatusOK = false; this.flowStatusError = `Flow with id=${this.flow.id} is not paused.`; this.disableActionBtns = false; } ); } resume() { this.flowStatus = 'Resuming'; this.isFlowStatusOK = true; this.disableActionBtns = true; this.flowService.getConfiguration(this.flow.id).subscribe( data => { this.flowService.setConfiguration(this.flow.id, data.body, 'true').subscribe(data2 => { this.flowService.resume(this.flow.id).subscribe( response => { if (response.status === 200) { // this.setFlowStatus('resumed'); } this.disableActionBtns = false; }, err => { this.getFlowLastError(this.flow.id, 'Resume', err.error); this.isFlowStatusOK = false; this.flowStatusError = `Flow with id=${this.flow.id} is not resumed.`; this.disableActionBtns = false; } ); }); }, err => { this.flowConfigurationNotObtained(this.flow.id); this.disableActionBtns = false; } ); } restart() { this.flowStatus = 'Restarting'; this.isFlowStatusOK = true; this.disableActionBtns = true; this.flowService.getConfiguration(this.flow.id).subscribe( data => { this.flowService.setConfiguration(this.flow.id, data.body, 'true').subscribe(data2 => { this.flowService.restart(this.flow.id).subscribe( response => { if (response.status === 200) { // this.setFlowStatus('restarted'); } this.disableActionBtns = false; }, err => { this.getFlowLastError(this.flow.id, 'Restart', err.error); this.isFlowStatusOK = false; this.flowStatusError = `Flow with id=${this.flow.id} is not restarted.`; this.disableActionBtns = false; } ); }); }, err => { this.flowConfigurationNotObtained(this.flow.id); this.disableActionBtns = false; } ); } stop() { this.flowStatus = 'Stopping'; this.isFlowStatusOK = true; this.disableActionBtns = true; this.flowService.stop(this.flow.id).subscribe( response => { if (response.status === 200) { // this.setFlowStatus('stopped'); } this.disableActionBtns = false; }, err => { this.getFlowLastError(this.flow.id, 'Stop', err.error); this.isFlowStatusOK = false; this.flowStatusError = `Flow with id=${this.flow.id} is not stopped.`; this.disableActionBtns = false; } ); } receive() { return this.listener; } subscribe(type) { const topic = '/topic/' + this.flow.id + '/' + type; this.connection.then(() => { this.subscriber = this.stompClient.subscribe(topic, data => { if (!this.listenerObserver) { this.listener = this.createListener(); } this.listenerObserver.next(data.body); }); }); } unsubscribe() { if (this.subscriber !== null) { this.subscriber.unsubscribe(); } this.listener = this.createListener(); } private createListener(): Observable<any> { return new Observable(observer => { this.listenerObserver = observer; }); } }
the_stack
import * as https from "https"; import Long from "long"; import * as PromisePool from "promise-pool-executor"; import { Readable } from "stream"; import { Credentials } from "df/api/commands/credentials"; import { IDbAdapter, IDbClient, OnCancel } from "df/api/dbadapters/index"; import { parseSnowflakeEvalError } from "df/api/utils/error_parsing"; import { LimitedResultSet } from "df/api/utils/results"; import { ErrorWithCause } from "df/common/errors/errors"; import { Flags } from "df/common/flags"; import { collectEvaluationQueries, QueryOrAction } from "df/core/adapters"; import { dataform } from "df/protos/ts"; const HEARTBEAT_INTERVAL_SECONDS = 30; const flags = { snowflakeLogLevel: Flags.string("snowflake-log-level", "info"), snowflakeUseOcsp: Flags.boolean("snowflake-use-ocsp", true) }; // This is horrible. However, it allows us to set the 'APPLICATION' parameter on client.environment, // which is passed all the way through to Snowflake's connection code. Pending a fix for // https://github.com/snowflakedb/snowflake-connector-nodejs/issues/100, this is the only way // we can achieve that. // tslint:disable-next-line: no-var-requires const snowflake = require("snowflake-sdk/lib/core")({ httpClientClass: require("snowflake-sdk/lib/http/node"), loggerClass: require("snowflake-sdk/lib/logger/node"), client: { version: require("snowflake-sdk/lib/util").driverVersion, environment: { ...process.versions, APPLICATION: "Dataform" } } }) as ISnowflake; snowflake.configure({ logLevel: flags.snowflakeLogLevel.get(), insecureConnect: !flags.snowflakeUseOcsp.get() }); interface ISnowflake { configure: (options: { logLevel?: string; insecureConnect?: boolean }) => void; createConnection: (options: { account: string; username: string; password: string; database: string; warehouse: string; role: string; clientSessionKeepAlive: boolean; clientSessionKeepAliveHeartbeatFrequency: number; }) => ISnowflakeConnection; } interface ISnowflakeConnection { connect: (callback: (err: any, connection: ISnowflakeConnection) => void) => void; execute: (options: { sqlText: string; binds?: any[]; streamResult?: boolean; complete: (err: any, statement: ISnowflakeStatement, rows: any[]) => void; }) => ISnowflakeStatement; destroy: (err: any) => void; } interface ISnowflakeStatement { cancel: (err: any) => void; streamRows: (options?: { start?: number; end?: number }) => Readable; } export class SnowflakeDbAdapter implements IDbAdapter { public static async create(credentials: Credentials, options?: { concurrencyLimit?: number }) { const connection = await connect(credentials as dataform.ISnowflake); return new SnowflakeDbAdapter(connection, options); } // Unclear exactly what snowflakes limit's are here, we can experiment with increasing this. private pool: PromisePool.PromisePoolExecutor; constructor( private readonly connection: ISnowflakeConnection, options?: { concurrencyLimit?: number } ) { this.pool = new PromisePool.PromisePoolExecutor({ concurrencyLimit: options?.concurrencyLimit || 10, frequencyWindow: 1000, frequencyLimit: 10 }); } public async execute( sqlText: string, options: { binds?: any[]; onCancel?: OnCancel; rowLimit?: number; byteLimit?: number; } = { rowLimit: 1000, byteLimit: 1024 * 1024 } ) { return { rows: await this.pool .addSingleTask({ generator: () => new Promise<any[]>((resolve, reject) => { const statement = this.connection.execute({ sqlText, binds: options?.binds, streamResult: true, complete(err, stmt) { if (err) { let message = `Snowflake SQL query failed: ${err.message}.`; if (err.cause) { message += ` Root cause: ${err.cause}`; } reject(new ErrorWithCause(message, err)); return; } const results = new LimitedResultSet({ rowLimit: options?.rowLimit, byteLimit: options?.byteLimit }); const stream = stmt.streamRows(); stream .on("error", e => reject(e)) .on("data", row => { if (!results.push(row)) { stream.destroy(); } }) .on("end", () => resolve(results.rows)) .on("close", () => resolve(results.rows)); } }); options?.onCancel?.(() => { statement.cancel((e: any) => { if (e) { reject(e); } }); }); }) }) .promise(), metadata: {} }; } public async withClientLock<T>(callback: (client: IDbClient) => Promise<T>) { return await callback(this); } public async evaluate(queryOrAction: QueryOrAction) { const validationQueries = collectEvaluationQueries(queryOrAction, false, (query: string) => !!query ? `select system$explain_plan_json($$${query}$$)` : "" ).map((validationQuery, index) => ({ index, validationQuery })); const validationQueriesWithoutWrappers = collectEvaluationQueries(queryOrAction, false); const queryEvaluations = new Array<dataform.IQueryEvaluation>(); for (const { index, validationQuery } of validationQueries) { let evaluationResponse: dataform.IQueryEvaluation = { status: dataform.QueryEvaluation.QueryEvaluationStatus.SUCCESS }; try { await this.execute(validationQuery.query); } catch (e) { evaluationResponse = { status: dataform.QueryEvaluation.QueryEvaluationStatus.FAILURE, error: parseSnowflakeEvalError(e.message) }; } queryEvaluations.push( dataform.QueryEvaluation.create({ ...evaluationResponse, incremental: validationQuery.incremental, query: validationQueriesWithoutWrappers[index].query }) ); } return queryEvaluations; } public async tables(): Promise<dataform.ITarget[]> { const { rows } = await this.execute( ` select table_name, table_schema, table_catalog from information_schema.tables where LOWER(table_schema) != 'information_schema'`, { rowLimit: 10000 } ); return rows.map(row => ({ database: row.TABLE_CATALOG, schema: row.TABLE_SCHEMA, name: row.TABLE_NAME })); } public async search( searchText: string, options: { limit: number } = { limit: 1000 } ): Promise<dataform.ITableMetadata[]> { const results = await this.execute( `select * from ( select tables.table_catalog as table_catalog, tables.table_schema as table_schema, tables.table_name as table_name from information_schema.tables as tables left join information_schema.columns as columns on tables.table_catalog = columns.table_catalog and tables.table_schema = columns.table_schema and tables.table_name = columns.table_name where tables.table_catalog ilike :1 or tables.table_schema ilike :1 or tables.table_name ilike :1 or tables.comment ilike :1 or columns.column_name ilike :1 or columns.comment ilike :1 group by 1, 2, 3 ) where LOWER(table_schema) != 'information_schema' `, { binds: [`%${searchText}%`], rowLimit: options.limit } ); return await Promise.all( results.rows.map(row => this.table({ database: row.TABLE_CATALOG, schema: row.TABLE_SCHEMA, name: row.TABLE_NAME }) ) ); } public async table(target: dataform.ITarget): Promise<dataform.ITableMetadata> { const binds = [target.schema, target.name]; const [tableResults, columnResults] = await Promise.all([ this.execute( ` select table_type, last_altered, comment from ${target.database ? `"${target.database}".` : ""}information_schema.tables where table_schema = :1 and table_name = :2`, { binds } ), this.execute( ` select column_name, data_type, is_nullable, comment from ${target.database ? `"${target.database}".` : ""}information_schema.columns where table_schema = :1 and table_name = :2`, { binds } ) ]); if (tableResults.rows.length === 0) { // The table does not exist. return null; } return dataform.TableMetadata.create({ target, type: tableResults.rows[0].TABLE_TYPE === "VIEW" ? dataform.TableMetadata.Type.VIEW : dataform.TableMetadata.Type.TABLE, fields: columnResults.rows.map(row => dataform.Field.create({ name: row.COLUMN_NAME, primitive: convertFieldType(row.DATA_TYPE), flags: row.DATA_TYPE === "ARRAY" ? [dataform.Field.Flag.REPEATED] : [], description: row.COMMENT }) ), lastUpdatedMillis: Long.fromNumber(tableResults.rows[0].LAST_ALTERED), description: tableResults.rows[0].COMMENT }); } public async preview(target: dataform.ITarget, limitRows: number = 10): Promise<any[]> { const { rows } = await this.execute( `SELECT * FROM "${target.schema}"."${target.name}" LIMIT ${limitRows}` ); return rows; } public async schemas(database: string): Promise<string[]> { const { rows } = await this.execute( `select SCHEMA_NAME from ${database ? `"${database}".` : ""}information_schema.schemata` ); return rows.map(row => row.SCHEMA_NAME); } public async createSchema(database: string, schema: string): Promise<void> { await this.execute( `create schema if not exists ${database ? `"${database}".` : ""}"${schema}"` ); } public async close() { await new Promise((resolve, reject) => { this.connection.destroy((err: any) => { if (err) { reject(err); } else { resolve(); } }); }); } public async setMetadata(action: dataform.IExecutionAction): Promise<void> { const { target, actionDescriptor, tableType } = action; const queries: Array<Promise<any>> = []; if (actionDescriptor.description) { queries.push( this.execute( `comment on ${tableType === "view" ? "view" : "table"} ${ target.database ? `"${target.database}".` : "" }"${target.schema}"."${target.name}" is '${actionDescriptor.description.replace( /'/g, "\\'" )}'` ) ); } if (tableType !== "view" && actionDescriptor.columns?.length > 0) { actionDescriptor.columns .filter(column => column.path.length === 1) .forEach(column => { queries.push( this.execute( `comment if exists on column ${target.database ? `"${target.database}".` : ""}"${ target.schema }"."${target.name}"."${column.path[0]}" is '${column.description.replace( /'/g, "\\'" )}'` ) ); }); } await Promise.all(queries); } } async function connect(snowflakeCredentials: dataform.ISnowflake) { // We are forced to try our own HTTPS connection to the final <accountId>.snowflakecomputing.com URL // in order to verify its certificate. If we don't do this, and pass an invalid account ID (which thus // resolves to an invalid URL) to the snowflake connect() API, snowflake-sdk will not handle the // resulting error correctly (and thus crash this process). await testHttpsConnection(`https://${snowflakeCredentials.accountId}.snowflakecomputing.com`); try { return await new Promise<ISnowflakeConnection>((resolve, reject) => { snowflake .createConnection({ account: snowflakeCredentials.accountId, username: snowflakeCredentials.username, password: snowflakeCredentials.password, database: snowflakeCredentials.databaseName, warehouse: snowflakeCredentials.warehouse, role: snowflakeCredentials.role, clientSessionKeepAlive: true, clientSessionKeepAliveHeartbeatFrequency: HEARTBEAT_INTERVAL_SECONDS }) .connect((err, conn) => { if (err) { reject(err); } else { resolve(conn); } }); }); } catch (e) { throw new ErrorWithCause(`Could not connect to Snowflake: ${e.message}`, e); } } async function testHttpsConnection(url: string) { try { await new Promise<void>((resolve, reject) => { const req = https.request(url); req.on("error", e => { reject(e); }); req.end(() => { resolve(); }); }); } catch (e) { throw new ErrorWithCause(`Could not open HTTPS connection to ${url}.`, e); } } // See https://docs.snowflake.com/en/sql-reference/intro-summary-data-types.html function convertFieldType(type: string) { switch (String(type).toUpperCase()) { case "FLOAT": case "FLOAT4": case "FLOAT8": case "DOUBLE": case "DOUBLE PRECISION": case "REAL": return dataform.Field.Primitive.FLOAT; case "INTEGER": case "INT": case "BIGINT": case "SMALLINT": return dataform.Field.Primitive.INTEGER; case "NUMBER": case "DECIMAL": case "NUMERIC": return dataform.Field.Primitive.NUMERIC; case "BOOLEAN": return dataform.Field.Primitive.BOOLEAN; case "STRING": case "VARCHAR": case "CHAR": case "CHARACTER": case "TEXT": return dataform.Field.Primitive.STRING; case "DATE": return dataform.Field.Primitive.DATE; case "DATETIME": return dataform.Field.Primitive.DATETIME; case "TIMESTAMP": case "TIMESTAMP_LTZ": case "TIMESTAMP_NTZ": case "TIMESTAMP_TZ": return dataform.Field.Primitive.TIMESTAMP; case "TIME": return dataform.Field.Primitive.TIME; case "BINARY": case "VARBINARY": return dataform.Field.Primitive.BYTES; case "VARIANT": case "ARRAY": case "OBJECT": return dataform.Field.Primitive.ANY; case "GEOGRAPHY": return dataform.Field.Primitive.GEOGRAPHY; default: return dataform.Field.Primitive.UNKNOWN; } }
the_stack
import axios from 'axios'; import fs = require('fs'); import path from 'path'; import { GoogleToken } from 'gtoken'; import pLimit from 'p-limit'; import dayjs from 'dayjs'; import Table from 'cli-table3'; import constants = require('../.constants'); var AUTH: any; const FOLDER_TYPE = 'application/vnd.google-apps.folder' let axins = axios.create({}); const RETRY_LIMIT = 5; const FILE_EXCEED_MSG = 'The number of files on your team drive has exceeded the limit (400,000), Please move the folder that has not been copied to another team drive, and then run the copy command to resume the transfer'; const SA_LOCATION = 'accounts'; const SA_BATCH_SIZE = 1000 const SA_FILES: any = constants.USE_SERVICE_ACCOUNT ? fs.readdirSync(path.join(__dirname, '../..', SA_LOCATION)).filter(v => v.endsWith('.json')) : []; SA_FILES.flag = 0 let SA_TOKENS = get_sa_batch() //TODO: Move these to constants.js const PARALLEL_LIMIT = 20 // The number of parallel network requests can be adjusted according to the network environment const PAGE_SIZE = 1000 // Each network request to read the number of files in the directory, the larger the value, the more likely it will time out, and it should not exceed 1000 // How many milliseconds for a single request to time out(Reference value,If continuous timeout, it will be adjusted to twice the previous time) const TIMEOUT_BASE = 7000 // Maximum timeout setting,For example, for a certain request, the first 7s timeout, the second 14s, the third 28s, the fourth 56s, the fifth is not 112s but 60 const TIMEOUT_MAX = 60000 const sleep = (ms: number) => new Promise<void>((resolve, reject) => setTimeout(resolve, ms)); const EXCEED_LIMIT = 7; const FID_TO_NAME: any = {}; export async function real_copy(source: string, target: string, tg?: any) { SA_FILES.flag = 0; // set this to 0 for every new copy async function get_new_root() { const file = await get_info_by_id(source) if (!file) throw new Error(`Unable to access the link, please check if the link is valid and SA has the appropriate permissions:https://drive.google.com/drive/folders/${source}`) return create_folder(file.name, target) } const new_root = await get_new_root() const arr = await walk_and_save(source) const smy = arr && arr.length > 0 ? summary(arr) : null; const folders: any[] = []; const files = arr.filter((v: any) => { if (v.mimeType !== FOLDER_TYPE) return true; else { if (v.mimeType === FOLDER_TYPE) folders.push(v); return false; } }); console.log('Number of folders to be copied:', folders.length) console.log('Number of files to be copied:', files.length) if (files.length === 0) { throw new Error("No files found for copying."); } const mapping = await create_folders( source, folders, new_root.id, smy, tg ); await copy_files(files, mapping, new_root.id, smy, tg) return { id: new_root.id, folderSize: smy.total_size } } async function get_info_by_id(fid: string) { let url = `https://www.googleapis.com/drive/v3/files/${fid}` let params = { includeItemsFromAllDrives: true, supportsAllDrives: true, corpora: 'allDrives', fields: 'id, name, size, parents, mimeType, modifiedTime' } url += '?' + params_to_query(params) let retry = 0 while (retry < RETRY_LIMIT) { try { const headers = await gen_headers() const { data } = await axins.get(url, { headers }) return data } catch (e) { retry++ handle_error(e) } } // throw new Error('Unable to access this FolderID:' + fid) } async function create_folder(name: string, parent: string, limit?: any) { let url = `https://www.googleapis.com/drive/v3/files` const params = { supportsAllDrives: true } url += '?' + params_to_query(params) const post_data = { name, mimeType: FOLDER_TYPE, parents: [parent] } let retry = 0 let err_message while (retry < RETRY_LIMIT) { try { const headers = await gen_headers() return (await axins.post(url, post_data, { headers })).data } catch (err) { err_message = err.message retry++ handle_error(err) const data = err && err.response && err.response.data const message = data && data.error && data.error.message if (message && message.toLowerCase().includes('file limit')) { if (limit) limit.clearQueue() throw new Error(FILE_EXCEED_MSG) } console.log('Creating Folder and Retrying:', name, 'No of retries:', retry) } } throw new Error(err_message + ' Folder Name:' + name) } function params_to_query(data: any) { const ret = [] for (let d in data) { ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d])) } return ret.join('&') } function handle_error(err: any) { const data = err && err.response && err.response.data if (data) { console.error(JSON.stringify(data)) } else { if (!err.message.includes('timeout')) console.error(err.message) } } async function gen_headers() { const access_token = constants.USE_SERVICE_ACCOUNT ? (await get_sa_token()).access_token : (await get_access_token()); return { authorization: 'Bearer ' + access_token } } async function get_sa_token() { if (!SA_TOKENS.length) SA_TOKENS = get_sa_batch() while (SA_TOKENS.length) { const tk = get_random_element(SA_TOKENS) try { return await real_get_sa_token(tk) } catch (e) { console.warn('SA failed to get access_token:', e.message) SA_TOKENS = SA_TOKENS.filter((v: any) => v.gtoken !== tk.gtoken) if (!SA_TOKENS.length) SA_TOKENS = get_sa_batch() } } throw new Error('No SA available') } async function real_get_sa_token(el: any) { const { value, expires, gtoken } = el // The reason for passing out gtoken is that when an account is exhausted, it can be filtered accordingly if (Date.now() < expires) return { access_token: value, gtoken } const { access_token, expires_in } = await gtoken.getToken({ forceRefresh: true }) el.value = access_token el.expires = Date.now() + 1000 * (expires_in - 60 * 5) // 5 mins passed is taken as Expired return { access_token, gtoken } } async function get_access_token() { if (AUTH && AUTH.expires > Date.now()) { return AUTH.access_token; } let cred: any = fs.readFileSync('./credentials.json').toString(); let client_sec: any = fs.readFileSync('./client_secret.json').toString(); if (cred) { cred = JSON.parse(cred); client_sec = JSON.parse(client_sec) cred = { ...cred, ...client_sec.installed } } const { client_id, client_secret, refresh_token } = cred const url = 'https://www.googleapis.com/oauth2/v4/token' const headers = { 'Content-Type': 'application/x-www-form-urlencoded' } const config = { headers } const params = { client_id, client_secret, refresh_token, grant_type: 'refresh_token' } const { data } = await axins.post(url, params_to_query(params), config) AUTH = cred; AUTH.access_token = data.access_token AUTH.expires = Date.now() + 1000 * data.expires_in return data.access_token } function get_sa_batch() { const new_flag = SA_FILES.flag + SA_BATCH_SIZE const files = SA_FILES.slice(SA_FILES.flag, new_flag) SA_FILES.flag = new_flag return files.map((filename: string) => { const gtoken = new GoogleToken({ keyFile: path.join(__dirname, '../..', SA_LOCATION, filename), scope: ['https://www.googleapis.com/auth/drive'] }) return { gtoken, expires: 0 } }) } function get_random_element(arr: any[]) { return arr[~~(arr.length * Math.random())] } export async function walk_and_save(fid: string, tg?: any) { let result: any = []; const unfinished_folders: any[] = [] const limit = pLimit(PARALLEL_LIMIT) const loop = setInterval(() => { const now = dayjs().format('HH:mm:ss') const message = `${now} | Copied ${result.length} | Ongoing ${limit.activeCount} | Pending ${limit.pendingCount}` print_progress(message) }, 1000) const tg_loop = tg && setInterval(() => { tg({ obj_count: result.length, processing_count: limit.activeCount, pending_count: limit.pendingCount }) }, constants.STATUS_UPDATE_INTERVAL_MS ? constants.STATUS_UPDATE_INTERVAL_MS : 12000); async function recur(parent: string) { let files = await limit(() => ls_folder(parent)) if (!files) return null; if (files.unfinished) unfinished_folders.push(parent) const folders = files.filter((v: any) => v.mimeType === FOLDER_TYPE) files.forEach((v: any) => v.parent = parent) result = result.concat(files) return Promise.all(folders.map((v: any) => recur(v.id))) } try { await recur(fid) } catch (e) { console.error(e) } console.log('\nInfo obtained') unfinished_folders.length ? console.log('Unread FolderID:', JSON.stringify(unfinished_folders)) : console.log('All Folders have been read') clearInterval(loop) if (tg_loop) { clearInterval(tg_loop) // tg({ // obj_count: result.length, // processing_count: limit.activeCount, // pending_count: limit.pendingCount // }) } result.unfinished_number = unfinished_folders.length return result } function print_progress(msg: string) { if (process.stdout.cursorTo) { let tmp: any; process.stdout.cursorTo(0, tmp) process.stdout.write(msg + ' ') } else { console.log(msg) } } export function summary(info: any[], sort_by?: string) { const files = info.filter(v => v.mimeType !== FOLDER_TYPE); const file_count = files.length; const folder_count = info.filter(v => v.mimeType === FOLDER_TYPE).length let total_size: any = info.map(v => Number(v.size) || 0).reduce((acc, val) => acc + val, 0); total_size = format_size(total_size) const exts: any = {} const sizes: any = {} let no_ext = 0; let no_ext_size = 0 files.forEach(v => { let { name, size } = v size = Number(size) || 0 const ext = name.split('.').pop().toLowerCase() if (!name.includes('.') || ext.length > 10) { // If there are more than 10 characters after . , it is judged as no extension no_ext_size += size return no_ext++ } if (exts[ext]) { exts[ext]++ } else { exts[ext] = 1 } if (sizes[ext]) { sizes[ext] += size } else { sizes[ext] = size } return v; }) const details: any = Object.keys(exts).map(ext => { const count = exts[ext] const size = sizes[ext] return { ext, count, size: format_size(size), raw_size: size } }) if (sort_by === 'size') { details.sort((a: any, b: any) => b.raw_size - a.raw_size) } else if (sort_by === 'name') { details.sort((a: any, b: any) => (a.ext > b.ext) ? 1 : -1) } else { details.sort((a: any, b: any) => b.count - a.count) } if (no_ext) details.push({ ext: 'No Extension', count: no_ext, size: format_size(no_ext_size), raw_size: no_ext_size }) if (folder_count) details.push({ ext: 'Folder', count: folder_count, size: 0, raw_size: 0 }) return { file_count, folder_count, total_size, details } } function format_size(n: any) { n = Number(n) if (Number.isNaN(n)) return '' if (n < 0) return 'invalid size' const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] let flag = 0 while (n >= 1024) { n = (n / 1024) flag++ } return n.toFixed(2) + ' ' + units[flag] } async function ls_folder(fid: string, with_modifiedTime?: boolean) { let files: any = [] let pageToken const search_all = { includeItemsFromAllDrives: true, supportsAllDrives: true } const params: any = fid === 'root' ? {} : search_all params.q = `'${fid}' in parents and trashed = false` params.orderBy = 'folder,name desc' params.fields = 'nextPageToken, files(id, name, mimeType, size, md5Checksum)' if (with_modifiedTime) { params.fields = 'nextPageToken, files(id, name, mimeType, modifiedTime, size, md5Checksum)' } params.pageSize = Math.min(PAGE_SIZE, 1000) const use_sa = (fid !== 'root') && constants.USE_SERVICE_ACCOUNT // const headers = await gen_headers(use_sa) // For Folders with a large number of subfolders(1ctMwpIaBg8S1lrZDxdynLXJpMsm5guAl),The access_token may have expired before listing // Because nextPageToken is needed to get the data of the next page,So you cannot use parallel requests,The test found that each request to obtain 1000 files usually takes more than 20 seconds to complete const gtoken = use_sa && (await get_sa_token()).gtoken do { if (pageToken) params.pageToken = pageToken let url = 'https://www.googleapis.com/drive/v3/files' url += '?' + params_to_query(params) let retry = 0 let data const payload: any = { timeout: TIMEOUT_BASE } while (!data && (retry < RETRY_LIMIT)) { const access_token = gtoken ? (await gtoken.getToken()).access_token : (await get_access_token()); const headers = { authorization: 'Bearer ' + access_token } payload.headers = headers try { data = (await axins.get(url, payload)).data } catch (err) { handle_error(err) retry++ payload.timeout = Math.min(payload.timeout * 2, TIMEOUT_MAX) } } if (!data) { console.error('Folder is not read completely, Parameters:', params) files.unfinished = true return files } files = files.concat(data.files) pageToken = data.nextPageToken } while (pageToken) return files } async function create_folders(source: string, folders: any[], root: string, smy?: any, tg?: any) { if (!Array.isArray(folders)) throw new Error('folders must be Array:' + folders) const mapping: any = {}; mapping[source] = root if (!folders.length) return mapping const missed_folders = folders.filter(v => !mapping[v.id]) console.log('Start copying folders, total:', missed_folders.length) const limit = pLimit(PARALLEL_LIMIT) let count = 0 let same_levels = folders.filter(v => v.parent === folders[0].parent) const loop = setInterval(() => { const now = dayjs().format('HH:mm:ss') const message = `${now} | Folders Created ${count} | Ongoing ${limit.activeCount} | Pending ${limit.pendingCount}` print_progress(message) }, 1000) const tg_loop = smy && tg && setInterval(() => { tg({ isCopyingFolder: true, copiedCount: count, ...smy }) }, constants.STATUS_UPDATE_INTERVAL_MS ? constants.STATUS_UPDATE_INTERVAL_MS : 12000); while (same_levels.length) { const same_levels_missed = same_levels.filter(v => !mapping[v.id]) await Promise.all(same_levels_missed.map(async v => { try { const { name, id, parent } = v const target = mapping[parent] || root const new_folder = await limit(() => create_folder(name, target, limit)) count++ mapping[id] = new_folder.id } catch (e) { if (e.message === FILE_EXCEED_MSG) { clearInterval(loop) if (tg_loop) clearInterval(tg_loop) throw new Error(FILE_EXCEED_MSG) } console.error('Error creating Folder:', e.message) } })) same_levels = [].concat(...same_levels.map(v => folders.filter(vv => vv.parent === v.id))) } clearInterval(loop) if (tg_loop) clearInterval(tg_loop); return mapping } async function copy_files(files: any[], mapping: any[], root: string, smy?: any, tg?: any) { if (!files.length) return console.log('\nStarted copying files, total:', files.length) const loop = setInterval(() => { const now = dayjs().format('HH:mm:ss') const message = `${now} | Number of files copied ${count} | ongoing ${concurrency} | Number of Files Pending ${files.length}` print_progress(message) }, 1000) const tg_loop = smy && tg && setInterval(() => { tg({ isCopyingFolder: false, copiedCount: count, ...smy }) }, constants.STATUS_UPDATE_INTERVAL_MS ? constants.STATUS_UPDATE_INTERVAL_MS : 12000); let count = 0 let concurrency = 0 let err do { if (err) { clearInterval(loop) if (tg_loop) clearInterval(tg_loop) files = null throw new Error(err); } if (concurrency >= PARALLEL_LIMIT) { await sleep(100) continue } const file = files.shift() if (!file) { await sleep(1000) continue } concurrency++ const { id, parent } = file const target = mapping[parent] || root copy_file(id, target).then((new_file: any) => { if (new_file) { count++ } }).catch(e => { err = e }).finally(() => { concurrency-- }) } while (concurrency || files.length) clearInterval(loop) if (tg_loop) clearInterval(tg_loop) if (err) throw new Error(err); } export async function copy_file(id: string, parent: string, limit?: any) { let url = `https://www.googleapis.com/drive/v3/files/${id}/copy` let params = { supportsAllDrives: true, fields: 'id, name, mimeType, size' } url += '?' + params_to_query(params) const config: any = {} let retry = 0 while (retry < RETRY_LIMIT) { let gtoken: any; if (constants.USE_SERVICE_ACCOUNT) { const temp = await get_sa_token() gtoken = temp.gtoken config.headers = { authorization: 'Bearer ' + temp.access_token } } else { config.headers = await gen_headers() } try { const { data } = await axins.post(url, { parents: [parent] }, config) if (gtoken) gtoken.exceed_count = 0 return data } catch (err) { retry++ handle_error(err) const data = err && err.response && err.response.data; const message = data && data.error && data.error.message; if (message && message.toLowerCase().includes('file limit')) { if (limit) limit.clearQueue() throw new Error(FILE_EXCEED_MSG) } if (!constants.USE_SERVICE_ACCOUNT && message && message.toLowerCase().includes('rate limit')) { throw new Error('Personal Drive Limit:' + message) } if (constants.USE_SERVICE_ACCOUNT && message && message.toLowerCase().includes('rate limit')) { retry-- if (gtoken.exceed_count >= EXCEED_LIMIT) { SA_TOKENS = SA_TOKENS.filter((v: any) => v.gtoken !== gtoken) if (!SA_TOKENS.length) SA_TOKENS = get_sa_batch() console.log(`This account (${gtoken.keyFile}) has triggered the daily usage limit${EXCEED_LIMIT} consecutive times, the remaining amount of SA available in this batch:`, SA_TOKENS.length) } else { // console.log('This account triggers its daily usage limit and has been marked. If the next request is normal, it will be unmarked, otherwise the SA will be removed') if (gtoken.exceed_count) { gtoken.exceed_count++ } else { gtoken.exceed_count = 1 } } } } } if (constants.USE_SERVICE_ACCOUNT && !SA_TOKENS.length) { if (limit) limit.clearQueue() throw new Error('All SA are exhausted') } else { console.warn('File creation failed,Fileid: ' + id) } } export async function gen_count_body({ fid, limit, tg, smy }: any) { function render_smy(smy: any, unfinished_number?: string) { if (!smy) return smy = (typeof smy === 'object') ? smy : JSON.parse(smy) let result = make_tg_table(smy, limit) if (unfinished_number) result += `\nNumber of Folders not read:${unfinished_number}` return result } const file = await get_info_by_id(fid); if (file && file.mimeType !== FOLDER_TYPE) return render_smy(summary([file])) if (!file) { throw new Error(`Unable to access the link, please check if the link is valid and SA has the appropriate permissions:https://drive.google.com/drive/folders/${fid}`) } if (!smy) { smy = summary(await walk_and_save(fid, tg)); } return { table: render_smy(smy), smy }; } function make_tg_table({ file_count, folder_count, total_size, details }: any, limit?: number) { const tb: any = new Table({ style: { head: [], border: [] } }) const hAlign = 'center' const headers = ['Type', 'Count', 'Size'].map(v => ({ content: v, hAlign })) details.forEach((v: any) => { if (v.ext === 'Folder') v.ext = '[Folder]' if (v.ext === 'No Extension') v.ext = '[NoExt]' }) let records = details.map((v: any) => [v.ext, v.count, v.size]).map((arr: any) => arr.map((content: any) => ({ content, hAlign }))) const folder_row = records.pop() if (limit) records = records.slice(0, limit) if (folder_row) records.push(folder_row) const total_count = file_count + folder_count const tails = ['Total', total_count, total_size].map(v => ({ content: v, hAlign })) tb.push(headers, ...records) tb.push(tails) return tb.toString().replace(/─/g, '—') // Prevent the table from breaking on the mobile phone and it will look more beautiful in pc after removing the replace } async function get_name_by_id(fid: string) { const info = await get_info_by_id(fid) return info ? info.name : fid } export async function get_folder_name(fid: string) { let name = FID_TO_NAME[fid] if (name) return name name = await get_name_by_id(fid) return FID_TO_NAME[fid] = name }
the_stack
import { dispatch } from "d3-dispatch"; const cloudRadians = Math.PI / 180; const cw = 1 << 11 >> 5; const ch = 1 << 11; export function d3Cloud() { const event = dispatch("word", "end"); const cloud: any = {}; let size = [256, 256]; let text = cloudText; let font = cloudFont; let fontSize = cloudFontSize; let fontStyle = cloudFontNormal; let fontWeight = cloudFontNormal; let rotate = cloudRotate; let padding = cloudPadding; let words = []; let spiral = archimedeanSpiral; let timeInterval = Infinity; let timer = null; let random = Math.random; let canvas = cloudCanvas; cloud.canvas = function (_) { return arguments.length ? (canvas = functor(_), cloud) : canvas; }; cloud.start = function () { const contextAndRatio = getContext(canvas()); const board = zeroArray((size[0] >> 5) * size[1]); let bounds = null; const n = words.length; let i = -1; const tags = []; const data = words.map(function (d, i) { d.text = text.call(this, d, i); d.font = font.call(this, d, i); d.style = fontStyle.call(this, d, i); d.weight = fontWeight.call(this, d, i); d.rotate = rotate.call(this, d, i); d.size = ~~fontSize.call(this, d, i); d.padding = padding.call(this, d, i); return d; }).sort(function (a, b) { return b.size - a.size; }); if (timer) clearInterval(timer); timer = setInterval(step, 0); step(); return cloud; function step() { const start = Date.now(); while (Date.now() - start < timeInterval && ++i < n && timer) { const d = data[i]; d.x = (size[0] * (random() + .5)) >> 1; d.y = (size[1] * (random() + .5)) >> 1; cloudSprite(contextAndRatio, d, data, i); if (d.hasText && place(board, d, bounds)) { tags.push(d); event.call("word", cloud, d); if (bounds) cloudBounds(bounds, d); else bounds = [{ x: d.x + d.x0, y: d.y + d.y0 }, { x: d.x + d.x1, y: d.y + d.y1 }]; // Temporary hack d.x -= size[0] >> 1; d.y -= size[1] >> 1; } } if (i >= n) { cloud.stop(); event.call("end", cloud, tags, bounds); } } }; cloud.stop = function () { if (timer) { clearInterval(timer); timer = null; } return cloud; }; function getContext(canvas) { canvas.width = canvas.height = 1; const ratio = Math.sqrt(canvas.getContext("2d").getImageData(0, 0, 1, 1).data.length >> 2); canvas.width = (cw << 5) / ratio; canvas.height = ch / ratio; const context = canvas.getContext("2d"); context.fillStyle = context.strokeStyle = "red"; context.textAlign = "center"; return { context, ratio }; } function place(board, tag, bounds) { const startX = tag.x; const startY = tag.y; const maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]); const s = spiral(size); const dt = random() < .5 ? 1 : -1; let t = -dt; let dxdy; let dx; let dy; // eslint-disable-next-line no-cond-assign while (dxdy = s(t += dt)) { dx = ~~dxdy[0]; dy = ~~dxdy[1]; if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break; tag.x = startX + dx; tag.y = startY + dy; if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 || tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue; // TODO only check for collisions within current bounds. if (!bounds || !cloudCollide(tag, board, size[0])) { if (!bounds || collideRects(tag, bounds)) { const sprite = tag.sprite; const w = tag.width >> 5; const sw = size[0] >> 5; const lx = tag.x - (w << 4); const sx = lx & 0x7f; const msx = 32 - sx; const h = tag.y1 - tag.y0; let x = (tag.y + tag.y0) * sw + (lx >> 5); let last; for (let j = 0; j < h; j++) { last = 0; for (let i = 0; i <= w; i++) { board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0); } x += sw; } delete tag.sprite; return true; } } } return false; } cloud.timeInterval = function (_) { return arguments.length ? (timeInterval = _ == null ? Infinity : _, cloud) : timeInterval; }; cloud.words = function (_) { return arguments.length ? (words = _, cloud) : words; }; cloud.size = function (_) { return arguments.length ? (size = [+_[0], +_[1]], cloud) : size; }; cloud.font = function (_) { return arguments.length ? (font = functor(_), cloud) : font; }; cloud.fontStyle = function (_) { return arguments.length ? (fontStyle = functor(_), cloud) : fontStyle; }; cloud.fontWeight = function (_) { return arguments.length ? (fontWeight = functor(_), cloud) : fontWeight; }; cloud.rotate = function (_) { return arguments.length ? (rotate = functor(_), cloud) : rotate; }; cloud.text = function (_) { return arguments.length ? (text = functor(_), cloud) : text; }; cloud.spiral = function (_) { return arguments.length ? (spiral = spirals[_] || _, cloud) : spiral; }; cloud.fontSize = function (_) { return arguments.length ? (fontSize = functor(_), cloud) : fontSize; }; cloud.padding = function (_) { return arguments.length ? (padding = functor(_), cloud) : padding; }; cloud.random = function (_) { return arguments.length ? (random = _, cloud) : random; }; cloud.on = function () { const value = event.on.apply(event, arguments); return value === event ? cloud : value; }; return cloud; } function cloudText(d) { return d.text; } function cloudFont() { return "serif"; } function cloudFontNormal() { return "normal"; } function cloudFontSize(d) { return Math.sqrt(d.value); } function cloudRotate() { return (~~(Math.random() * 6) - 3) * 30; } function cloudPadding() { return 1; } // Fetches a monochrome sprite bitmap for the specified text. // Load in batches for speed. function cloudSprite(contextAndRatio, d, data, di) { if (d.sprite) return; const c = contextAndRatio.context; const ratio = contextAndRatio.ratio; c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio); let x = 0; let y = 0; let maxh = 0; const n = data.length; --di; while (++di < n) { d = data[di]; c.save(); c.font = d.style + " " + d.weight + " " + ~~((d.size + 1) / ratio) + "px " + d.font; let w = c.measureText(d.text + "m").width * ratio; let h = d.size << 1; if (d.rotate) { const sr = Math.sin(d.rotate * cloudRadians); const cr = Math.cos(d.rotate * cloudRadians); const wcr = w * cr; const wsr = w * sr; const hcr = h * cr; const hsr = h * sr; w = (Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5 << 5; h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr)); } else { w = (w + 0x1f) >> 5 << 5; } if (h > maxh) maxh = h; if (x + w >= (cw << 5)) { x = 0; y += maxh; maxh = 0; } if (y + h >= ch) break; c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio); if (d.rotate) c.rotate(d.rotate * cloudRadians); c.fillText(d.text, 0, 0); if (d.padding) c.lineWidth = 2 * d.padding, c.strokeText(d.text, 0, 0); c.restore(); d.width = w; d.height = h; d.xoff = x; d.yoff = y; d.x1 = w >> 1; d.y1 = h >> 1; d.x0 = -d.x1; d.y0 = -d.y1; d.hasText = true; x += w; } const pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data; const sprite = []; while (--di >= 0) { d = data[di]; if (!d.hasText) continue; const w = d.width; const w32 = w >> 5; let h = d.y1 - d.y0; // Zero the buffer for (let i = 0; i < h * w32; i++) sprite[i] = 0; x = d.xoff; if (x == null) return; y = d.yoff; let seen = 0; let seenRow = -1; for (let j = 0; j < h; j++) { for (let i = 0; i < w; i++) { const k = w32 * j + (i >> 5); const m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0; sprite[k] |= m; seen |= m; } if (seen) seenRow = j; else { d.y0++; h--; j--; y++; } } d.y1 = d.y0 + seenRow; d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32); } } // Use mask-based collision detection. function cloudCollide(tag, board, sw) { sw >>= 5; const sprite = tag.sprite; const w = tag.width >> 5; const lx = tag.x - (w << 4); const sx = lx & 0x7f; const msx = 32 - sx; const h = tag.y1 - tag.y0; let x = (tag.y + tag.y0) * sw + (lx >> 5); let last; for (let j = 0; j < h; j++) { last = 0; for (let i = 0; i <= w; i++) { if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0)) & board[x + i]) return true; } x += sw; } return false; } function cloudBounds(bounds, d) { const b0 = bounds[0]; const b1 = bounds[1]; if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0; if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0; if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1; if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1; } function collideRects(a, b) { return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y; } function archimedeanSpiral(size) { const e = size[0] / size[1]; return function (t) { return [e * (t *= .1) * Math.cos(t), t * Math.sin(t)]; }; } function rectangularSpiral(size) { const dy = 4; const dx = dy * size[0] / size[1]; let x = 0; let y = 0; return function (t) { const sign = t < 0 ? -1 : 1; // See triangular numbers: T_n = n * (n + 1) / 2. switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) { case 0: x += dx; break; case 1: y += dy; break; case 2: x -= dx; break; default: y -= dy; break; } return [x, y]; }; } // TODO reuse arrays? function zeroArray(n) { const a = []; let i = -1; while (++i < n) a[i] = 0; return a; } function cloudCanvas() { return document.createElement("canvas"); } function functor(d) { return typeof d === "function" ? d : function () { return d; }; } const spirals = { archimedean: archimedeanSpiral, rectangular: rectangularSpiral };
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Servers } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { AzureAnalysisServices } from "../azureAnalysisServices"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { AnalysisServicesServer, ServersListByResourceGroupOptionalParams, ServersListOptionalParams, ServersGetDetailsOptionalParams, ServersGetDetailsResponse, ServersCreateOptionalParams, ServersCreateResponse, ServersDeleteOptionalParams, AnalysisServicesServerUpdateParameters, ServersUpdateOptionalParams, ServersUpdateResponse, ServersSuspendOptionalParams, ServersResumeOptionalParams, ServersListByResourceGroupResponse, ServersListResponse, ServersListSkusForNewOptionalParams, ServersListSkusForNewResponse, ServersListSkusForExistingOptionalParams, ServersListSkusForExistingResponse, ServersListGatewayStatusOptionalParams, ServersListGatewayStatusResponse, ServersDissociateGatewayOptionalParams, CheckServerNameAvailabilityParameters, ServersCheckNameAvailabilityOptionalParams, ServersCheckNameAvailabilityResponse, ServersListOperationResultsOptionalParams, ServersListOperationStatusesOptionalParams, ServersListOperationStatusesResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Servers operations. */ export class ServersImpl implements Servers { private readonly client: AzureAnalysisServices; /** * Initialize a new instance of the class Servers class. * @param client Reference to the service client */ constructor(client: AzureAnalysisServices) { this.client = client; } /** * Gets all the Analysis Services servers for the given resource group. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: ServersListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<AnalysisServicesServer> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: ServersListByResourceGroupOptionalParams ): AsyncIterableIterator<AnalysisServicesServer[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: ServersListByResourceGroupOptionalParams ): AsyncIterableIterator<AnalysisServicesServer> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Lists all the Analysis Services servers for the given subscription. * @param options The options parameters. */ public list( options?: ServersListOptionalParams ): PagedAsyncIterableIterator<AnalysisServicesServer> { const iter = this.listPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(options); } }; } private async *listPagingPage( options?: ServersListOptionalParams ): AsyncIterableIterator<AnalysisServicesServer[]> { let result = await this._list(options); yield result.value || []; } private async *listPagingAll( options?: ServersListOptionalParams ): AsyncIterableIterator<AnalysisServicesServer> { for await (const page of this.listPagingPage(options)) { yield* page; } } /** * Gets details about the specified Analysis Services server. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be a minimum of 3 characters, * and a maximum of 63. * @param options The options parameters. */ getDetails( resourceGroupName: string, serverName: string, options?: ServersGetDetailsOptionalParams ): Promise<ServersGetDetailsResponse> { return this.client.sendOperationRequest( { resourceGroupName, serverName, options }, getDetailsOperationSpec ); } /** * Provisions the specified Analysis Services server based on the configuration specified in the * request. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be a minimum of 3 characters, * and a maximum of 63. * @param serverParameters Contains the information used to provision the Analysis Services server. * @param options The options parameters. */ async beginCreate( resourceGroupName: string, serverName: string, serverParameters: AnalysisServicesServer, options?: ServersCreateOptionalParams ): Promise< PollerLike<PollOperationState<ServersCreateResponse>, ServersCreateResponse> > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ServersCreateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serverName, serverParameters, options }, createOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Provisions the specified Analysis Services server based on the configuration specified in the * request. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be a minimum of 3 characters, * and a maximum of 63. * @param serverParameters Contains the information used to provision the Analysis Services server. * @param options The options parameters. */ async beginCreateAndWait( resourceGroupName: string, serverName: string, serverParameters: AnalysisServicesServer, options?: ServersCreateOptionalParams ): Promise<ServersCreateResponse> { const poller = await this.beginCreate( resourceGroupName, serverName, serverParameters, options ); return poller.pollUntilDone(); } /** * Deletes the specified Analysis Services server. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be at least 3 characters in * length, and no more than 63. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, serverName: string, options?: ServersDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serverName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Deletes the specified Analysis Services server. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be at least 3 characters in * length, and no more than 63. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, serverName: string, options?: ServersDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, serverName, options ); return poller.pollUntilDone(); } /** * Updates the current state of the specified Analysis Services server. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be at least 3 characters in * length, and no more than 63. * @param serverUpdateParameters Request object that contains the updated information for the server. * @param options The options parameters. */ async beginUpdate( resourceGroupName: string, serverName: string, serverUpdateParameters: AnalysisServicesServerUpdateParameters, options?: ServersUpdateOptionalParams ): Promise< PollerLike<PollOperationState<ServersUpdateResponse>, ServersUpdateResponse> > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ServersUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serverName, serverUpdateParameters, options }, updateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Updates the current state of the specified Analysis Services server. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be at least 3 characters in * length, and no more than 63. * @param serverUpdateParameters Request object that contains the updated information for the server. * @param options The options parameters. */ async beginUpdateAndWait( resourceGroupName: string, serverName: string, serverUpdateParameters: AnalysisServicesServerUpdateParameters, options?: ServersUpdateOptionalParams ): Promise<ServersUpdateResponse> { const poller = await this.beginUpdate( resourceGroupName, serverName, serverUpdateParameters, options ); return poller.pollUntilDone(); } /** * Suspends operation of the specified Analysis Services server instance. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be at least 3 characters in * length, and no more than 63. * @param options The options parameters. */ async beginSuspend( resourceGroupName: string, serverName: string, options?: ServersSuspendOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serverName, options }, suspendOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Suspends operation of the specified Analysis Services server instance. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be at least 3 characters in * length, and no more than 63. * @param options The options parameters. */ async beginSuspendAndWait( resourceGroupName: string, serverName: string, options?: ServersSuspendOptionalParams ): Promise<void> { const poller = await this.beginSuspend( resourceGroupName, serverName, options ); return poller.pollUntilDone(); } /** * Resumes operation of the specified Analysis Services server instance. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be at least 3 characters in * length, and no more than 63. * @param options The options parameters. */ async beginResume( resourceGroupName: string, serverName: string, options?: ServersResumeOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serverName, options }, resumeOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Resumes operation of the specified Analysis Services server instance. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be at least 3 characters in * length, and no more than 63. * @param options The options parameters. */ async beginResumeAndWait( resourceGroupName: string, serverName: string, options?: ServersResumeOptionalParams ): Promise<void> { const poller = await this.beginResume( resourceGroupName, serverName, options ); return poller.pollUntilDone(); } /** * Gets all the Analysis Services servers for the given resource group. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: ServersListByResourceGroupOptionalParams ): Promise<ServersListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * Lists all the Analysis Services servers for the given subscription. * @param options The options parameters. */ private _list( options?: ServersListOptionalParams ): Promise<ServersListResponse> { return this.client.sendOperationRequest({ options }, listOperationSpec); } /** * Lists eligible SKUs for Analysis Services resource provider. * @param options The options parameters. */ listSkusForNew( options?: ServersListSkusForNewOptionalParams ): Promise<ServersListSkusForNewResponse> { return this.client.sendOperationRequest( { options }, listSkusForNewOperationSpec ); } /** * Lists eligible SKUs for an Analysis Services resource. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be at least 3 characters in * length, and no more than 63. * @param options The options parameters. */ listSkusForExisting( resourceGroupName: string, serverName: string, options?: ServersListSkusForExistingOptionalParams ): Promise<ServersListSkusForExistingResponse> { return this.client.sendOperationRequest( { resourceGroupName, serverName, options }, listSkusForExistingOperationSpec ); } /** * Return the gateway status of the specified Analysis Services server instance. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. * @param options The options parameters. */ listGatewayStatus( resourceGroupName: string, serverName: string, options?: ServersListGatewayStatusOptionalParams ): Promise<ServersListGatewayStatusResponse> { return this.client.sendOperationRequest( { resourceGroupName, serverName, options }, listGatewayStatusOperationSpec ); } /** * Dissociates a Unified Gateway associated with the server. * @param resourceGroupName The name of the Azure Resource group of which a given Analysis Services * server is part. This name must be at least 1 character in length, and no more than 90. * @param serverName The name of the Analysis Services server. It must be at least 3 characters in * length, and no more than 63. * @param options The options parameters. */ dissociateGateway( resourceGroupName: string, serverName: string, options?: ServersDissociateGatewayOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, serverName, options }, dissociateGatewayOperationSpec ); } /** * Check the name availability in the target location. * @param location The region name which the operation will lookup into. * @param serverParameters Contains the information used to provision the Analysis Services server. * @param options The options parameters. */ checkNameAvailability( location: string, serverParameters: CheckServerNameAvailabilityParameters, options?: ServersCheckNameAvailabilityOptionalParams ): Promise<ServersCheckNameAvailabilityResponse> { return this.client.sendOperationRequest( { location, serverParameters, options }, checkNameAvailabilityOperationSpec ); } /** * List the result of the specified operation. * @param location The region name which the operation will lookup into. * @param operationId The target operation Id. * @param options The options parameters. */ listOperationResults( location: string, operationId: string, options?: ServersListOperationResultsOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { location, operationId, options }, listOperationResultsOperationSpec ); } /** * List the status of operation. * @param location The region name which the operation will lookup into. * @param operationId The target operation Id. * @param options The options parameters. */ listOperationStatuses( location: string, operationId: string, options?: ServersListOperationStatusesOptionalParams ): Promise<ServersListOperationStatusesResponse> { return this.client.sendOperationRequest( { location, operationId, options }, listOperationStatusesOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const getDetailsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AnalysisServices/servers/{serverName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AnalysisServicesServer }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serverName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const createOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AnalysisServices/servers/{serverName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.AnalysisServicesServer }, 201: { bodyMapper: Mappers.AnalysisServicesServer }, 202: { bodyMapper: Mappers.AnalysisServicesServer }, 204: { bodyMapper: Mappers.AnalysisServicesServer }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.serverParameters, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serverName, Parameters.subscriptionId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AnalysisServices/servers/{serverName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serverName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AnalysisServices/servers/{serverName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.AnalysisServicesServer }, 201: { bodyMapper: Mappers.AnalysisServicesServer }, 202: { bodyMapper: Mappers.AnalysisServicesServer }, 204: { bodyMapper: Mappers.AnalysisServicesServer }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.serverUpdateParameters, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serverName, Parameters.subscriptionId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const suspendOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AnalysisServices/servers/{serverName}/suspend", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serverName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const resumeOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AnalysisServices/servers/{serverName}/resume", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serverName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AnalysisServices/servers", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AnalysisServicesServers }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.AnalysisServices/servers", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AnalysisServicesServers }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listSkusForNewOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.AnalysisServices/skus", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SkuEnumerationForNewResourceResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listSkusForExistingOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AnalysisServices/servers/{serverName}/skus", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SkuEnumerationForExistingResourceResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serverName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listGatewayStatusOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AnalysisServices/servers/{serverName}/listGatewayStatus", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.GatewayListStatusLive }, default: { bodyMapper: Mappers.GatewayListStatusError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serverName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const dissociateGatewayOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AnalysisServices/servers/{serverName}/dissociateGateway", httpMethod: "POST", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serverName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const checkNameAvailabilityOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.AnalysisServices/locations/{location}/checkNameAvailability", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.CheckServerNameAvailabilityResult }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.serverParameters1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.location ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listOperationResultsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.AnalysisServices/locations/{location}/operationresults/{operationId}", httpMethod: "GET", responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.location, Parameters.operationId ], headerParameters: [Parameters.accept], serializer }; const listOperationStatusesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.AnalysisServices/locations/{location}/operationstatuses/{operationId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.OperationStatus }, 202: { bodyMapper: Mappers.OperationStatus }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.location, Parameters.operationId ], headerParameters: [Parameters.accept], serializer };
the_stack
declare const figma: PluginAPI declare const __html__: string interface PluginAPI { readonly currentPage: PageNode // Root of the current Figma document. readonly root: DocumentNode // API for accessing viewport information. readonly viewport: ViewportAPI // call this once your plugin is finished executing. closePlugin(): void // Command that the user chose through menu when launching the plugin. readonly command: string // Finds a node by its id. If not found, returns null. getNodeById(id: string): BaseNode | null // Finds a style by its id. If not found, returns null. getStyleById(id: string): BaseStyle | null // Access browser APIs and/or show UI to the user. showUI(html: string, options?: ShowUIOptions): void readonly ui: UIAPI // Lets you store persistent data on the user's local machine readonly clientStorage: ClientStorageAPI // This value is returned when a property is in a "mixed" state. // In order to check if a property is in a mixed state, always // compare directly to this value. I.e. // `if (node.cornerRadius === figma.mixed) { ... }` mixed: symbol // Creates new nodes. Nodes will start off inserted // into the current page. // To move them elsewhere use `appendChild` or `insertChild` createRectangle(): RectangleNode createLine(): LineNode createEllipse(): EllipseNode createPolygon(): PolygonNode createStar(): StarNode createVector(): VectorNode createText(): TextNode createBooleanOperation(): BooleanOperationNode createFrame(): FrameNode createComponent(): ComponentNode createPage(): PageNode createSlice(): SliceNode // Creates styles. A style's id can be assigned to // node properties like textStyleId, fillStyleId, etc. createPaintStyle(): PaintStyle createTextStyle(): TextStyle createEffectStyle(): EffectStyle createGridStyle(): GridStyle // These let you insert stuff from the team library if you have the key importComponentByKeyAsync(key: string): Promise<ComponentNode> importStyleByKeyAsync(key: string): Promise<BaseStyle> // Return all fonts currently supported for use with the "fontName" property listAvailableFontsAsync(): Promise<Font[]> // You must await the promise returned here before being able to use "fontName" loadFontAsync(fontName: FontName): Promise<void> // Creates node from an SVG string. createNodeFromSvg(svg: string): FrameNode // Creates an Image object using the provided file contents. createImage(data: Uint8Array): Image // Groups every node in `nodes` under a new group. group(nodes: ReadonlyArray<BaseNode>, parent: BaseNode & ChildrenMixin, index?: number): FrameNode // Flattens every node in `nodes` into a single vector network. flatten(nodes: ReadonlyArray<BaseNode>, parent?: BaseNode & ChildrenMixin, index?: number): VectorNode } interface ClientStorageAPI { // This stores information in the browser, not on the server. It's similar to localStorage, but is // asynchronous, and allows storing objects, arrays, strings, numbers, booleans, null, undefined and Uint8Arrays. getAsync(key: string): Promise<any | undefined> setAsync(key: string, value: any): Promise<void> } type ShowUIOptions = { visible?: boolean, // defaults to true width?: number, // defaults to 300 height?: number, // defaults to 200 } interface UIAPI { show(): void hide(): void resize(width: number, height: number): void close(): void // Sends a message to the iframe. postMessage(pluginMessage: any): void // Registers a callback for messages sent by the iframe. onmessage: ((pluginMessage: any) => void) | undefined } interface ViewportAPI { center: { x: number, y: number } // 1.0 means 100% zoom, 0.5 means 50% zoom. zoom: number // Adjust the viewport such that it shows the provided nodes. scrollAndZoomIntoView(nodes: ReadonlyArray<BaseNode>) } // manifest.json format interface ManifestJson { // Name of the plugin. name: string // Version of the runtime that the plugin uses, e.g. '0.5.0'. version: string // The file name that contains the plugin code. script: string // The file name that contains the html code made available in script. html?: string // Shell command to be executed before the contents of the `html` and `script` files are read. build?: string // Menu items to show up in UI. menu?: ManifestMenuItem[] } type ManifestMenuItem = // Clickable menu item. { name: string, command: string } | // Separator { separator: true } | // Submenu { name: string, menu: ManifestMenuItem[] } //////////////////////////////////////////////////////////////////////////////// // Values // These are the top two rows of a 3x3 matrix. This is enough to represent // translation, rotation, and skew. type Transform = [ [number, number, number], [number, number, number] ] interface Vector { readonly x: number readonly y: number } interface RGB { readonly r: number readonly g: number readonly b: number } interface RGBA { readonly r: number readonly g: number readonly b: number readonly a: number } interface FontName { readonly family: string readonly style: string } interface ArcData { readonly startingAngle: number readonly endingAngle: number readonly innerRadius: number } interface ShadowEffect { readonly type: "DROP_SHADOW" | "INNER_SHADOW" readonly color: RGBA readonly offset: Vector readonly radius: number readonly visible: boolean readonly blendMode: BlendMode } interface BlurEffect { readonly type: "LAYER_BLUR" | "BACKGROUND_BLUR" readonly radius: number readonly visible: boolean } type Effect = ShadowEffect | BlurEffect type ConstraintType = "MIN" | "CENTER" | "MAX" | "STRETCH" | "SCALE" interface Constraints { readonly horizontal: ConstraintType readonly vertical: ConstraintType } interface ColorStop { readonly position: number readonly color: RGBA } interface SolidPaint { readonly type: "SOLID" readonly color: RGB readonly visible?: boolean readonly opacity?: number } interface GradientPaint { readonly type: "GRADIENT_LINEAR" | "GRADIENT_RADIAL" | "GRADIENT_ANGULAR" | "GRADIENT_DIAMOND" readonly gradientTransform: Transform readonly gradientStops: ReadonlyArray<ColorStop> readonly visible?: boolean readonly opacity?: number } interface ImagePaint { readonly type: "IMAGE" readonly scaleMode: "FILL" | "FIT" | "CROP" | "TILE" readonly image: Image | null readonly imageTransform?: Transform // setting for "CROP" readonly scalingFactor?: number // setting for "TILE" readonly visible?: boolean readonly opacity?: number } type Paint = SolidPaint | GradientPaint | ImagePaint interface Guide { readonly axis: "X" | "Y" readonly offset: number } interface RowsColsLayoutGrid { readonly pattern: "ROWS" | "COLUMNS" readonly alignment: "MIN" | "STRETCH" | "CENTER" readonly gutterSize: number readonly count: number // Infinity when "Auto" is set in the UI readonly sectionSize?: number // Not set for alignment: "STRETCH" readonly offset?: number // Not set for alignment: "CENTER" readonly visible?: boolean readonly color?: RGBA } interface GridLayoutGrid { readonly pattern: "GRID" readonly sectionSize: number readonly visible?: boolean readonly color?: RGBA } type LayoutGrid = RowsColsLayoutGrid | GridLayoutGrid interface ExportSettingsImage { format: "JPG" | "PNG" contentsOnly?: boolean // defaults to true suffix?: string constraint?: { // defaults to unscaled ({ type: "SCALE", value: 1 }) type: "SCALE" | "WIDTH" | "HEIGHT" value: number } } interface ExportSettingsSVG { format: "SVG" contentsOnly?: boolean // defaults to true suffix?: string svgOutlineText?: boolean // defaults to true svgIdAttribute?: boolean // defaults to false svgSimplifyStroke?: boolean // defaults to true } interface ExportSettingsPDF { format: "PDF" contentsOnly?: boolean // defaults to true suffix?: string } type ExportSettings = ExportSettingsImage | ExportSettingsSVG | ExportSettingsPDF type WindingRule = "NONZERO" | "EVENODD" interface VectorVertex { readonly x: number readonly y: number readonly strokeCap?: StrokeCap readonly strokeJoin?: StrokeJoin readonly cornerRadius?: number readonly handleMirroring?: HandleMirroring } interface VectorSegment { readonly start: number readonly end: number readonly tangentStart?: Vector // Defaults to { x: 0, y: 0 } readonly tangentEnd?: Vector // Defaults to { x: 0, y: 0 } } interface VectorRegion { readonly windingRule: WindingRule readonly loops: ReadonlyArray<ReadonlyArray<number>> } interface VectorNetwork { readonly vertices: ReadonlyArray<VectorVertex> readonly segments: ReadonlyArray<VectorSegment> readonly regions?: ReadonlyArray<VectorRegion> // Defaults to [] } interface VectorPath { // Similar to the svg fill-rule // "NONE" means an open path won't have a fill readonly windingRule: WindingRule | "NONE" readonly data: string } type VectorPaths = ReadonlyArray<VectorPath> interface NumberWithUnits { readonly value: number readonly units: "PIXELS" | "PERCENT" } type BlendMode = "PASS_THROUGH" | "NORMAL" | "DARKEN" | "MULTIPLY" | "LINEAR_BURN" | "COLOR_BURN" | "LIGHTEN" | "SCREEN" | "LINEAR_DODGE" | "COLOR_DODGE" | "OVERLAY" | "SOFT_LIGHT" | "HARD_LIGHT" | "DIFFERENCE" | "EXCLUSION" | "HUE" | "SATURATION" | "COLOR" | "LUMINOSITY" interface Font { fontName: FontName } //////////////////////////////////////////////////////////////////////////////// // Mixins interface BaseNodeMixin { readonly id: string readonly parent: (BaseNode & ChildrenMixin) | null name: string visible: boolean locked: boolean removed: boolean toString(): string remove(): void // Attach custom data to a node. Only your plugin will be able to read this. getPluginData(key: string): string setPluginData(key: string, value: string): void // Attach custom data to a node. All plugins will be able to read this. // Namespace is a string that must be at least 3 alphanumeric characters, and should // be a name related to your plugin. This is a mandatory argument to avoid multiple // multiple plugins adding keys like "data" and colliding with each other. Other // plugins will still be able to read shared plugin data as long as they know the // namespace you use. getSharedPluginData(namespace: string, key: string): string setSharedPluginData(namespace: string, key: string, value: string): void } interface ChildrenMixin { // Sorted back-to-front. I.e. the top-most child is last in this array. readonly children: ReadonlyArray<BaseNode> // Adds to the end of the .children array. I.e. visually on top of all other // children. appendChild(child: BaseNode): void insertChild(index: number, child: BaseNode): void findAll(callback?: (node: BaseNode) => boolean): ReadonlyArray<BaseNode> findOne(callback: (node: BaseNode) => boolean): BaseNode | null } interface LayoutMixin { readonly absoluteTransform: Transform relativeTransform: Transform x: number // The same as "relativeTransform[0][2]" y: number // The same as "relativeTransform[1][2]" rotation: number // The angle of the x axis of "relativeTransform" in degrees. Returns values from -180 to 180. readonly size: Vector readonly width: number // The same as "size.x" readonly height: number // The same as "size.y" // Resizes the node. If children of the node has constraints, it applies those constraints // width and height must be >= 0.01 resize(width: number, height: number): void // Resizes the node. Children of the node are never resized, even if those children have // constraints. width and height must be >= 0.01 resizeWithoutConstraints(width: number, height: number): void constraints: Constraints } interface BlendMixin { opacity: number blendMode: BlendMode isMask: boolean effects: ReadonlyArray<Effect> effectStyleId: string } interface FrameMixin { backgrounds: ReadonlyArray<Paint> layoutGrids: ReadonlyArray<LayoutGrid> clipsContent: boolean guides: ReadonlyArray<Guide> gridStyleId: string backgroundStyleId: string } type StrokeCap = "NONE" | "ROUND" | "SQUARE" | "ARROW_LINES" | "ARROW_EQUILATERAL" type StrokeJoin = "MITER" | "BEVEL" | "ROUND" type HandleMirroring = "NONE" | "ANGLE" | "ANGLE_AND_LENGTH" interface GeometryMixin { fills: ReadonlyArray<Paint> | symbol // This can return figma.mixed on TEXT nodes strokes: ReadonlyArray<Paint> strokeWeight: number strokeAlign: "CENTER" | "INSIDE" | "OUTSIDE" strokeCap: StrokeCap | symbol // This can return figma.mixed on VECTOR nodes if vertices have different strokeCap values strokeJoin: StrokeJoin | symbol // This can return figma.mixed on VECTOR nodes if vertices have different strokeJoin values dashPattern: ReadonlyArray<number> fillStyleId: string | symbol // This can return figma.mixed on TEXT nodes strokeStyleId: string } interface CornerMixin { // This can return figma.mixed on VECTOR nodes if vertices have different cornerRadius values, // and on RECTANGLE nodes if node.topLeftRadius etc has different values cornerRadius: number | symbol cornerSmoothing: number } interface ExportMixin { exportSettings: ExportSettings[] exportAsync(settings?: ExportSettings): Promise<Uint8Array> // Defaults to PNG format } //////////////////////////////////////////////////////////////////////////////// // Nodes interface DocumentNode extends BaseNodeMixin, ChildrenMixin { readonly type: "DOCUMENT" clone(): DocumentNode // Note: this always throws an error } interface PageNode extends BaseNodeMixin, ChildrenMixin, ExportMixin { readonly type: "PAGE" clone(): PageNode // cloned node starts off inserted into current page guides: ReadonlyArray<Guide> selection: ReadonlyArray<BaseNode> } interface FrameNode extends BaseNodeMixin, BlendMixin, ChildrenMixin, FrameMixin, LayoutMixin, ExportMixin { readonly type: "FRAME" | "GROUP" clone(): FrameNode // cloned node starts off inserted into current page } interface SliceNode extends BaseNodeMixin, LayoutMixin, ExportMixin { readonly type: "SLICE" clone(): SliceNode // cloned node starts off inserted into current page } interface RectangleNode extends BaseNodeMixin, BlendMixin, CornerMixin, GeometryMixin, LayoutMixin, ExportMixin { readonly type: "RECTANGLE" clone(): RectangleNode // cloned node starts off inserted into current page topLeftRadius: number topRightRadius: number bottomLeftRadius: number bottomRightRadius: number } interface LineNode extends BaseNodeMixin, BlendMixin, GeometryMixin, LayoutMixin, ExportMixin { readonly type: "LINE" clone(): LineNode // cloned node starts off inserted into current page } interface EllipseNode extends BaseNodeMixin, BlendMixin, CornerMixin, GeometryMixin, LayoutMixin, ExportMixin { readonly type: "ELLIPSE" clone(): EllipseNode // cloned node starts off inserted into current page arcData: ArcData } interface PolygonNode extends BaseNodeMixin, BlendMixin, CornerMixin, GeometryMixin, LayoutMixin, ExportMixin { readonly type: "POLYGON" clone(): PolygonNode // cloned node starts off inserted into current page pointCount: number } interface StarNode extends BaseNodeMixin, BlendMixin, CornerMixin, GeometryMixin, LayoutMixin, ExportMixin { readonly type: "STAR" clone(): StarNode // cloned node starts off inserted into current page pointCount: number // This is a percentage value from 0 to 1 innerRadius: number } interface VectorNode extends BaseNodeMixin, BlendMixin, CornerMixin, GeometryMixin, LayoutMixin, ExportMixin { readonly type: "VECTOR" clone(): VectorNode // cloned node starts off inserted into current page vectorNetwork: VectorNetwork vectorPaths: VectorPaths handleMirroring: HandleMirroring | symbol // This can return figma.mixed if vertices have different handleMirroring values } interface TextNode extends BaseNodeMixin, BlendMixin, GeometryMixin, LayoutMixin, ExportMixin { readonly type: "TEXT" clone(): TextNode // cloned node starts off inserted into current page characters: string textAlignHorizontal: "LEFT" | "CENTER" | "RIGHT" | "JUSTIFIED" textAlignVertical: "TOP" | "CENTER" | "BOTTOM" textAutoResize: "NONE" | "WIDTH_AND_HEIGHT" | "HEIGHT" paragraphIndent: number paragraphSpacing: number autoRename: boolean // These properties can all return figma.mixed if the text has multiple values for the property textStyleId: string | symbol fontSize: number | symbol fontName: FontName | symbol textCase: "ORIGINAL" | "UPPER" | "LOWER" | "TITLE" | symbol textDecoration: "NONE" | "UNDERLINE" | "STRIKETHROUGH" | symbol letterSpacing: NumberWithUnits | symbol lineHeight: NumberWithUnits | symbol } interface ComponentNode extends BaseNodeMixin, BlendMixin, ChildrenMixin, FrameMixin, LayoutMixin, ExportMixin { readonly type: "COMPONENT" clone(): ComponentNode // cloned node starts off inserted into current page createInstance(): InstanceNode // instance starts off inserted into current page description: string readonly remote: boolean readonly key: string // The key to use with "importComponentByKeyAsync" } interface InstanceNode extends BaseNodeMixin, BlendMixin, ChildrenMixin, FrameMixin, LayoutMixin, ExportMixin { readonly type: "INSTANCE" clone(): InstanceNode // cloned node starts off inserted into current page masterComponent: ComponentNode } interface BooleanOperationNode extends BaseNodeMixin, BlendMixin, ChildrenMixin, CornerMixin, GeometryMixin, LayoutMixin, ExportMixin { readonly type: "BOOLEAN_OPERATION" clone(): BooleanOperationNode // cloned node starts off inserted into current page booleanOperation: "UNION" | "INTERSECT" | "SUBTRACT" | "EXCLUDE" } type BaseNode = DocumentNode | PageNode | SliceNode | FrameNode | ComponentNode | InstanceNode | BooleanOperationNode | VectorNode | StarNode | LineNode | EllipseNode | PolygonNode | RectangleNode | TextNode type NodeType = "DOCUMENT" | "PAGE" | "SLICE" | "FRAME" | "GROUP" | "COMPONENT" | "INSTANCE" | "BOOLEAN_OPERATION" | "VECTOR" | "STAR" | "LINE" | "ELLIPSE" | "POLYGON" | "RECTANGLE" | "TEXT" //////////////////////////////////////////////////////////////////////////////// // Styles type StyleType = "PAINT" | "TEXT" | "EFFECT" | "GRID" interface BaseStyle { // The string to uniquely identify a style by readonly id: string readonly type: StyleType name: string // Note: setting this also sets "autoRename" to false on TextNodes description: string remote: boolean readonly key: string // The key to use with "importStyleByKeyAsync" remove(): void } interface PaintStyle extends BaseStyle { type: "PAINT" paints: ReadonlyArray<Paint> } interface TextStyle extends BaseStyle { type: "TEXT" fontSize: number textDecoration: "NONE" | "UNDERLINE" | "STRIKETHROUGH" fontName: FontName letterSpacing: NumberWithUnits lineHeight: NumberWithUnits paragraphIndent: number paragraphSpacing: number textCase: "ORIGINAL" | "UPPER" | "LOWER" | "TITLE" } interface EffectStyle extends BaseStyle { type: "EFFECT" effects: ReadonlyArray<Paint> } interface GridStyle extends BaseStyle { type: "GRID" layoutGrids: ReadonlyArray<LayoutGrid> } //////////////////////////////////////////////////////////////////////////////// // Other interface Image { // Returns a unique hash for the image readonly hash: string // The contents of the image file getBytesAsync(): Promise<Uint8Array> }
the_stack
import React, { useRef, useState, useEffect, useMemo, Fragment } from 'react' import { Box, Button, GridColumn, GridContainer, GridRow, Hidden, Icon, Inline, ModalBase, Stack, Tag, Text, } from '@island.is/island-ui/core' import { TimelineSlice as Timeline } from '@island.is/web/graphql/schema' import cn from 'classnames' import * as timelineStyles from './TimelineSlice.css' import * as eventStyles from './Event.css' import { useDateUtils } from '@island.is/web/i18n/useDateUtils' import Link from 'next/link' import ReactDOM from 'react-dom' import { renderSlices, SliceType } from '@island.is/island-ui/contentful' import { flatten } from '@nestjs/common' function setDefault<K, V>(map: Map<K, V>, key: K, value: V): V { if (!map.has(key)) map.set(key, value) return map.get(key) as V } const mapEvents = ( events: Timeline['events'], ): Map<number, Map<number, Timeline['events']>> => { events = events .slice() .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()) .reverse() const byYear = new Map() for (const event of events) { const byMonth = setDefault( byYear, new Date(event.date).getFullYear(), new Map(), ) setDefault( byMonth, new Date(event.date).getMonth(), [] as Timeline['events'], ).push(event) } return byYear } const getTimeline = ( eventMap: Map<number, Map<number, Timeline['events']>>, getMonthByIndex, ) => { let i = 0 let offset = 50 let lastTimestamp = 0 let lastYear = 0 let currentMonth = 0 const items = [] const today = new Date() today.setMonth(today.getMonth() - 1) Array.from(eventMap.entries(), ([year, eventsByMonth]) => { Array.from(eventsByMonth.entries(), ([month, monthEvents]) => { const monthDate = new Date(`${year}-${month + 1}`) // we want to find the closest month to today and center the timeline view on it if (currentMonth === 0 && monthDate >= today) { currentMonth = offset } offset += 100 items.push( <MonthItem month={getMonthByIndex(month)} year={year.toString()} offset={offset} />, ) lastYear = year monthEvents.map((event, idx) => { // we increase the space between items if they are far apart in time const timestamp = new Date(event.date).getTime() offset += idx > 0 ? Math.max(90, Math.min(160, (timestamp - lastTimestamp) / 4320000)) : 100 items.push( <> <TimelineItem event={event} offset={offset} index={i} detailed={!!event.body} /> <BulletLine offset={offset} angle={90 + (i % 2) * 180} length={i % 4 > 1 ? 'long' : 'short'} /> </>, ) i++ lastTimestamp = timestamp }) }) }) return { currentMonth, items } } interface SliceProps { slice: Timeline } export const TimelineSlice: React.FC<SliceProps> = ({ slice }) => { const { getMonthByIndex } = useDateUtils() const frameRef = useRef<HTMLDivElement>(null) const [position, setPosition] = useState(-1) const eventMap = useMemo(() => mapEvents(slice.events), [slice.events]) const { currentMonth, items } = useMemo( () => getTimeline(eventMap, getMonthByIndex), [], ) const moveTimeline = (dir: 'left' | 'right') => { if (dir === 'right') { setPosition( Math.min( position + 500, frameRef.current.scrollWidth - frameRef.current.offsetWidth + 50, ), ) } else { setPosition(Math.max(position - 500, 0)) } } useEffect(() => { setPosition(currentMonth - 100) frameRef.current.scrollTo({ left: currentMonth - 100, }) }, [currentMonth]) useEffect(() => { // used to ignore initial state if (position < 0) return frameRef.current.scrollTo({ left: position, behavior: 'smooth', }) }, [position]) const months = flatten( Array.from(eventMap).map((x) => { return Array.from(x[1]).map((y) => { return { year: x[0], month: y[0] } }) }), ) const [month, setMonth] = useState(() => { const today = new Date() const futureMonths = months .map((x, idx) => x.year >= today.getFullYear() && x.month >= today.getMonth() ? idx : 0, ) .filter((x) => x > 0) return Math.min(...futureMonths) }) const monthEvents = eventMap.get(months[month].year).get(months[month].month) return ( <section key={slice.id} aria-labelledby={'sliceTitle-' + slice.id}> <GridContainer> <Box paddingLeft={1}> <GridContainer> <GridRow> <GridColumn span={['9/9', '9/9', '7/9']} offset={['0', '0', '1/9']} > <Box borderTopWidth="standard" borderColor="standard" paddingTop={6} > <Text variant="h2" paddingBottom={3}> {slice.title} </Text> <Text>{slice.intro}</Text> </Box> </GridColumn> </GridRow> </GridContainer> <Hidden below="lg"> <div className={timelineStyles.timelineContainer}> <ArrowButtonShadow type="prev"> <ArrowButton type="prev" onClick={() => moveTimeline('left')} disabled={position === 0} /> </ArrowButtonShadow> <ArrowButtonShadow type="next"> <ArrowButton type="next" onClick={() => moveTimeline('right')} disabled={ frameRef.current?.scrollWidth - frameRef.current?.offsetWidth === position } /> </ArrowButtonShadow> <div className={timelineStyles.timelineGradient} /> <div ref={frameRef} className={timelineStyles.timelineComponent}> {items} </div> </div> </Hidden> <Hidden above="md"> <div className={timelineStyles.timelineContainer} style={{ height: 140 + monthEvents.length * 104, }} > <ArrowButtonShadow type="prev"> <ArrowButton type="prev" onClick={() => setMonth(Math.max(0, month - 1))} /> </ArrowButtonShadow> <ArrowButtonShadow type="next"> <ArrowButton type="next" onClick={() => setMonth(Math.min(months.length - 1, month + 1)) } /> </ArrowButtonShadow> <div className={timelineStyles.monthItem}> <Text color="blue600" variant="h2"> {months[month].year} </Text> <Text color="blue600" variant="eyebrow"> {getMonthByIndex(months[month].month)} </Text> </div> <div className={timelineStyles.mobileContainer}> {monthEvents.map((event) => ( <TimelineItem event={event} offset={0} index={0} detailed={!!event.body} mobile={true} /> ))} </div> </div> </Hidden> </Box> </GridContainer> </section> ) } interface ArrowButtonShadowProps { type: 'prev' | 'next' } const ArrowButtonShadow: React.FC<ArrowButtonShadowProps> = ({ children, type, }) => { return ( <div className={timelineStyles.arrowButtonShadow[type]}>{children}</div> ) } interface ArrowButtonProps { type: 'prev' | 'next' disabled?: boolean onClick: () => void } const ArrowButton = ({ type = 'prev', disabled = false, onClick, }: ArrowButtonProps) => { return ( <Box className={cn( timelineStyles.arrowButton, timelineStyles.arrowButtonTypes[type], )} > <Button colorScheme="light" circle icon="arrowBack" disabled={disabled} onClick={onClick} /> </Box> ) } const TimelineItem = ({ event, offset, index, detailed, mobile = false }) => { const positionStyles = [ { bottom: 136 }, { top: 136 }, { bottom: 20 }, { top: 20 }, ] const style = mobile ? {} : { left: offset - 208, alignItems: index % 2 ? 'flex-end' : 'flex-start', ...positionStyles[index % 4], } const [visible, setVisible] = useState(false) const portalRef = useRef() useEffect(() => { portalRef.current = document.querySelector('#__next') }) return detailed ? ( <div className={timelineStyles.item} style={{ alignItems: index % 2 ? 'flex-end' : 'flex-start', ...style, }} > <div className={timelineStyles.detailedItem} onClick={() => setVisible(true)} > <div className={timelineStyles.itemText}>{event.title}</div> </div> {visible && ReactDOM.createPortal( <ModalBase baseId="eventDetails" isVisible={true} initialVisibility={true} onVisibilityChange={(isVisible) => !isVisible && setVisible(false)} hideOnEsc={true} > <EventModal event={event} onClose={() => setVisible(false)} /> </ModalBase>, portalRef.current, )} </div> ) : ( <div className={timelineStyles.item} style={style}> <div className={timelineStyles.basicItem} style={{ alignItems: index % 2 ? 'flex-end' : 'flex-start' }} > <div className={timelineStyles.itemText}>{event.title}</div> </div> </div> ) } const BulletLine = ({ offset, angle, length = 'short', selected = false, }: { offset: number angle: number length: 'short' | 'long' selected?: boolean }) => { return ( <div className={timelineStyles.bulletLine} style={{ left: offset - 12, transform: `rotate(${angle}deg)`, }} > <svg xmlns="http://www.w3.org/2000/svg" width="244" height="24" fill="none" viewBox="0 0 244 24" > <path fill={selected ? '#ff0050' : '#99c0ff'} fillRule="evenodd" d={ length === 'short' ? 'M118.126 13A4.002 4.002 0 00126 12a4 4 0 00-8 0H24c0-6.627-5.373-12-12-12S0 5.373 0 12s5.373 12 12 12c6.29 0 11.45-4.84 11.959-11h94.167zM8 12a4 4 0 108 0 4 4 0 00-8 0z' : 'M234.126 13c1.185 4.535 7.86 3.687 7.874-1 0-5.333-8-5.333-8 0H24c0-6.627-5.373-12-12-12S0 5.373 0 12s5.373 12 12 12c6.29 0 11.45-4.84 11.959-11zM8 12c0 5.333 8 5.333 8 0s-8-5.333-8 0z' } clipRule="evenodd" ></path> </svg> </div> ) } const MonthItem = ({ month, offset, year = '' }) => { return ( <div className={timelineStyles.monthItem} style={{ left: offset }}> <Text color="blue600" variant="eyebrow"> {month} </Text> <Text color="blue600" variant="eyebrow"> {year} </Text> </div> ) } interface EventModalProps { event: Timeline['events'][0] onClose: () => void } const formatNumber = (value: number) => value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.') const EventModal = ({ event, onClose }: EventModalProps) => { if (!event) { return null } return ( <div className={eventStyles.eventModal}> <Box className={eventStyles.eventBarTitle} background="white" display="inlineFlex" > <Box className={eventStyles.eventBarIcon}> <Icon type="filled" icon="person" color="purple400" size="medium" /> </Box> {!!event.numerator && ( <Box display="inlineFlex" alignItems="center" className={eventStyles.nowrap} paddingLeft={2} paddingRight={4} > <Text variant="h2" color="purple400" as="span"> {formatNumber(event.numerator)} </Text> {!!event.denominator && ( <Text variant="h2" color="purple400" as="span" fontWeight="light"> /{formatNumber(event.denominator)} </Text> )} <Box marginLeft={1}> <Text variant="eyebrow" color="purple400" fontWeight="semiBold"> {event.label?.split(/[\r\n]+/).map((line, i) => ( <Fragment key={i}> {line} <br /> </Fragment> ))} </Text> </Box> </Box> )} </Box> <Box padding={6}> <Box className={eventStyles.eventModalClose}> <Button circle colorScheme="negative" icon="close" onClick={onClose} /> </Box> <Stack space={2}> <Text variant="h2" as="h3"> {event.title} </Text> {event.tags && ( <Inline space={2}> {event.tags.map((label, index) => ( <Tag key={index} variant="purple" outlined> {label} </Tag> ))} </Inline> )} {Boolean(event.body) && renderSlices([(event.body as unknown) as SliceType])} {event.link && ( <Link href={event.link}> <Button variant="text" icon="arrowForward"> Lesa meira </Button> </Link> )} </Stack> </Box> </div> ) }
the_stack
import {MemBuffer, Serializeable} from '../../misc/membuffer'; import {Utility} from '../../misc/utility'; /** * Watchpoint class used by 'watchPointMemory'. */ interface SimWatchpoint { // read/write are counters. They are reference counts and count how many // read/write access points have been set. If 0 then no watchpoint is set. read: number; write: number; } /** * Represents the simulated memory. * It is a base class to allow memory paging etc. * The simulated memory always works with slots although they might not be visible * to the outside. * I.e. the ZX48K is built of 4 slots per 16K. 1rst is ROM the other 3 are RAM. * To the outside is does not show any of these slots. * But for configuration (what is ROM/RAM) it is required. */ export class SimulatedMemory implements Serializeable { // The memory in one big block. // If banking is used in a derived class this array will extend 64k. protected memoryData: Uint8Array; // Holds the slot assignments to the banks. protected slots: number[]; // For each bank this array tells if it is ROM. protected romBanks: boolean[]; // The used bank size. protected bankSize: number; // The number of bits to shift to get the slot from the address protected shiftCount: number; // Visual memory: shows the access as an image. // The image is just 1 pixel high. protected visualMemory: Array<number>; // The size of the visual memory. protected VISUAL_MEM_SIZE_SHIFT=8; // Colors: protected VISUAL_MEM_COL_READ=1; protected VISUAL_MEM_COL_WRITE=2; protected VISUAL_MEM_COL_PROG=3; // Flag that is set if a watchpoint was hot. // Has to be reset manually before the next turn. public watchpointHit: boolean; // If watchpointHit was set the address where the hit occurred. // -1 if no hit. public hitAddress: number; // The kind of access, 'r'ead or 'w'rite. public hitAccess: string; // An array of 0-0xFFFF entries, one for each address. // If an address has no watchpoint it is undefined. // If it has it points to a SimWatchpoint. // Note: as watchpoints are areas, several addresses might share the same SimWatchpoint. protected watchPointMemory: Array<SimWatchpoint>; /** * Constructor. * Configures the slot and bank count. * @param slotCount Number of slots. * @param bankCount Number of banks. */ constructor(slotCount: number, bankCount: number) { Utility.assert(bankCount>=slotCount); // Create visual memory this.visualMemory=new Array<number>(1<<(16-this.VISUAL_MEM_SIZE_SHIFT)); this.clearVisualMemory(); // The "real" memory this.bankSize=0x10000/slotCount; // Create RAM this.memoryData=new Uint8Array(bankCount*this.bankSize); // No ROM at start this.romBanks=new Array<boolean>(bankCount); // All initialized to false. this.romBanks.fill(false); // Calculate number of bits to shift to get the slot index from the address. let sc=slotCount; let bits=0; while (sc>1) { bits++; sc/=2; } this.shiftCount=16-bits; // Associate banks with slots this.slots=new Array<number>(slotCount); for (let i=0; i<slotCount; i++) this.slots[i]=i; // Breakpoints this.clearHit(); // Create watchpoint area this.watchPointMemory=Array.from({length: 0x10000}, () => ({read: 0, write: 0})); } /** * Clears the whole memory (all banks) with 0s. * So far only used by unit tests. */ public clear() { this.memoryData.fill(0); } /** * Returns the memory used in all banks. * @returns this.memoryData */ public getMemoryData(): Uint8Array { return this.memoryData; } /** * At start all banks are RAM, even 0xFE and 0xFF. * Use this method to switch a bank to ROM. * I.e. any write8() will do nothing. * Is used e.g. if "loadZxRom" is used. * @param bank The bank number, e.g. 0xFE. * @param enableRom true to turn bank into ROM, false to turn it into RAM. */ /* public setRomBank(bank: number, enableRom: boolean) { this.romBanks[bank]=enableRom; } */ /** * Returns the size the serialized object would consume. */ public getSerializedSize(): number { // Create a MemBuffer to calculate the size. const memBuffer=new MemBuffer(); // Serialize object to obtain size this.serialize(memBuffer); // Get size const size=memBuffer.getSize(); return size; } /** * Serializes the object. */ public serialize(memBuffer: MemBuffer) { // Get slot/bank mapping memBuffer.write8(this.slots.length); for (const bank of this.slots) memBuffer.write8(bank); // Get RAM memBuffer.writeArrayBuffer(this.memoryData); } /** * Deserializes the object. */ public deserialize(memBuffer: MemBuffer) { // Store slot/bank association const slotLength=memBuffer.read8(); this.slots=[]; for (let i=0; i<slotLength; i++) this.slots.push(memBuffer.read8()); // Create memory banks const buffer=memBuffer.readArrayBuffer(); Utility.assert(buffer.length==this.memoryData.byteLength); this.memoryData.set(buffer); // Clear visual memory this.clearVisualMemory(); } /** * Adds a watchpoint address range. * @param address The watchpoint long address. * @param size The size of the watchpoint. address+size-1 is the last address for the watchpoint. * @param access 'r', 'w' or 'rw'. */ public setWatchpoint(address: number, size: number, access: string) { const readAdd=access.includes('r')? 1:0; const writeAdd=access.includes('w')? 1:0; // Set area for (let i=0; i<size; i++) { const wp=this.watchPointMemory[address&0xFFFF]; wp.read+=readAdd; wp.write+=writeAdd; address++; } } /** * Removes a watchpoint address range. * @param address The watchpoint long address. * @param size The size of the watchpoint. address+size-1 is the last address for the watchpoint. * @param access 'r', 'w' or 'rw'. */ public removeWatchpoint(address: number, size: number, access: string) { const readAdd=access.includes('r')? 1:0; const writeAdd=access.includes('w')? 1:0; // remove area for (let i=0; i<size; i++) { const wp=this.watchPointMemory[address&0xFFFF]; if (wp.read>0) wp.read-=readAdd; if(wp.write>0) wp.write-=writeAdd; address++; } } /** * Clears the hit flag and the arrays. */ public clearHit() { this.hitAddress=-1; this.hitAccess=''; } // Read 1 byte. // This is used by the Z80 CPU. public read8(addr: number): number { // Check for watchpoint access const wp=this.watchPointMemory[addr]; if (wp) { // Check access if ((this.hitAddress<0)&&wp.read>0) { // Read access this.hitAddress=addr; this.hitAccess='r'; } } // Visual memory this.visualMemory[addr>>>this.VISUAL_MEM_SIZE_SHIFT]=this.VISUAL_MEM_COL_READ; // Read const slotIndex=addr>>>this.shiftCount; const bankNr=this.slots[slotIndex]; const ramAddr=bankNr*this.bankSize+(addr&(this.bankSize-1)); // Convert to flat address const value=this.memoryData[ramAddr]; return value; } // Write 1 byte. // This is used by the Z80 CPU. public write8(addr: number, val: number) { // Check for watchpoint access const wp=this.watchPointMemory[addr]; if (wp) { // Check access if ((this.hitAddress<0)&&wp.write>0) { // Write access this.hitAddress=addr; this.hitAccess='w'; } } // Visual memory this.visualMemory[addr>>>this.VISUAL_MEM_SIZE_SHIFT]=this.VISUAL_MEM_COL_WRITE; // Convert to bank const slotIndex=addr>>>this.shiftCount; const bankNr=this.slots[slotIndex]; // Don't write if ROM if (this.romBanks[bankNr]) return; // Convert to flat address const ramAddr=bankNr*this.bankSize+(addr&(this.bankSize-1)); // Write this.memoryData[ramAddr]=val; } // Reads one byte. // This is **not** used by the Z80 CPU. public getMemory8(addr: number): number { const slotIndex=addr>>>this.shiftCount; const bankNr=this.slots[slotIndex]; const ramAddr=bankNr*this.bankSize+(addr&(this.bankSize-1)); // Convert to flat address const value=this.memoryData[ramAddr]; return value; } // Reads 2 bytes. // This is **not** used by the Z80 CPU. public getMemory16(addr: number): number { // First byte let address=addr&(this.bankSize-1); let slotIndex=addr>>>this.shiftCount; let bankNr=this.slots[slotIndex]; let ramAddr=bankNr*this.bankSize+address; // Convert to flat address const mem=this.memoryData; let value=mem[ramAddr]; // Second byte address++; if (address<this.bankSize) { // No overflow, same bank, normal case ramAddr++; } else { // Overflow slotIndex=((addr+1)&0xFFFF)>>>this.shiftCount; bankNr=this.slots[slotIndex]; ramAddr=bankNr*this.bankSize; // Convert to flat address } value+=mem[ramAddr]<<8; return value; } // Reads 4 bytes. // This is **not** used by the Z80 CPU. public getMemory32(addr: number): number { // First byte let address=addr&(this.bankSize-1); let slotIndex=addr>>>this.shiftCount; let bankNr=this.slots[slotIndex]; let ramAddr=bankNr*this.bankSize+address; // Convert to flat address const mem=this.memoryData; let value=mem[ramAddr]; // Second byte if (address<=this.bankSize-3) { // E.g. 0x2000-3 // No overflow, same bank, normal case value+=mem[++ramAddr]<<8; value+=mem[++ramAddr]<<16; value+=mem[++ramAddr]*256*65536; // Otherwise the result might be negative } else { // Overflow, do each part one-by-one let mult=256; for (let i=3; i>0; i--) { addr++; address=addr&(this.bankSize-1); slotIndex=(addr&0xFFFF)>>>this.shiftCount; bankNr=this.slots[slotIndex]; ramAddr=bankNr*this.bankSize+address; // Convert to flat address value+=mem[ramAddr]*mult; // Next mult*=256; } } return value; } // Sets one byte. // This is **not** used by the Z80 CPU. public setMemory8(addr: number, val: number) { // First byte let address=addr&(this.bankSize-1); let slotIndex=addr>>>this.shiftCount; let bankNr=this.slots[slotIndex]; let ramAddr=bankNr*this.bankSize+address; // Convert to flat address const mem=this.memoryData; mem[ramAddr]=val&0xFF; } // Sets one word. // This is **not** used by the Z80 CPU. public setMemory16(addr: number, val: number) { // First byte let address=addr&(this.bankSize-1); let slotIndex=addr>>>this.shiftCount; let bankNr=this.slots[slotIndex]; let ramAddr=bankNr*this.bankSize+address; // Convert to flat address const mem=this.memoryData; mem[ramAddr]=val&0xFF; // Second byte address++; if (address<0x2000) { // No overflow, same bank, normal case ramAddr++; } else { // Overflow slotIndex=((addr+1)&0xFFFF)>>>this.shiftCount; bankNr=this.slots[slotIndex]; ramAddr=bankNr*this.bankSize; // Convert to flat address } mem[ramAddr]=val>>>8; } /** * Write to memoryData direcly. * Is e.g. used during SNA / NEX file loading. * @param offset Offset into the memData. I.e. can be bigger than 0x10000. * @param data The data to write. */ public writeMemoryData(offset: number, data: Uint8Array) { // Check size let size=data.length; if (offset+size>this.memoryData.length) size=this.memoryData.length-offset; if (size<=0) return; // Nothing to write // Copy const data2=data.slice(0, size); this.memoryData.set(data2, offset); } // Write 1 byte. public setVisualProg(addr: number) { // Visual memory this.visualMemory[addr>>>this.VISUAL_MEM_SIZE_SHIFT]=this.VISUAL_MEM_COL_PROG; } /** * Returns the bank memory and the address into it. * @param addr The ZX spectrum memory address. * @returns [number, Uint8Array] The address (0-0x1FFF) and the memory bank array. */ /* public getBankForAddr(addr: number): [number, Uint8Array] { const slot=(addr>>>13)&0x07; const bankAddr=addr&0x1FFF; const bank=this.slots[slot]; const bankMem=this.banks[bank]; Utility.assert(bankMem); return [bankAddr, bankMem]; } */ /** * Associates a slot with a bank number. */ public setSlot(slot: number, bank: number) { this.slots[slot]=bank; } /** * Returns the slots array. */ public getSlots(): number[]|undefined { //return this.slots; return undefined; } /** * Reads a block of bytes. * @param startAddress Start address. * @param size The size of the block. */ public readBlock(startAddress: number, size: number): Uint8Array { const totalBlock=new Uint8Array(size); let offset=0; // The block may span several banks. let addr=startAddress; const mem=this.memoryData; while (size>0) { // Get memory bank const slot=(addr&0xFFFF)>>>this.shiftCount; const bankAddr=addr&(this.bankSize-1); const bank=this.slots[slot]; let ramAddr=bank*this.bankSize+bankAddr; // Get block within one bank let blockEnd=bankAddr+size; if (blockEnd>this.bankSize) blockEnd=this.bankSize; const partBlockSize=blockEnd-bankAddr; // Copy partial block const partBlock=mem.subarray(ramAddr, ramAddr+partBlockSize); // Add to total block totalBlock.set(partBlock, offset); // Next offset+=partBlockSize; size-=partBlockSize; addr+=partBlockSize; } return totalBlock; } /** * Writes a block of bytes. * @param startAddress Start address. * @param totalBlock The block to write. */ public writeBlock(startAddress: number, totalBlock: Buffer|Uint8Array) { if (!(totalBlock instanceof Uint8Array)) totalBlock=new Uint8Array(totalBlock); let offset=0; // The block may span several banks. let addr=startAddress; let size=totalBlock.length; const mem=this.memoryData; while (size>0) { // Get memory bank const slot=(addr&0xFFFF)>>>this.shiftCount; const bankAddr=addr&(this.bankSize-1); const bank=this.slots[slot]; let ramAddr=bank*this.bankSize+bankAddr; // Get block within one bank let blockEnd=bankAddr+size; if (blockEnd>this.bankSize) blockEnd=this.bankSize; const partBlockSize=blockEnd-bankAddr; // Copy partial block const partBlock=totalBlock.subarray(offset, offset+partBlockSize); // Copy to memory bank mem.set(partBlock, ramAddr); // Next offset+=partBlockSize; size-=partBlockSize; addr+=partBlockSize; } return totalBlock; } /** * Writes a complete memory bank. * @param bank The bank number. * @param block The block to write. */ public writeBank(bank: number, block: Buffer|Uint8Array) { if (block.length!=this.bankSize) throw Error("writeBank: Block length "+block.length+" not allowed. Expected "+this.bankSize+"."); let ramAddr=bank*this.bankSize; this.memoryData.set(block, ramAddr); } /** * Clears the visual buffer. */ public clearVisualMemory() { this.visualMemory.fill(0); } /** * @returns The visual memory as a buffer. */ public getVisualMemory(): number[] { return this.visualMemory; } }
the_stack
import { Auto, IPlugin, execPromise, getLernaPackages, inFolder, validatePluginConfiguration, } from "@auto-it/core"; import envCi from "env-ci"; import endent from "endent"; import botList from "@auto-it/bot-list"; import fs from "fs"; import path from "path"; import match from "anymatch"; import on from "await-to-js"; import { IExtendedCommit } from "@auto-it/core/src/log-parse"; import * as t from "io-ts"; import fromEntries from "fromentries"; import addContributor from "all-contributors-cli/dist/contributors"; import generateReadme from "all-contributors-cli/dist/generate"; const contributionTypes = [ "blog", "bug", "business", "code", "content", "data", "design", "doc", "eventOrganizing", "example", "financial", "fundingFinding", "ideas", "infra", "maintenance", "platform", "plugin", "projectManagement", "question", "review", "security", "talk", "test", "tool", "translation", "tutorial", "userTesting", "video", ] as const; type Contribution = typeof contributionTypes[number]; /** Determine if it's a valid contribution type */ const isContribution = ( contribution: string | Contribution ): contribution is Contribution => contributionTypes.includes(contribution as Contribution); /** Get an rc file if there is one. */ function getRcFile(auto: Auto) { const rcFile = path.join(process.cwd(), ".all-contributorsrc"); if (!fs.existsSync(rcFile)) { auto.logger.verbose.warn( `No all-contributors configuration file found at: ${rcFile}` ); return; } try { const config: AllContributorsRc = JSON.parse( fs.readFileSync(rcFile, "utf8") ); return { ...config, config: rcFile }; } catch (error) { auto.logger.log.error( `Encountered errors loading all-contributors configuration at ${rcFile}`, error ); process.exit(1); } } const pattern = t.union([t.string, t.array(t.string)]); const pluginOptions = t.partial({ /** Usernames to exclude from the contributors */ exclude: t.array(t.string), /** Globs to detect change types by */ types: t.partial( fromEntries(contributionTypes.map((c) => [c, pattern])) as Record< Contribution, typeof pattern > ), }); export type IAllContributorsPluginOptions = t.TypeOf<typeof pluginOptions>; interface Contributor { /** GitHub username */ login: string; /** Types of contributions they've made */ contributions: Contribution[]; } interface AllContributorsRc { /** All of the current contributors */ contributors: Contributor[]; /** Files to generate a markdown table of contributors in */ files?: string[]; } const defaultOptions: IAllContributorsPluginOptions = { exclude: botList, types: { doc: ["**/*.mdx", "**/*.md", "**/docs/**/*", "**/documentation/**/*"], example: ["**/*.stories*", "**/*.story.*"], infra: ["**/.circle/**/*", "**/.github/**/*", "**/travis.yml"], test: ["**/*.test.*", "**/test/**", "**/__tests__/**"], code: ["**/src/**/*", "**/lib/**/*", "**/package.json", "**/tsconfig.json"], }, }; const title = /[#]{0,5}[ ]*[C|c]ontributions/; const contributorLine = /^[-*] @(\S+)\s+[:-]\s+([\S ,]+)$/; /** Find contributions listed in PR bodies */ function getExtraContributors(body?: string | null) { const authorContributions: Record<string, Set<string>> = {}; if (!body) { return; } const start = body.match(title); if (!start) { return; } body .slice((start.index || 0) + (start[0] || "").length) .replace(/\r\n/g, "\n") .split("\n") .forEach((line) => { if (line.startsWith("#") || line.startsWith("<!--")) { return; } const contributor = line.match(contributorLine); if (!contributor) { return; } const [, username, contributions] = contributor; if (!authorContributions[username]) { authorContributions[username] = new Set(); } contributions .split(",") .map((contribution) => contribution.trim()) .forEach((contribution) => authorContributions[username].add(contribution) ); }); return authorContributions; } /** Determine which files need to display contributors and generate contributors */ function generateContributorReadme( config: AllContributorsRc, contributors: any ) { return Promise.all( (config.files || ["README.md"]).map(async (file) => { const oldReadMe = fs.readFileSync(file, { encoding: "utf-8", }); const newReadMe = await generateReadme( { contributorsPerLine: 7, imageSize: 100, ...config, contributors, }, contributors, oldReadMe ); fs.writeFileSync(file, newReadMe); }) ); } /** Automatically add contributors as changelogs are produced. */ export default class AllContributorsPlugin implements IPlugin { /** The name of the plugin */ name = "all-contributors"; /** The options of the plugin */ readonly options: Required<IAllContributorsPluginOptions>; /** Has the Readme been initialized */ private generatedReadme: boolean; /** Initialize the plugin with it's options */ constructor(options: IAllContributorsPluginOptions = {}) { this.options = { exclude: [...(defaultOptions.exclude || []), ...(options.exclude || [])], types: { ...defaultOptions.types, ...options.types }, }; this.generatedReadme = false; } /** Tap into auto plugin points. */ apply(auto: Auto) { const env = envCi(); auto.hooks.validateConfig.tapPromise(this.name, async (name, options) => { if (name === this.name || name === `@auto-it/${this.name}`) { return validatePluginConfiguration(this.name, pluginOptions, options); } }); auto.hooks.beforeShipIt.tapPromise(this.name, async (context) => { if ( context.releaseType === "latest" || context.releaseType === "old" || !("pr" in env) ) { return; } const pr = Number(env.pr); if (!pr) { return; } const prInfo = await auto.git?.getPullRequest(pr); auto.logger.log.info(this.name, { prInfo }); if (!prInfo) { return; } const extra = getExtraContributors(prInfo.data.body); auto.logger.log.info(this.name, { extra }); if (!extra || !Object.keys(extra).length) { return; } const allContributions = Object.values(extra).reduce<string[]>( (all, i) => [...all, ...i], [] ); const unknownTypes = allContributions.filter( (contribution) => !contributionTypes.includes(contribution as Contribution) ); const hasValidTypes = allContributions.length !== unknownTypes.length; const message = endent` # Extra Contributions ${ hasValidTypes ? endent` The following contributions will be added to all-contributors (as well as any code contributions) when this PR is released :tada:: ${Object.entries(extra) .map(([username, contributions]) => { const validContributions = [...contributions].filter( isContribution ); if (!validContributions.length) { return ""; } return `- @${username} - ${validContributions.join(", ")}`; }) .filter(Boolean) .join("\n")} ` : "No valid contribution types found!" } ${ unknownTypes.length ? endent` ## Unknown Contribution Types We found some unknown contribution types in your PR body! These contributions will not be counted and you should fix them. ${unknownTypes.map((type) => `- \`${type}\``)} ` : "" } `; await auto.comment({ pr, context: "Extra Contributions", edit: true, message, }); }); auto.hooks.afterChangelog.tapPromise(this.name, async ({ commits }) => { const rootDir = process.cwd(); // Always do the root package let packages = [{ path: rootDir, name: "root-package" }]; try { // Try to get sub-packages packages = [...packages, ...(await getLernaPackages())]; } catch (error) {} // Go through each package and update code contributions await packages.reduce(async (last, { name, path }) => { // Cannot run git operations in parallel await last; auto.logger.verbose.info(`Updating contributors for: ${name}`); const includedCommits = commits.filter((commit) => commit.files.some((file) => inFolder(path, file)) ); if (includedCommits.length > 0) { auto.logger.verbose.success( `${name} has ${includedCommits.length} new commits.` ); auto.logger.veryVerbose.info( `With commits: ${JSON.stringify(includedCommits, null, 2)}` ); process.chdir(path); await this.updateContributors(auto, includedCommits); } }, Promise.resolve()); process.chdir(rootDir); const changedFiles = await execPromise("git", ["status", "--porcelain"]); if (changedFiles) { await execPromise("git", ["add", "README.md"]); await execPromise("git", ["add", ".all-contributorsrc"]); await on(execPromise("git", ["add", "**/README.md"])); await on(execPromise("git", ["add", "**/.all-contributorsrc"])); await execPromise("git", [ "commit", "--no-verify", "-m", '"Update contributors [skip ci]"', ]); } }); auto.hooks.onCreateLogParse.tap(this.name, (logParse) => { logParse.hooks.parseCommit.tapPromise(this.name, async (commit) => { const extraContributions = getExtraContributors(commit.rawBody); if (!extraContributions) { return commit; } const contributors = ( await Promise.all( Object.keys(extraContributions).map(async (contributor) => auto.git?.getUserByUsername(contributor) ) ) ).filter((c): c is NonNullable<typeof c> => Boolean(c)); return { ...commit, authors: [ ...commit.authors, ...contributors.map((c) => ({ ...c, username: c.login })), ], }; }); }); } /** Update the contributors rc for a package. */ private async updateContributors(auto: Auto, commits: IExtendedCommit[]) { const config = getRcFile(auto); if (!config) { return; } const authorContributions: Record<string, Set<Contribution>> = {}; let didUpdate = false; const commitsWithAllChangedFiles = await Promise.all( commits.map(async (commit) => { const extra = await execPromise("git", [ "show", '--pretty=""', "--name-only", "--first-parent", "-m", commit.hash, "-l0", ]); commit.files = [...new Set([...commit.files, ...extra.split("\n")])]; return commit; }) ); // 1. Find all the authors and their contribution types commitsWithAllChangedFiles.forEach((commit) => { const { authors } = commit; let { files } = commit; // Find automated contribution for type globs Object.keys(this.options.types || {}) .filter((type): type is Contribution => { /** Determine if path is the contribution type */ const isType = (file: string) => match(this.options.types[type as Contribution] || [], file); const isMatch = files.some(isType); files = files.filter((file) => !isType(file)); return isMatch; }) .forEach((contribution) => { authors.forEach(({ username }) => { if (!username) { return; } if (!authorContributions[username]) { authorContributions[username] = new Set(); } authorContributions[username].add(contribution); }); }); // Find contributions listed in PR bodies const extra = getExtraContributors(commit.rawBody); if (extra) { Object.entries(extra).forEach(([username, contributions]) => { if (!authorContributions[username]) { authorContributions[username] = new Set(); } [...contributions] .filter(isContribution) .forEach((contribution) => authorContributions[username].add(contribution) ); }); } }); auto.logger.verbose.info("Found contributions:", authorContributions); // 2. Determine if contributor has update for await (const [username, contributions] of Object.entries( authorContributions )) { const { contributions: old = [] } = config.contributors.find( (contributor) => contributor.login.toLowerCase() === username.toLowerCase() ) || {}; const hasNew = [...contributions].find( (contribution) => !old.includes(contribution) ); if (hasNew && !this.options.exclude.includes(username)) { const newContributions = new Set([...old, ...contributions]); didUpdate = true; auto.logger.log.info(`Adding "${username}"'s contributions...`); // If a PRIVATE_TOKEN is not set for all-contributors-cli // use the GH_TOKEN if (process.env.PRIVATE_TOKEN === undefined) { process.env.PRIVATE_TOKEN = process.env.GH_TOKEN; } // Update/add contributor in RC file const { contributors } = await addContributor( config, username, Array.from(newContributions).join(",") ); this.generatedReadme = true; // Update files that contain contributors table await generateContributorReadme(config, contributors); } else { auto.logger.verbose.warn(`"${username}" had no new contributions...`); } } if (config.contributors.length && !this.generatedReadme) { // if the all-contributors has not been generated ... generate it try { // test if the first file in the list of files has been init const file = path.join( process.cwd(), config.files ? config.files[0] : "README.md" ); const displayFile = file ? fs.readFileSync(file, "utf8") : ""; const notInitalized = displayFile.indexOf( "<!-- markdownlint-disable -->\n<!-- markdownlint-restore -->" ); if (notInitalized && file) { await generateContributorReadme(config, config.contributors); } } catch {} } if (didUpdate) { auto.logger.log.success("Updated contributors!"); } } }
the_stack
import { EventDispatcher, MOUSE, Quaternion, Vector2, Vector3, PerspectiveCamera, OrthographicCamera } from 'three' class TrackballControls extends EventDispatcher { public enabled = true public screen = { left: 0, top: 0, width: 0, height: 0 } public rotateSpeed = 1.0 public zoomSpeed = 1.2 public panSpeed = 0.3 public noRotate = false public noZoom = false public noPan = false public staticMoving = false public dynamicDampingFactor = 0.2 public minDistance = 0 public maxDistance = Infinity public keys: [string, string, string] = ['KeyA' /*A*/, 'KeyS' /*S*/, 'KeyD' /*D*/] public mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN, } public object: PerspectiveCamera | OrthographicCamera public domElement: HTMLElement | undefined public cursorZoom: boolean = false private target = new Vector3() private mousePosition = new Vector2() // internals private STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4, } private EPS = 0.000001 private lastZoom = 1 private lastPosition = new Vector3() private cursorVector = new Vector3() private targetVector = new Vector3() private _state = this.STATE.NONE private _keyState = this.STATE.NONE private _eye = new Vector3() private _movePrev = new Vector2() private _moveCurr = new Vector2() private _lastAxis = new Vector3() private _lastAngle = 0 private _zoomStart = new Vector2() private _zoomEnd = new Vector2() private _touchZoomDistanceStart = 0 private _touchZoomDistanceEnd = 0 private _panStart = new Vector2() private _panEnd = new Vector2() private target0: Vector3 private position0: Vector3 private up0: Vector3 private zoom0: number // events private changeEvent = { type: 'change' } private startEvent = { type: 'start' } private endEvent = { type: 'end' } constructor(object: PerspectiveCamera | OrthographicCamera, domElement?: HTMLElement) { super() this.object = object // for reset this.target0 = this.target.clone() this.position0 = this.object.position.clone() this.up0 = this.object.up.clone() this.zoom0 = this.object.zoom // connect events if (domElement !== undefined) this.connect(domElement) // force an update at start this.update() } private onScreenVector = new Vector2() private getMouseOnScreen = (pageX: number, pageY: number): Vector2 => { this.onScreenVector.set( (pageX - this.screen.left) / this.screen.width, (pageY - this.screen.top) / this.screen.height, ) return this.onScreenVector } private onCircleVector = new Vector2() private getMouseOnCircle = (pageX: number, pageY: number): Vector2 => { this.onCircleVector.set( (pageX - this.screen.width * 0.5 - this.screen.left) / (this.screen.width * 0.5), (this.screen.height + 2 * (this.screen.top - pageY)) / this.screen.width, // screen.width intentional ) return this.onCircleVector } private axis = new Vector3() private quaternion = new Quaternion() private eyeDirection = new Vector3() private objectUpDirection = new Vector3() private objectSidewaysDirection = new Vector3() private moveDirection = new Vector3() private angle: number = 0 private rotateCamera = (): void => { this.moveDirection.set(this._moveCurr.x - this._movePrev.x, this._moveCurr.y - this._movePrev.y, 0) this.angle = this.moveDirection.length() if (this.angle) { this._eye.copy(this.object.position).sub(this.target) this.eyeDirection.copy(this._eye).normalize() this.objectUpDirection.copy(this.object.up).normalize() this.objectSidewaysDirection.crossVectors(this.objectUpDirection, this.eyeDirection).normalize() this.objectUpDirection.setLength(this._moveCurr.y - this._movePrev.y) this.objectSidewaysDirection.setLength(this._moveCurr.x - this._movePrev.x) this.moveDirection.copy(this.objectUpDirection.add(this.objectSidewaysDirection)) this.axis.crossVectors(this.moveDirection, this._eye).normalize() this.angle *= this.rotateSpeed this.quaternion.setFromAxisAngle(this.axis, this.angle) this._eye.applyQuaternion(this.quaternion) this.object.up.applyQuaternion(this.quaternion) this._lastAxis.copy(this.axis) this._lastAngle = this.angle } else if (!this.staticMoving && this._lastAngle) { this._lastAngle *= Math.sqrt(1.0 - this.dynamicDampingFactor) this._eye.copy(this.object.position).sub(this.target) this.quaternion.setFromAxisAngle(this._lastAxis, this._lastAngle) this._eye.applyQuaternion(this.quaternion) this.object.up.applyQuaternion(this.quaternion) } this._movePrev.copy(this._moveCurr) } private zoomCamera = (): void => { let factor if (this._state === this.STATE.TOUCH_ZOOM_PAN) { factor = this._touchZoomDistanceStart / this._touchZoomDistanceEnd this._touchZoomDistanceStart = this._touchZoomDistanceEnd if ((this.object as PerspectiveCamera).isPerspectiveCamera) { this._eye.multiplyScalar(factor) } else if ((this.object as OrthographicCamera).isOrthographicCamera) { this.object.zoom /= factor this.object.updateProjectionMatrix() } else { console.warn('THREE.TrackballControls: Unsupported camera type') } } else { factor = 1.0 + (this._zoomEnd.y - this._zoomStart.y) * this.zoomSpeed if (Math.abs(factor - 1.0) > this.EPS && factor > 0.0) { if ((this.object as PerspectiveCamera).isPerspectiveCamera) { if (factor > 1.0 && this._eye.length() >= this.maxDistance - this.EPS) { factor = 1.0 } this._eye.multiplyScalar(factor) } else if ((this.object as OrthographicCamera).isOrthographicCamera) { if (factor > 1.0 && this.object.zoom < this.maxDistance * this.maxDistance) { factor = 1.0 } this.object.zoom /= factor } else { console.warn('THREE.TrackballControls: Unsupported camera type') } } if (this.staticMoving) { this._zoomStart.copy(this._zoomEnd) } else { this._zoomStart.y += (this._zoomEnd.y - this._zoomStart.y) * this.dynamicDampingFactor } if (this.cursorZoom) { //determine 3D position of mouse cursor (on target plane) this.targetVector.copy(this.target).project(this.object) let worldPos = this.cursorVector .set(this.mousePosition.x, this.mousePosition.y, this.targetVector.z) .unproject(this.object) //adjust target point so that "point" stays in place this.target.lerpVectors(worldPos, this.target, factor) } // Update the projection matrix after all properties are changed if ((this.object as OrthographicCamera).isOrthographicCamera) { this.object.updateProjectionMatrix() } } } private mouseChange = new Vector2() private objectUp = new Vector3() private pan = new Vector3() private panCamera = (): void => { if (!this.domElement) return this.mouseChange.copy(this._panEnd).sub(this._panStart) if (this.mouseChange.lengthSq() > this.EPS) { if ((this.object as OrthographicCamera).isOrthographicCamera) { const orthoObject = this.object as OrthographicCamera const scale_x = (orthoObject.right - orthoObject.left) / this.object.zoom const scale_y = (orthoObject.top - orthoObject.bottom) / this.object.zoom this.mouseChange.x *= scale_x this.mouseChange.y *= scale_y } else { this.mouseChange.multiplyScalar(this._eye.length() * this.panSpeed) } this.pan.copy(this._eye).cross(this.object.up).setLength(this.mouseChange.x) this.pan.add(this.objectUp.copy(this.object.up).setLength(this.mouseChange.y)) this.object.position.add(this.pan) this.target.add(this.pan) if (this.staticMoving) { this._panStart.copy(this._panEnd) } else { this._panStart.add( this.mouseChange.subVectors(this._panEnd, this._panStart).multiplyScalar(this.dynamicDampingFactor), ) } } } private checkDistances = (): void => { if (!this.noZoom || !this.noPan) { if (this._eye.lengthSq() > this.maxDistance * this.maxDistance) { this.object.position.addVectors(this.target, this._eye.setLength(this.maxDistance)) this._zoomStart.copy(this._zoomEnd) } if (this._eye.lengthSq() < this.minDistance * this.minDistance) { this.object.position.addVectors(this.target, this._eye.setLength(this.minDistance)) this._zoomStart.copy(this._zoomEnd) } } } public handleResize = (): void => { if (!this.domElement) return const box = this.domElement.getBoundingClientRect() // adjustments come from similar code in the jquery offset() function const d = this.domElement.ownerDocument.documentElement this.screen.left = box.left + window.pageXOffset - d.clientLeft this.screen.top = box.top + window.pageYOffset - d.clientTop this.screen.width = box.width this.screen.height = box.height } public update = (): void => { this._eye.subVectors(this.object.position, this.target) if (!this.noRotate) { this.rotateCamera() } if (!this.noZoom) { this.zoomCamera() } if (!this.noPan) { this.panCamera() } this.object.position.addVectors(this.target, this._eye) if ((this.object as PerspectiveCamera).isPerspectiveCamera) { this.checkDistances() this.object.lookAt(this.target) if (this.lastPosition.distanceToSquared(this.object.position) > this.EPS) { this.dispatchEvent(this.changeEvent) this.lastPosition.copy(this.object.position) } } else if ((this.object as OrthographicCamera).isOrthographicCamera) { this.object.lookAt(this.target) if (this.lastPosition.distanceToSquared(this.object.position) > this.EPS || this.lastZoom !== this.object.zoom) { this.dispatchEvent(this.changeEvent) this.lastPosition.copy(this.object.position) this.lastZoom = this.object.zoom } } else { console.warn('THREE.TrackballControls: Unsupported camera type') } } public reset = (): void => { this._state = this.STATE.NONE this._keyState = this.STATE.NONE this.target.copy(this.target0) this.object.position.copy(this.position0) this.object.up.copy(this.up0) this.object.zoom = this.zoom0 this.object.updateProjectionMatrix() this._eye.subVectors(this.object.position, this.target) this.object.lookAt(this.target) this.dispatchEvent(this.changeEvent) this.lastPosition.copy(this.object.position) this.lastZoom = this.object.zoom } private keydown = (event: KeyboardEvent): void => { if (this.enabled === false) return window.removeEventListener('keydown', this.keydown) if (this._keyState !== this.STATE.NONE) { return } else if (event.code === this.keys[this.STATE.ROTATE] && !this.noRotate) { this._keyState = this.STATE.ROTATE } else if (event.code === this.keys[this.STATE.ZOOM] && !this.noZoom) { this._keyState = this.STATE.ZOOM } else if (event.code === this.keys[this.STATE.PAN] && !this.noPan) { this._keyState = this.STATE.PAN } } private onPointerDown = (event: PointerEvent): void => { if (this.enabled === false) return switch (event.pointerType) { case 'mouse': case 'pen': this.onMouseDown(event) break // TODO touch } } private onPointerMove = (event: PointerEvent): void => { if (this.enabled === false) return switch (event.pointerType) { case 'mouse': case 'pen': this.onMouseMove(event) break // TODO touch } } private onPointerUp = (event: PointerEvent): void => { if (this.enabled === false) return switch (event.pointerType) { case 'mouse': case 'pen': this.onMouseUp() break // TODO touch } } private keyup = (): void => { if (this.enabled === false) return this._keyState = this.STATE.NONE window.addEventListener('keydown', this.keydown) } private onMouseDown = (event: MouseEvent): void => { if (!this.domElement) return if (this._state === this.STATE.NONE) { switch (event.button) { case this.mouseButtons.LEFT: this._state = this.STATE.ROTATE break case this.mouseButtons.MIDDLE: this._state = this.STATE.ZOOM break case this.mouseButtons.RIGHT: this._state = this.STATE.PAN break default: this._state = this.STATE.NONE } } const state = this._keyState !== this.STATE.NONE ? this._keyState : this._state if (state === this.STATE.ROTATE && !this.noRotate) { this._moveCurr.copy(this.getMouseOnCircle(event.pageX, event.pageY)) this._movePrev.copy(this._moveCurr) } else if (state === this.STATE.ZOOM && !this.noZoom) { this._zoomStart.copy(this.getMouseOnScreen(event.pageX, event.pageY)) this._zoomEnd.copy(this._zoomStart) } else if (state === this.STATE.PAN && !this.noPan) { this._panStart.copy(this.getMouseOnScreen(event.pageX, event.pageY)) this._panEnd.copy(this._panStart) } this.domElement.ownerDocument.addEventListener('pointermove', this.onPointerMove) this.domElement.ownerDocument.addEventListener('pointerup', this.onPointerUp) this.dispatchEvent(this.startEvent) } private onMouseMove = (event: MouseEvent): void => { if (this.enabled === false) return const state = this._keyState !== this.STATE.NONE ? this._keyState : this._state if (state === this.STATE.ROTATE && !this.noRotate) { this._movePrev.copy(this._moveCurr) this._moveCurr.copy(this.getMouseOnCircle(event.pageX, event.pageY)) } else if (state === this.STATE.ZOOM && !this.noZoom) { this._zoomEnd.copy(this.getMouseOnScreen(event.pageX, event.pageY)) } else if (state === this.STATE.PAN && !this.noPan) { this._panEnd.copy(this.getMouseOnScreen(event.pageX, event.pageY)) } } private onMouseUp = (): void => { if (!this.domElement) return if (this.enabled === false) return this._state = this.STATE.NONE this.domElement.ownerDocument.removeEventListener('pointermove', this.onPointerMove) this.domElement.ownerDocument.removeEventListener('pointerup', this.onPointerUp) this.dispatchEvent(this.endEvent) } private mousewheel = (event: WheelEvent): void => { if (this.enabled === false) return if (this.noZoom === true) return event.preventDefault() switch (event.deltaMode) { case 2: // Zoom in pages this._zoomStart.y -= event.deltaY * 0.025 break case 1: // Zoom in lines this._zoomStart.y -= event.deltaY * 0.01 break default: // undefined, 0, assume pixels this._zoomStart.y -= event.deltaY * 0.00025 break } this.mousePosition.x = (event.offsetX / this.screen.width) * 2 - 1 this.mousePosition.y = -(event.offsetY / this.screen.height) * 2 + 1 this.dispatchEvent(this.startEvent) this.dispatchEvent(this.endEvent) } private touchstart = (event: TouchEvent): void => { if (this.enabled === false) return event.preventDefault() switch (event.touches.length) { case 1: this._state = this.STATE.TOUCH_ROTATE this._moveCurr.copy(this.getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY)) this._movePrev.copy(this._moveCurr) break default: // 2 or more this._state = this.STATE.TOUCH_ZOOM_PAN const dx = event.touches[0].pageX - event.touches[1].pageX const dy = event.touches[0].pageY - event.touches[1].pageY this._touchZoomDistanceEnd = this._touchZoomDistanceStart = Math.sqrt(dx * dx + dy * dy) const x = (event.touches[0].pageX + event.touches[1].pageX) / 2 const y = (event.touches[0].pageY + event.touches[1].pageY) / 2 this._panStart.copy(this.getMouseOnScreen(x, y)) this._panEnd.copy(this._panStart) break } this.dispatchEvent(this.startEvent) } private touchmove = (event: TouchEvent): void => { if (this.enabled === false) return event.preventDefault() switch (event.touches.length) { case 1: this._movePrev.copy(this._moveCurr) this._moveCurr.copy(this.getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY)) break default: // 2 or more const dx = event.touches[0].pageX - event.touches[1].pageX const dy = event.touches[0].pageY - event.touches[1].pageY this._touchZoomDistanceEnd = Math.sqrt(dx * dx + dy * dy) const x = (event.touches[0].pageX + event.touches[1].pageX) / 2 const y = (event.touches[0].pageY + event.touches[1].pageY) / 2 this._panEnd.copy(this.getMouseOnScreen(x, y)) break } } private touchend = (event: TouchEvent): void => { if (this.enabled === false) return switch (event.touches.length) { case 0: this._state = this.STATE.NONE break case 1: this._state = this.STATE.TOUCH_ROTATE this._moveCurr.copy(this.getMouseOnCircle(event.touches[0].pageX, event.touches[0].pageY)) this._movePrev.copy(this._moveCurr) break } this.dispatchEvent(this.endEvent) } private contextmenu = (event: MouseEvent): void => { if (this.enabled === false) return event.preventDefault() } // https://github.com/mrdoob/three.js/issues/20575 public connect = (domElement: HTMLElement): void => { if ((domElement as any) === document) { console.error( 'THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.', ) } this.domElement = domElement this.domElement.addEventListener('contextmenu', this.contextmenu) this.domElement.addEventListener('pointerdown', this.onPointerDown) this.domElement.addEventListener('wheel', this.mousewheel) this.domElement.addEventListener('touchstart', this.touchstart) this.domElement.addEventListener('touchend', this.touchend) this.domElement.addEventListener('touchmove', this.touchmove) this.domElement.ownerDocument.addEventListener('pointermove', this.onPointerMove) this.domElement.ownerDocument.addEventListener('pointerup', this.onPointerUp) window.addEventListener('keydown', this.keydown) window.addEventListener('keyup', this.keyup) this.handleResize() } public dispose = (): void => { if (!this.domElement) return this.domElement.removeEventListener('contextmenu', this.contextmenu) this.domElement.removeEventListener('pointerdown', this.onPointerDown) this.domElement.removeEventListener('wheel', this.mousewheel) this.domElement.removeEventListener('touchstart', this.touchstart) this.domElement.removeEventListener('touchend', this.touchend) this.domElement.removeEventListener('touchmove', this.touchmove) this.domElement.ownerDocument.removeEventListener('pointermove', this.onPointerMove) this.domElement.ownerDocument.removeEventListener('pointerup', this.onPointerUp) window.removeEventListener('keydown', this.keydown) window.removeEventListener('keyup', this.keyup) } } export { TrackballControls }
the_stack
import React, { ReactElement, useState } from "react"; import { fireEvent, render } from "@testing-library/react"; import { TextField } from "../TextField"; describe("TextField", () => { it("should render correctly", () => { const props = { id: "field" }; const { container, rerender } = render(<TextField {...props} />); expect(container).toMatchSnapshot(); rerender(<TextField {...props} label="Label" placeholder="Placeholder" />); expect(container).toMatchSnapshot(); rerender( <TextField {...props} label="Label" placeholder="Placeholder" disabled /> ); expect(container).toMatchSnapshot(); expect(document.getElementById("field")).toHaveAttribute("disabled"); }); it("should correctly call the onChange event", () => { const onChange = jest.fn(); const { getByRole } = render( <TextField id="field" label="Label" onChange={onChange} /> ); const field = getByRole("textbox"); expect(onChange).not.toBeCalled(); fireEvent.change(field, { target: { value: "2" } }); expect(onChange).toBeCalledTimes(1); }); it("should add the inactive floating label state when a number text field is blurred while containing an invalid value", () => { const { getByRole, getByText } = render( <TextField id="text-field" label="Label" type="number" defaultValue="" /> ); const field = getByRole("spinbutton") as HTMLInputElement; const label = getByText("Label"); expect(field).toHaveAttribute("value", ""); expect(label.className).not.toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.focus(field); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.change(field, { target: { value: "123" } }); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); // TODO: Look into writing real browser tests since this isn't implemented in JSDOM Object.defineProperty(field.validity, "badInput", { writable: true, value: true, }); expect(field.validity.badInput).toBe(true); fireEvent.change(field, { target: { value: "123-" }, }); expect(field.validity.badInput).toBe(true); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.blur(field); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).toContain("rmd-floating-label--inactive"); }); it("should add the inactive floating label state when a number text field is blurred while containing an invalid value when controlled", () => { function Test(): ReactElement { const [value, setValue] = useState(""); return ( <TextField id="text-field" label="Label" type="number" value={value} onChange={(event) => setValue(event.currentTarget.value)} /> ); } const { getByRole, getByText } = render(<Test />); const field = getByRole("spinbutton") as HTMLInputElement; const label = getByText("Label"); expect(field).toHaveAttribute("value", ""); expect(label.className).not.toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.focus(field); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.change(field, { target: { value: "123" } }); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); // TODO: Look into writing real browser tests since this isn't implemented in JSDOM Object.defineProperty(field.validity, "badInput", { writable: true, value: true, }); expect(field.validity.badInput).toBe(true); fireEvent.change(field, { target: { value: "123-" }, }); expect(field.validity.badInput).toBe(true); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.blur(field); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).toContain("rmd-floating-label--inactive"); }); it("should add the floating inactive state for a number field that is initially rendered with a value", () => { const onBlur = jest.fn(); const onFocus = jest.fn(); function Test(): ReactElement { const [value, setValue] = useState("0"); return ( <TextField id="text-field" label="Label" type="number" value={value} onBlur={onBlur} onFocus={onFocus} onChange={(event) => setValue(event.currentTarget.value)} /> ); } const { getByRole, getByText } = render(<Test />); const field = getByRole("spinbutton") as HTMLInputElement; const label = getByText("Label"); expect(field).toHaveAttribute("value", "0"); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).toContain("rmd-floating-label--inactive"); fireEvent.focus(field); expect(onFocus).toBeCalledTimes(1); fireEvent.change(field, { target: { value: "" } }); fireEvent.blur(field); expect(onBlur).toBeCalledTimes(1); expect(label.className).not.toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.focus(field); fireEvent.change(field, { target: { value: "3" } }); fireEvent.change(field, { target: { value: "3-" } }); fireEvent.change(field, { target: { value: "3" } }); fireEvent.blur(field); expect(onBlur).toBeCalledTimes(2); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).toContain("rmd-floating-label--inactive"); }); it("should add the inactive floating label state on blur if the change event never really got fired", () => { function Test(): ReactElement { return <TextField id="text-field" label="Label" type="number" />; } const { getByRole, getByText } = render(<Test />); const field = getByRole("spinbutton") as HTMLInputElement; const label = getByText("Label"); expect(field.value).toBe(""); expect(label.className).not.toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.change(field, { target: { value: "-" } }); expect(label.className).not.toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); // TODO: Look into writing real browser tests since this isn't implemented in JSDOM Object.defineProperty(field.validity, "badInput", { writable: true, value: true, }); fireEvent.blur(field); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).toContain("rmd-floating-label--inactive"); }); it("should not add the inactive floating label state when a non-number type has a badInput validity", () => { const { getByRole, getByText } = render( <TextField id="text-field" label="Label" type="url" defaultValue="" /> ); const field = getByRole("textbox") as HTMLInputElement; const label = getByText("Label"); expect(field).toHaveAttribute("value", ""); expect(label.className).not.toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.focus(field); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); // TODO: Look into writing real browser tests since this isn't implemented in JSDOM Object.defineProperty(field.validity, "badInput", { writable: true, value: true, }); fireEvent.change(field, { target: { value: "123" } }); expect(field.validity.badInput).toBe(true); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.blur(field); expect(field.validity.badInput).toBe(true); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).toContain("rmd-floating-label--inactive"); fireEvent.focus(field); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.change(field, { target: { value: "" } }); fireEvent.blur(field); expect(label.className).not.toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); }); it("should not add the inactive floating label state when a non-number type has a badInput validity when controlled", () => { function Test(): ReactElement { const [value, setValue] = useState(""); return ( <TextField id="text-field" label="Label" type="url" value={value} onChange={(event) => setValue(event.currentTarget.value)} /> ); } const { getByRole, getByText } = render(<Test />); const field = getByRole("textbox") as HTMLInputElement; const label = getByText("Label"); expect(field).toHaveAttribute("value", ""); expect(label.className).not.toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.focus(field); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); // TODO: Look into writing real browser tests since this isn't implemented in JSDOM Object.defineProperty(field.validity, "badInput", { writable: true, value: true, }); fireEvent.change(field, { target: { value: "123" } }); expect(field.validity.badInput).toBe(true); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.blur(field); expect(field.validity.badInput).toBe(true); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).toContain("rmd-floating-label--inactive"); fireEvent.focus(field); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.change(field, { target: { value: "" } }); fireEvent.blur(field); expect(label.className).not.toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); }); it("should correctly update the floating state if the controlled TextField value changes outside of a change event", () => { function Test(): ReactElement { const [value, setValue] = useState(""); return ( <> <button type="button" onClick={() => setValue("100")}> Set </button> <button type="button" onClick={() => setValue("")}> Reset </button> <TextField id="field-id" label="Label" value={value} onChange={(event) => setValue(event.currentTarget.value)} /> </> ); } const { getByRole, getByText } = render(<Test />); const setButton = getByRole("button", { name: "Set" }); const resetButton = getByRole("button", { name: "Reset" }); const field = getByRole("textbox") as HTMLInputElement; const label = getByText("Label"); expect(label.className).not.toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.click(setButton); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).toContain("rmd-floating-label--inactive"); fireEvent.focus(field); fireEvent.change(field, { target: { value: "100-" } }); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); fireEvent.blur(field); expect(label.className).toContain("rmd-floating-label--active"); expect(label.className).toContain("rmd-floating-label--inactive"); fireEvent.click(resetButton); expect(label.className).not.toContain("rmd-floating-label--active"); expect(label.className).not.toContain("rmd-floating-label--inactive"); }); });
the_stack
import React, { useState } from 'react' import LRU from 'lru-cache' import { renderHook, act } from '@testing-library/react-hooks' import MockAdapter from 'axios-mock-adapter' import axios from 'axios' import { ApiProvider } from '../ApiProvider' import { useApi, reducer, fetchApi, handleUseApiOptions } from '../useApi' import { ACTIONS, initState } from '../common' const mock = new MockAdapter(axios) const originalLog = console.log beforeEach(() => { jest.resetModules() mock.reset() }) afterEach(() => { console.log = originalLog }) describe('useApi tests', () => { const url = '/api/v1/foo/bar' const apiData = { foo: { bar: true, }, } const listUrl = '/api/v1/list' const listData = [ { foo: 'bar', }, { abc: 123, }, ] const errorUrl = '/api/v1/500' const errorData = { msg: '500 Server Error', } beforeEach(() => { mock.onGet(url).reply(200, apiData) mock.onGet(listUrl).reply(200, listData) mock.onGet(errorUrl).reply(500, errorData) }) const createWrapper = (context: ReactUseApi.CustomContext) => ({ children, }) => <ApiProvider context={context}>{children}</ApiProvider> it('should work well without options', async () => { const context = { settings: { isSSR: () => false, }, } as ReactUseApi.CustomContext const wrapper = createWrapper(context) const { result, waitForNextUpdate, rerender } = renderHook( () => useApi({ url, }), { wrapper } ) const [data, state, request] = result.current expect(data).toBeUndefined() expect(state).toEqual({ loading: true, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', error: undefined, }) expect(request).toBeTruthy() await waitForNextUpdate() const [uData, uState] = result.current expect(uData).toEqual(apiData) expect(uState).toEqual({ loading: false, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', error: undefined, prevData: undefined, prevState: { loading: true, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', error: undefined, }, response: { status: 200, data: apiData, headers: undefined }, dependencies: undefined, data: apiData, }) const { collection: { ssrConfigs }, } = context expect(ssrConfigs.length).toBe(0) rerender() // should be same after rerender const [nData, nState] = result.current expect(nData).toBe(uData) expect(nState).toBe(uState) }) it('should work well by string type config without options', async () => { const wrapper = createWrapper({ settings: { isSSR: () => false, }, }) const { result, waitForNextUpdate, rerender } = renderHook( () => useApi(url), { wrapper } ) const [data, state, request] = result.current expect(data).toBeUndefined() expect(state).toEqual({ loading: true, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', error: undefined, }) expect(request).toBeTruthy() await waitForNextUpdate() const [uData, uState] = result.current expect(uData).toEqual(apiData) expect(uState).toEqual({ loading: false, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', error: undefined, prevData: undefined, prevState: { loading: true, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', error: undefined, }, response: { status: 200, data: apiData, headers: undefined }, dependencies: undefined, data: apiData, }) rerender() // should be same after rerender const [nData, nState] = result.current expect(nData).toBe(uData) expect(nState).toBe(uState) }) it('should work well with cache data', async () => { console.log = jest.fn() const cache = new LRU<string, ReactUseApi.CacheData | any>() const context = { settings: { cache, isSSR: () => false, debug: true, }, } as ReactUseApi.CustomContext const cacheKey = '{"url":"/api/v1/foo/bar"}' cache.set(cacheKey, { response: { data: apiData, }, }) const wrapper = createWrapper(context) const { result, rerender } = renderHook( () => useApi({ url, }), { wrapper } ) const [data, state] = result.current expect(console.log).toHaveBeenCalledWith('[ReactUseApi][Feed]', cacheKey) expect(data).toEqual(apiData) expect(state).toEqual({ loading: false, fromCache: true, $cacheKey: cacheKey, error: undefined, prevData: undefined, prevState: initState, response: { data: apiData, }, dependencies: undefined, data: apiData, }) // cannot use waitForNextUpdate to test the non-rerender situation, use rerender instead // await waitForNextUpdate() rerender() const [uData, uState] = result.current expect(uData).toBe(data) expect(uState).toEqual(state) }) describe('SSR tests', () => { const cache = new LRU<string, ReactUseApi.CacheData | any>() beforeEach(() => { cache.reset() console.log = jest.fn() }) it('should work well with cache data', async () => { const context = { settings: { cache, isSSR: () => true, debug: true, }, } as ReactUseApi.CustomContext const cacheKey = '{"url":"/api/v1/foo/bar"}' cache.set(cacheKey, { response: { data: apiData, }, }) const wrapper = createWrapper(context) const { result, waitForNextUpdate, rerender } = renderHook( () => useApi({ url, }), { wrapper } ) const [data, state] = result.current expect(console.log).toHaveBeenCalledWith('[ReactUseApi][Feed]', cacheKey) expect(data).toEqual(apiData) expect(state).toEqual({ loading: false, fromCache: false, $cacheKey: cacheKey, error: undefined, prevData: undefined, prevState: initState, response: { data: apiData, }, dependencies: undefined, data: apiData, }) // cannot use waitForNextUpdate to test the non-rerender situation, use rerender instead // await waitForNextUpdate() rerender() const [uData, uState] = result.current expect(uData).toBe(data) expect(uState).toEqual(state) }) it('should work well without cache data', async () => { const context = { settings: { cache, isSSR: () => true, debug: true, }, } as ReactUseApi.CustomContext const cacheKey = '{"url":"/api/v1/foo/bar"}' const wrapper = createWrapper(context) renderHook( () => useApi({ url, }), { wrapper } ) const { collection: { ssrConfigs, cacheKeys }, } = context expect(console.log).toHaveBeenCalledWith( '[ReactUseApi][Collect]', cacheKey ) expect(ssrConfigs).toEqual([ { config: { url, }, cacheKey, }, ]) expect(cacheKeys.size).toBe(1) }) }) it('should request work well without options', async () => { const wrapper = createWrapper({ settings: { isSSR: () => false, }, }) const { result, waitForNextUpdate } = renderHook( () => useApi({ url, }), { wrapper } ) const [, , request] = result.current await waitForNextUpdate() act(() => { request() }) const [data, state] = result.current expect(data).toEqual(apiData) expect(state).toEqual({ loading: true, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', error: undefined, prevData: undefined, prevState: { loading: true, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', error: undefined, }, response: { status: 200, data: apiData, headers: undefined }, dependencies: undefined, data: apiData, }) await waitForNextUpdate() const [uData, uState] = result.current expect(uData).toEqual(apiData) expect(uState).toEqual({ loading: false, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', error: undefined, prevData: { foo: { bar: true } }, response: { status: 200, data: apiData, headers: undefined }, dependencies: undefined, data: { foo: { bar: true } }, prevState: { loading: true, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', error: undefined, prevData: undefined, response: { status: 200, data: apiData, headers: undefined }, dependencies: undefined, data: { foo: { bar: true } }, }, }) }) it('should request work well for advanced usage', async () => { const apiListUrl = '/api/v1/itemList' const apiListData = [ [1, 2], [3, 4], [5, 6], ] mock .onGet(apiListUrl, { params: { start: 0, count: 2, }, }) .reply(200, apiListData[0]) mock .onGet(apiListUrl, { params: { start: 2, count: 4, }, }) .reply(200, apiListData[1]) mock .onGet(apiListUrl, { params: { start: 4, count: 6, }, }) .reply(200, apiListData[2]) const wrapper = createWrapper({ settings: { isSSR: () => false, }, }) const { result, waitForNextUpdate } = renderHook( () => { const [myState, setMyState] = useState(0) const options = { dependencies: {}, handleData(data: ReactUseApi.Data, newState: ReactUseApi.State) { const { prevData = [] } = newState data = Array.isArray(data) ? data : [] // since React 16.9 supports calling a state setter inside useReducer setMyState(1) return [...prevData, ...data] }, } const result = useApi( { url: apiListUrl, params: { start: 0, count: 2, }, }, options ) return [...result, myState] }, { wrapper } ) await waitForNextUpdate() const [data, state, request] = result.current expect(data).toEqual(apiListData[0]) act(() => { request( { url: apiListUrl, params: { start: 2, count: 4, }, }, true ) }) await waitForNextUpdate() const [nData, nState, , myState] = result.current expect(nData).toEqual([...apiListData[0], ...apiListData[1]]) expect(nState.$cacheKey).toEqual(state.$cacheKey) expect(myState).toBe(1) act(() => { request( { url: apiListUrl, params: { start: 4, count: 6, }, }, true ) }) await waitForNextUpdate() const [uData, uState] = result.current expect(uData).toEqual([ ...apiListData[0], ...apiListData[1], ...apiListData[2], ]) expect(uState.$cacheKey).toEqual(state.$cacheKey) }) it('should shouldRequest work well', async () => { const wrapper = createWrapper({ settings: { isSSR: () => false, }, }) let shouldFetchData = false const ref = { current: { isRequesting: false } } const spy = jest.spyOn(React, 'useRef').mockReturnValue(ref) const options = { shouldRequest() { if (shouldFetchData) { shouldFetchData = false return true } return false }, } const { result, waitForNextUpdate, rerender } = renderHook( () => useApi( { url, }, options ), { wrapper } ) await waitForNextUpdate() expect(ref.current.isRequesting).toBe(false) // first rerender test const [, state] = result.current rerender() const [nData, nState] = result.current // should be same expect(nState).toBe(state) shouldFetchData = true rerender() expect(ref.current.isRequesting).toBe(true) await waitForNextUpdate() const [uData, uState] = result.current expect(uData).not.toBe(nData) expect(uData).toEqual(apiData) expect(uState).toEqual({ loading: false, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', prevData: apiData, response: { status: 200, data: apiData, headers: undefined }, dependencies: undefined, error: undefined, data: apiData, prevState: { loading: true, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', prevData: undefined, response: { status: 200, data: apiData, headers: undefined }, dependencies: undefined, error: undefined, data: apiData, }, }) expect(ref.current.isRequesting).toBe(false) spy.mockRestore() }) it('should shouldUseApiCache work well', async () => { console.log = jest.fn() const cache = new LRU<string, ReactUseApi.CacheData | any>() const context = { settings: { cache, debug: true, isSSR: () => false, shouldUseApiCache: (config, cacheKey) => { if (cacheKey.includes('/no/cache')) { return false } return true }, }, } as ReactUseApi.CustomContext const cacheKey = '{"url":"/api/v1/foo/bar"}' cache.set(cacheKey, { response: { data: apiData, }, }) const noCacheData = { no: 'dont touch me', } const noCacheApiUrl = '/api/v1/no/cache' cache.set(`{"url":"${noCacheApiUrl}"}`, { response: { data: noCacheData, }, }) mock.onGet(noCacheApiUrl).reply(200, { foo: 'bar', }) const wrapper = createWrapper(context) const { result, rerender, waitForNextUpdate } = renderHook( () => { const [data1] = useApi(url) const [data2] = useApi(noCacheApiUrl) return [data1, data2] }, { wrapper } ) await waitForNextUpdate() const [data1, data2] = result.current expect(data1).toEqual(apiData) expect(data2).not.toEqual(noCacheData) }) it('should watch work well', async () => { const wrapper = createWrapper({ settings: { isSSR: () => false, }, }) const watch = [123, 456] const options = { watch, } const { result, waitForNextUpdate, rerender } = renderHook( () => useApi( { url, }, options ), { wrapper } ) await waitForNextUpdate() // first rerender test const [, state] = result.current rerender() const [nData, nState] = result.current // should be same expect(nState).toBe(state) watch[1] = 123 rerender() await waitForNextUpdate() const [uData, uState] = result.current expect(uData).not.toBe(nData) expect(uData).toEqual(apiData) expect(uState).toEqual({ loading: false, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', prevData: apiData, response: { status: 200, data: apiData, headers: undefined }, dependencies: undefined, error: undefined, data: apiData, prevState: { loading: true, fromCache: false, $cacheKey: '{"url":"/api/v1/foo/bar"}', prevData: undefined, response: { status: 200, data: apiData, headers: undefined }, dependencies: undefined, error: undefined, data: apiData, }, }) }) it('should multiple requests work well', async () => { const wrapper = createWrapper({ settings: { isSSR: () => false, }, }) const { result, waitForNextUpdate } = renderHook( () => useApi([ { url, }, { url: listUrl }, ]), { wrapper } ) await waitForNextUpdate() const [data, state] = result.current expect(data).toEqual([apiData, listData]) expect(state).toEqual({ loading: false, fromCache: false, $cacheKey: '[{"url":"/api/v1/foo/bar"},{"url":"/api/v1/list"}]', error: undefined, prevData: undefined, prevState: { loading: true, fromCache: false, $cacheKey: '[{"url":"/api/v1/foo/bar"},{"url":"/api/v1/list"}]', error: undefined, }, response: [ { status: 200, data: apiData, headers: undefined }, { status: 200, data: listData, headers: undefined }, ], dependencies: undefined, data: [apiData, listData], }) }) it('should work as expected about multiple requests, even if one of them fails', async () => { const wrapper = createWrapper({ settings: { isSSR: () => false, }, }) const { result, waitForNextUpdate } = renderHook( () => useApi([ { url, }, { url: errorUrl }, ]), { wrapper } ) await waitForNextUpdate() const [data, state] = result.current expect(data).toBeUndefined() expect(state.response).toBeUndefined() expect(state.error.response.data).toEqual(errorData) }) it('should HTTP error request work as expected', async () => { const wrapper = createWrapper({ settings: { isSSR: () => false, }, }) const { result, waitForNextUpdate } = renderHook(() => useApi(errorUrl), { wrapper, }) await waitForNextUpdate() const [data, state] = result.current expect(data).toBeUndefined() expect(state.response).toBeUndefined() expect(state.error.response.data).toEqual(errorData) }) it('should skip work well', async () => { const cache = new LRU<string, ReactUseApi.CacheData | any>() const context = { settings: { cache, isSSR: () => false, }, } as ReactUseApi.CustomContext const wrapper = createWrapper(context) const { result, waitForNextUpdate, rerender } = renderHook( () => useApi( { url, }, { skip: true, } ), { wrapper } ) const [data, state] = result.current expect(data).toBeUndefined() expect(state).toEqual(initState) // cannot use waitForNextUpdate to test the non-rerender situation, use rerender instead // await waitForNextUpdate() rerender() const [uData, uState] = result.current expect(uData).toBeUndefined() expect(uState).toEqual(initState) }) describe('useCache tests', () => { const cache = new LRU<string, ReactUseApi.CacheData | any>() const context = { settings: { cache, isSSR: () => false, }, } as ReactUseApi.Context beforeEach(() => { cache.reset() }) it('should work well with cache data come from server side', async () => { const cacheKey = '{"url":"/api/v1/foo/bar"}' const cacheData = { data: { msg: 'this is cached data', }, } cache.set(cacheKey, { response: { data: cacheData, }, }) const wrapper = createWrapper(context) const { result, waitForNextUpdate, rerender } = renderHook( () => useApi( { url, }, { useCache: true, } ), { wrapper } ) const [data] = result.current expect(data).toEqual(cacheData) // render by the same api again const { result: result2 } = renderHook( () => useApi( { url, }, { useCache: true, } ), { wrapper } ) const [data2] = result2.current expect(data2).toEqual(cacheData) }) it('should work well without cache data come from server side', async () => { const cacheKey = '{"url":"/api/v1/foo/bar"}' const cacheData = { msg: 'this is cached data', } mock.onGet(url).reply(200, cacheData) const wrapper = createWrapper(context) const { result, waitForNextUpdate } = renderHook( () => useApi( { url, }, { useCache: true, } ), { wrapper } ) await waitForNextUpdate() const [data] = result.current expect(data).toEqual(cacheData) expect(cache.get(cacheKey)).toEqual({ error: undefined, response: { data: cacheData, headers: undefined, status: 200, }, }) // render by the same api again, use cache data still by default const { result: result2 } = renderHook( () => useApi({ url, }), { wrapper } ) const [data2] = result2.current expect(data2).toEqual(cacheData) // render by the same api again but useCache=false const { result: result3, waitForNextUpdate: waitForNextUpdate3, } = renderHook( () => useApi( { url, }, { useCache: false, } ), { wrapper } ) await waitForNextUpdate3() const [data3] = result3.current expect(data3).toEqual(cacheData) }) it('should work with multiple same api calls', async () => { const url = '/api/v3/cache/test' const cacheKey = `{"url":"${url}"}` const cacheData = { msg: 'this is cached data', } mock.onGet(url).reply(200, cacheData) const wrapper = createWrapper(context) const { result, waitForNextUpdate } = renderHook( () => { const [data1] = useApi(url, { useCache: true }) const [data2] = useApi(url) const [data3, , request] = useApi(url, { useCache: false }) return [data1, data2, data3, request] }, { wrapper } ) await waitForNextUpdate() const [data1, data2, data3, request] = result.current expect(data1).toEqual(cacheData) expect(data2).toEqual(cacheData) expect(data3).toEqual(cacheData) expect(cache.get(cacheKey)).toEqual({ error: undefined, response: { data: cacheData, headers: undefined, status: 200, }, }) const newCacheData = { msg: 'cached data 2', } mock.onGet(url).reply(200, newCacheData) await act(async () => { request() }) const [, , ndata3] = result.current expect(ndata3).toEqual(newCacheData) }) it('should work with multiple same api calls invoked by nested components and clearLastCacheWhenConfigChanges=false', async () => { const url = '/api/v3/api/test' const apiData = { msg: 'this is api test data', } const urlMock = jest.fn().mockReturnValue([200, apiData]) mock.onGet(url).reply(urlMock) const newUrl = `${url}?foo=bar` const newApiData = { msg: 'this is api test data 2', } const newUrlMock = jest.fn().mockReturnValue([200, newApiData]) mock.onGet(newUrl).reply(newUrlMock) let currentUrl = url let childData const Child = () => { const [data] = useApi(currentUrl, { useCache: true }) childData = data return <>hello</> } const provide = (context: ReactUseApi.CustomContext) => ({ children, }) => { return ( <ApiProvider context={context}> {children} <Child /> </ApiProvider> ) } const wrapper = provide({ settings: { cache, isSSR: () => false, clearLastCacheWhenConfigChanges: false, }, } as ReactUseApi.Context) const { result, waitForNextUpdate, rerender } = renderHook( () => { const [data1, request] = useApi(currentUrl, { useCache: true }) const [data2] = useApi(currentUrl, { useCache: false }) return [data1, data2, request] }, { wrapper } ) await waitForNextUpdate() const [data1, data2] = result.current expect(data1).toEqual(apiData) expect(data2).toEqual(apiData) expect(childData).toEqual(apiData) expect(urlMock.mock.calls.length).toBe(2) currentUrl = newUrl rerender() await waitForNextUpdate() expect(result.current[0]).toEqual(newApiData) expect(result.current[1]).toEqual(newApiData) expect(childData).toEqual(newApiData) expect(urlMock.mock.calls.length).toBe(2) currentUrl = url urlMock.mockClear() rerender() await waitForNextUpdate() expect(result.current[0]).toEqual(apiData) expect(result.current[1]).toEqual(apiData) expect(childData).toEqual(apiData) expect(urlMock.mock.calls.length).toBe(1) // should have cache data expect(cache.has(`{"url":"${url}"}`)).toBe(true) expect(cache.has(`{"url":"${newUrl}"}`)).toBe(true) }) it('should work with multiple same api calls invoked by nested components', async () => { const url = '/api/v3/api/test' const apiData = { msg: 'this is api test data', } const urlMock = jest.fn().mockReturnValue([200, apiData]) mock.onGet(url).reply(urlMock) const newUrl = `${url}?foo=bar` const newApiData = { msg: 'this is api test data 2', } const newUrlMock = jest.fn().mockReturnValue([200, newApiData]) mock.onGet(newUrl).reply(newUrlMock) let currentUrl = url let childData const Child = () => { const [data] = useApi(currentUrl, { useCache: true }) childData = data return <>hello</> } const provide = (context: ReactUseApi.CustomContext) => ({ children, }) => { return ( <ApiProvider context={context}> {children} <Child /> </ApiProvider> ) } const wrapper = provide(context) const { result, waitForNextUpdate, rerender } = renderHook( () => { const [data1, request] = useApi(currentUrl, { useCache: true }) const [data2] = useApi(currentUrl, { useCache: false }) return [data1, data2, request] }, { wrapper } ) await waitForNextUpdate() const [data1, data2] = result.current expect(data1).toEqual(apiData) expect(data2).toEqual(apiData) expect(childData).toEqual(apiData) expect(urlMock.mock.calls.length).toBe(2) currentUrl = newUrl rerender() expect(cache.has(`{"url":"${url}"}`)).toBe(false) await waitForNextUpdate() expect(result.current[0]).toEqual(newApiData) expect(result.current[1]).toEqual(newApiData) expect(childData).toEqual(newApiData) expect(urlMock.mock.calls.length).toBe(2) currentUrl = url urlMock.mockClear() rerender() expect(cache.has(`{"url":"${newUrl}"}`)).toBe(false) await waitForNextUpdate() expect(result.current[0]).toEqual(apiData) expect(result.current[1]).toEqual(apiData) expect(childData).toEqual(apiData) expect(urlMock.mock.calls.length).toBe(2) // should have cache data expect(cache.has(`{"url":"${url}"}`)).toBe(true) }) }) }) describe('fetchApi tests', () => { const cache = new LRU<string, ReactUseApi.CacheData | any>() const context = { settings: { axios, cache }, } as ReactUseApi.Context const url = '/api/v1/user' const config = { url, } const options = { $cacheKey: url, } beforeEach(() => { jest.restoreAllMocks() cache.reset() }) it('should loading and success work well', async () => { const apiData = { message: 'ok', } mock.onGet(url).reply(200, apiData) const dispatch = jest.fn() await fetchApi(context, config, options, dispatch) expect(dispatch).toHaveBeenCalledWith({ type: ACTIONS.REQUEST_START, options, }) expect(dispatch).toHaveBeenCalledWith({ type: ACTIONS.REQUEST_END, response: { data: apiData, headers: undefined, status: 200, }, error: undefined, options, fromCache: false, }) }) it('should loading and error work well', async () => { const apiData = { message: 'fail', } mock.onGet(url).reply(500, apiData) const dispatch = jest.fn() await fetchApi(context, config, options, dispatch) expect(dispatch).toHaveBeenCalledWith({ type: ACTIONS.REQUEST_START, options, }) const args = dispatch.mock.calls[1][0] expect(args.type).toEqual(ACTIONS.REQUEST_END) expect(args.error.response).toEqual({ data: apiData, headers: undefined, status: 500, }) expect(args.response).toBeUndefined() expect(args.options).toEqual(options) }) it('should loading and success work well by cache data', async () => { const apiData = { message: 'ok', } cache.set(url, { response: { data: apiData, }, }) const dispatch = jest.fn() const opt = { ...options, useCache: true, } await fetchApi(context, config, opt, dispatch) expect(dispatch).not.toHaveBeenCalledWith({ type: ACTIONS.REQUEST_START, options: opt, }) expect(dispatch).toHaveBeenCalledWith({ type: ACTIONS.REQUEST_END, response: { data: apiData, }, error: undefined, fromCache: true, options: opt, }) }) it('should loading and error work well by cache data', async () => { const apiData = { message: 'fail', } cache.set(url, { error: { data: apiData, }, }) const opt = { ...options, useCache: true, } const dispatch = jest.fn() await fetchApi(context, config, opt, dispatch) expect(dispatch).not.toHaveBeenCalledWith({ type: ACTIONS.REQUEST_START, options: opt, }) const args = dispatch.mock.calls[0][0] expect(args.type).toEqual(ACTIONS.REQUEST_END) expect(args.error).toEqual({ data: apiData, }) expect(args.response).toBeUndefined() expect(args.options).toEqual(opt) }) }) describe('reducer tests', () => { it('should get initState from REQUEST_START', () => { const state = { ...initState } const action = { type: ACTIONS.REQUEST_START, options: { $cacheKey: '/foo/bar', }, } const newState = reducer(state, action) expect(newState).not.toBe(state) expect(newState).toEqual({ ...state, loading: true, fromCache: false, error: undefined, $cacheKey: '/foo/bar', }) }) it('should get previous state with loading = true from REQUEST_START', () => { const state = { myData: '123', fromCache: false, loading: false, $cacheKey: '/foo/bar', } as ReactUseApi.State const action = { type: ACTIONS.REQUEST_START, options: { $cacheKey: '/foo/bar', }, } const newState = reducer(state, action) expect(newState).not.toBe(state) expect(newState).toEqual({ ...state, loading: true, fromCache: false, error: undefined, $cacheKey: '/foo/bar', }) }) it('should reset to initState from REQUEST_START if cacheKey changes', () => { const state = { myData: '123', fromCache: false, loading: false, $cacheKey: '/foo/bar', } as ReactUseApi.State const action = { type: ACTIONS.REQUEST_START, options: { $cacheKey: '/abc/def', }, } const newState = reducer(state, action) expect(newState).not.toBe(state) expect(newState).toEqual({ loading: true, fromCache: false, error: undefined, $cacheKey: '/abc/def', }) }) it('should REQUEST_END work well if response', () => { const state = { ...initState } const action = { type: ACTIONS.REQUEST_END, response: { data: { message: 'ok', }, } as any, options: { dependencies: { foo: 'bar', }, $cacheKey: '/foo/bar', }, } as ReactUseApi.Action const newState = reducer(state, action) expect(newState).not.toBe(state) expect(newState).toEqual({ loading: false, fromCache: false, prevData: undefined, prevState: initState, response: { data: { message: 'ok' } }, dependencies: { foo: 'bar' }, error: undefined, data: { message: 'ok' }, $cacheKey: '/foo/bar', }) }) it('should REQUEST_END work well if error', () => { const state = { ...initState } const action = { type: ACTIONS.REQUEST_END, error: { data: { message: 'fail', }, } as any, options: { dependencies: { foo: 'bar', }, $cacheKey: '/foo/bar', }, } as ReactUseApi.Action const newState = reducer(state, action) expect(newState).not.toBe(state) expect(newState).toEqual({ loading: false, fromCache: false, prevData: undefined, prevState: initState, response: undefined, dependencies: { foo: 'bar' }, error: { data: { message: 'fail' } }, data: undefined, $cacheKey: '/foo/bar', }) }) it('should get the same state if the action is not found', () => { const state = { ...initState } const action = { type: 'NOT_FOUND', options: { $cacheKey: '/foo/bar', }, } const newState = reducer(state, action) expect(newState).toBe(state) }) }) describe('handleUseApiOptions tests', () => { it('should work well with object options', () => { const opt = { watch: [123, 456], handleData: () => null, shouldRequest: () => false, dependencies: {}, } const options = handleUseApiOptions( opt, { shouldUseApiCache: jest.fn() as any, } as ReactUseApi.Settings, '/foo/bar', '/foo/bar' ) expect(options).toEqual({ ...opt, $cacheKey: '/foo/bar', }) }) it('should work well with watch options', () => { const watch = [123, 456] const options = handleUseApiOptions( watch, { shouldUseApiCache: jest.fn() as any, } as ReactUseApi.Settings, '/foo/bar', '/foo/bar' ) expect(options).toEqual({ watch, handleData: undefined, $cacheKey: '/foo/bar', }) }) it('should work well with handleData options', () => { const handleData = jest.fn() const options = handleUseApiOptions( handleData, { shouldUseApiCache: jest.fn() as any, } as ReactUseApi.Settings, '/foo/bar', '/foo/bar' ) expect(options).toEqual({ watch: [], handleData, $cacheKey: '/foo/bar', }) }) it('should work well with settings.alwaysUseCache', () => { const handleData = jest.fn() const settings = { alwaysUseCache: true, shouldUseApiCache: jest.fn() as any, } as ReactUseApi.Settings const options = handleUseApiOptions( handleData, settings, '/foo/bar', '/foo/bar' ) expect(options).toEqual({ watch: [], handleData, $cacheKey: '/foo/bar', useCache: true, }) }) it('should options.useCache = false when settings.shouldUseApiCache returns false', () => { const handleData = jest.fn() const settings = { shouldUseApiCache: jest.fn(() => false) as any, } as ReactUseApi.Settings const options = handleUseApiOptions( handleData, settings, '/foo/bar', '/foo/bar' ) expect(options).toEqual({ watch: [], handleData, $cacheKey: '/foo/bar', useCache: false, }) }) })
the_stack
import { PathSegment } from './../rendering/canvas-interface'; import { PointModel } from '../primitives/point-model'; /** * These utility methods help to process the data and to convert it to desired dimensions */ /** @private */ export function processPathData(data: string): Object[] { let collection: Object[] = []; let j: number; let arrayCollection: Object[] = parsePathData(data); if (arrayCollection.length > 0) { for (let i: number = 0; i < arrayCollection.length; i++) { let ob: Object = arrayCollection[i]; let char: string = ''; char = ob[0]; switch (char.toLowerCase()) { case 'm': for (j = 1; j < (ob as Object[]).length; j++) { collection.push({ command: char, x: ob[j], y: ob[j + 1] }); j = j + 1; if (char === 'm') { char = 'l'; } else if (char === 'M') { char = 'L'; } } break; case 'l': case 't': for (j = 1; j < (ob as Object[]).length; j++) { collection.push({ command: char, x: ob[j], y: ob[j + 1] }); j = j + 1; } break; case 'h': for (j = 1; j < (ob as Object[]).length; j++) { collection.push({ command: char, x: ob[j] }); } break; case 'v': for (j = 1; j < (ob as Object[]).length; j++) { collection.push({ command: char, y: ob[j] }); } break; case 'z': collection.push({ command: char }); break; case 'c': for (j = 1; j < (ob as Object[]).length; j++) { collection.push({ command: char, x1: ob[j], y1: ob[j + 1], x2: ob[j + 2], y2: ob[j + 3], x: ob[j + 4], y: ob[j + 5] }); j = j + 5; } break; case 's': for (j = 1; j < (ob as Object[]).length; j++) { collection.push({ command: char, x2: ob[j], y2: ob[j + 1], x: ob[j + 2], y: ob[j + 3] }); j = j + 3; } break; case 'q': for (j = 1; j < (ob as Object[]).length; j++) { collection.push({ command: char, x1: ob[j], y1: ob[j + 1], x: ob[j + 2], y: ob[j + 3] }); j = j + 3; } break; case 'a': for (j = 1; j < (ob as Object[]).length; j++) { collection.push({ command: char, r1: ob[j], r2: ob[j + 1], angle: ob[j + 2], largeArc: ob[j + 3], sweep: ob[j + 4], x: ob[j + 5], y: ob[j + 6] }); j = j + 6; } break; } } } return collection; } /** @private */ export function parsePathData(data: string): Object[] { let tokenizer: RegExp = /([a-z]+)|([+-]?(?:\d+\.?\d*|\.\d+))/gi; let current: Object[] = []; let commands: Object[] = []; let match: Object = {}; tokenizer.lastIndex = 0; let isExponential: boolean = false; match = tokenizer.exec(data); while (match) { if (match[1] === 'e') { let s1: string = ''; isExponential = true; } else if (match[1]) { if (match[1].toLowerCase() === 'zm') { if (current.length) { commands.push(current); } commands.push(['Z']); current = [match[1].substring(1, 2)]; } else { if (current.length) { commands.push(current); } current = [match[1]]; } isExponential = false; } else { if (!current.length) { current = []; } if (!isExponential) { current.push(Number(match[2])); } isExponential = false; } match = tokenizer.exec(data); } if (current.length) { commands.push(current); } return commands; } /** * Used to find the path for rounded rect */ export function getRectanglePath(cornerRadius: number, height: number, width: number): string { let x: number = 0; let y: number = 0; let path: string = ''; let points: PointModel[] = [{ x: x + cornerRadius, y: y }, { x: x + width - cornerRadius, y: y }, { x: x + width, y: y + cornerRadius }, { x: x + width, y: y + height - cornerRadius }, { x: x + width - cornerRadius, y: y + height }, { x: x + cornerRadius, y: y + height }, { x: x, y: y + height - cornerRadius }, { x: x, y: y + cornerRadius } ]; let corners: PointModel[] = [{ x: x + width, y: y }, { x: x + width, y: y + height }, { x: x, y: y + height }, { x: x, y: y }]; let corner: number = 0; let point2: PointModel; let next: PointModel; path = 'M' + points[0].x + ' ' + points[0].y; let i: number; for (i = 0; i < points.length; i = i + 2) { point2 = points[i + 1]; path += 'L' + point2.x + ' ' + point2.y; next = points[i + 2] || points[0]; path += 'Q' + corners[corner].x + ' ' + corners[corner].y + ' ' + next.x + ' ' + next.y; corner++; } return path; } /** @private */ export function pathSegmentCollection(collection: Object[]): Object[] { let x0: number; let y0: number; let x1: number; let y1: number; let x2: number; let y2: number; let x: number; let y: number; let length: number; let i: number; let initx: number; let inity: number; let segments: PathSegment[] = []; for (x = 0, y = 0, i = 0, length = collection.length; i < length; ++i) { let obj: Object = collection[i]; let seg: PathSegment = obj; let char: string = ''; char = seg.command; if ('y1' in seg) { y1 = seg.y1; } if ('y2' in seg) { y2 = seg.y2; } if ('x1' in seg) { x1 = seg.x1; } if ('x2' in seg) { x2 = seg.x2; } if ('x' in seg) { x = seg.x; } if ('y' in seg) { y = seg.y; } let prev: PathSegment = segments[segments.length - 1]; switch (char) { case 'M': segments.push({ command: 'M', x: x, y: y }); break; case 'L': segments.push({ command: 'L', x0: x0, y0: y0, x: x, y: y }); break; case 'H': segments.push({ command: 'L', x0: x0, y0: y0, x: x, y: y0 }); break; case 'V': segments.push({ command: 'L', x0: x0, y0: y0, x: x0, y: y }); break; case 'C': segments.push({ command: 'C', x0: x0, y0: y0, x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y }); break; case 'S': if (prev) { let ctrl: PointModel; if (prev.command === 'C' || prev.command === 'S') { ctrl = { x: prev.x2, y: prev.y2 }; } else { ctrl = { x: x0, y: y0 }; } let cpt2: PointModel = { x: 2 * x0 - ctrl.x, y: 2 * y0 - ctrl.y }; segments.push({ command: 'C', x0: x0, y0: y0, x1: cpt2.x, y1: cpt2.y, x2: x2, y2: y2, x: x, y: y }); } break; case 'Q': //ctx.quadraticCurveTo(x1, y1, x, y); segments.push({ command: 'Q', x0: x0, y0: y0, x1: x1, y1: y1, x: x, y: y }); break; case 'T': if (prev) { let ctrl: PointModel; if (prev.command === 'Q') { ctrl = { x: prev.x1, y: prev.y1 }; } else { ctrl = { x: x0, y: y0 }; } let cpt2: PointModel = { x: 2 * x0 - ctrl.x, y: 2 * y0 - ctrl.y }; segments.push({ command: 'Q', x0: x0, y0: y0, x1: cpt2.x, y1: cpt2.y, x: x, y: y }); } break; case 'A': let newSeg: PathSegment = seg; newSeg.command = 'A'; segments.push(newSeg); break; case 'Z': case 'z': segments.push({ command: 'Z' }); x = x0; y = y0; break; } if (char === 'M' || char === 'm') { initx = x; inity = y; } x0 = x; y0 = y; } return segments; } /** @private */ export function transformPath(arr: Object[], sX: number, sY: number, s: boolean, bX: number, bY: number, iX: number, iY: number): string { let x0: number; let y0: number; let x1: number; let y1: number; let x2: number; let y2: number; let x: number; let y: number; let length: number; let i: number; let newSeg: PathSegment; for (x = 0, y = 0, i = 0, length = arr.length; i < length; ++i) { let obj: Object = arr[i]; let seg: PathSegment = obj; let char: string = seg.command; if ('x' in seg) { x = seg.x; } if ('y' in seg) { y = seg.y; } if ('y1' in seg) { y1 = seg.y1; } if ('y2' in seg) { y2 = seg.y2; } if ('x1' in seg) { x1 = seg.x1; } if ('x2' in seg) { x2 = seg.x2; } if (s) { if (x !== undefined) { x = scalePathData(x, sX, bX, iX); } if (y !== undefined) { y = scalePathData(y, sY, bY, iY); } if (x1 !== undefined) { x1 = scalePathData(x1, sX, bX, iX); } if (y1 !== undefined) { y1 = scalePathData(y1, sY, bY, iY); } if (x2 !== undefined) { x2 = scalePathData(x2, sX, bX, iX); } if (y2 !== undefined) { y2 = scalePathData(y2, sY, bY, iY); } } else { if (x !== undefined) { x = Number((x + sX).toFixed(2)); } if (y !== undefined) { y = Number((y + sY).toFixed(2)); } if (x1 !== undefined) { x1 = Number((x1 + sX).toFixed(2)); } if (y1 !== undefined) { y1 = Number((y1 + sY).toFixed(2)); } if (x2 !== undefined) { x2 = Number((x2 + sX).toFixed(2)); } if (y2 !== undefined) { y2 = Number((y2 + sY).toFixed(2)); } } let scaledPath: PathSegment = { x: x, y: y, x1: x1, y1: y1, x2: x2, y2: y2, r1: seg.r1, r2: seg.r2 }; newSeg = updatedSegment(seg, char, scaledPath, s, sX, sY); if (newSeg) { arr[i] = newSeg; } // Record the start of a subpath if (char === 'M' || char === 'm') { x0 = x; y0 = y; } } let pathData: string = getPathString(arr); return pathData; } /** @private */ export function updatedSegment(segment: PathSegment, char: string, obj: PathSegment, isScale: boolean, sX: number, sY: number): Object { switch (char) { case 'M': segment.x = obj.x; segment.y = obj.y; break; case 'L': segment.x = obj.x; segment.y = obj.y; break; case 'H': segment.x = obj.x; break; case 'V': segment.y = obj.y; break; case 'C': segment.x = obj.x; segment.y = obj.y; segment.x1 = obj.x1; segment.y1 = obj.y1; segment.x2 = obj.x2; segment.y2 = obj.y2; break; case 'S': segment.x = obj.x; segment.y = obj.y; segment.x2 = obj.x2; segment.y2 = obj.y2; break; case 'Q': segment.x = obj.x; segment.y = obj.y; segment.x1 = obj.x1; segment.y1 = obj.y1; break; case 'T': segment.x = obj.x; segment.y = obj.y; break; case 'A': let r1: number = obj.r1; let r2: number = obj.r2; if (isScale) { obj.r1 = r1 = (r1 * sX); obj.r2 = r2 = (r2 * sY); } segment.x = obj.x; segment.y = obj.y; segment.r1 = obj.r1; segment.r2 = obj.r2; break; case 'z': case 'Z': segment = { command: 'Z' }; break; } return segment; } /** @private */ export function scalePathData(val: number, scaleFactor: number, oldOffset: number, newOffset: number): number { if (val !== oldOffset) { if (newOffset !== oldOffset) { val = (((val * scaleFactor) - (Number(oldOffset) * scaleFactor - Number(oldOffset))) + (newOffset - Number(oldOffset))); } else { val = ((Number(val) * scaleFactor) - (Number(oldOffset) * scaleFactor - Number(oldOffset))); } } else { if (newOffset !== oldOffset) { val = newOffset; } } return Number(val.toFixed(2)); } /** @private */ export function splitArrayCollection(arrayCollection: Object[]): Object[] { let x0: number; let y0: number; let x1: number; let y1: number; let x2: number; let y2: number; let x: number; let y: number; let length: number; let i: number; for (x = 0, y = 0, i = 0, length = arrayCollection.length; i < length; ++i) { let path: Object = arrayCollection[i]; let seg: PathSegment = path; let char: string = seg.command; if (/[MLHVCSQTA]/.test(char)) { if ('x' in seg) { seg.x = x = seg.x; } if ('y' in seg) { seg.y = y = seg.y; } } else { if ('x1' in seg) { seg.x1 = x1 = x + seg.x1; } if ('x2' in seg) { seg.x2 = x2 = x + seg.x2; } if ('y1' in seg) { seg.y1 = y1 = y + seg.y1; } if ('y2' in seg) { seg.y2 = y2 = y + seg.y2; } if ('x' in seg) { seg.x = x += seg.x; } if ('y' in seg) { seg.y = y += seg.y; } let newSeg: PathSegment; switch (char) { case 'm': case 'M': newSeg = { command: 'M', x: x, y: y }; break; case 'l': case 'L': newSeg = { command: 'L', x: x, y: y }; break; case 'h': case 'H': newSeg = { command: 'H', x: x }; break; case 'v': case 'V': newSeg = { command: 'V', y: y }; break; case 'c': case 'C': newSeg = { command: 'C', x: x, y: y, x1: x1, y1: y1, x2: x2, y2: y2 }; break; case 's': case 'S': newSeg = { command: 'S', x: x, y: y, x2: x2, y2: y2 }; break; case 'q': case 'Q': newSeg = { command: 'Q', x: x, y: y, x1: x1, y1: y1 }; break; case 't': case 'T': newSeg = { command: 'T', x: x, y: y }; break; case 'a': case 'A': newSeg = { command: 'A', x: x, y: y }; newSeg.r1 = seg.r1; newSeg.r2 = seg.r2; newSeg.angle = seg.angle; newSeg.largeArc = seg.largeArc; newSeg.sweep = seg.sweep; break; case 'z': case 'Z': newSeg = { command: 'Z' }; x = x0; y = y0; newSeg = arrayCollection[i]; break; } if (newSeg) { arrayCollection[i] = newSeg; } } if (char === 'M' || char === 'm') { x0 = x; y0 = y; } } return arrayCollection; } /** @private */ export function getPathString(arrayCollection: Object[]): string { let getNewString: string = ''; let i: number; for (i = 0; i < arrayCollection.length; i++) { if (i === 0) { getNewString += getString(arrayCollection[i]); } else { getNewString += ' ' + getString(arrayCollection[i]); } } return getNewString; } /** @private */ export function getString(obj: PathSegment): string { let string: string = ''; switch (obj.command) { case 'Z': case 'z': string = obj.command; break; case 'M': case 'm': case 'L': case 'l': string = obj.command + ' ' + obj.x + ' ' + obj.y; break; case 'C': case 'c': string = obj.command + ' ' + obj.x1 + ' ' + obj.y1 + ' ' + obj.x2 + ' ' + obj.y2 + ' ' + obj.x + ' ' + obj.y; break; case 'Q': case 'q': string = obj.command + ' ' + obj.x1 + ' ' + obj.y1 + ' ' + obj.x + ' ' + obj.y; break; case 'A': case 'a': let cmd: string = obj.command; let ang: number = obj.angle; let l: string = (obj.largeArc ? '1' : '0'); let s: string = (obj.sweep ? '1' : '0'); string = cmd + ' ' + obj.r1 + ' ' + obj.r2 + ' ' + ang + ' ' + l + ' ' + s + ' ' + obj.x + ' ' + obj.y; break; case 'H': case 'h': string = obj.command + ' ' + obj.x; break; case 'V': case 'v': string = obj.command + ' ' + obj.y; break; case 'S': case 's': string = obj.command + ' ' + obj.x2 + ' ' + obj.y2 + ' ' + obj.x + ' ' + obj.y; break; case 'T': case 't': string = obj.command + ' ' + obj.x + ' ' + obj.y; } return string; }
the_stack
import { Component, Property, Event, EmitType, closest, Collection, Complex, attributes, detach, Instance, isNullOrUndefined } from '@syncfusion/ej2-base'; import { INotifyPropertyChanged, NotifyPropertyChanges, ChildProperty, select, isVisible } from '@syncfusion/ej2-base'; import { KeyboardEvents, KeyboardEventArgs, MouseEventArgs, Effect, Browser, formatUnit, DomElements, L10n } from '@syncfusion/ej2-base'; import { setStyleAttribute as setStyle, isNullOrUndefined as isNOU, selectAll, addClass, removeClass, remove } from '@syncfusion/ej2-base'; import { EventHandler, rippleEffect, Touch, SwipeEventArgs, compile, Animation, AnimationModel, BaseEventArgs } from '@syncfusion/ej2-base'; import { getRandomId, SanitizeHtmlHelper, Draggable, DragEventArgs as DragArgs, DropEventArgs } from '@syncfusion/ej2-base'; import { Base } from '@syncfusion/ej2-base'; import { Popup, PopupModel } from '@syncfusion/ej2-popups'; import { Toolbar, OverflowMode, ClickEventArgs } from '../toolbar/toolbar'; import { TabModel, TabItemModel, HeaderModel, TabActionSettingsModel, TabAnimationSettingsModel } from './tab-model'; import { ToolbarModel } from '../toolbar'; type HTEle = HTMLElement; type Str = string; /** * Options to set the orientation of Tab header. */ export type HeaderPosition = 'Top' | 'Bottom' | 'Left' | 'Right'; /** * Options to set the content element height adjust modes. */ export type HeightStyles = 'None' | 'Auto' | 'Content' | 'Fill'; /** * Specifies the options of Tab content display mode. */ export type ContentLoad = 'Dynamic' | 'Init' | 'Demand'; const CLS_TAB: string = 'e-tab'; const CLS_HEADER: string = 'e-tab-header'; const CLS_BLA_TEM: string = 'blazor-template'; const CLS_CONTENT: string = 'e-content'; const CLS_NEST: string = 'e-nested'; const CLS_ITEMS: string = 'e-items'; const CLS_ITEM: string = 'e-item'; const CLS_TEMPLATE: string = 'e-template'; const CLS_RTL: string = 'e-rtl'; const CLS_ACTIVE: string = 'e-active'; const CLS_DISABLE: string = 'e-disable'; const CLS_HIDDEN: string = 'e-hidden'; const CLS_FOCUS: string = 'e-focused'; const CLS_ICONS: string = 'e-icons'; const CLS_ICON: string = 'e-icon'; const CLS_ICON_TAB: string = 'e-icon-tab'; const CLS_ICON_CLOSE: string = 'e-close-icon'; const CLS_CLOSE_SHOW: string = 'e-close-show'; const CLS_TEXT: string = 'e-tab-text'; const CLS_INDICATOR: string = 'e-indicator'; const CLS_WRAP: string = 'e-tab-wrap'; const CLS_TEXT_WRAP: string = 'e-text-wrap'; const CLS_TAB_ICON: string = 'e-tab-icon'; const CLS_TB_ITEMS: string = 'e-toolbar-items'; const CLS_TB_ITEM: string = 'e-toolbar-item'; const CLS_TB_POP: string = 'e-toolbar-pop'; const CLS_TB_POPUP: string = 'e-toolbar-popup'; const CLS_HOR_NAV: string = 'e-hor-nav'; const CLS_POPUP_OPEN: string = 'e-popup-open'; const CLS_POPUP_CLOSE: string = 'e-popup-close'; const CLS_PROGRESS: string = 'e-progress'; const CLS_IGNORE: string = 'e-ignore'; const CLS_OVERLAY: string = 'e-overlay'; const CLS_HSCRCNT: string = 'e-hscroll-content'; const CLS_VSCRCNT: string = 'e-vscroll-content'; const CLS_VTAB: string = 'e-vertical-tab'; const CLS_VERTICAL: string = 'e-vertical'; const CLS_VLEFT: string = 'e-vertical-left'; const CLS_VRIGHT: string = 'e-vertical-right'; const CLS_HBOTTOM: string = 'e-horizontal-bottom'; const CLS_FILL: string = 'e-fill-mode'; const TABITEMPREFIX: string = 'tabitem_'; /** An interface that holds options to control the selected item action. */ export interface SelectEventArgs extends BaseEventArgs { /** Defines the previous Tab item element. */ previousItem: HTMLElement /** Defines the previous Tab item index. */ previousIndex: number /** Defines the selected Tab item element. */ selectedItem: HTMLElement /** Defines the selected Tab item index. */ selectedIndex: number /** Defines the content selection done through swiping. */ isSwiped: boolean /** Defines the prevent action. */ cancel?: boolean /** Defines the selected content. */ selectedContent: HTMLElement } /** An interface that holds options to control the selecting item action. */ export interface SelectingEventArgs extends SelectEventArgs { /** Defines the selecting Tab item element. */ selectingItem: HTMLElement /** Defines the selecting Tab item index. */ selectingIndex: number /** Defines the selecting Tab item content. */ selectingContent: HTMLElement /** Defines the type of the event. */ event?: Event } /** An interface that holds options to control the removing and removed item action. */ export interface RemoveEventArgs extends BaseEventArgs { /** Defines the removed Tab item element. */ removedItem: HTMLElement /** Defines the removed Tab item index. */ removedIndex: number /** Defines the prevent action. */ cancel?: boolean } /** An interface that holds options to control the adding and added item action. */ export interface AddEventArgs extends BaseEventArgs { /** Defines the added Tab item element */ addedItems: TabItemModel[] /** Defines the prevent action. */ cancel?: boolean } /** An interface that holds option to control the dragging and dragged item action. */ export interface DragEventArgs extends BaseEventArgs { /** Defines the current dragged Tab item. */ draggedItem: HTMLElement /** Defines the dropped Tab item. */ droppedItem: HTMLElement /** defines the Dragged Tab item index. */ index: number /** Return the actual event. */ event: MouseEvent /** Return the target element */ target: HTMLElement /** Return the clone element */ clonedElement: HTMLElement /** Defines the prevent action. */ cancel?: boolean } /** * Objects used for configuring the Tab selecting item action properties. */ export class TabActionSettings extends ChildProperty<TabActionSettings> { /** * Specifies the animation effect for displaying Tab content. * * @default 'SlideLeftIn' * @aspType string */ @Property('SlideLeftIn') public effect: 'None' | Effect; /** * Specifies the time duration to transform content. * * @default 600 */ @Property(600) public duration: number; /** * Specifies easing effect applied while transforming content. * * @default 'ease' */ @Property('ease') public easing: string; } /** * Objects used for configuring the Tab animation properties. */ export class TabAnimationSettings extends ChildProperty<TabAnimationSettings> { /** * Specifies the animation to appear while moving to previous Tab content. * * @default { effect: 'SlideLeftIn', duration: 600, easing: 'ease' } */ @Complex<TabActionSettingsModel>({ effect: 'SlideLeftIn', duration: 600, easing: 'ease' }, TabActionSettings) public previous: TabActionSettingsModel; /** * Specifies the animation to appear while moving to next Tab content. * * @default { effect: 'SlideRightIn', duration: 600, easing: 'ease' } */ @Complex<TabActionSettingsModel>({ effect: 'SlideRightIn', duration: 600, easing: 'ease' }, TabActionSettings) public next: TabActionSettingsModel; } /** * Objects used for configuring the Tab item header properties. */ export class Header extends ChildProperty<Header> { /** * Specifies the display text of the Tab item header. * * @default '' */ @Property('') public text: string | HTMLElement; /** * Specifies the icon class that is used to render an icon in the Tab header. * * @default '' */ @Property('') public iconCss: string; /** * Options for positioning the icon in the Tab item header. This property depends on `iconCss` property. * The possible values are: * - Left: Places the icon to the `left` of the item. * - Top: Places the icon on the `top` of the item. * - Right: Places the icon to the `right` end of the item. * - Bottom: Places the icon at the `bottom` of the item. * * @default 'left' */ @Property('left') public iconPosition: string; } /** * An array of object that is used to configure the Tab. */ export class TabItem extends ChildProperty<TabItem> { /** * The object used for configuring the Tab item header properties. * * @default {} */ @Complex<HeaderModel>({}, Header) public header: HeaderModel; /** * Specifies the header text of Tab item. * * @default null */ @Property(null) public headerTemplate: string; /** * Specifies the content of Tab item, that is displayed when concern item header is selected. * * @default '' */ @Property('') public content: string | HTMLElement; /** * Sets the CSS classes to the Tab item to customize its styles. * * @default '' */ @Property('') public cssClass: string; /** * Sets true to disable user interactions of the Tab item. * * @default false */ @Property(false) public disabled: boolean; /** * Sets false to hide the Tab item. * * @default true */ @Property(true) public visible: boolean; /** * Sets unique ID to Tab item. * * @default null */ @Property() public id: string; } /** @hidden */ // eslint-disable-next-line @typescript-eslint/no-unused-vars interface EJ2Instance extends HTMLElement { /* eslint-disable */ ej2_instances: Object[] } /** * Tab is a content panel to show multiple contents in a single space, one at a time. * Each Tab item has an associated content, that will be displayed based on the active Tab header item. * ```html * <div id="tab"></div> * <script> * var tabObj = new Tab(); * tab.appendTo("#tab"); * </script> * ``` */ @NotifyPropertyChanges export class Tab extends Component<HTMLElement> implements INotifyPropertyChanged { private hdrEle: HTEle; private cntEle: HTEle; private tbObj: Toolbar; public tabId: string; private tbItems: HTEle; private tbItem: HTEle[]; private tbPop: HTEle; private isTemplate: boolean; private isPopup: boolean; private isReplace: boolean; private prevIndex: number; private prevItem: HTEle; private popEle: DomElements; private actEleId: string; private bdrLine: HTEle; private popObj: Popup; private btnCls: HTEle; private cnt: string; private show: object = {}; private hide: object = {}; private enableAnimation: boolean; private keyModule: KeyboardEvents; private tabKeyModule: KeyboardEvents; private touchModule: Touch; private maxHeight: number = 0; private title: Str = 'Close'; private initRender: boolean; private prevActiveEle: string; private lastIndex: number = 0; private isSwipeed: boolean; private isNested: boolean; private itemIndexArray: string[]; private templateEle: string[]; private scrCntClass: string; private isAdd: boolean = false; private content: HTEle; private selectedID: string; private selectingID: string; private isIconAlone: boolean = false; private dragItem: HTMLElement; private cloneElement: HTMLElement; private droppedIndex: number; private draggingItems: TabItemModel[]; private draggableItems: Draggable[] = []; private tbId : string; private resizeContext: EventListenerObject = this.refreshActElePosition.bind(this); /** * Contains the keyboard configuration of the Tab. */ private keyConfigs: { [key: string]: Str } = { tab: 'tab', home: 'home', end: 'end', enter: 'enter', space: 'space', delete: 'delete', moveLeft: 'leftarrow', moveRight: 'rightarrow', moveUp: 'uparrow', moveDown: 'downarrow' }; /** * An array of object that is used to configure the Tab component. * ```typescript * let tabObj: Tab = new Tab( { * items: [ * { header: { text: 'TabItem1' }, content: 'Tab Item1 Content' }, * { header: { text: 'TabItem2' }, content: 'Tab Item2 Content' } * ] * }); * tabObj.appendTo('#tab'); * ``` * * @default [] */ @Collection<TabItemModel>([], TabItem) public items: TabItemModel[]; /** * Specifies the width of the Tab component. Default, Tab width sets based on the width of its parent. * * @default '100%' */ @Property('100%') public width: string | number; /** * Specifies the height of the Tab component. By default, Tab height is set based on the height of its parent. * To use height property, heightAdjustMode must be set to 'None'. * * @default 'auto' */ @Property('auto') public height: string | number; /** * Sets the CSS classes to root element of the Tab that helps to customize component styles. * * @default '' */ @Property('') public cssClass: string; /** * Specifies the index for activating the current Tab item. * ```typescript * let tabObj: Tab = new Tab( { * selectedItem: 1, * items: [ * { header: { text: 'TabItem1' }, content: 'Tab Item1 Content' }, * { header: { text: 'TabItem2' }, content: 'Tab Item2 Content' } * ] * }); * tabObj.appendTo('#tab'); * ``` * * @default 0 */ @Property(0) public selectedItem: number; /** * Specifies the orientation of Tab header. * The possible values are: * - Top: Places the Tab header on the top. * - Bottom: Places the Tab header at the bottom. * - Left: Places the Tab header on the left. * - Right: Places the Tab header at the right. * * @default 'Top' */ @Property('Top') public headerPlacement: HeaderPosition; /** * Specifies the height style for Tab content. * The possible values are: * - None: Based on the given height property, the content panel height is set. * - Auto: Tallest panel height of a given Tab content is set to all the other panels. * - Content: Based on the corresponding content height, the content panel height is set. * - Fill: Based on the parent height, the content panel height is set. * * @default 'Content' */ @Property('Content') public heightAdjustMode: HeightStyles; /** * Specifies the Tab display mode when Tab content exceeds the viewing area. * The possible modes are: * - Scrollable: All the elements are displayed in a single line with horizontal scrolling enabled. * - Popup: Tab container holds the items that can be placed within the available space and rest of the items are moved to the popup. * If the popup content overflows the height of the page, the rest of the elements can be viewed by scrolling the popup. * * @default 'Scrollable' */ @Property('Scrollable') public overflowMode: OverflowMode; /** * Specifies the modes for Tab content. * The possible modes are: * `Dynamic` Load Tab content dynamically at the time of switching it's header. * `Init` Load all tab contents at initial load. * `Demand` Load Tab content when required but keep content once it is rendered. * * @default 'Dynamic' */ @Property('Dynamic') protected loadOn: ContentLoad; /** * Enable or disable persisting component's state between page reloads. * If enabled, following list of states will be persisted. * 1. selectedItem * * @default false */ @Property(false) public enablePersistence: boolean; /** * Defines whether to allow the cross-scripting site or not. * * @default false */ @Property(false) public enableHtmlSanitizer: boolean; /** * Specifies whether to show the close button for header items to remove the item from the Tab. * * @default false */ @Property(false) public showCloseButton: boolean; /** * Specifies the scrolling distance in scroller. * * @default null */ @Property() public scrollStep: number; /** * Defines the area in which the draggable element movement will be occurring. Outside that area will be restricted * for the draggable element movement. By default, the draggable element movement occurs in the toolbar. * @default null */ @Property() public dragArea: string; /** * Sets true to allow drag and drop the Tab items * @default false */ @Property(false) public allowDragAndDrop: boolean; /** * Specifies the animation configuration settings while showing the content of the Tab. * * @default * { previous: { effect: 'SlideLeftIn', duration: 600, easing: 'ease' }, * next: { effect: 'SlideRightIn', duration: 600, easing: 'ease' } } */ @Complex<TabAnimationSettingsModel>({}, TabAnimationSettings) public animation: TabAnimationSettingsModel; /** * The event will be fired once the component rendering is completed. * * @event */ @Event() public created: EmitType<Event>; /** * The event will be fired before adding the item to the Tab. * * @event */ @Event() public adding: EmitType<AddEventArgs>; /** * The event will be fired after adding the item to the Tab. * * @event */ @Event() public added: EmitType<AddEventArgs>; /** * The event will be fired before the item gets selected. * * @event */ @Event() public selecting: EmitType<SelectingEventArgs>; /** * The event will be fired after the item gets selected. * * @event */ @Event() public selected: EmitType<SelectEventArgs>; /** * The event will be fired before removing the item from the Tab. * * @event */ @Event() public removing: EmitType<RemoveEventArgs>; /** * The event will be fired after removing the item from the Tab. * * @event */ @Event() public removed: EmitType<RemoveEventArgs>; /** * The event will be fired before dragging the item from Tab * @event */ @Event() public onDragStart: EmitType<DragEventArgs>; /** * The event will be fired while dragging the Tab item * @event */ @Event() public dragging: EmitType<DragEventArgs>; /** * The event will be fired after dropping the Tab item * @event */ @Event() public dragged: EmitType<DragEventArgs>; /** * The event will be fired when the component gets destroyed. * * @event */ @Event() public destroyed: EmitType<Event>; /** * Removes the component from the DOM and detaches all its related event handlers, attributes and classes. * * @returns {void} */ public destroy(): void { if ((this as any).isReact) { this.clearTemplate(); } if (!isNOU(this.tbObj)) { this.tbObj.destroy(); } this.unWireEvents(); ['role', 'aria-disabled', 'aria-activedescendant', 'tabindex', 'aria-orientation'].forEach((val: string): void => { this.element.removeAttribute(val); }); this.expTemplateContent(); if (!this.isTemplate) { while (this.element.firstElementChild) { remove(this.element.firstElementChild); } } else { const cntEle: Element = select('.' + CLS_TAB + ' > .' + CLS_CONTENT, this.element); this.element.classList.remove(CLS_TEMPLATE); if (!isNOU(cntEle)) { cntEle.innerHTML = this.cnt; } } super.destroy(); this.trigger('destroyed'); } /** * Refresh the tab component * * @returns {void} */ public refresh(): void { if ((this as any).isReact) { this.clearTemplate(); } super.refresh(); if ((this as any).isReact) { this.renderReactTemplates(); } } /** * Initialize component * * @private * @returns {void} */ protected preRender(): void { const nested: Element = closest(this.element, '.' + CLS_CONTENT); this.prevIndex = 0; this.isNested = false; this.isPopup = false; this.initRender = true; this.isSwipeed = false; this.itemIndexArray = []; this.templateEle = []; if (!isNOU(nested)) { nested.parentElement.classList.add(CLS_NEST); this.isNested = true; } const name: Str = Browser.info.name; const css: Str = (name === 'msie') ? 'e-ie' : (name === 'edge') ? 'e-edge' : (name === 'safari') ? 'e-safari' : ''; setStyle(this.element, { 'width': formatUnit(this.width), 'height': formatUnit(this.height) }); this.setCssClass(this.element, this.cssClass, true); attributes(this.element, { role: 'tablist', 'aria-disabled': 'false', 'aria-activedescendant': '' }); this.setCssClass(this.element, css, true); this.updatePopAnimationConfig(); } /** * Initializes a new instance of the Tab class. * * @param {TabModel} options - Specifies Tab model properties as options. * @param {string | HTMLElement} element - Specifies the element that is rendered as a Tab. */ public constructor(options?: TabModel, element?: string | HTMLElement) { super(options, <HTEle | Str>element); } /** * Initialize the component rendering * * @private * @returns {void} */ protected render(): void { this.btnCls = this.createElement('span', { className: CLS_ICONS + ' ' + CLS_ICON_CLOSE, attrs: { title: this.title } }); this.tabId = this.element.id.length > 0 ? ('-' + this.element.id) : getRandomId(); this.renderContainer(); this.wireEvents(); this.initRender = false; } private renderContainer(): void { const ele: HTEle = this.element; this.items.forEach((item: TabItemModel, index: number) => { if (isNOU(item.id) && !isNOU((item as Base<HTMLElement>).setProperties)) { (item as Base<HTMLElement>).setProperties({ id: TABITEMPREFIX + index.toString() }, true); } }); if (this.items.length > 0 && ele.children.length === 0) { ele.appendChild(this.createElement('div', { className: CLS_CONTENT })); this.setOrientation(this.headerPlacement, this.createElement('div', { className: CLS_HEADER })); this.isTemplate = false; } else if (this.element.children.length > 0) { this.isTemplate = true; ele.classList.add(CLS_TEMPLATE); const header: HTEle = <HTEle>ele.querySelector('.' + CLS_HEADER); if (header && this.headerPlacement === 'Bottom') { this.setOrientation(this.headerPlacement, header); } } if (!isNOU(select('.' + CLS_HEADER, this.element)) && !isNOU(select('.' + CLS_CONTENT, this.element))) { this.renderHeader(); this.tbItems = <HTEle>select('.' + CLS_HEADER + ' .' + CLS_TB_ITEMS, this.element); if (!isNOU(this.tbItems)) { rippleEffect(this.tbItems, { selector: '.e-tab-wrap' }); } this.renderContent(); if (selectAll('.' + CLS_TB_ITEM, this.element).length > 0) { this.tbItems = <HTEle>select('.' + CLS_HEADER + ' .' + CLS_TB_ITEMS, this.element); this.bdrLine = this.createElement('div', { className: CLS_INDICATOR + ' ' + CLS_HIDDEN + ' ' + CLS_IGNORE }); const scrCnt: HTEle = <HTEle>select('.' + this.scrCntClass, this.tbItems); if (!isNOU(scrCnt)) { scrCnt.insertBefore(this.bdrLine, scrCnt.firstChild); } else { this.tbItems.insertBefore(this.bdrLine, this.tbItems.firstChild); } this.setContentHeight(true); this.select(this.selectedItem); } if (!isNOU(this.tbItem)) { for (let i: number = 0; i < this.items.length; i++) { const tabID: string = this.items[i].id; this.tbItem[i].setAttribute('data-id', tabID); } } this.setRTL(this.enableRtl); } } private serverItemsChanged(): void { this.enableAnimation = false; this.setActive(this.selectedItem, true); if (this.loadOn !== 'Dynamic' && !isNOU(this.cntEle)) { const itemCollection: HTMLElement[] = [].slice.call(this.cntEle.children); const content: string = CLS_CONTENT + this.tabId + '_' + this.selectedItem; itemCollection.forEach((item: HTEle) => { if (item.classList.contains(CLS_ACTIVE) && item.id !== content) { item.classList.remove(CLS_ACTIVE); } if (item.id === content) { item.classList.add(CLS_ACTIVE); } }); this.prevIndex = this.selectedItem; this.triggerAnimation(CLS_ITEM + this.tabId + '_' + this.selectedItem, false); } this.enableAnimation = true; } private headerReady(): void { this.initRender = true; this.hdrEle = this.getTabHeader(); this.setOrientation(this.headerPlacement, this.hdrEle); if (!isNOU(this.hdrEle)) { this.tbObj = (<ToolbarModel>(this.hdrEle && (<Instance>this.hdrEle).ej2_instances[0])) as Toolbar; } this.tbObj.clicked = this.clickHandler.bind(this); this.tbObj.on('onItemsChanged', this.serverItemsChanged.bind(this)); this.tbItems = <HTEle>select('.' + CLS_HEADER + ' .' + CLS_TB_ITEMS, this.element); if (!isNOU(this.tbItems)) { rippleEffect(this.tbItems, { selector: '.e-tab-wrap' }); } if (selectAll('.' + CLS_TB_ITEM, this.element).length > 0) { this.bdrLine = <HTEle>select('.' + CLS_INDICATOR + '.' + CLS_IGNORE, this.element); const scrollCnt: HTEle = <HTEle>select('.' + this.scrCntClass, this.tbItems); if (!isNOU(scrollCnt)) { scrollCnt.insertBefore(this.bdrLine, scrollCnt.firstElementChild); } else { this.tbItems.insertBefore(this.bdrLine, this.tbItems.firstElementChild); } this.select(this.selectedItem); } this.cntEle = <HTEle>select('.' + CLS_TAB + ' > .' + CLS_CONTENT, this.element); if (!isNOU(this.cntEle)) { this.touchModule = new Touch(this.cntEle, { swipe: this.swipeHandler.bind(this) }); } if (this.loadOn === 'Demand') { const id: string = this.setActiveContent(); this.triggerAnimation(id, false); } this.initRender = false; this.renderComplete(); } private setActiveContent(): string { const id: string = CLS_ITEM + this.tabId + '_' + this.selectedItem; const item: HTEle = this.getTrgContent(this.cntEle, this.extIndex(id)); if (!isNOU(item)) { item.classList.add(CLS_ACTIVE); } return id; } private renderHeader(): void { const hdrPlace: HeaderPosition = this.headerPlacement; let tabItems: Object[] = []; this.hdrEle = this.getTabHeader(); this.addVerticalClass(); if (!this.isTemplate) { tabItems = this.parseObject(this.items, 0); } else { if (this.element.children.length > 1 && this.element.children[1].classList.contains(CLS_HEADER)) { this.setProperties({ headerPlacement: 'Bottom' }, true); } const count: number = this.hdrEle.children.length; const hdrItems: string[] = []; for (let i: number = 0; i < count; i++) { hdrItems.push(this.hdrEle.children.item(i).innerHTML); } if (count > 0) { while (this.hdrEle.firstElementChild) { detach(this.hdrEle.firstElementChild); } const tabItems: HTMLElement = this.createElement('div', { className: CLS_ITEMS }); this.hdrEle.appendChild(tabItems); hdrItems.forEach((item: string, index: number) => { this.lastIndex = index; const attr: object = { className: CLS_ITEM, id: CLS_ITEM + this.tabId + '_' + index, attrs: { role: 'tab', 'aria-controls': CLS_CONTENT + this.tabId + '_' + index, 'aria-selected': 'false' } }; const txt: Str = this.createElement('span', { className: CLS_TEXT, innerHTML: item, attrs: { 'role': 'presentation' } }).outerHTML; const cont: Str = this.createElement('div', { className: CLS_TEXT_WRAP, innerHTML: txt + this.btnCls.outerHTML }).outerHTML; const wrap: HTEle = this.createElement('div', { className: CLS_WRAP, innerHTML: cont, attrs: { tabIndex: '-1' } }); tabItems.appendChild(this.createElement('div', attr)); selectAll('.' + CLS_ITEM, tabItems)[index].appendChild(wrap); }); } } this.tbObj = new Toolbar({ width: (hdrPlace === 'Left' || hdrPlace === 'Right') ? 'auto' : '100%', height: (hdrPlace === 'Left' || hdrPlace === 'Right') ? '100%' : 'auto', overflowMode: this.overflowMode, items: (tabItems.length !== 0) ? tabItems : [], clicked: this.clickHandler.bind(this), scrollStep: this.scrollStep, enableHtmlSanitizer: this.enableHtmlSanitizer }); this.tbObj.isStringTemplate = true; this.tbObj.createElement = this.createElement; this.tbObj.appendTo(<HTEle>this.hdrEle); attributes(this.hdrEle, { 'aria-label': 'tab-header' }); this.updateOrientationAttribute(); this.setCloseButton(this.showCloseButton); } private renderContent(): void { this.cntEle = <HTEle>select('.' + CLS_CONTENT, this.element); const hdrItem: HTEle[] = selectAll('.' + CLS_TB_ITEM, this.element); if (this.isTemplate) { this.cnt = (this.cntEle.children.length > 0) ? this.cntEle.innerHTML : ''; const contents: HTMLCollection = this.cntEle.children; for (let i: number = 0; i < hdrItem.length; i++) { if (contents.length - 1 >= i) { addClass([contents.item(i)], CLS_ITEM); attributes(contents.item(i), { 'role': 'tabpanel', 'aria-labelledby': CLS_ITEM + this.tabId + '_' + i }); contents.item(i).id = CLS_CONTENT + this.tabId + '_' + i; } } } } private reRenderItems(): void { this.renderContainer(); if (!isNOU(this.cntEle)) { this.touchModule = new Touch(this.cntEle, { swipe: this.swipeHandler.bind(this) }); } } private parseObject(items: TabItemModel[], index: number): object[] { const tbCount: number = selectAll('.' + CLS_TB_ITEM, this.element).length; const tItems: Object[] = []; let txtWrapEle: HTEle; const spliceArray: number[] = []; const i: number = 0; items.forEach((item: TabItemModel, i: number) => { const pos: Str = (isNOU(item.header) || isNOU(item.header.iconPosition)) ? '' : item.header.iconPosition; const css: Str = (isNOU(item.header) || isNOU(item.header.iconCss)) ? '' : item.header.iconCss; if ((isNOU(item.headerTemplate)) && (isNOU(item.header) || isNOU(item.header.text) || (((<string>item.header.text).length === 0)) && (css === ''))) { spliceArray.push(i); return; } let txt: Str | HTEle = item.headerTemplate || item.header.text; if (typeof txt === 'string' && this.enableHtmlSanitizer) { txt = SanitizeHtmlHelper.sanitize(<Str>txt); } let itemIndex: number; if (this.isReplace && !isNOU(this.tbId) && this.tbId !== '') { const num: number = (this.tbId.indexOf('_')); itemIndex = parseInt(this.tbId.substring(num + 1), 10); this.tbId = ''; } else { itemIndex = index + i; } const addIndex: number = this.isAdd ? tbCount + i : this.lastIndex + 1; this.lastIndex = ((tbCount === 0) ? i : ((this.isReplace) ? (itemIndex) : (addIndex))); const disabled: Str = (item.disabled) ? ' ' + CLS_DISABLE + ' ' + CLS_OVERLAY : ''; const hidden: Str = (item.visible === false) ? ' ' + CLS_HIDDEN : ''; txtWrapEle = this.createElement('div', { className: CLS_TEXT, attrs: { 'role': 'presentation' } }); const tHtml: Str = ((txt instanceof Object) ? (<HTEle>txt).outerHTML : txt); const txtEmpty: boolean = (!isNOU(tHtml) && tHtml !== ''); if (!isNOU((<HTEle>txt).tagName)) { txtWrapEle.appendChild(txt as HTEle); } else { this.headerTextCompile(txtWrapEle, txt as string, i); } let tEle: HTEle; const icon: HTEle = this.createElement('span', { className: CLS_ICONS + ' ' + CLS_TAB_ICON + ' ' + CLS_ICON + '-' + pos + ' ' + css }); const tCont: HTEle = this.createElement('div', { className: CLS_TEXT_WRAP }); tCont.appendChild(txtWrapEle); if ((txt !== '' && txt !== undefined) && css !== '') { if ((pos === 'left' || pos === 'top')) { tCont.insertBefore(icon, tCont.firstElementChild); } else { tCont.appendChild(icon); } tEle = txtWrapEle; this.isIconAlone = false; } else { tEle = ((css === '') ? txtWrapEle : icon); if (tEle === icon) { detach(txtWrapEle); tCont.appendChild(icon); this.isIconAlone = true; } } const wrapAttrs: { [key: string]: string } = (item.disabled) ? {} : { tabIndex: '-1' }; tCont.appendChild(this.btnCls.cloneNode(true)); const wrap: HTEle = this.createElement('div', { className: CLS_WRAP, attrs: wrapAttrs }); wrap.appendChild(tCont); if (this.itemIndexArray === []) { this.itemIndexArray.push(CLS_ITEM + this.tabId + '_' + this.lastIndex); } else { this.itemIndexArray.splice((index + i), 0, CLS_ITEM + this.tabId + '_' + this.lastIndex); } const attrObj: Object = { id: CLS_ITEM + this.tabId + '_' + this.lastIndex, role: 'tab', 'aria-selected': 'false' }; const tItem: { [key: string]: {} } = { htmlAttributes: attrObj, template: wrap }; tItem.cssClass = ((item.cssClass !== undefined) ? item.cssClass : ' ') + ' ' + disabled + ' ' + hidden + ' ' + ((css !== '') ? 'e-i' + pos : '') + ' ' + ((!txtEmpty) ? CLS_ICON : ''); if (pos === 'top' || pos === 'bottom') { this.element.classList.add('e-vertical-icon'); } tItems.push(tItem); i++; }); if (!this.isAdd) { spliceArray.forEach((spliceItemIndex: number) => { this.items.splice(spliceItemIndex, 1); }); } if (this.isIconAlone) { this.element.classList.add(CLS_ICON_TAB); } else { this.element.classList.remove(CLS_ICON_TAB); } return tItems; } private removeActiveClass(): void { const tabHeader: HTMLElement = this.getTabHeader(); if (tabHeader) { const tabItems: HTMLElement[] = selectAll('.' + CLS_TB_ITEM + '.' + CLS_ACTIVE, tabHeader); [].slice.call(tabItems).forEach((node: HTMLElement) => node.classList.remove(CLS_ACTIVE)); } } private checkPopupOverflow(ele: HTEle): boolean { this.tbPop = <HTEle>select('.' + CLS_TB_POP, this.element); const popIcon: HTEle = (<HTEle>select('.e-hor-nav', this.element)); const tbrItems: HTEle = (<HTEle>select('.' + CLS_TB_ITEMS, this.element)); const lastChild: HTEle = <HTMLElement>tbrItems.lastChild; let isOverflow: boolean = false; if (!this.isVertical() && ((this.enableRtl && ((popIcon.offsetLeft + popIcon.offsetWidth) > tbrItems.offsetLeft)) || (!this.enableRtl && popIcon.offsetLeft < tbrItems.offsetWidth))) { isOverflow = true; } else if (this.isVertical() && (popIcon.offsetTop < lastChild.offsetTop + lastChild.offsetHeight)) { isOverflow = true; } if (isOverflow) { ele.classList.add(CLS_TB_POPUP); this.tbPop.insertBefore(<Node>ele, selectAll('.' + CLS_TB_POPUP, this.tbPop)[0]); } return true; } private popupHandler(target: HTEle): number { const ripEle: HTEle = <HTEle>target.querySelector('.e-ripple-element'); if (!isNOU(ripEle)) { ripEle.outerHTML = ''; target.querySelector('.' + CLS_WRAP).classList.remove('e-ripple'); } this.tbItem = selectAll('.' + CLS_TB_ITEMS + ' .' + CLS_TB_ITEM, this.hdrEle); const lastChild: HTEle = <HTEle>this.tbItem[this.tbItem.length - 1]; if (this.tbItem.length !== 0) { target.classList.remove(CLS_TB_POPUP); target.removeAttribute('style'); this.tbItems.appendChild(target); this.actEleId = target.id; if (this.checkPopupOverflow(lastChild)) { const prevEle: HTEle = <HTEle>(<HTEle>this.tbItems.lastChild).previousElementSibling; this.checkPopupOverflow(prevEle); } this.isPopup = true; } return selectAll('.' + CLS_TB_ITEM, this.tbItems).length - 1; } private updateOrientationAttribute(): void { attributes(this.element, { 'aria-orientation': (this.isVertical() ? 'vertical' : 'horizontal') }); } private setCloseButton(val: boolean): void { const trg: Element = select('.' + CLS_HEADER, this.element); if (val === true) { trg.classList.add(CLS_CLOSE_SHOW); } else { trg.classList.remove(CLS_CLOSE_SHOW); } this.tbObj.refreshOverflow(); this.refreshActElePosition(); } private prevCtnAnimation(prev: number, current: number): AnimationModel { let animation: AnimationModel; const checkRTL: boolean = this.enableRtl || this.element.classList.contains(CLS_RTL); if (this.isPopup || prev <= current) { if (this.animation.previous.effect === 'SlideLeftIn') { animation = { name: 'SlideLeftOut', duration: this.animation.previous.duration, timingFunction: this.animation.previous.easing }; } else { animation = null; } } else { if (this.animation.next.effect === 'SlideRightIn') { animation = { name: 'SlideRightOut', duration: this.animation.next.duration, timingFunction: this.animation.next.easing }; } else { animation = null; } } return animation; } private triggerPrevAnimation(oldCnt: HTEle, prevIndex: number): void { const animateObj: AnimationModel = this.prevCtnAnimation(prevIndex, this.selectedItem); if (!isNOU(animateObj)) { animateObj.begin = () => { setStyle(oldCnt, { 'position': 'absolute' }); oldCnt.classList.add(CLS_PROGRESS); oldCnt.classList.add('e-view'); }; animateObj.end = () => { oldCnt.style.display = 'none'; oldCnt.classList.remove(CLS_ACTIVE); oldCnt.classList.remove(CLS_PROGRESS); oldCnt.classList.remove('e-view'); setStyle(oldCnt, { 'display': '', 'position': '' }); if (oldCnt.childNodes.length === 0 && !this.isTemplate) { detach(oldCnt); } }; new Animation(animateObj).animate(oldCnt); } else { oldCnt.classList.remove(CLS_ACTIVE); } } private triggerAnimation(id: Str, value: boolean): void { const prevIndex: number = this.prevIndex; let oldCnt: HTEle; const itemCollection: HTMLElement[] = [].slice.call(this.element.querySelector('.' + CLS_CONTENT).children); itemCollection.forEach((item: HTEle) => { if (item.id === this.prevActiveEle) { oldCnt = item; } }); const prevEle: HTEle = this.tbItem[prevIndex]; const newCnt: HTEle = this.getTrgContent(this.cntEle, this.extIndex(id)); if (isNOU(oldCnt) && !isNOU(prevEle)) { const idNo: Str = this.extIndex(prevEle.id); oldCnt = this.getTrgContent(this.cntEle, idNo); } if (!isNOU(newCnt)) { this.prevActiveEle = newCnt.id; } if (this.initRender || value === false || this.animation === {} || isNOU(this.animation)) { if (oldCnt && oldCnt !== newCnt) { oldCnt.classList.remove(CLS_ACTIVE); } return; } const cnt: HTEle = <HTEle>select('.' + CLS_CONTENT, this.element); let animateObj: AnimationModel; if (this.prevIndex > this.selectedItem && !this.isPopup) { const openEff: Effect = <Effect>this.animation.previous.effect; animateObj = { name: <Effect>((openEff === <Effect>'None') ? '' : ((openEff !== <Effect>'SlideLeftIn') ? openEff : 'SlideLeftIn')), duration: this.animation.previous.duration, timingFunction: this.animation.previous.easing }; } else if (this.isPopup || this.prevIndex < this.selectedItem || this.prevIndex === this.selectedItem) { const clsEff: Effect = <Effect>this.animation.next.effect; animateObj = { name: <Effect>((clsEff === <Effect>'None') ? '' : ((clsEff !== <Effect>'SlideRightIn') ? clsEff : 'SlideRightIn')), duration: this.animation.next.duration, timingFunction: this.animation.next.easing }; } animateObj.progress = () => { cnt.classList.add(CLS_PROGRESS); this.setActiveBorder(); }; animateObj.end = () => { cnt.classList.remove(CLS_PROGRESS); newCnt.classList.add(CLS_ACTIVE); }; if (!this.initRender && !isNOU(oldCnt)) { this.triggerPrevAnimation(oldCnt, prevIndex); } this.isPopup = false; if (animateObj.name === <Effect>'') { newCnt.classList.add(CLS_ACTIVE); } else { new Animation(animateObj).animate(newCnt); } } private keyPressed(trg: HTEle): void { const trgParent: HTEle = <HTEle>closest(trg, '.' + CLS_HEADER + ' .' + CLS_TB_ITEM); const trgIndex: number = this.getEleIndex(trgParent); if (!isNOU(this.popEle) && trg.classList.contains('e-hor-nav')) { (this.popEle.classList.contains(CLS_POPUP_OPEN)) ? this.popObj.hide(this.hide) : this.popObj.show(this.show); } else if (trg.classList.contains('e-scroll-nav')) { trg.click(); } else { if (!isNOU(trgParent) && trgParent.classList.contains(CLS_ACTIVE) === false) { this.select(trgIndex); if (!isNOU(this.popEle)) { this.popObj.hide(this.hide); } } } } private getTabHeader(): HTMLElement { if (isNOU(this.element)) { return undefined; } const headers: HTMLElement[] = [].slice.call(this.element.children).filter((e: HTMLElement) => e.classList.contains(CLS_HEADER)); if (headers.length > 0) { return headers[0]; } else { const wrap: HTMLElement = [].slice.call(this.element.children).filter((e: HTMLElement) => !e.classList.contains(CLS_BLA_TEM))[0]; if (!wrap) { return undefined; } return [].slice.call(wrap.children).filter((e: HTMLElement) => e.classList.contains(CLS_HEADER))[0]; } } private getEleIndex(item: HTEle): number { return Array.prototype.indexOf.call(selectAll('.' + CLS_TB_ITEM, this.getTabHeader()), item); } private extIndex(id: string): string { return id.replace(CLS_ITEM + this.tabId + '_', ''); } private expTemplateContent(): void { this.templateEle.forEach((eleStr: Str): void => { if (!isNOU(this.element.querySelector(eleStr))) { (<HTEle>document.body.appendChild(this.element.querySelector(eleStr))).style.display = 'none'; } }); } private templateCompile(ele: HTEle, cnt: Str, index: number): void { const tempEle: HTEle = this.createElement('div'); this.compileElement(tempEle, cnt, 'content', index); if (tempEle.childNodes.length !== 0) { ele.appendChild(tempEle); } if ((this as any).isReact) { this.renderReactTemplates(); } } private compileElement(ele: HTEle, val: string, prop: string, index: number): void { let templateFn: Function; if (typeof val === 'string') { val = val.trim(); ele.innerHTML = SanitizeHtmlHelper.sanitize(val); } else { templateFn = compile(val); } let templateFUN: HTMLElement[]; if (!isNOU(templateFn)) { templateFUN = templateFn({}, this, prop); } if (!isNOU(templateFn) && templateFUN.length > 0) { [].slice.call(templateFUN).forEach((el: HTEle): void => { ele.appendChild(el); }); } } private headerTextCompile(element: HTEle, text: string, index: number): void { this.compileElement(element, text, 'headerTemplate', index); } private getContent(ele: HTEle, cnt: Str | HTEle, callType: string, index: number): void { let eleStr: Str; if (typeof cnt === 'string' || isNOU((<HTEle>cnt).innerHTML)) { if (typeof cnt === 'string' && this.enableHtmlSanitizer) { cnt = SanitizeHtmlHelper.sanitize(<Str>cnt); } if ((<Str>cnt)[0] === '.' || (<Str>cnt)[0] === '#') { if (document.querySelectorAll(<string>cnt).length) { const eleVal: HTEle = <HTEle>document.querySelector(<string>cnt); eleStr = eleVal.outerHTML.trim(); if (callType === 'clone') { ele.appendChild(eleVal.cloneNode(true)); } else { ele.appendChild(eleVal); eleVal.style.display = ''; } } else { this.templateCompile(ele, <Str>cnt, index); } } else { this.templateCompile(ele, <Str>cnt, index); } } else { ele.appendChild(cnt); } if (!isNOU(eleStr)) { if (this.templateEle.indexOf(cnt.toString()) === -1) { this.templateEle.push(cnt.toString()); } } } private getTrgContent(cntEle: HTEle, no: Str): HTEle { let ele: HTEle; if (this.element.classList.contains(CLS_NEST)) { ele = <HTEle>select('.' + CLS_NEST + '> .' + CLS_CONTENT + ' > #' + CLS_CONTENT + this.tabId + '_' + no, this.element); } else { ele = this.findEle(cntEle.children, CLS_CONTENT + this.tabId + '_' + no); } return ele; } private findEle(items: HTMLCollection, key: Str): HTEle { let ele: HTEle; for (let i: number = 0; i < items.length; i++) { if (items[i].id === key) { ele = <HTEle>items[i]; break; } } return ele; } private isVertical(): boolean { const isVertical: boolean = (this.headerPlacement === 'Left' || this.headerPlacement === 'Right') ? true : false; this.scrCntClass = (isVertical) ? CLS_VSCRCNT : CLS_HSCRCNT; return isVertical; } private addVerticalClass(): void { if (this.isVertical()) { const tbPos: string = (this.headerPlacement === 'Left') ? CLS_VLEFT : CLS_VRIGHT; addClass([this.hdrEle], [CLS_VERTICAL, tbPos]); if (!this.element.classList.contains(CLS_NEST)) { addClass([this.element], [CLS_VTAB, tbPos]); } else { addClass([this.hdrEle], [CLS_VTAB, tbPos]); } } if (this.headerPlacement === 'Bottom') { addClass([this.hdrEle], [CLS_HBOTTOM]); } } private updatePopAnimationConfig(): void { this.show = { name: (this.isVertical() ? 'FadeIn' : 'SlideDown'), duration: 100 }; this.hide = { name: (this.isVertical() ? 'FadeOut' : 'SlideUp'), duration: 100 }; } private changeOrientation(place: Str): void { this.setOrientation(place, this.hdrEle); const activeTab: HTMLElement = this.hdrEle.querySelector('.' + CLS_ACTIVE); const isVertical: boolean = this.hdrEle.classList.contains(CLS_VERTICAL) ? true : false; removeClass([this.element], [CLS_VTAB]); removeClass([this.hdrEle], [CLS_VERTICAL, CLS_VLEFT, CLS_VRIGHT]); if (isVertical !== this.isVertical()) { this.changeToolbarOrientation(); if (!isNOU(activeTab) && activeTab.classList.contains(CLS_TB_POPUP)) { this.popupHandler(activeTab); } } this.addVerticalClass(); this.updateOrientationAttribute(); this.setActiveBorder(); this.focusItem(); } private focusItem(): void { const curActItem: HTEle = <HTEle>select(' #' + CLS_ITEM + this.tabId + '_' + this.selectedItem, this.hdrEle); if (!isNOU(curActItem)) { (<HTEle>curActItem.firstElementChild).focus(); } } private changeToolbarOrientation(): void { this.tbObj.setProperties({ height: (this.isVertical() ? '100%' : 'auto'), width: (this.isVertical() ? 'auto' : '100%') }, true); this.tbObj.changeOrientation(); this.updatePopAnimationConfig(); } private setOrientation(place: Str, ele: HTEle): void { const headerPos: number = Array.prototype.indexOf.call(this.element.children, ele); const contentPos: number = Array.prototype.indexOf.call(this.element.children, this.element.querySelector('.' + CLS_CONTENT)); if (place === 'Bottom' && (contentPos > headerPos)) { this.element.appendChild(ele); } else { removeClass([ele], [CLS_HBOTTOM]); this.element.insertBefore(ele, select('.' + CLS_CONTENT, this.element)); } } private setCssClass(ele: HTEle, cls: Str, val: boolean): void { if (cls === '') { return; } const list: Str[] = cls.split(' '); for (let i: number = 0; i < list.length; i++) { if (val) { ele.classList.add(list[i]); } else { ele.classList.remove(list[i]); } } } private setContentHeight(val: boolean): void { if (this.element.classList.contains(CLS_FILL)) { removeClass([this.element], [CLS_FILL]); } if (isNOU(this.cntEle)) { return; } const hdrEle: HTEle = this.getTabHeader(); if (this.heightAdjustMode === 'None') { if (this.height === 'auto') { return; } else { if (!this.isVertical()) { setStyle(this.cntEle, { 'height': (this.element.offsetHeight - hdrEle.offsetHeight) + 'px' }); } } } else if (this.heightAdjustMode === 'Fill') { addClass([this.element], [CLS_FILL]); setStyle(this.element, { 'height': '100%' }); setStyle(this.cntEle, { 'height': (this.element.offsetHeight - hdrEle.offsetHeight) + 'px' }); } else if (this.heightAdjustMode === 'Auto') { if (this.isTemplate === true) { const cnt: HTEle[] = selectAll('.' + CLS_CONTENT + ' > .' + CLS_ITEM, this.element); for (let i: number = 0; i < cnt.length; i++) { cnt[i].setAttribute('style', 'display:block; visibility: visible'); this.maxHeight = Math.max(this.maxHeight, this.getHeight(cnt[i])); cnt[i].style.removeProperty('display'); cnt[i].style.removeProperty('visibility'); } } else { this.cntEle = <HTEle>select('.' + CLS_CONTENT, this.element); if (val === true) { this.cntEle.appendChild(this.createElement('div', { id: (CLS_CONTENT + this.tabId + '_' + 0), className: CLS_ITEM + ' ' + CLS_ACTIVE, attrs: { 'role': 'tabpanel', 'aria-labelledby': CLS_ITEM + this.tabId + '_' + 0 } })); } const ele: HTEle = <HTEle>this.cntEle.children.item(0); for (let i: number = 0; i < this.items.length; i++) { this.getContent(ele, this.items[i].content, 'clone', i); this.maxHeight = Math.max(this.maxHeight, this.getHeight(ele)); while (ele.firstChild) { ele.removeChild(ele.firstChild); } } if ((this as any).isReact) { this.clearTemplate(['content']); } this.templateEle = []; this.getContent(ele, this.items[0].content, 'render', 0); if (this.prevIndex !== this.selectedItem) { ele.classList.remove(CLS_ACTIVE); } } setStyle(this.cntEle, { 'height': this.maxHeight + 'px' }); } else { setStyle(this.cntEle, { 'height': 'auto' }); } } private getHeight(ele: HTEle): number { const cs: CSSStyleDeclaration = window.getComputedStyle(ele); return ele.offsetHeight + parseFloat(cs.getPropertyValue('padding-top')) + parseFloat(cs.getPropertyValue('padding-bottom')) + parseFloat(cs.getPropertyValue('margin-top')) + parseFloat(cs.getPropertyValue('margin-bottom')); } private setActiveBorder(): void { const trgHdrEle: Element = this.getTabHeader(); const trg: HTEle = <HTEle>select('.' + CLS_TB_ITEM + '.' + CLS_ACTIVE, trgHdrEle); if (trg === null) { return; } const root: HTEle = <HTEle>closest(trg, '.' + CLS_TAB); if (this.element !== root) { return; } this.tbItems = <HTEle>select('.' + CLS_TB_ITEMS, trgHdrEle); const bar: HTEle = <HTEle>select('.' + CLS_INDICATOR, trgHdrEle); const scrollCnt: HTEle = <HTEle>select('.' + CLS_TB_ITEMS + ' .' + this.scrCntClass, trgHdrEle); if (this.isVertical()) { setStyle(bar, { 'left': '', 'right': '' }); const tbHeight: number = (isNOU(scrollCnt)) ? this.tbItems.offsetHeight : scrollCnt.offsetHeight; if (tbHeight !== 0) { setStyle(bar, { 'top': trg.offsetTop + 'px', 'height': trg.offsetHeight + 'px' }); } else { setStyle(bar, { 'top': 0, 'height': 0 }); } } else { if (this.overflowMode === 'MultiRow') { let bar: HTEle = <HTEle>select('.' + CLS_INDICATOR, this.element); setStyle(bar, { 'top': trg.offsetHeight + trg.offsetTop + 'px', 'height': '' }); } else { setStyle(bar, { 'top': '', 'height': '' }); } let tbWidth: number = (isNOU(scrollCnt)) ? this.tbItems.offsetWidth : scrollCnt.offsetWidth; if (tbWidth !== 0) { setStyle(bar, { 'left': trg.offsetLeft + 'px', 'right': tbWidth - (trg.offsetLeft + trg.offsetWidth) + 'px' }); } else { setStyle(bar, { 'left': 'auto', 'right': 'auto' }); } } if (!isNOU(this.bdrLine)) { this.bdrLine.classList.remove(CLS_HIDDEN); } } private setActive(value: number, skipDataBind: boolean = false): void { this.tbItem = selectAll('.' + CLS_TB_ITEM, this.getTabHeader()); const trg: HTEle = this.tbItem[value]; if (value < 0 || isNaN(value) || this.tbItem.length === 0) { return; } if (value >= 0 && !skipDataBind) { this.allowServerDataBinding = false; this.setProperties({ selectedItem: value }, true); this.allowServerDataBinding = true; if (!this.initRender) { this.serverDataBind(); } } if (trg.classList.contains(CLS_ACTIVE)) { this.setActiveBorder(); return; } if (!this.isTemplate) { const prev: HTEle = this.tbItem[this.prevIndex]; if (!isNOU(prev)) { prev.removeAttribute('aria-controls'); } attributes(trg, { 'aria-controls': CLS_CONTENT + this.tabId + '_' + value }); } const id: Str = trg.id; this.removeActiveClass(); trg.classList.add(CLS_ACTIVE); this.tbItem[this.prevIndex].setAttribute('aria-selected', 'false'); trg.setAttribute('aria-selected', 'true'); const no: number = Number(this.extIndex(id)); if (isNOU(this.prevActiveEle)) { this.prevActiveEle = CLS_CONTENT + this.tabId + '_' + no; } attributes(this.element, { 'aria-activedescendant': id }); if (this.isTemplate) { if (select('.' + CLS_CONTENT, this.element).children.length > 0) { const trg: HTEle = this.findEle(select('.' + CLS_CONTENT, this.element).children, CLS_CONTENT + this.tabId + '_' + no); if (!isNOU(trg)) { trg.classList.add(CLS_ACTIVE); } this.triggerAnimation(id, this.enableAnimation); } } else { this.cntEle = <HTEle>select('.' + CLS_TAB + ' > .' + CLS_CONTENT, this.element); const item: HTEle = this.getTrgContent(this.cntEle, this.extIndex(id)); if (isNOU(item)) { this.cntEle.appendChild(this.createElement('div', { id: CLS_CONTENT + this.tabId + '_' + this.extIndex(id), className: CLS_ITEM + ' ' + CLS_ACTIVE, attrs: { role: 'tabpanel', 'aria-labelledby': CLS_ITEM + this.tabId + '_' + this.extIndex(id) } })); const eleTrg: HTEle = this.getTrgContent(this.cntEle, this.extIndex(id)); const itemIndex: number = Array.prototype.indexOf.call(this.itemIndexArray, id); this.getContent(eleTrg, this.items[itemIndex].content, 'render', itemIndex); } else { item.classList.add(CLS_ACTIVE); } this.triggerAnimation(id, this.enableAnimation); } this.setActiveBorder(); this.refreshItemVisibility(trg); if (!this.initRender && !skipDataBind) { (<HTEle>trg.firstElementChild).focus(); const eventArg: SelectEventArgs = { previousItem: this.prevItem, previousIndex: this.prevIndex, selectedItem: trg, selectedIndex: value, selectedContent: <HTEle>select('#' + CLS_CONTENT + this.tabId + '_' + this.selectingID, this.content), isSwiped: this.isSwipeed }; this.trigger('selected', eventArg); } } private contentReady(): void { const id: string = this.setActiveContent(); this.triggerAnimation(id, this.enableAnimation); } private setItems(items: object[]): void { this.isReplace = true; this.tbItems = <HTEle>select('.' + CLS_TB_ITEMS, this.getTabHeader()); this.tbObj.items = this.parseObject(items, 0); this.tbObj.dataBind(); this.isReplace = false; } private setRTL(value: boolean): void { this.tbObj.enableRtl = value; this.tbObj.dataBind(); this.setCssClass(this.element, CLS_RTL, value); this.refreshActiveBorder(); } private refreshActiveBorder(): void { if (!isNOU(this.bdrLine)) { this.bdrLine.classList.add(CLS_HIDDEN); } this.setActiveBorder(); } private showPopup(config: object): void { const tbPop: HTEle = <HTEle>select('.e-popup.e-toolbar-pop', this.hdrEle); if (tbPop.classList.contains('e-popup-close')) { const tbPopObj: Popup = (<PopupModel>(tbPop && (<Instance>tbPop).ej2_instances[0])) as Popup; tbPopObj.position.X = (this.headerPlacement === 'Left') ? 'left' : 'right'; tbPopObj.dataBind(); tbPopObj.show(config); } } private bindDraggable(): void { if (this.allowDragAndDrop) { const tabHeader: Element = this.element.querySelector('.' + CLS_HEADER); const items: NodeList = tabHeader.querySelectorAll('.' + CLS_TB_ITEM); items.forEach((element: HTMLElement) => { this.initializeDrag(element as HTMLElement); }); } } private wireEvents(): void { this.bindDraggable(); window.addEventListener('resize', this.resizeContext); EventHandler.add(this.element, 'mouseover', this.hoverHandler, this); EventHandler.add(this.element, 'keydown', this.spaceKeyDown, this); if (!isNOU(this.cntEle)) { this.touchModule = new Touch(this.cntEle, { swipe: this.swipeHandler.bind(this) }); } this.keyModule = new KeyboardEvents(this.element, { keyAction: this.keyHandler.bind(this), keyConfigs: this.keyConfigs }); this.tabKeyModule = new KeyboardEvents(this.element, { keyAction: this.keyHandler.bind(this), keyConfigs: { openPopup: 'shift+f10', tab: 'tab', shiftTab: 'shift+tab' }, eventName: 'keydown' }); } private unWireEvents(): void { if (!isNOU(this.keyModule)) { this.keyModule.destroy(); } if (!isNOU(this.tabKeyModule)) { this.tabKeyModule.destroy(); } if (!isNOU(this.cntEle) && !isNOU(this.touchModule)) { this.touchModule.destroy(); } window.removeEventListener('resize', this.resizeContext); EventHandler.remove(this.element, 'mouseover', this.hoverHandler); EventHandler.remove(this.element, 'keydown', this.spaceKeyDown); this.element.classList.remove(CLS_RTL); this.element.classList.remove(CLS_FOCUS); } private clickHandler(args: ClickEventArgs): void { this.element.classList.remove(CLS_FOCUS); const trg: HTEle = <HTEle>args.originalEvent.target; const trgParent: HTEle = <HTEle>closest(trg, '.' + CLS_TB_ITEM); const trgIndex: number = this.getEleIndex(trgParent); if (trg.classList.contains(CLS_ICON_CLOSE)) { this.removeTab(trgIndex); } else if (this.isVertical() && closest(trg, '.' + CLS_HOR_NAV)) { this.showPopup(this.show); } else { this.isPopup = false; if (!isNOU(trgParent) && (trgIndex !== this.selectedItem || trgIndex !== this.prevIndex)) { this.select(trgIndex, args.originalEvent); } } } private swipeHandler(e: SwipeEventArgs): void { if (e.velocity < 3 && isNOU(e.originalEvent.changedTouches)) { return; } if (e.originalEvent && this.isNested) { e.originalEvent.stopPropagation(); } this.isSwipeed = true; if (e.swipeDirection === 'Right' && this.selectedItem !== 0) { for (let k: number = this.selectedItem - 1; k >= 0; k--) { if (!this.tbItem[k].classList.contains(CLS_HIDDEN)) { this.select(k); break; } } } else if (e.swipeDirection === 'Left' && (this.selectedItem !== selectAll('.' + CLS_TB_ITEM, this.element).length - 1)) { for (let i: number = this.selectedItem + 1; i < this.tbItem.length; i++) { if (!this.tbItem[i].classList.contains(CLS_HIDDEN)) { this.select(i); break; } } } this.isSwipeed = false; } private spaceKeyDown(e: KeyboardEvent): void { if ((e.keyCode === 32 && e.which === 32) || (e.keyCode === 35 && e.which === 35)) { const clstHead: HTEle = <HTEle>closest(<Element>e.target, '.' + CLS_HEADER); if (!isNOU(clstHead)) { e.preventDefault(); } } } private keyHandler(e: KeyboardEventArgs): void { if (this.element.classList.contains(CLS_DISABLE)) { return; } this.element.classList.add(CLS_FOCUS); const trg: HTEle = <HTEle>e.target; const tabHeader: HTMLElement = this.getTabHeader(); const actEle: HTEle = <HTEle>select('.' + CLS_ACTIVE, tabHeader); this.popEle = <DomElements>select('.' + CLS_TB_POP, tabHeader); if (!isNOU(this.popEle)) { this.popObj = <Popup>this.popEle.ej2_instances[0]; } const item: HTEle = <HTEle>closest(document.activeElement, '.' + CLS_TB_ITEM); const trgParent: HTEle = <HTEle>closest(trg, '.' + CLS_TB_ITEM); switch (e.action) { case 'space': case 'enter': if (trg.parentElement.classList.contains(CLS_DISABLE)) { return; } if (e.action === 'enter' && trg.classList.contains('e-hor-nav')) { this.showPopup(this.show); break; } this.keyPressed(trg); break; case 'tab': case 'shiftTab': if (trg.classList.contains(CLS_WRAP) && (<HTEle>closest(trg, '.' + CLS_TB_ITEM)).classList.contains(CLS_ACTIVE) === false) { trg.setAttribute('tabindex', '-1'); } if (this.popObj && isVisible(this.popObj.element)) { this.popObj.hide(this.hide); } actEle.children.item(0).setAttribute('tabindex', '0'); break; case 'moveLeft': case 'moveRight': if (!isNOU(item)) { this.refreshItemVisibility(item); } break; case 'openPopup': e.preventDefault(); if (!isNOU(this.popEle) && this.popEle.classList.contains(CLS_POPUP_CLOSE)) { this.popObj.show(this.show); } break; case 'delete': if (this.showCloseButton === true && !isNOU(trgParent)) { const nxtSib: HTEle = <HTEle>trgParent.nextSibling; if (!isNOU(nxtSib) && nxtSib.classList.contains(CLS_TB_ITEM)) { (<HTEle>nxtSib.firstElementChild).focus(); } this.removeTab(this.getEleIndex(trgParent)); } this.setActiveBorder(); break; } } private refreshActElePosition(): void { const activeEle: Element = select('.' + CLS_TB_ITEM + '.' + CLS_TB_POPUP + '.' + CLS_ACTIVE, this.element); if (!isNOU(activeEle)) { this.select(this.getEleIndex(<HTEle>activeEle)); } this.refreshActiveBorder(); } private refreshItemVisibility(target: HTEle): void { const scrCnt: HTEle = <HTEle>select('.' + this.scrCntClass, this.tbItems); if (!this.isVertical() && !isNOU(scrCnt)) { const scrBar: HTEle = <HTEle>select('.e-hscroll-bar', this.tbItems); const scrStart: number = scrBar.scrollLeft; const scrEnd: number = scrStart + scrBar.offsetWidth; const eleStart: number = target.offsetLeft; const eleWidth: number = target.offsetWidth; const eleEnd: number = target.offsetLeft + target.offsetWidth; if ((scrStart < eleStart) && (scrEnd < eleEnd)) { const eleViewRange: number = scrEnd - eleStart; scrBar.scrollLeft = scrStart + (eleWidth - eleViewRange); } else { if ((scrStart > eleStart) && (scrEnd > eleEnd)) { const eleViewRange: number = eleEnd - scrStart; scrBar.scrollLeft = scrStart - (eleWidth - eleViewRange); } } } else { return; } } private hoverHandler(e: MouseEventArgs): void { const trg: HTEle = <HTEle>e.target; if (!isNOU(trg.classList) && trg.classList.contains(CLS_ICON_CLOSE)) { trg.setAttribute('title', new L10n('tab', { closeButtonTitle: this.title }, this.locale).getConstant('closeButtonTitle')); } } private evalOnPropertyChangeItems(newProp: TabModel, oldProp: TabModel): void { if (!(newProp.items instanceof Array && oldProp.items instanceof Array)) { const changedProp: Object[] = Object.keys(newProp.items); for (let i: number = 0; i < changedProp.length; i++) { const index: number = parseInt(Object.keys(newProp.items)[i], 10); const property: Str = Object.keys(newProp.items[index])[0]; const oldVal: Str = Object(oldProp.items[index])[property]; const newVal: Str | Object = Object(newProp.items[index])[property]; const hdr: HTEle = <HTEle>this.element.querySelectorAll('.' + CLS_TB_ITEM)[index]; let itemIndex: number; if (hdr && !isNOU(hdr.id) && hdr.id !== '') { const num: number = (hdr.id.indexOf('_')); itemIndex = parseInt(hdr.id.substring(num + 1), 10); } else { itemIndex = index; } const hdrItem: HTEle = <HTEle>select('.' + CLS_TB_ITEMS + ' #' + CLS_ITEM + this.tabId + '_' + itemIndex, this.element); const cntItem: HTEle = <HTEle>select('.' + CLS_CONTENT + ' #' + CLS_CONTENT + this.tabId + '_' + itemIndex, this.element); if (property === 'header' || property === 'headerTemplate') { const icon: Str | Object = (isNOU(this.items[index].header) || isNOU(this.items[index].header.iconCss)) ? '' : this.items[index].header.iconCss; const textVal: Str | Object = this.items[index].headerTemplate || this.items[index].header.text; if ((textVal === '') && (icon === '')) { this.removeTab(index); } else { this.tbId = hdr.id; const arr: Object[] = []; arr.push(<TabItemModel>this.items[index]); this.items.splice(index, 1); this.itemIndexArray.splice(index, 1); this.tbObj.items.splice(index, 1); const isHiddenEle: boolean = hdrItem.classList.contains(CLS_HIDDEN); detach(hdrItem); this.isReplace = true; this.addTab(arr, index); if (isHiddenEle) { this.hideTab(index); } this.isReplace = false; } } if (property === 'content' && !isNOU(cntItem)) { const strVal: boolean = typeof newVal === 'string' || isNOU((<HTEle>newVal).innerHTML); if (strVal && ((<Str>newVal)[0] === '.' || (<Str>newVal)[0] === '#') && (<Str>newVal).length) { const eleVal: HTEle = <HTEle>document.querySelector(<Str>newVal); cntItem.appendChild(eleVal); eleVal.style.display = ''; } else if (newVal === '' && oldVal[0] === '#') { (<HTEle>document.body.appendChild(this.element.querySelector(oldVal))).style.display = 'none'; cntItem.innerHTML = <Str>newVal; } else if ((this as any).isReact && typeof newVal === 'object') { cntItem.innerHTML = ''; this.templateCompile(cntItem, <Str>newVal, index); } else if (typeof newVal !== 'function') { cntItem.innerHTML = <Str>newVal; } } if (property === 'cssClass') { if (!isNOU(hdrItem)) { hdrItem.classList.remove(oldVal); hdrItem.classList.add(<Str>newVal); } if (!isNOU(cntItem)) { cntItem.classList.remove(oldVal); cntItem.classList.add(<Str>newVal); } } if (property === 'disabled') { this.enableTab(index, ((newVal === true) ? false : true)); } if (property === 'visible') { this.hideTab(index, ((newVal === true) ? false : true)); } } } else { this.lastIndex = 0; if (isNOU(this.tbObj)) { this.reRenderItems(); } else { if ((this as any).isRect) { this.clearTemplate(); } this.setItems(<TabItemModel[]>newProp.items); if (this.templateEle.length > 0) { this.expTemplateContent(); } this.templateEle = []; const selectElement: HTEle = <HTEle>select('.' + CLS_TAB + ' > .' + CLS_CONTENT, this.element); while (selectElement.firstElementChild) { detach(selectElement.firstElementChild); } this.select(this.selectedItem); } } } private initializeDrag(target: HTEle): void { this.dragArea = !isNOU(this.dragArea) ? this.dragArea : '#' + this.element.id + ' ' + ('.' + CLS_HEADER); let dragObj: Draggable = new Draggable(target, { dragArea: this.dragArea, dragTarget: '.' + CLS_TB_ITEM, clone: true, helper: this.helper.bind(this), dragStart: this.itemDragStart.bind(this), drag: (e: DragArgs) => { let dragIndex: number = this.getEleIndex(this.dragItem); let dropIndex: number; let dropItem: HTMLElement; let dragArgs: DragEventArgs = { draggedItem: <HTMLElement>this.dragItem, event: e.event, target: e.target, droppedItem: <HTMLElement>e.target.closest('.' + CLS_TB_ITEM), clonedElement: this.cloneElement, index: dragIndex }; if (!isNOU(e.target.closest('.' + CLS_TAB)) && !e.target.closest('.' + CLS_TAB).isEqualNode(this.element) && this.dragArea !== '.' + CLS_HEADER) { this.trigger('dragging', dragArgs); } else { if (!(e.target.closest(this.dragArea)) && this.overflowMode !== 'Popup') { document.body.style.cursor = 'not-allowed'; addClass([this.cloneElement], CLS_HIDDEN); if (this.dragItem.classList.contains(CLS_HIDDEN)) { removeClass([this.dragItem], CLS_HIDDEN); } (<HTEle>this.dragItem.querySelector('.' + CLS_WRAP)).style.visibility = 'visible'; } else { document.body.style.cursor = ''; (<HTEle>this.dragItem.querySelector('.' + CLS_WRAP)).style.visibility = 'hidden'; if (this.cloneElement.classList.contains(CLS_HIDDEN)) { removeClass([this.cloneElement], CLS_HIDDEN); } } if (this.overflowMode === 'Scrollable' && !isNOU(this.element.querySelector('.e-hscroll'))) { let scrollRightNavEle: HTMLElement = this.element.querySelector('.e-scroll-right-nav'); let scrollLeftNavEle: HTMLElement = this.element.querySelector('.e-scroll-left-nav'); let hscrollBar: HTMLElement = this.element.querySelector('.e-hscroll-bar'); if (!isNOU(scrollRightNavEle) && Math.abs((scrollRightNavEle.offsetWidth / 2) + scrollRightNavEle.offsetLeft) > this.cloneElement.offsetLeft + this.cloneElement.offsetWidth) { hscrollBar.scrollLeft -= 10; } if (!isNOU(scrollLeftNavEle) && Math.abs((scrollLeftNavEle.offsetLeft + scrollLeftNavEle.offsetWidth) - this.cloneElement.offsetLeft) > (scrollLeftNavEle.offsetWidth / 2)) { hscrollBar.scrollLeft += 10; } } this.cloneElement.style.pointerEvents = 'none'; dropItem = <HTMLElement>closest(e.target, '.' + CLS_TB_ITEM + '.e-draggable'); let scrollContentWidth: number = 0; if (this.overflowMode === 'Scrollable' && !isNOU(this.element.querySelector('.e-hscroll'))) { scrollContentWidth = (<HTMLElement>this.element.querySelector('.e-hscroll-content')).offsetWidth; } if (dropItem != null && !dropItem.isSameNode(this.dragItem) && dropItem.closest('.' + CLS_TAB).isSameNode(this.dragItem.closest('.' + CLS_TAB))) { dropIndex = this.getEleIndex(dropItem); if (dropIndex < dragIndex && (Math.abs((dropItem.offsetLeft + dropItem.offsetWidth) - this.cloneElement.offsetLeft) > (dropItem.offsetWidth / 2))) { this.dragAction(dropItem, dragIndex, dropIndex); } if (dropIndex > dragIndex && (Math.abs(dropItem.offsetWidth / 2) + dropItem.offsetLeft - scrollContentWidth) < this.cloneElement.offsetLeft + this.cloneElement.offsetWidth) { this.dragAction(dropItem, dragIndex, dropIndex); } } this.droppedIndex = this.getEleIndex(this.dragItem); this.trigger('dragging', dragArgs); } }, dragStop: this.itemDragStop.bind(this) }); this.draggableItems.push(dragObj); } private helper(e: { sender: MouseEvent & TouchEvent, element: HTMLElement }): HTMLElement { this.cloneElement = this.createElement('div'); if (e.element) { this.cloneElement = <HTMLElement>(e.element.cloneNode(true)); addClass([this.cloneElement], 'e-tab-clone-element'); if (this.element.querySelector('.' + CLS_HEADER).classList.contains(CLS_CLOSE_SHOW)) { addClass([this.cloneElement], CLS_CLOSE_SHOW); } removeClass([this.cloneElement.querySelector('.' + CLS_WRAP)], 'e-ripple'); if (!isNOU(this.cloneElement.querySelector('.e-ripple-element'))) { remove(this.cloneElement.querySelector('.e-ripple-element')); } document.body.appendChild(this.cloneElement); } return this.cloneElement; } private itemDragStart(e: DragArgs): void { this.draggingItems = this.items.map((x: TabItemModel) => x); this.dragItem = e.element; let dragArgs: DragEventArgs = { draggedItem: e.element, event: e.event, target: e.target, droppedItem: null, index: this.getEleIndex(this.dragItem), clonedElement: this.cloneElement, cancel: false }; this.trigger('onDragStart', dragArgs, (tabitemDragArgs: DragEventArgs) => { if (tabitemDragArgs.cancel) { detach(this.cloneElement); } else { this.removeActiveClass(); addClass([this.tbItems.querySelector('.' + CLS_INDICATOR)], CLS_HIDDEN); (<HTEle>this.dragItem.querySelector('.' + CLS_WRAP)).style.visibility = 'hidden'; } }); } private dragAction(dropItem: HTMLElement, dragsIndex: number, dropIndex: number): void { if (this.items.length > 0) { let item: TabItemModel = this.draggingItems[dragsIndex]; this.draggingItems.splice(dragsIndex, 1); this.draggingItems.splice(dropIndex, 0, item); } if (this.overflowMode === 'MultiRow') { dropItem.parentNode.insertBefore(this.dragItem, dropItem.nextElementSibling); } if (dragsIndex > dropIndex) { if (!(this.dragItem.parentElement).isSameNode(dropItem.parentElement)) { if (this.overflowMode === 'Extended') { if (dropItem.isSameNode(dropItem.parentElement.lastChild)) { let popupContainer: Node = this.dragItem.parentNode; dropItem.parentNode.insertBefore(this.dragItem, dropItem); popupContainer.insertBefore(dropItem.parentElement.lastChild, popupContainer.childNodes[0]); } else { this.dragItem.parentNode.insertBefore( (dropItem.parentElement.lastChild), this.dragItem.parentElement.childNodes[0]); dropItem.parentNode.insertBefore(this.dragItem, dropItem); } } else { let lastEle: HTMLElement = <HTEle>(dropItem.parentElement).lastChild; if (dropItem.isSameNode(lastEle)) { let popupContainer: Node = <HTEle>this.dragItem.parentNode; dropItem.parentNode.insertBefore(this.dragItem, dropItem); popupContainer.insertBefore(lastEle, popupContainer.childNodes[0]); } else { this.dragItem.parentNode.insertBefore( (dropItem.parentElement).lastChild, this.dragItem.parentElement.childNodes[0]); dropItem.parentNode.insertBefore(this.dragItem, dropItem); } } } else { this.dragItem.parentNode.insertBefore(this.dragItem, dropItem); } } if (dragsIndex < dropIndex) { if (!(this.dragItem.parentElement).isSameNode(dropItem.parentElement)) { if (this.overflowMode === 'Extended') { this.dragItem.parentElement.appendChild(dropItem.parentElement.firstElementChild); dropItem.parentNode.insertBefore(this.dragItem, dropItem.nextSibling); } else { this.dragItem.parentNode.insertBefore( (dropItem.parentElement).lastChild, this.dragItem.parentElement.childNodes[0]); dropItem.parentNode.insertBefore(this.dragItem, dropItem); } } else { this.dragItem.parentNode.insertBefore(dropItem, this.dragItem); } } } private itemDragStop(e: DropEventArgs): void { detach(this.cloneElement); (<HTEle>this.dragItem.querySelector('.' + CLS_WRAP)).style.visibility = 'visible'; document.body.style.cursor = ''; let dragStopArgs: DragEventArgs = { draggedItem: <HTEle>this.dragItem, event: e.event, target: e.target, droppedItem: this.tbItem[this.droppedIndex], clonedElement: null, index: this.droppedIndex, cancel: false }; this.trigger('dragged', dragStopArgs, (tabItemDropArgs: DragEventArgs) => { if (tabItemDropArgs.cancel) { this.refresh(); } else { if (this.items.length > 0 && this.draggingItems.length > 0) { this.items = this.draggingItems; this.selectedItem = this.droppedIndex; this.refresh(); } else { (<HTEle>this.dragItem.querySelector('.' + CLS_WRAP)).style.visibility = ''; removeClass([<HTEle>this.tbItems.querySelector('.' + CLS_INDICATOR)], CLS_HIDDEN); this.select(this.droppedIndex); } } }); } /** * Enables or disables the specified Tab item. On passing value as `false`, the item will be disabled. * * @param {number} index - Index value of target Tab item. * @param {boolean} value - Boolean value that determines whether the command should be enabled or disabled. * By default, isEnable is true. * @returns {void}. */ public enableTab(index: number, value: boolean): void { const tbItems: HTEle = selectAll('.' + CLS_TB_ITEM, this.element)[index]; if (isNOU(tbItems)) { return; } if (value === true) { tbItems.classList.remove(CLS_DISABLE, CLS_OVERLAY); (<HTEle>tbItems.firstElementChild).setAttribute('tabindex', '-1'); } else { tbItems.classList.add(CLS_DISABLE, CLS_OVERLAY); (<HTEle>tbItems.firstElementChild).removeAttribute('tabindex'); if (tbItems.classList.contains(CLS_ACTIVE)) { this.select(index + 1); } } if (!isNOU(this.items[index])) { this.items[index].disabled = !value; this.dataBind(); } tbItems.setAttribute('aria-disabled', (value === true) ? 'false' : 'true'); } /** * Adds new items to the Tab that accepts an array as Tab items. * * @param {TabItemModel[]} items - An array of item that is added to the Tab. * @param {number} index - Number value that determines where the items to be added. By default, index is 0. * @returns {void}. */ public addTab(items: TabItemModel[], index?: number): void { const addArgs: AddEventArgs = { addedItems: items, cancel: false }; if (!this.isReplace) { this.trigger('adding', addArgs, (tabAddingArgs: AddEventArgs) => { if (!tabAddingArgs.cancel) { this.addingTabContent(items, index); } }); } else { this.addingTabContent(items, index); } if ((this as any).isReact) { this.renderReactTemplates(); } } private addingTabContent(items: TabItemModel[], index?: number): void { let lastEleIndex: number = 0; this.hdrEle = <HTEle>select('.' + CLS_HEADER, this.element); if (isNOU(this.hdrEle)) { this.items = items; this.reRenderItems(); } else { const itemsCount: number = selectAll('.' + CLS_TB_ITEM, this.element).length; if (itemsCount !== 0) { lastEleIndex = this.lastIndex + 1; } if (isNOU(index)) { index = itemsCount - 1; } if (itemsCount < index || index < 0 || isNaN(index)) { return; } if (itemsCount === 0 && !isNOU(this.hdrEle)) { this.hdrEle.style.display = ''; } if (!isNOU(this.bdrLine)) { this.bdrLine.classList.add(CLS_HIDDEN); } this.tbItems = <HTEle>select('.' + CLS_TB_ITEMS, this.getTabHeader()); this.isAdd = true; const tabItems: object[] = this.parseObject(items, index); this.isAdd = false; let i: number = 0; let textValue: string | HTEle; items.forEach((item: TabItemModel, place: number) => { textValue = item.headerTemplate || item.header.text; if (!(isNOU(item.headerTemplate || item.header) || isNOU(textValue) || ((<string>textValue).length === 0) && isNOU(item.header.iconCss))) { this.items.splice((index + i), 0, item); i++; } if (this.isTemplate && !isNOU(item.header) && !isNOU(item.header.text)) { const no: number = lastEleIndex + place; const ele: HTEle = this.createElement('div', { id: CLS_CONTENT + this.tabId + '_' + no, className: CLS_ITEM, attrs: { role: 'tabpanel', 'aria-labelledby': CLS_ITEM + '_' + no } }); this.cntEle.insertBefore(ele, this.cntEle.children[(index + place)]); const eleTrg: HTEle = this.getTrgContent(this.cntEle, no.toString()); this.getContent(eleTrg, item.content, 'render', index); } }); this.tbObj.addItems(tabItems, index); if (!this.isReplace) { this.trigger('added', { addedItems: items }); } if (this.selectedItem === index) { this.select(index); } else { this.setActiveBorder(); } this.bindDraggable(); } } /** * Removes the items in the Tab from the specified index. * * @param {number} index - Index of target item that is going to be removed. * @returns {void}. */ public removeTab(index: number): void { const trg: HTEle = selectAll('.' + CLS_TB_ITEM, this.element)[index]; if (isNOU(trg)) { return; } const removeArgs: RemoveEventArgs = { removedItem: trg, removedIndex: index, cancel: false }; this.trigger('removing', removeArgs, (tabRemovingArgs: RemoveEventArgs) => { if (!tabRemovingArgs.cancel) { this.tbObj.removeItems(index); if (this.allowDragAndDrop && (index !== Array.prototype.indexOf.call(this.itemIndexArray, trg.id))) { index = Array.prototype.indexOf.call(this.itemIndexArray, trg.id); } this.items.splice(index, 1); this.itemIndexArray.splice(index, 1); this.refreshActiveBorder(); const cntTrg: HTEle = <HTEle>select('#' + CLS_CONTENT + this.tabId + '_' + this.extIndex(trg.id), select('.' + CLS_CONTENT, this.element)); if (!isNOU(cntTrg)) { detach(cntTrg); } this.trigger('removed', tabRemovingArgs); if (trg.classList.contains(CLS_ACTIVE)) { index = (index > selectAll('.' + CLS_TB_ITEM + ':not(.' + CLS_TB_POPUP + ')', this.element).length - 1) ? index - 1 : index; this.enableAnimation = false; this.selectedItem = index; this.select(index); } if (selectAll('.' + CLS_TB_ITEM, this.element).length === 0) { this.hdrEle.style.display = 'none'; } this.enableAnimation = true; } }); } /** * Shows or hides the Tab that is in the specified index. * * @param {number} index - Index value of target item. * @param {boolean} value - Based on this Boolean value, item will be hide (false) or show (true). By default, value is true. * @returns {void}. */ public hideTab(index: number, value?: boolean): void { let items: HTMLElement[]; const item: HTEle = selectAll('.' + CLS_TB_ITEM, this.element)[index]; if (isNOU(item)) { return; } if (isNOU(value)) { value = true; } this.bdrLine.classList.add(CLS_HIDDEN); if (value === true) { item.classList.add(CLS_HIDDEN); items = selectAll('.' + CLS_TB_ITEM + ':not(.' + CLS_HIDDEN + ')', this.tbItems); if (items.length !== 0 && item.classList.contains(CLS_ACTIVE)) { if (index !== 0) { for (let i: number = index - 1; i >= 0; i--) { if (!this.tbItem[i].classList.contains(CLS_HIDDEN)) { this.select(i); break; } else if (i === 0) { for (let k: number = index + 1; k < this.tbItem.length; k++) { if (!this.tbItem[k].classList.contains(CLS_HIDDEN)) { this.select(k); break; } } } } } else { for (let k: number = index + 1; k < this.tbItem.length; k++) { if (!this.tbItem[k].classList.contains(CLS_HIDDEN)) { this.select(k); break; } } } } else if (items.length === 0) { this.element.classList.add(CLS_HIDDEN); } } else { this.element.classList.remove(CLS_HIDDEN); items = selectAll('.' + CLS_TB_ITEM + ':not(.' + CLS_HIDDEN + ')', this.tbItems); item.classList.remove(CLS_HIDDEN); if (items.length === 0) { this.select(index); } } this.setActiveBorder(); item.setAttribute('aria-hidden', '' + value); if (this.overflowMode === 'Popup' && this.tbObj) { this.tbObj.refreshOverflow(); } } /** * Specifies the index or HTMLElement to select an item from the Tab. * * @param {number | HTMLElement} args - Index or DOM element is used for selecting an item from the Tab. * @param {Event} event - An event which takes place in DOM. * @returns {void}. */ public select(args: number | HTEle, event?: Event): void { const tabHeader: HTMLElement = this.getTabHeader(); this.tbItems = <HTEle>select('.' + CLS_TB_ITEMS, tabHeader); this.tbItem = selectAll('.' + CLS_TB_ITEM, tabHeader); this.content = <HTEle>select('.' + CLS_CONTENT, this.element); this.prevItem = this.tbItem[this.prevIndex]; if (isNOU(this.selectedItem) || (this.selectedItem < 0) || (this.tbItem.length <= this.selectedItem) || isNaN(this.selectedItem)) { this.selectedItem = 0; } else { this.selectedID = this.extIndex(this.tbItem[this.selectedItem].id); } const trg: HTEle = this.tbItem[args as number]; if (isNOU(trg)) { this.selectedID = '0'; } else { this.selectingID = this.extIndex(trg.id); } if (!isNOU(this.prevItem) && !this.prevItem.classList.contains(CLS_DISABLE)) { this.prevItem.children.item(0).setAttribute('tabindex', '-1'); } const eventArg: SelectingEventArgs = { event: event, previousItem: this.prevItem, previousIndex: this.prevIndex, selectedItem: this.tbItem[this.selectedItem], selectedIndex: this.selectedItem, selectedContent: !isNOU(this.content) ? <HTEle>select('#' + CLS_CONTENT + this.tabId + '_' + this.selectedID, this.content) : null, selectingItem: trg, selectingIndex: args as number, selectingContent: !isNOU(this.content) ? <HTEle>select('#' + CLS_CONTENT + this.tabId + '_' + this.selectingID, this.content) : null, isSwiped: this.isSwipeed, cancel: false }; if (!this.initRender) { this.trigger('selecting', eventArg, (selectArgs: SelectingEventArgs) => { if (!selectArgs.cancel) { this.selectingContent(args); } }); } else { this.selectingContent(args); } } private selectingContent(args: number | HTEle): void { if (typeof args === 'number') { if (!isNOU(this.tbItem[args]) && (this.tbItem[<number>args].classList.contains(CLS_DISABLE) || this.tbItem[<number>args].classList.contains(CLS_HIDDEN))) { for (let i: number = <number>args + 1; i < this.items.length; i++) { if (this.items[i].disabled === false && this.items[i].visible === true) { args = i; break; } else { args = 0; } } } if (this.tbItem.length > args && args >= 0 && !isNaN(args)) { this.prevIndex = this.selectedItem; if (this.tbItem[args].classList.contains(CLS_TB_POPUP)) { this.setActive(this.popupHandler(this.tbItem[args])); if ((!isNOU(this.items) && this.items.length > 0) && this.allowDragAndDrop) { this.tbItem = selectAll('.' + CLS_TB_ITEMS + ' .' + CLS_TB_ITEM, this.hdrEle); let item: TabItemModel = this.items[args]; this.items.splice(args, 1); this.items.splice(this.tbItem.length - 1, 0, item); } } else { this.setActive(args); } } else { this.setActive(0); } } else if (args instanceof (HTMLElement)) { this.setActive(this.getEleIndex(args)); } } /** * Gets the item index from the Tab. * * @param {string} tabItemId - Item ID is used for getting index from the Tab. * @returns {number} - It returns item index. */ public getItemIndex(tabItemId: string): number { let tabIndex: number; for (let i: number = 0; i < this.tbItem.length; i++) { const value: string = this.tbItem[i].getAttribute('data-id'); if (tabItemId === value) { tabIndex = i; break; } } return tabIndex; } /** * Specifies the value to disable/enable the Tab component. * When set to `true`, the component will be disabled. * * @param {boolean} value - Based on this Boolean value, Tab will be enabled (false) or disabled (true). * @returns {void}. */ public disable(value: boolean): void { this.setCssClass(this.element, CLS_DISABLE, value); this.element.setAttribute('aria-disabled', '' + value); } /** * Get the properties to be maintained in the persisted state. * * @returns {string} - It returns the persisted state. */ protected getPersistData(): string { return this.addOnPersist(['selectedItem', 'actEleId']); } /** * Returns the current module name. * * @returns {string} - It returns the current module name. * @private */ protected getModuleName(): string { return 'tab'; } /** * Gets called when the model property changes.The data that describes the old and new values of the property that changed. * * @param {TabModel} newProp - It contains the new value of data. * @param {TabModel} oldProp - It contains the old value of data. * @returns {void} * @private */ public onPropertyChanged(newProp: TabModel, oldProp: TabModel): void { for (const prop of Object.keys(newProp)) { switch (prop) { case 'width': setStyle(this.element, { width: formatUnit(newProp.width) }); break; case 'height': setStyle(this.element, { height: formatUnit(newProp.height) }); this.setContentHeight(false); break; case 'cssClass': if (oldProp.cssClass !== '' && !isNullOrUndefined(oldProp.cssClass)) { this.setCssClass(this.element, oldProp.cssClass, false); this.setCssClass(this.element, newProp.cssClass, true); } else { this.setCssClass(this.element, newProp.cssClass, true); } break; case 'items': this.evalOnPropertyChangeItems(newProp, oldProp); break; case 'showCloseButton': this.setCloseButton(newProp.showCloseButton); break; case 'selectedItem': this.selectedItem = oldProp.selectedItem; this.select(newProp.selectedItem); break; case 'headerPlacement': this.changeOrientation(newProp.headerPlacement); break; case 'enableRtl': this.setRTL(newProp.enableRtl); break; case 'overflowMode': this.tbObj.overflowMode = newProp.overflowMode; this.tbObj.dataBind(); this.refreshActElePosition(); break; case 'heightAdjustMode': this.setContentHeight(false); this.select(this.selectedItem); break; case 'scrollStep': if (this.tbObj) { this.tbObj.scrollStep = this.scrollStep; } break; case 'allowDragAndDrop': this.bindDraggable(); break; case 'dragArea': if (this.allowDragAndDrop) { this.draggableItems.forEach((item: Draggable) => { item.dragArea = this.dragArea; }); this.refresh(); } break; } } } public refreshActiveTab(): void { if ((this as any).isReact) { this.clearTemplate(); } if (!this.isTemplate) { if (this.element.querySelector('.' + CLS_TB_ITEM + '.' + CLS_ACTIVE)) { detach(this.element.querySelector('.' + CLS_TB_ITEM + '.' + CLS_ACTIVE).children[0]); detach(this.element.querySelector('.' + CLS_CONTENT).querySelector('.' + CLS_ACTIVE).children[0]); const item: TabItemModel = this.items[this.selectedItem]; const pos: Str = (isNOU(item.header) || isNOU(item.header.iconPosition)) ? '' : item.header.iconPosition; const css: Str = (isNOU(item.header) || isNOU(item.header.iconCss)) ? '' : item.header.iconCss; const text: Str | HTEle = item.headerTemplate || item.header.text; const txtWrap: HTEle = this.createElement('div', { className: CLS_TEXT, attrs: { 'role': 'presentation' } }); if (!isNOU((<HTEle>text).tagName)) { txtWrap.appendChild(text as HTEle); } else { this.headerTextCompile(txtWrap, text as string, this.selectedItem); } let tEle: HTEle; const icon: HTEle = this.createElement('span', { className: CLS_ICONS + ' ' + CLS_TAB_ICON + ' ' + CLS_ICON + '-' + pos + ' ' + css }); const tConts: HTEle = this.createElement('div', { className: CLS_TEXT_WRAP }); tConts.appendChild(txtWrap); if ((text !== '' && text !== undefined) && css !== '') { if ((pos === 'left' || pos === 'top')) { tConts.insertBefore(icon, tConts.firstElementChild); } else { tConts.appendChild(icon); } tEle = txtWrap; this.isIconAlone = false; } else { tEle = ((css === '') ? txtWrap : icon); if (tEle === icon) { detach(txtWrap); tConts.appendChild(icon); this.isIconAlone = true; } } const wrapAtt: { [key: string]: string } = (item.disabled) ? {} : { tabIndex: '-1' }; tConts.appendChild(this.btnCls.cloneNode(true)); const wraper: HTEle = this.createElement('div', { className: CLS_WRAP, attrs: wrapAtt }); wraper.appendChild(tConts); if (pos === 'top' || pos === 'bottom') { this.element.classList.add('e-vertical-icon'); } this.element.querySelector('.' + CLS_TB_ITEM + '.' + CLS_ACTIVE).appendChild(wraper); const crElem: HTEle = this.createElement('div'); let cnt: string | HTMLElement = item.content; let eleStr: string; if (typeof cnt === 'string' || isNOU((<HTEle>cnt).innerHTML)) { if (typeof cnt === 'string' && this.enableHtmlSanitizer) { cnt = SanitizeHtmlHelper.sanitize(<Str>cnt); } if ((<Str>cnt)[0] === '.' || (<Str>cnt)[0] === '#') { if (document.querySelectorAll(<string>cnt).length) { const eleVal: HTEle = <HTEle>document.querySelector(<string>cnt); eleStr = eleVal.outerHTML.trim(); crElem.appendChild(eleVal); eleVal.style.display = ''; } else { this.compileElement(crElem, <Str>cnt, 'content', this.selectedItem); } } else { this.compileElement(crElem, <Str>cnt, 'content', this.selectedItem); } } else { crElem.appendChild(cnt); } if (!isNOU(eleStr)) { if (this.templateEle.indexOf(cnt.toString()) === -1) { this.templateEle.push(cnt.toString()); } } this.element.querySelector('.' + CLS_ITEM + '.' + CLS_ACTIVE).appendChild(crElem); } } else { const tabItems: HTMLElement = this.element.querySelector('.' + CLS_TB_ITEMS); const element: HTMLElement = this.element.querySelector('.' + CLS_TB_ITEM + '.' + CLS_ACTIVE); const id: string | number = element.id; const num: number = (id.indexOf('_')); const index: number = parseInt(id.substring(num + 1), 10); const header: string = element.innerText; const detachContent: Element = this.element.querySelector('.' + CLS_CONTENT).querySelector('.' + CLS_ACTIVE).children[0]; const mainContents: string = detachContent.innerHTML; detach(element); detach(detachContent); const attr: object = { className: CLS_TB_ITEM + ' ' + CLS_TEMPLATE + ' ' + CLS_ACTIVE, id: CLS_ITEM + this.tabId + '_' + index, attrs: { role: 'tab', 'aria-controls': CLS_CONTENT + this.tabId + '_' + index, 'aria-disabled': 'false', 'aria-selected': 'true' } }; const txtString: Str = this.createElement('span', { className: CLS_TEXT, innerHTML: header, attrs: { 'role': 'presentation' } }).outerHTML; const conte: Str = this.createElement('div', { className: CLS_TEXT_WRAP, innerHTML: txtString + this.btnCls.outerHTML }).outerHTML; const wrap: HTEle = this.createElement('div', { className: CLS_WRAP, innerHTML: conte, attrs: { tabIndex: '-1' } }); tabItems.insertBefore(this.createElement('div', attr), tabItems.children[index + 1]); this.element.querySelector('.' + CLS_TB_ITEM + '.' + CLS_ACTIVE).appendChild(wrap); const crElem: HTEle = this.createElement('div', { innerHTML: mainContents }); this.element.querySelector('.' + CLS_CONTENT).querySelector('.' + CLS_ACTIVE).appendChild(crElem); } if ((this as any).isReact) { this.renderReactTemplates(); } } }
the_stack
type Function = (...args: any[]) => any export type ExtractFunctions<T> = { [P in keyof T]: T[P] extends Function ? P : never }[keyof T] /** * Unwraps the promise */ type UnWrapPromise<T> = T extends Promise<infer U> ? U : T /** * Shape of the bind callback method */ export type BindCallback<ReturnValue extends any, Container extends IocContract> = ( container: Container ) => ReturnValue /** * Shape of the fake callback method */ export type FakeCallback<ReturnValue extends any, Container extends IocContract> = ( container: Container, originalValue: ReturnValue ) => ReturnValue /** * Shape of resolved lookup node, resolved using `getResolver().resolve()` * method. */ export type IocResolverLookupNode<Namespace extends string> = { namespace: Namespace type: 'binding' | 'alias' method: string } /** * Shape of class constructor */ export type Constructor<T> = new (...args: any[]) => T /** * Shape of class constructor with `makePlain` property */ export type PlainConstructor = { makePlain: true } /** * Type of the "withBindings" method */ export interface WithBindings<ContainerBindings extends any> { <Bindings extends (keyof ContainerBindings)[]>( namespaces: [...Bindings], cb: ( ...args: { [M in keyof Bindings]: Bindings[M] extends keyof ContainerBindings ? ContainerBindings[Bindings[M]] : any } ) => void ): void <Namespace extends (keyof ContainerBindings | string)[]>( namespaces: readonly [...Namespace], cb: ( ...args: { [M in keyof Namespace]: Namespace[M] extends keyof ContainerBindings ? ContainerBindings[Namespace[M]] : any } ) => void ): void } /** * Finding return type of the `ioc.make` method based upon the * input argument. * * - String and LookupNode = Returns any * - Class constructor with "makePlain" are returned as it is * - Otherwise an instance of the class constructor is returned * - All other values are returned as it is */ export type InferMakeType<T> = T extends string | LookupNode<string> ? any : T extends PlainConstructor ? T : T extends Constructor<infer A> ? A : T /** * Shape of lookup node pulled using `ioc.lookup` method. This node * can be passed to `ioc.use`, or `ioc.make` to skip many checks * and resolve the binding right away. */ export type LookupNode<Namespace extends string> = { namespace: Namespace type: 'binding' | 'alias' } /** * Ioc container interface */ export interface IocContract<ContainerBindings extends any = any> { /** * Registered aliases. The key is the alias and value is the * absolute directory path */ importAliases: { [alias: string]: string } /** * Enable/disable proxies. Proxies are mainly required for fakes to * work */ useProxies(enable?: boolean): this /** * Define the module type for resolving auto import aliases. Defaults * to `cjs` */ module: 'cjs' | 'esm' /** * Register a binding with a callback. The callback return value will be * used when binding is resolved */ bind<Binding extends keyof ContainerBindings>( binding: Binding, callback: BindCallback<ContainerBindings[Binding], this> ): this bind<Binding extends string>( binding: Binding, callback: BindCallback< Binding extends keyof ContainerBindings ? ContainerBindings[Binding] : any, this > ): this /** * Same as the [[bind]] method, but registers a singleton only. Singleton's callback * is invoked only for the first time and then the cached value is used */ singleton<Binding extends keyof ContainerBindings>( binding: Binding, callback: BindCallback<ContainerBindings[Binding], this> ): this singleton<Binding extends string>( binding: Binding, callback: BindCallback< Binding extends keyof ContainerBindings ? ContainerBindings[Binding] : any, this > ): this /** * Define an import alias */ alias(absolutePath: string, alias: string): this /** * Register a fake for a namespace. Fakes works both for "bindings" and "import aliases". * Fakes only work when proxies are enabled using "useProxies". */ fake<Namespace extends keyof ContainerBindings>( namespace: Namespace, callback: FakeCallback<ContainerBindings[Namespace], this> ): this fake<Namespace extends string>( namespace: Namespace, callback: FakeCallback< Namespace extends keyof ContainerBindings ? ContainerBindings[Namespace] : any, this > ): this /** * Clear selected or all the fakes. Calling the method with no arguments * will clear all the fakes */ restore<Namespace extends keyof ContainerBindings>(namespace?: Namespace): this restore(namespace?: string): this /** * Find if a fake has been registered for a given namespace */ hasFake<Namespace extends keyof ContainerBindings>(namespace: Namespace): boolean hasFake(namespace: string): boolean /** * Find if a binding exists for a given namespace */ hasBinding<Binding extends keyof ContainerBindings>(namespace: Binding): boolean hasBinding(namespace: string): boolean /** * Find if a namespace is part of the auto import aliases. Returns false, when namespace * is an alias path but has an explicit binding too */ isAliasPath(namespace: string): boolean /** * Lookup a namespace. The output contains the complete namespace, * along with its type. The type is an "alias" or a "binding". * * Null is returned when unable to lookup the namespace inside the container * * Note: This method just checks if a namespace is registered or binding * or can be it resolved from auto import aliases or not. However, * it doesn't check for the module existence on the disk. * * Optionally you can define a prefix namespace * to be used to build the complete namespace. For example: * * - namespace: UsersController * - prefixNamespace: App/Controllers/Http * - Output: App/Controllers/Http/UsersController * * Prefix namespace is ignored for absolute namespaces. For example: * * - namespace: /App/UsersController * - prefixNamespace: App/Controllers/Http * - Output: App/UsersController */ lookup<Namespace extends Extract<keyof ContainerBindings, string>>( namespace: Namespace | LookupNode<Namespace>, prefixNamespace?: string ): LookupNode<Namespace> lookup<Namespace extends string>( namespace: Namespace | LookupNode<Namespace>, prefixNamespace?: string ): Namespace extends keyof ContainerBindings ? LookupNode<Namespace> : LookupNode<string> | null /** * Same as [[lookup]]. But raises exception instead of returning null */ lookupOrFail<Namespace extends Extract<keyof ContainerBindings, string>>( namespace: Namespace | LookupNode<Namespace>, prefixNamespace?: string ): LookupNode<Namespace> lookupOrFail<Namespace extends string>( namespace: Namespace | LookupNode<Namespace>, prefixNamespace?: string ): Namespace extends keyof ContainerBindings ? LookupNode<Namespace> : LookupNode<string> /** * Resolve a binding by invoking the binding factory function. An exception * is raised, if the binding namespace is unregistered. */ resolveBinding<Binding extends Extract<keyof ContainerBindings, string>>( binding: Binding ): ContainerBindings[Binding] resolveBinding<Binding extends string>( namespace: Binding ): Binding extends keyof ContainerBindings ? ContainerBindings[Binding] : any /** * Import namespace from the auto import aliases. This method assumes you are * using native ES modules */ import(namespace: string): Promise<any> /** * Same as the "import" method, but uses CJS for requiring the module from its * path */ require(namespace: string): any /** * The use method looks up a namespace inside both the bindings and the * auto import aliases */ use<Binding extends Extract<keyof ContainerBindings, string>>( lookupNode: Binding | LookupNode<Binding> ): ContainerBindings[Binding] use<Binding extends string>( lookupNode: Binding | LookupNode<Binding> ): Binding extends keyof ContainerBindings ? ContainerBindings[Binding] : any /** * Same as the [[use]] method, but instead uses ES modules for resolving * the auto import aliases */ useAsync<Binding extends Extract<keyof ContainerBindings, string>>( lookupNode: Binding | LookupNode<Binding> ): Promise<ContainerBindings[Binding]> useAsync<Binding extends string>( lookupNode: Binding | LookupNode<Binding> ): Promise<Binding extends keyof ContainerBindings ? ContainerBindings[Binding] : any> /** * Makes an instance of the class by first resolving it. */ make<Binding extends Extract<keyof ContainerBindings, string>>( lookupNode: Binding | LookupNode<Binding>, args?: any[] ): ContainerBindings[Binding] make<T extends any>( value: T | LookupNode<string>, args?: any[] ): T extends keyof ContainerBindings ? ContainerBindings[T] : InferMakeType<T> /** * Same as the [[make]] method, but instead uses ES modules for resolving * the auto import aliases */ makeAsync<Binding extends Extract<keyof ContainerBindings, string>>( lookupNode: Binding | LookupNode<Binding>, args?: any[] ): Promise<ContainerBindings[Binding]> makeAsync<T extends any>( value: T | LookupNode<string>, args?: any[] ): Promise<T extends keyof ContainerBindings ? ContainerBindings[T] : InferMakeType<T>> /** * The "withBindings" method invokes the defined callback when it is * able to resolve all the mentioned bindings. */ withBindings: WithBindings<ContainerBindings> /** * @deprecated: Use "withBindings" instead */ with: WithBindings<ContainerBindings> /** * Call a method on an object and automatically inject its depdencies */ call<T extends any, Method extends ExtractFunctions<T>>( target: T, method: Method, args?: any[] ): T[Method] extends Function ? ReturnType<T[Method]> : any /** * Call a method on an object and automatically inject its depdencies */ callAsync<T extends any, Method extends ExtractFunctions<T>>( target: T, method: Method, args?: any[] ): T[Method] extends Function ? Promise<UnWrapPromise<ReturnType<T[Method]>>> : Promise<any> /** * Trap container lookup calls. It includes * * - Ioc.use * - Ioc.useAsync * - Ioc.make * - Ioc.makeAsync * - Ioc.require * - Ioc.import * - Ioc.resolveBinding */ trap(callback: (namespace: string) => any): this /** * Returns the resolver instance to resolve Ioc container bindings with * little ease. Since, the IocResolver uses an in-memory cache to * improve the lookup speed, we suggest keeping a reference to * the output of this method to leverage caching */ getResolver( fallbackMethod?: string, rcNamespaceKey?: string, fallbackNamespace?: string ): IocResolverContract<ContainerBindings> } /** * IoC resolver allows resolving IoC container bindings by defining * prefix namespaces */ export interface IocResolverContract<ContainerBindings extends any> { /** * Resolve IoC container binding */ resolve<Namespace extends Extract<keyof ContainerBindings, string>>( namespace: Namespace, prefixNamespace?: string ): IocResolverLookupNode<Namespace> resolve<Namespace extends string>( namespace: Namespace, prefixNamespace?: string ): Namespace extends keyof ContainerBindings ? IocResolverLookupNode<Namespace> : IocResolverLookupNode<string> /** * Call method on an IoC container binding */ call<Namespace extends Extract<keyof ContainerBindings, string>>( namespace: Namespace | string, prefixNamespace?: string, args?: any[] ): Promise<any> call<Namespace extends Extract<keyof ContainerBindings, string>>( namespace: IocResolverLookupNode<Namespace | string>, prefixNamespace: undefined, args?: any[] ): Promise<any> }
the_stack
import { jsx } from "@emotion/core"; import * as React from "react"; import { usePositioner } from "./Hooks/use-positioner"; import { useUid } from "./Hooks/use-uid"; import { safeBind } from "./Hooks/compose-bind"; import { useTheme } from "./Theme/Providers"; import { Text } from "./Text"; import { Touchable } from "./Touchable"; import { useMeasure, Bounds } from "./Hooks/use-measure"; import { Layer } from "./Layer"; import Highlighter from "react-highlight-words"; import { InputBase } from "./Form"; /** * Combobox context */ interface ComboBoxContextType { /** element refs */ inputRef: React.RefObject<HTMLInputElement>; listRef: React.RefObject<HTMLElement>; /** list options */ options: React.MutableRefObject<string[] | null>; makeHash: (i: string) => string; selected: string | null; expanded: boolean; /** event handlers */ onInputChange: (e: React.ChangeEvent<HTMLInputElement>) => void; handleBlur: () => void; handleFocus: () => void; handleOptionSelect: (value: string) => void; onKeyDown: (e: React.KeyboardEvent) => void; /** popover positions */ position: any; inputSize: Bounds; listId: string; query: string; autocomplete: boolean; } export const ComboBoxContext = React.createContext<ComboBoxContextType | null>( null ); /** * Context provider / manager */ export interface ComboBoxProps { onSelect?: (selected: string) => void; query: string; onQueryChange: (value: string) => void; autocomplete?: boolean; } export const ComboBox: React.FunctionComponent<ComboBoxProps> = ({ children, onSelect, autocomplete = false, query, onQueryChange }) => { const inputRef = React.useRef(null); const listRef = React.useRef(null); const listId = `list${useUid()}`; const options = React.useRef<string[] | null>([]); const position = usePositioner({ modifiers: { flip: { enabled: false } } }); const [expanded, setExpanded] = React.useState(false); const [selected, setSelected] = React.useState<string | null>(null); const inputSize = useMeasure(inputRef); /** * Handle input change */ const onInputChange = React.useCallback( (e: React.ChangeEvent<HTMLInputElement>) => { // potentially show popover setSelected(null); if (!expanded) { setExpanded(true); } onQueryChange(e.target.value); }, [expanded] ); /** * Escape key pressed */ const onEscape = React.useCallback(() => { setExpanded(false); setSelected(null); }, []); /** * Enter pressed or item clicked */ const onItemSelect = React.useCallback(() => { // call the parent with the selected value? setExpanded(false); onSelect && onSelect(selected as string); setSelected(null); }, [selected]); /** * Get the currently active option index * */ const getSelectedIndex = React.useCallback(() => { if (!selected) return -1; return options.current!.indexOf(selected || ""); }, [options, selected]); /** * Arrow up pressed */ const onArrowUp = React.useCallback(() => { const opts = options.current!; const i = getSelectedIndex(); // on input? cycle to bottom if (i === -1) { setSelected(opts[opts.length - 1]); // select prev } else { setSelected(opts[i - 1]); } }, [getSelectedIndex]); /** * Arrow down pressed */ const onArrowDown = React.useCallback(() => { const opts = options.current!; const i = getSelectedIndex(); // if last, cycle to first if (i + 1 === opts.length) { setSelected(opts[0]); // or next } else { setSelected(opts[i + 1]); } }, [getSelectedIndex, selected]); /** * Handle keydown events */ const onKeyDown = React.useCallback( (e: React.KeyboardEvent) => { switch (e.key) { case "ArrowUp": e.preventDefault(); onArrowUp(); break; case "ArrowDown": e.preventDefault(); onArrowDown(); break; case "Escape": e.preventDefault(); onEscape(); break; case "Enter": e.preventDefault(); onItemSelect(); break; } }, [onArrowDown, onArrowUp, onEscape, onItemSelect] ); /** * Handle blur events */ const handleBlur = React.useCallback(() => { requestAnimationFrame(() => { const focusedElement = document.activeElement; const list = listRef.current as any; if (focusedElement == inputRef.current || focusedElement == list) { // ignore return; } // ignore if our popover contains the focused element if (list && list.contains(focusedElement)) { return; } // hide popover setExpanded(false); setSelected(null); }); }, []); /** * handle input focus */ const handleFocus = React.useCallback(() => { setExpanded(true); }, []); /** * Handle item clicks */ const handleOptionSelect = React.useCallback((value: string) => { onSelect && onSelect(value); setExpanded(false); setSelected(null); }, []); /** * Make a unique hash for list + option */ const makeHash = React.useCallback( (i: string) => { return listId + i; }, [listId] ); return ( <ComboBoxContext.Provider value={{ listId, inputRef, listRef, options, onInputChange, selected, onKeyDown, handleBlur, handleFocus, handleOptionSelect, position, makeHash, expanded, inputSize: inputSize.bounds, query, autocomplete }} > {children} </ComboBoxContext.Provider> ); }; /** * Input element */ export interface ComboBoxInputProps extends React.HTMLAttributes<any> { "aria-label": string; component?: React.ReactType<any>; [key: string]: any; } export const ComboBoxInput: React.FunctionComponent<ComboBoxInputProps> = ({ component: Component = InputBase, ...other }) => { const context = React.useContext(ComboBoxContext); const [localValue, setLocalValue] = React.useState(""); if (!context) { throw new Error("ComboBoxInput must be wrapped in a ComboBox component"); } const { onKeyDown, makeHash, selected, position, handleBlur, query, autocomplete, handleFocus, onInputChange, listId, inputRef } = context; /** support autocomplete on selection */ React.useEffect(() => { if (!autocomplete) { return; } if (selected) { setLocalValue(selected); } else { setLocalValue(""); } }, [selected, autocomplete]); return ( <Component id={listId} onKeyDown={onKeyDown} onChange={onInputChange} onBlur={handleBlur} onFocus={handleFocus} aria-controls={listId} autoComplete="off" value={localValue || query} aria-readonly aria-autocomplete="list" role="textbox" aria-activedescendant={selected ? makeHash(selected) : undefined} {...safeBind( { ref: inputRef }, { ref: position.target.ref }, other )} /> ); }; /** * Popover container */ export interface ComboBoxListProps extends React.HTMLAttributes<HTMLUListElement> { autoHide?: boolean; } export const ComboBoxList: React.FunctionComponent<ComboBoxListProps> = ({ children, autoHide = true, ...other }) => { const context = React.useContext(ComboBoxContext); const theme = useTheme(); if (!context) { throw new Error("ComboBoxInput must be wrapped in a ComboBox component"); } const { inputSize, expanded, listId, handleBlur, listRef, position, options } = context; React.useLayoutEffect(() => { options.current = []; return () => { options.current = []; }; }); return ( <React.Fragment> {(expanded || !autoHide) && ( <Layer tabIndex={-1} elevation="sm" key="1" style={position.popover.style} data-placement={position.popover.placement} id={listId} role="listbox" onBlur={handleBlur} className="ComboBoxList" css={{ overflow: "hidden", borderRadius: theme.radii.sm, outline: "none", width: inputSize.width + inputSize.left + (inputSize.right - inputSize.width) + "px", margin: 0, padding: 0 }} {...safeBind( { ref: listRef }, { ref: position.popover.ref }, other )} > {children} <div ref={position.arrow.ref} style={position.arrow.style} /> </Layer> )} </React.Fragment> ); }; /** * Individual combo box options */ export interface ComboBoxOptionProps extends React.HTMLAttributes<HTMLLIElement> { value: string; } export const ComboBoxOption: React.FunctionComponent<ComboBoxOptionProps> = ({ value, children, ...other }) => { const context = React.useContext(ComboBoxContext); const theme = useTheme(); if (!context) { throw new Error("ComboBoxInput must be wrapped in a ComboBox component"); } const { makeHash, handleOptionSelect, options, selected } = context; React.useEffect(() => { if (options.current) { options.current.push(value); } }); const isSelected = selected === value; const onClick = React.useCallback(() => { handleOptionSelect(value); }, [value]); return ( <Touchable tabIndex={-1} id={makeHash(value)} role="option" component="li" onPress={onClick} aria-selected={isSelected ? "true" : "false"} css={{ outline: "none", width: "100%", boxSizing: "border-box", display: "block", listStyleType: "none", margin: 0, padding: `0.5rem 0.75rem`, cursor: "pointer", background: isSelected ? theme.colors.background.tint1 : "none", "&.Touchable--hover": { background: theme.colors.background.tint1 }, "&.Touchable--active": { background: theme.colors.background.tint2 } }} {...other} > {children || <ComboBoxOptionText value={value} />} </Touchable> ); }; /** * ComboBox Item text with highlighting */ export interface ComboBoxOptionTextProps { value: string; } export const ComboBoxOptionText: React.FunctionComponent< ComboBoxOptionTextProps > = ({ value, ...other }) => { const context = React.useContext(ComboBoxContext); const theme = useTheme(); if (!context) { throw new Error("ComboBoxInput must be wrapped in a ComboBox component"); } const { query } = context; return ( <Text className="ComboBoxOptionText" css={{ fontWeight: theme.fontWeights.heading }} {...other} > <Highlighter highlightStyle={{ color: theme.colors.text.selected, background: "transparent" }} className="ComboBoxOptionText__Highlighter" searchWords={[query]} autoEscape={true} textToHighlight={value} /> </Text> ); };
the_stack
// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. declare const __karma__: any; declare const SystemJS: any; // "No stacktrace"" is usually best for app testing. // (Error as any).stackTraceLimit = 0; // Uncomment to get full stacktrace output. Sometimes helpful, usually not. // Error.stackTraceLimit = Infinity; // jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; // builtPaths: root paths for output ("built") files // get from karma.config.js, then prefix with '/base/' (default is 'src/') const builtPaths = (__karma__.config.builtPaths || ['src/']) .map(function(p: string) { return '/base/'+p;}); // Prevent Karma from running prematurely. __karma__.loaded = function () {}; function isJsFile(path: string) { return path.slice(-3) === '.js'; } function isSpecFile(path: string) { return /\.spec\.(.*\.)?js$/.test(path); } // Is a "built" file if is JavaScript file in one of the "built" folders function isBuiltFile(path: string) { return isJsFile(path) && builtPaths.reduce(function(keep: string, bp: string) { return keep || (path.substr(0, bp.length) === bp); }, false); } const allSpecFiles = Object.keys((window as any).__karma__.files) .filter(isSpecFile) .filter(isBuiltFile); SystemJS.config({ // Base URL for System.js calls. 'base/' is where Karma serves files from. baseURL: 'base/src/main/resources/static/js', defaultJSExtensions: true, // Extend usual application package list with test folder packages: { 'testing': { main: 'index.js', defaultExtension: 'js' } }, paths: { "angular-material-icons":"vendor/angular-material-icons/angular-material-icons", "bower:": "/base/src/main/resources/static/bower_components/", "dirPagination":"vendor/dirPagination/dirPagination", "kylo-common":"common/module-require", "kylo-common-module":"common/module", "kylo-feedmgr":"feed-mgr/module-require", "kylo-feedmgr-module":"feed-mgr/module", "kylo-services":"services/module-require", "kylo-services-module":"services/module", "kylo-side-nav":"side-nav/module-require", "kylo-side-nav-module":"side-nav/module", "npm:": "/base/node_modules/", "ng-text-truncate":"vendor/ng-text-truncate/ng-text-truncate", }, // Assume npm: is set in `paths` in systemjs.config // Map the angular testing umd bundles map: { '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.min', '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.min', '@angular/cdk': 'npm:@angular/cdk/bundles/cdk.umd.js', '@angular/cdk/a11y':'npm:@angular/cdk/bundles/cdk-a11y.umd.js', '@angular/cdk/accordion':'npm:@angular/cdk/bundles/cdk-accordion.umd.js', '@angular/cdk/bidi':'npm:@angular/cdk/bundles/cdk-bidi.umd.js', '@angular/cdk/coercion':'npm:@angular/cdk/bundles/cdk-coercion.umd.js', '@angular/cdk/collections':'npm:@angular/cdk/bundles/cdk-collections.umd.js', '@angular/cdk/keycodes':'npm:@angular/cdk/bundles/cdk-keycodes.umd.js', '@angular/cdk/layout':'npm:@angular/cdk/bundles/cdk-layout.umd.js', '@angular/cdk/observers':'npm:@angular/cdk/bundles/cdk-observers.umd.js', '@angular/cdk/overlay':'npm:@angular/cdk/bundles/cdk-overlay.umd.js', '@angular/cdk/platform':'npm:@angular/cdk/bundles/cdk-platform.umd.js', '@angular/cdk/portal':'npm:@angular/cdk/bundles/cdk-portal.umd.js', '@angular/cdk/scrolling':'npm:@angular/cdk/bundles/cdk-scrolling.umd.js', '@angular/cdk/stepper':'npm:@angular/cdk/bundles/cdk-stepper.umd.js', '@angular/cdk/table':'npm:@angular/cdk/bundles/cdk-table.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.min', '@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.min', '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.min', '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js', '@angular/core': 'npm:@angular/core/bundles/core.umd.min', '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js', '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.min', '@angular/forms/testing': 'npm:@angular/forms/bundles/forms-testing.umd.js', '@angular/http': 'npm:@angular/http/bundles/http.umd.min', '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js', '@angular/material': 'npm:@angular/material/bundles/material.umd.min', '@angular/material/autocomplete': 'npm:@angular/material/bundles/material-autocomplete.umd.min', '@angular/material/button': 'npm:@angular/material/bundles/material-button.umd.min', '@angular/material/button-toggle': 'npm:@angular/material/bundles/material-button-toggle.umd.min', '@angular/material/card': 'npm:@angular/material/bundles/material-card.umd.min', '@angular/material/checkbox': 'npm:@angular/material/bundles/material-checkbox.umd.min', '@angular/material/chips': 'npm:@angular/material/bundles/material-chips.umd.min', '@angular/material/core': 'npm:@angular/material/bundles/material-core.umd.min', '@angular/material/datepicker': 'npm:@angular/material/bundles/material-datepicker.umd.min', '@angular/material/dialog': 'npm:@angular/material/bundles/material-dialog.umd.min', '@angular/material/expansion': 'npm:@angular/material/bundles/material-expansion.umd.min', '@angular/material/form-field': 'npm:@angular/material/bundles/material-form-field.umd.min', '@angular/material/grid-list': 'npm:@angular/material/bundles/material-grid-list.umd.min', '@angular/material/icon': 'npm:@angular/material/bundles/material-icon.umd.min', '@angular/material/input': 'npm:@angular/material/bundles/material-input.umd.min', '@angular/material/list': 'npm:@angular/material/bundles/material-list.umd.min', '@angular/material/menu': 'npm:@angular/material/bundles/material-menu.umd.min', '@angular/material/paginator': 'npm:@angular/material/bundles/material-paginator.umd.min', '@angular/material/progress-bar': 'npm:@angular/material/bundles/material-progress-bar.umd.min', '@angular/material/progress-spinner': 'npm:@angular/material/bundles/material-progress-spinner.umd.min', '@angular/material/radio': 'npm:@angular/material/bundles/material-radio.umd.min', '@angular/material/select': 'npm:@angular/material/bundles/material-select.umd.min', '@angular/material/sidenav': 'npm:@angular/material/bundles/material-sidenav.umd.min', '@angular/material/slide-toggle': 'npm:@angular/material/bundles/material-slide-toggle.umd.min', '@angular/material/slider': 'npm:@angular/material/bundles/material-slider.umd.min', '@angular/material/snack-bar': 'npm:@angular/material/bundles/material-snack-bar.umd.min', '@angular/material/sort': 'npm:@angular/material/bundles/material-sort.umd.min', '@angular/material/stepper': 'npm:@angular/material/bundles/material-stepper.umd.min', '@angular/material/table': 'npm:@angular/material/bundles/material-table.umd.min', '@angular/material/tabs': 'npm:@angular/material/bundles/material-tabs.umd.min', '@angular/material/toolbar': 'npm:@angular/material/bundles/material-toolbar.umd.min', '@angular/material/tooltip': 'npm:@angular/material/bundles/material-tooltip.umd.min', '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.min', '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.min', '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.min', '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js', '@angular/router': 'npm:@angular/router/bundles/router.umd.min', '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js', '@angular/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.min', '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd', '@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd', '@covalent/core': 'npm:@covalent/core/bundles/core.umd', '@kylo/wrangler': 'feed-mgr/visual-query/wrangler/index', '@kylo/wrangler/api': 'feed-mgr/visual-query/wrangler/api/index', '@uirouter/angular': 'npm:@uirouter/angular/_bundles/ui-router-ng2', '@uirouter/angular-hybrid': 'npm:@uirouter/angular-hybrid/_bundles/ui-router-angular-hybrid', '@uirouter/angularjs': 'npm:@uirouter/angularjs/release/angular-ui-router', '@uirouter/core': 'npm:@uirouter/core/_bundles/ui-router-core', '@uirouter/rx': 'npm:@uirouter/rx/_bundles/ui-router-rx', "angular":"bower:angular/angular.min", "angular-drag-and-drop-lists":"bower:angular-drag-and-drop-lists/angular-drag-and-drop-lists.min", "angular-material-data-table":"bower:angular-material-data-table/dist/md-data-table.min", "angular-material-expansion-panel":"bower:angular-material-expansion-panel/dist/md-expansion-panel.min", 'angular-mocks': 'npm:angular-mocks/angular-mocks', "angular-nvd3":"bower:angular-nvd3/dist/angular-nvd3.min", "angular-sanitize":"bower:angular-sanitize/angular-sanitize.min", "angular-ui-codemirror":"bower:angular-ui-codemirror/ui-codemirror.min", "angular-ui-grid":"bower:angular-ui-grid/ui-grid.min", "angular-ui-router":"bower:angular-ui-router/release/angular-ui-router", "angular-visjs":"bower:angular-visjs/angular-vis", "angularAnimate":"bower:angular-animate/angular-animate.min", "angularAria":"bower:angular-aria/angular-aria.min", "angularLocalStorage": "bower:angularLocalStorage/dist/angularLocalStorage.min", "angularMaterial":"bower:angular-material/angular-material.min", "angularMessages":"bower:angular-messages/angular-messages.min", "c3":"bower:c3/c3.min", "codemirror": "bower:codemirror/lib/codemirror", "codemirror/addon/": "bower:codemirror/addon/", "codemirror/mode/": "bower:codemirror/mode/", "d3":"bower:d3/d3.min", "draggabilly":"bower:draggabilly/dist/draggabilly.pkgd.min", "fattable": "bower:fattable/fattable", "gsap": "bower:gsap/src/uncompressed/TweenMax", "jquery":"bower:jquery/dist/jquery.min", "jquery-ui":"bower:jquery-ui/jquery-ui.min", "lz-string": "bower:lz-string/libs/lz-string.min", "moment":"bower:moment/min/moment.min", 'ng-fx':"bower:ngFx/dist/ngFx.min", "nvd3": "bower:nvd3/build/nv.d3.min", "ocLazyLoad":"bower:oclazyload/dist/ocLazyLoad.require", "pivottable": "bower:pivottable/dist/pivot.min", "pivottable-c3-renderers":"bower:pivottable/dist/c3_renderers.min", "requirejs": "bower:requirejs/require", 'rxjs': 'npm:rxjs', "svg-morpheus":"bower:svg-morpheus/compile/unminified/svg-morpheus", 'tslib': 'npm:tslib/tslib', "ui-grid": "angular-ui-grid", "underscore":"bower:underscore/underscore-min", "vis":"bower:vis/dist/vis.min", "mdPickers":"bower:mdPickers/dist/mdPickers.min" }, meta: { "@angular/core": {deps:["angular"]}, "angular": {deps:["jquery"],exports: "angular"}, 'angular-ui-router': {deps:['angular']}, 'angularAria': ['angular'], 'angularMessages': ['angular'], 'angularAnimate': ['angular'], 'angularMaterial': ['angular','angularAnimate','angularAria','angularMessages'], 'angular-material-expansion-panel':['angular'], 'angular-material-icons':['angular'], 'angular-material-data-table':['angular'], "angular-nvd3":['angular','nvd3'], "angular-sanitize":["angular"], 'angular-ui-grid':['angular','angularAnimate'], 'angular-ui-codemirror':['angular','codemirror'], 'angular-visjs':['angular','vis'], "codemirror-pig": ["codemirror"], "codemirror-properties":["codemirror"], "codemirror-python":["codemirror"], "codemirror-xml":["codemirror"], "codemirror-shell":["codemirror"], "codemirror-javascript":["codemirror"], "codemirror-sql":["codemirror"], "codemirror-show-hint":["codemirror"], "codemirror-sql-hint":["codemirror"], "codemirror-xml-hint":["codemirror"], "codemirror-groovy":["codemirror"], "codemirror-dialog":["codemirror"], 'd3':{exports:'d3'}, 'dirPagination':['angular'], "jquery-ui":["jquery"], 'ocLazyLoad':['angular'], 'kylo-services-module':{deps:['angular','jquery']}, 'kylo-services':{deps:['angular','kylo-services-module','jquery']}, 'kylo-common-module':{deps:['angular','jquery']}, 'kylo-common':{deps:['angular','kylo-services','kylo-common-module','jquery','angular-material-icons'], exports:'kylo-common', format:"amd"}, 'kylo-feedmgr-module':{deps:['angular','jquery']}, 'kylo-feedmgr':{deps:['angular','kylo-services','kylo-common','kylo-feedmgr-module']}, 'kylo-opsmgr-module':{deps:['angular','jquery']}, 'kylo-opsmgr':{deps:['angular','kylo-services','kylo-common','kylo-opsmgr-module']}, 'kylo-side-nav-module':{deps:['angular','jquery']}, 'kylo-side-nav':{deps:['angular','kylo-services','jquery','angular-material-icons','kylo-side-nav-module'], exports:'kylo-side-nav', format:"amd"}, 'ment-io':['angular'], "ng-fx":{deps:["gsap"]}, "ng-text-truncate":["angular"], 'nvd3':{deps:['d3'],exports:'nv'}, 'pivottable':{deps:['c3','jquery']}, "pivottable-c3-renderers":{deps:['pivottable']}, 'vis':{exports:"vis"}, 'app':{deps:['ocLazyLoad','underscore','angularMaterial','jquery','angular-sanitize','ng-text-truncate'], exports:'app', format: "amd"}, 'routes':{deps:['app'], exports:'routes', format: "amd"} } } as any); initTestBed().then(initTesting); function initTestBed(){ return Promise.all([ SystemJS.import('@angular/core/testing'), SystemJS.import('@angular/platform-browser-dynamic/testing'), SystemJS.import('@uirouter/angular-hybrid'), SystemJS.import('@uirouter/core') ]) .then(function (providers) { const coreTesting = providers[0]; const browserTesting = providers[1]; const uiRouter = providers[3]; // Fix @uirouter/core unable to load uiRouter.servicesPlugin(null); // Load test environment coreTesting.TestBed.initTestEnvironment( browserTesting.BrowserDynamicTestingModule, browserTesting.platformBrowserDynamicTesting()); }) } // Import all spec files and start karma function initTesting () { return SystemJS.import('routes') .then(() => Promise.all(allSpecFiles.map(moduleName => SystemJS.import(moduleName)))) .then(__karma__.start, __karma__.error); }
the_stack
import { html, property, TemplateResult } from 'lit-element'; import { classMap } from 'lit-html/directives/class-map'; import { ComponentMediaQuery, Providers, ProviderState, MgtTemplatedComponent } from '@microsoft/mgt-element'; import { strings } from './strings'; /** * The foundation for creating task based components. * * @export * @class MgtTasksBase * @extends {MgtTemplatedComponent} */ export abstract class MgtTasksBase extends MgtTemplatedComponent { /** * determines if tasks are un-editable * @type {boolean} */ @property({ attribute: 'read-only', type: Boolean }) public readOnly: boolean; /** * sets whether the header is rendered * * @type {boolean} * @memberof MgtTasks */ @property({ attribute: 'hide-header', type: Boolean }) public hideHeader: boolean; /** * sets whether the options are rendered * * @type {boolean} * @memberof MgtTasks */ @property({ attribute: 'hide-options', type: Boolean }) public hideOptions: boolean; /** * if set, the component will only show tasks from the target list * @type {string} */ @property({ attribute: 'target-id', type: String }) public targetId: string; /** * if set, the component will first show tasks from this list * * @type {string} * @memberof MgtTodo */ @property({ attribute: 'initial-id', type: String }) public initialId: string; /** * The name of a potential new task * * @readonly * @protected * @type {string} * @memberof MgtTasksBase */ protected get newTaskName(): string { return this._newTaskName; } private _isNewTaskBeingAdded: boolean; private _isNewTaskVisible: boolean; private _newTaskName: string; private _previousMediaQuery: ComponentMediaQuery; protected get strings(): { [x: string]: string } { return strings; } constructor() { super(); this.clearState(); this._previousMediaQuery = this.mediaQuery; this.onResize = this.onResize.bind(this); } /** * Synchronizes property values when attributes change. * * @param {*} name * @param {*} oldValue * @param {*} newValue * @memberof MgtTasks */ public attributeChangedCallback(name: string, oldVal: string, newVal: string) { super.attributeChangedCallback(name, oldVal, newVal); switch (name) { case 'target-id': case 'initial-id': this.clearState(); this.requestStateUpdate(); break; } } /** * updates provider state * * @memberof MgtTasks */ public connectedCallback() { super.connectedCallback(); window.addEventListener('resize', this.onResize); } /** * removes updates on provider state * * @memberof MgtTasks */ public disconnectedCallback() { window.removeEventListener('resize', this.onResize); super.disconnectedCallback(); } /** * Invoked on each update to perform rendering tasks. This method must return * a lit-html TemplateResult. Setting properties inside this method will *not* * trigger the element to update. */ protected render() { const provider = Providers.globalProvider; if (!provider || provider.state !== ProviderState.SignedIn) { return html``; } if (this.isLoadingState) { return this.renderLoadingTask(); } const headerTemplate = !this.hideHeader ? this.renderHeader() : null; const newTaskTemplate = this._isNewTaskVisible ? this.renderNewTaskPanel() : null; const tasksTemplate = this.isLoadingState ? this.renderLoadingTask() : this.renderTasks(); return html` ${headerTemplate} ${newTaskTemplate} <div class="Tasks" dir=${this.direction}> ${tasksTemplate} </div> `; } /** * Render the header part of the component. * * @protected * @returns * @memberof MgtTodo */ protected renderHeader() { const headerContentTemplate = this.renderHeaderContent(); const addClasses = classMap({ AddBarItem: true, NewTaskButton: true, hidden: this.readOnly || this._isNewTaskVisible }); return html` <div class="Header" dir=${this.direction}> ${headerContentTemplate} <button class="${addClasses}" @click="${() => this.showNewTaskPanel()}"> <span class="TaskIcon"></span> <span>${this.strings.addTaskButtonSubtitle}</span> </button> </div> `; } /** * Render a task in a loading state. * * @protected * @returns * @memberof MgtTodo */ protected renderLoadingTask() { return html` <div class="Task LoadingTask"> <div class="TaskContent"> <div class="TaskCheckContainer"> <div class="TaskCheck"></div> </div> <div class="TaskDetailsContainer"> <div class="TaskTitle"></div> <div class="TaskDetails"> <span class="TaskDetail"> <div class="TaskDetailIcon"></div> <div class="TaskDetailName"></div> </span> <span class="TaskDetail"> <div class="TaskDetailIcon"></div> <div class="TaskDetailName"></div> </span> </div> </div> </div> </div> `; } /** * Render the panel for creating a new task * * @protected * @returns {TemplateResult} * @memberof MgtTasksBase */ protected renderNewTaskPanel(): TemplateResult { const newTaskName = this._newTaskName; const taskTitle = html` <input type="text" placeholder="${this.strings.newTaskPlaceholder}" .value="${newTaskName}" label="new-taskName-input" aria-label="new-taskName-input" role="input" @input="${(e: Event) => { this._newTaskName = (e.target as HTMLInputElement).value; this.requestUpdate(); }}" /> `; const taskAddClasses = classMap({ Disabled: !this._isNewTaskBeingAdded && (!newTaskName || !newTaskName.length), TaskAddButtonContainer: true }); const taskAddTemplate = !this._isNewTaskBeingAdded ? html` <div role='button' tabindex='0' class="TaskIcon TaskCancel" @click="${() => this.hideNewTaskPanel()}" @keypress="${(e: KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') this.hideNewTaskPanel(); }}"> <span>${this.strings.cancelNewTaskSubtitle}</span> </div> <div tabindex='0' class="TaskIcon TaskAdd" @click="${() => this.addTask()}" @keypress="${(e: KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') this.addTask(); }}" > <span></span> </div> ` : null; const newTaskDetailsTemplate = this.renderNewTaskDetails(); return html` <div dir=${this.direction} class="Task NewTask Incomplete"> <div class="TaskContent"> <div class="TaskDetailsContainer"> <div class="TaskTitle"> ${taskTitle} </div> <div class="TaskDetails"> ${newTaskDetailsTemplate} </div> </div> </div> <div class="${taskAddClasses}"> ${taskAddTemplate} </div> </div> `; } /** * Render the top header part of the component. * * @protected * @abstract * @returns {TemplateResult} * @memberof MgtTasksBase */ protected abstract renderHeaderContent(): TemplateResult; /** * Render the details part of the new task panel * * @protected * @abstract * @returns {TemplateResult} * @memberof MgtTasksBase */ protected abstract renderNewTaskDetails(): TemplateResult; /** * Render the list of todo tasks * * @protected * @abstract * @param {ITask[]} tasks * @returns {TemplateResult} * @memberof MgtTasksBase */ protected abstract renderTasks(): TemplateResult; /** * Render a bucket icon. * * @protected * @returns * @memberof MgtTodo */ protected renderBucketIcon() { return html` <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M14 2H2V4H3H5H6H10H11H13H14V2ZM10 5H6V6H10V5ZM5 5H3V14H13V5H11V6C11 6.55228 10.5523 7 10 7H6C5.44772 7 5 6.55228 5 6V5ZM1 5H2V14V15H3H13H14V14V5H15V4V2V1H14H2H1V2V4V5Z" fill="#3C3C3C" /> </svg> `; } /** * Create a new todo task and add it to the list * * @protected * @returns * @memberof MgtTasksBase */ protected async addTask() { if (this._isNewTaskBeingAdded || !this.newTaskName) { return; } this._isNewTaskBeingAdded = true; await this.requestUpdate(); try { await this.createNewTask(); } finally { this._isNewTaskBeingAdded = false; this._isNewTaskVisible = false; this.requestUpdate(); } } /** * Make a service call to create the new task object. * * @protected * @abstract * @memberof MgtTasksBase */ protected abstract createNewTask(): Promise<void>; /** * Clear the form data from the new task panel. * * @protected * @memberof MgtTasksBase */ protected clearNewTaskData(): void { this._newTaskName = ''; } /** * Clear the component state. * * @protected * @memberof MgtTasksBase */ protected clearState(): void { this.clearNewTaskData(); this._isNewTaskVisible = false; this.requestUpdate(); } /** * Handle when a task is clicked * * @protected * @param {Event} e * @param {TodoTask} task * @memberof MgtTasksBase */ protected handleTaskClick(e: Event, task: any) { this.fireCustomEvent('taskClick', { task }); } /** * Convert a date to a properly formatted string * * @protected * @param {Date} date * @returns * @memberof MgtTasksBase */ protected dateToInputValue(date: Date) { if (date) { return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().split('T')[0]; } return null; } private showNewTaskPanel(): void { this._isNewTaskVisible = true; this.requestUpdate(); } private hideNewTaskPanel(): void { this._isNewTaskVisible = false; this.clearNewTaskData(); this.requestUpdate(); } private onResize() { if (this.mediaQuery !== this._previousMediaQuery) { this._previousMediaQuery = this.mediaQuery; this.requestUpdate(); } } }
the_stack
import {DatasetView, IViewSerialization, TableSerialization} from "../datasetView"; import { AggregateDescription, AggregateKind, allAggregateKind, ColumnSortOrientation, CompareDatasetsInfo, Comparison, CreateIntervalColumnMapInfo, ExtractValueFromKeyMapInfo, FindResult, IColumnDescription, JSFilterInfo, kindIsTemporal, kindIsNumeric, kindIsString, NextKList, RangeFilterArrayDescription, RangeFilterDescription, RecordOrder, RemoteObjectId, RowData, RowFilterDescription, RowValue, Schema, StringFilterDescription, TableMetadata, GenericLogs, ExplodeColumnsInfo } from "../javaBridge"; import {OnCompleteReceiver, Receiver} from "../rpc"; import {SchemaClass} from "../schemaClass"; import {BaseReceiver, OnNextK, SchemaView, TableTargetAPI} from "../modules"; import {DataRangeUI} from "../ui/dataRangeUI"; import {IDataView} from "../ui/dataview"; import {Dialog, FieldKind, saveAs} from "../ui/dialog"; import {FullPage, PageTitle} from "../ui/fullPage"; import {ContextMenu, MenuItem, SubMenu, TopMenu, TopMenuItem} from "../ui/menu"; import {IScrollTarget, ScrollBar} from "../ui/scroll"; import {SelectionStateMachine} from "../ui/selectionStateMachine"; import {Resolution, SpecialChars, ViewKind} from "../ui/ui"; import { add, all, assert, cloneToSet, Converters, createComparisonFilter, Exporter, find, formatNumber, ICancellable, last, makeMissing, makeSpan, PartialResult, percent, sameAggregate, significantDigits, significantDigitsHtml, truncate } from "../util"; import {SpectrumReceiver} from "./spectrumView"; import {TSViewBase} from "./tsViewBase"; import {Grid} from "../ui/grid"; import {LogFileView, LogFragmentReceiver} from "./logFileView"; import {FindBar} from "../ui/findBar"; import {HillviewToplevel} from "../toplevel"; import {TableMeta} from "../ui/receiver"; import {RemoteTableReceiver} from "../initialObject"; /** * Displays a table in the browser. */ export class TableView extends TSViewBase implements IScrollTarget, OnNextK { // Data view part: received from remote site // Logical position of first row displayed protected startPosition: number; public order: RecordOrder; // Logical number of data rows displayed; includes count of each data row protected dataRowsDisplayed: number; public tableRowsDesired: number; protected scrollBar: ScrollBar; protected grid: Grid; protected nextKList: NextKList; protected contextMenu: ContextMenu; protected cellsPerColumn: Map<string, HTMLElement[]>; protected headerPerColumn: Map<string, HTMLElement>; // The selectedColumns state machine is indexed with the column index in the schema. protected selectedColumns = new SelectionStateMachine(); protected message: HTMLElement; protected strFilter: StringFilterDescription | null; public aggregates: AggregateDescription[] | null; // If true display the hidden columns public showHidden: boolean = true; protected findBar: FindBar; public constructor( remoteObjectId: RemoteObjectId, meta: TableMeta, page: FullPage) { super(remoteObjectId, meta, page, "Table"); this.defaultProvenance = "Table"; this.selectedColumns = new SelectionStateMachine(); this.tableRowsDesired = Resolution.tableRowsOnScreen; this.order = new RecordOrder([]); this.topLevel.id = "tableContainer"; this.topLevel.tabIndex = 1; // necessary for keyboard events? this.topLevel.onkeydown = (e) => this.keyDown(e); this.strFilter = null; this.aggregates = null; const items: TopMenuItem[] = []; items.push({ text: "Export", help: "Save information from this view in a local file.", subMenu: new SubMenu([{ text: "Schema", help: "Saves the schema of this data JSON file.", action: () => this.exportSchema() }, { text: "As CSV", help: "Saves the data in this view in a CSV file.", action: () => this.export() }]), }); if (HillviewToplevel.instance.uiconfig.enableSaveAs) items.push(this.saveAsMenu()); const viewSubMenu: MenuItem[] = [ { text: "Refresh", action: () => this.refresh(), help: "Redraw this view.", }, { text: "No columns", action: () => this.setOrder(new RecordOrder([]), false), help: "Make all columns invisible", }, { text: "Schema", action: () => this.viewSchema(), help: "Browse the list of columns of this table and choose a subset to visualize.", }, { text: "Change table size...", action: () => this.changeTableSize(), help: "Change the number of rows displayed", }, { text: "Conceal/reveal all hidden columns", action: () => { if (this.headerPerColumn.size == 0 && this.showHidden) { this.page.reportError("No columns are visible; ignoring."); return; } this.showHidden = !this.showHidden; this.selectedColumns.clear(); this.resize(); }, help: "Show or hide all columns that are currently hidden" }, { text: "Log view", action: () => this.openLogView(), help: "Open a log viewer in a new tab" }]; items.push({ text: "View", help: "Change the way the data is displayed.", subMenu: new SubMenu(viewSubMenu), }, this.chartMenu(), { text: "Filter", help: "Search specific values", subMenu: new SubMenu([ { text: "Find...", help: "Search for a string in the visible columns", action: () => { if (this.order.length() === 0) { this.page.reportError( "Find operates in the displayed column, " + "but no column is currently visible."); return; } this.findBar.show(true); } }, { text: "Filter...", help: "Filter rows that contain a specific value", action: () => this.showFilterDialog( null, this.order, this.tableRowsDesired, this.aggregates) }, { text: "Compare...", help: "Filter rows by comparing with a specific value", action: () => this.showCompareDialog( null, this.order, this.tableRowsDesired, this.aggregates) }, { text: "Filter using JavaScript...", help: "Filter rows with JavaScript", action: () => this.filterJSDialog() }, { text: "Compare subsets...", help: "Given other data views creates a column that indicates for each row the views it belongs to.", action: () => this.setCompareDialog() }, ]), }, this.dataset.combineMenu(this, page.pageId)); const menu = new TopMenu(items); this.page.setMenu(menu); this.contextMenu = new ContextMenu(this.topLevel); this.topLevel.appendChild(document.createElement("hr")); this.scrollBar = new ScrollBar(this, false); // to force the scroll bar next to the table we put them in yet another div const tblAndScrollBar = document.createElement("div"); tblAndScrollBar.className = "containerWithScrollbar"; this.topLevel.appendChild(tblAndScrollBar); this.grid = new Grid(80); tblAndScrollBar.appendChild(this.scrollBar.getHTMLRepresentation()); tblAndScrollBar.appendChild(this.grid.getHTMLRepresentation()); this.findBar = new FindBar((n, f) => this.find(n, f), () => this.findFilter()); this.topLevel.appendChild(this.findBar.getHTMLRepresentation()); if (this.isPrivate()) { menu.enable("Filter", false); menu.enable("Combine", false); menu.getSubmenu("View")!.enable("Change table size...", false); const chart = menu.getSubmenu("Chart")!; chart.enable("2D Histogram...", false); chart.enable("Trellis 2D histograms...", false); chart.enable("Trellis heatmaps...", false); } if (this.dataset.loaded.kind != "DB") { const saveAsMenu = menu.getSubmenu("Save as"); if (saveAsMenu != null) saveAsMenu.enable("Save as DB table...", false); } this.createDiv("summary"); } public export(): void { const lines = Exporter.tableAsCsv(this.order, this.meta.schema, this.aggregates, this.nextKList); const fileName = "table.csv"; saveAs(fileName, lines.join("\n")); } /** * This function is invoked when someone clicks the "Filter" button on the find bar. * This filters and keeps only rows that match the find criteria. */ private findFilter(): void { const filter = this.findBar.getFilter(); if (filter == null) { return; } const columns = this.order.getSchema().map((c) => c.name); if (columns.length === 0) { this.page.reportError("No columns are visible"); return; } const rr = this.createFilterColumnsRequest( { colNames: columns, stringFilterDescription: filter }); const title = "Filtered on: " + filter.compareValue; const newPage = this.dataset.newPage(new PageTitle(title, Converters.stringFilterDescription(filter)), this.page); rr.invoke(new TableOperationCompleted(newPage, rr, this.meta, this.order, this.tableRowsDesired, this.aggregates)); } public serialize(): IViewSerialization { // noinspection UnnecessaryLocalVariableJS const result: TableSerialization = { ...super.serialize(), order: this.order, tableRowsDesired: this.tableRowsDesired, firstRow: this.nextKList.rows.length > 0 ? this.nextKList.rows[0].values : null, }; return result; } public static reconstruct(ser: TableSerialization | null, page: FullPage): IDataView | null { if (ser == null) return null; const order = new RecordOrder(ser.order.sortOrientationList); const firstRow: RowValue[] | null = ser.firstRow; const schema = new SchemaClass([]).deserialize(ser.schema); const rowsDesired = ser.tableRowsDesired; if (order == null || schema == null || rowsDesired == null) return null; const meta: TableMeta = { rowCount: ser.rowCount, schema: schema, geoMetadata: ser.geoMetadata }; const tableView = new TableView(ser.remoteObjectId, meta, page); // We need to set the first row for the refresh. tableView.nextKList = { rowsScanned: 0, rows: firstRow != null ? [ { count: 0, values: firstRow } ] : [], aggregates: null, startPosition: 0 // not used }; tableView.order = order; tableView.tableRowsDesired = rowsDesired; return tableView; } private static compareFilters(a: StringFilterDescription | null, b: StringFilterDescription | null): boolean { if ((a == null) || (b == null)) return ((a == null) && (b == null)); else return ((a.compareValue === b.compareValue) && (a.asRegEx === b.asRegEx) && (a.asSubString === b.asSubString) && (a.caseSensitive === b.caseSensitive) && (a.complement === b.complement)); } private find(next: boolean, fromTop: boolean): void { if (this.order.length() === 0) { this.page.reportError("Find operates in the displayed column, but no column is currently visible."); return; } if (this.nextKList.rows.length === 0) { this.page.reportError("No data to search in"); return; } let excludeTopRow: boolean; const newFilter = this.findBar.getFilter(); if (TableView.compareFilters(this.strFilter, newFilter)) { excludeTopRow = true; // next search } else { this.strFilter = newFilter; excludeTopRow = false; // new search } if (!next) excludeTopRow = true; if (this.strFilter == null || this.strFilter.compareValue === "") { this.page.reportError("No current search string."); return; } const o = this.order.clone(); const topRow: RowValue[] | null = (fromTop ? null : this.nextKList.rows[0].values); const rr = this.createFindRequest(o, topRow, this.strFilter, excludeTopRow, next); rr.invoke(new FindReceiver(this.getPage(), rr, this, o)); } // noinspection JSUnusedLocalSymbols protected getCombineRenderer(title: PageTitle): (page: FullPage, operation: ICancellable<RemoteObjectId>) => BaseReceiver { return (page: FullPage, operation: ICancellable<RemoteObjectId>) => { return new TableOperationCompleted(page, operation, this.meta, this.order.clone(), this.tableRowsDesired, this.aggregates); }; } public getSelectedColCount(): number { return this.selectedColumns.size(); } /** * Invoked when scrolling has completed. */ public scrolledTo(position: number): void { if (this.nextKList == null) return; if (position <= 0) { this.begin(); } else if (position >= 1.0) { this.end(); } else { const o = this.order.clone(); const rr = this.createQuantileRequest(this.meta.rowCount, o, position); console.log("expecting quantile: " + String(position)); rr.invoke(new QuantileReceiver(this.getPage(), this, rr, o)); } } /** * Event handler called when a key is pressed */ protected keyDown(ev: KeyboardEvent): void { if (ev.code === "PageUp") { this.pageUp(); ev.preventDefault(); } else if (ev.code === "PageDown") { this.pageDown(); ev.preventDefault(); } else if (ev.code === "End") { this.end(); ev.preventDefault(); } else if (ev.code === "Home") { this.begin(); ev.preventDefault(); } } /** * Scroll one page up */ public pageUp(): void { if (this.nextKList == null || this.nextKList.rows.length === 0 || this.startPosition == null) return; if (this.startPosition <= 0) { this.page.reportError("Already at the top"); return; } const order = this.order.invert(); const rr = this.createNextKRequest(order, this.nextKList.rows[0].values, this.tableRowsDesired, this.aggregates, null); rr.invoke(new NextKReceiver(this.getPage(), this, rr, true, order, null)); } protected begin(): void { if (this.nextKList == null || this.nextKList.rows.length === 0 || this.startPosition == null) return; if (this.startPosition <= 0) { this.page.reportError("Already at the top"); return; } const o = this.order.clone(); const rr = this.createNextKRequest(o, null, this.tableRowsDesired, this.aggregates, null); rr.invoke(new NextKReceiver(this.getPage(), this, rr, false, o, null)); } protected end(): void { if (this.nextKList == null || this.nextKList.rows.length === 0 || this.startPosition == null) return; if (this.startPosition + this.dataRowsDisplayed >= this.meta.rowCount - 1) { this.page.reportError("Already at the bottom"); return; } const order = this.order.invert(); const rr = this.createNextKRequest(order, null, this.tableRowsDesired, this.aggregates, null); rr.invoke(new NextKReceiver(this.getPage(), this, rr, true, order, null)); } public pageDown(): void { if (this.nextKList == null || this.nextKList.rows.length === 0 || this.startPosition == null) return; if (this.startPosition + this.dataRowsDisplayed >= this.meta.rowCount - 1) { this.page.reportError("Already at the bottom"); return; } const o = this.order.clone(); const rr = this.createNextKRequest( o, last(this.nextKList.rows)!.values, this.tableRowsDesired, this.aggregates, null); rr.invoke(new NextKReceiver(this.getPage(), this, rr, false, o, null)); } protected setOrder(o: RecordOrder, preserveFirstRow: boolean): void { let firstRow: (RowValue | null)[] | null = null; let minValues: string[] | null = null; if (preserveFirstRow && this.nextKList != null && this.nextKList.rows != null && this.nextKList.rows.length > 0) { firstRow = []; minValues = []; } for (const cso of o.sortOrientationList) { const index = this.order.find(cso.columnDescription.name); if (firstRow != null) { if (index >= 0) { firstRow.push(this.nextKList.rows[0].values[index]); } else { firstRow.push(null); minValues!.push(cso.columnDescription.name); } } } const rr = this.createNextKRequest(o, firstRow, this.tableRowsDesired, this.aggregates, minValues); rr.invoke(new NextKReceiver(this.getPage(), this, rr, false, o, null)); } private getSortOrder(column: string): [boolean, number] | null { for (let i = 0; i < this.order.length(); i++) { const o = this.order.get(i); if (o.columnDescription.name === column) return [o.isAscending, i]; } return null; } private isVisible(column: string): boolean { const so = this.getSortOrder(column); return so != null; } private isAscending(column: string): boolean | null { const so = this.getSortOrder(column); if (so == null) return null; return so[0]; } private getSortIndex(column: string): number | null { const so = this.getSortOrder(column); if (so == null) return null; return so[1]; } public getSortArrow(column: string): string { const asc = this.isAscending(column); if (asc == null) return ""; else if (asc) return SpecialChars.downArrow; else return SpecialChars.upArrow; } private addHeaderCell(cd: IColumnDescription, colName: string, help: string, width: number, isVisible: boolean, isSortable: boolean): HTMLElement { const className = isSortable ? null : "meta"; const th = this.grid.addHeader(width, cd.name, !isVisible, className); this.headerPerColumn.set(colName, th); th.classList.add("preventselection"); th.title = help; if (!isVisible) { th.style.fontWeight = "normal"; } else if (isSortable) { const span = makeSpan("", false); span.innerHTML = this.getSortIndex(cd.name) + this.getSortArrow(cd.name); // #nosec span.style.cursor = "pointer"; span.onclick = () => this.toggleOrder(cd.name); th.appendChild(span); } th.appendChild(makeSpan(colName, false)); return th; } protected toggleOrder(colName: string): void { const o = this.order.toggle(colName); this.setOrder(o, true); } public showColumns(order: number, first: boolean): void { // order is 0 to hide // -1 to sort descending // 1 to sort ascending const o = this.order.clone(); this.getSelectedColNames().forEach((colName) => { const col = this.meta.schema.find(colName); if (order !== 0 && col != null) { if (first) o.sortFirst({columnDescription: col, isAscending: order > 0}); else o.addColumn({columnDescription: col, isAscending: order > 0}); } else o.hide(colName); }); // If we are inserting the first column then we do not preserve the first row this.setOrder(o, !first); } public resize(): void { this.updateView(this.nextKList, false, this.order, null); } public refresh(): void { if (this.nextKList == null) { this.page.reportError("Nothing to refresh"); return; } let firstRow = null; if (this.nextKList.rows != null && this.nextKList.rows.length > 0) firstRow = this.nextKList.rows[0].values; const rr = this.createNextKRequest(this.order, firstRow, this.tableRowsDesired, this.aggregates, null); rr.invoke(new NextKReceiver(this.page, this, rr, false, this.order, null)); } private createContextMenu( thd: HTMLElement, colIndex: number, visible: boolean): void { const cd = this.meta.schema.get(colIndex); thd.oncontextmenu = (e) => { this.columnClick(colIndex, e); if (e.ctrlKey && (e.button === 1)) { // Ctrl + click is interpreted as a right-click on macOS. // This makes sure it's interpreted as a column click with Ctrl. return; } const selectedCount = this.selectedColumns.size(); this.contextMenu.clear(); if (visible) { this.contextMenu.addItem({ text: "Hide", action: () => this.showColumns(0, true), help: "Hide the data in the selected columns", }, true); } else { this.contextMenu.addItem({ text: "Show", action: () => this.showColumns(1, false), help: "Show the data in the selected columns.", }, !this.isPrivate()); } this.contextMenu.addItem({ text: "Drop", action: () => this.dropColumns(), help: "Eliminate the selected columns from the view.", }, selectedCount !== 0); this.contextMenu.addItem({ text: "Estimate distinct elements", action: () => this.hLogLog(), help: "Compute an estimate of the number of different values that appear in the selected column.", }, selectedCount === 1); this.contextMenu.addItem({ text: "Sort ascending", action: () => this.showColumns(1, true), help: "Sort the data first on this column, in increasing order.", }, !this.isPrivate()); this.contextMenu.addItem({ text: "Sort descending", action: () => this.showColumns(-1, true), help: "Sort the data first on this column, in decreasing order", }, !this.isPrivate()); const foldoutMenu = this.contextMenu.addExpandableItem("Charts", "Choose a chart to draw."); this.contextMenu.addItem({ text: "Rename...", action: () => this.renameColumn(), help: "Give a new name to this column.", }, selectedCount === 1); this.contextMenu.addItem({ text: "Frequent Elements...", action: () => this.heavyHittersDialog(), help: "Find the values that occur most frequently in the selected columns.", }, !this.isPrivate()); this.contextMenu.addItem({ text: "PCA...", action: () => this.pca(true), help: "Perform Principal Component Analysis on a set of numeric columns. " + "This produces a smaller set of columns that preserve interesting properties of the data.", }, selectedCount > 1 && all(this.getSelectedColNames(), b => this.isNumericColumn(b)) && !this.isPrivate()); this.contextMenu.addItem({ text: "Plot Singular Value Spectrum", action: () => this.spectrum(true), help: "Plot singular values for the selected columns. ", }, selectedCount > 1 && all(this.getSelectedColNames(), b => this.isNumericColumn(b)) && !this.isPrivate()); this.contextMenu.addItem({ text: "Filter...", action: () => { const colName = this.getSelectedColNames()[0]; this.showFilterDialog( colName, this.order, this.tableRowsDesired, this.aggregates); }, help: "Eliminate data that matches/does not match a specific value.", }, selectedCount === 1 && !this.isPrivate()); this.contextMenu.addItem({ text: "Compare...", action: () => { const colName = this.getSelectedColNames()[0]; this.showCompareDialog(colName, this.order, this.tableRowsDesired, this.aggregates); }, help: "Eliminate data that matches/does not match a specific value.", }, selectedCount === 1 && !this.isPrivate()); this.contextMenu.addItem({ text: "Convert...", action: () => this.convert(cd.name, this.order, this.tableRowsDesired, this.aggregates), help: "Convert the data in the selected column to a different data type.", }, selectedCount === 1 && !this.isPrivate()); this.contextMenu.addItem({ text: "Create interval column...", action: () => this.createIntervalColumn(this.getSelectedColNames()), help: "Combine two numeric columns into a colum of intervals.", }, this.getSelectedColCount() == 2 && all(this.getSelectedColNames(), c => this.isNumericColumn(c)) && !this.isPrivate()); this.contextMenu.addItem({ text: "Create column in JS...", action: () => this.createJSColumnDialog( this.order, this.tableRowsDesired, this.aggregates), help: "Add a new column computed using Javascript from the selected columns.", }, !this.isPrivate()); this.contextMenu.addItem({ text: "Aggregate...", action: () => this.aggregateDialog(), help: "Compute an aggregate value for each row." }, all(this.getSelectedColNames(), (b) => this.isNumericColumn(b)) && !this.isPrivate()); this.contextMenu.addItem({ text: "Extract value...", action: () => { const colName = this.getSelectedColNames()[0]; this.createKVColumnDialog(colName, this.tableRowsDesired); }, help: "Extract a value associated with a specific key. " + " This is only applicable for some structured string or JSON columns." }, selectedCount === 1 && this.isKVColumn(this.getSelectedColNames()[0]) && !this.isPrivate()); this.contextMenu.addItem({ text: "Explode key-values...", action: () => { const colName = this.getSelectedColNames()[0]; this.explodeKVColumnDialog(colName, this.tableRowsDesired); }, help: "Explode a key-value column into a list of colums: one for each key that appears. " + " This is only applicable for some structured string or JSON columns." }, selectedCount === 1 /*&& this.isKVColumn(this.getSelectedColNames()[0])*/ && !this.isPrivate()); foldoutMenu.addItem({ text: "Histogram", action: () => this.chart( this.meta.schema.getCheckedDescriptions(this.getSelectedColNames()), this.getSelectedColCount() === 1 ? "Histogram" : "2DHistogram"), help: "Plot the data in the selected columns as a histogram. " + "Applies to one or two columns only.", }, selectedCount >= 1 && selectedCount <= 2 ); foldoutMenu.addItem({ text: "Quartiles", action: () => { console.log("Computing quartiles"); this.chart( this.meta.schema.getCheckedDescriptions(this.getSelectedColNames()), "QuartileVector") }, help: "Plot the data in the selected columns as a vector of quartiles. " + "Applies to one or two columns only.", }, selectedCount == 2 && this.isNumericColumn(this.getSelectedColNames()[1]) ); foldoutMenu.addItem({ text: "Heatmap", action: () => this.chart( this.meta.schema.getCheckedDescriptions(this.getSelectedColNames()), "Heatmap"), help: "Plot the data in the selected columns as a heatmap. " + "Applies to two or more columns only.", }, selectedCount >= 2 ); foldoutMenu.addItem({ text: "Trellis histograms", action: () => this.chart( this.meta.schema.getCheckedDescriptions(this.getSelectedColNames()), selectedCount > 2 ? "Trellis2DHistogram" : "TrellisHistogram"), help: "Plot the data in the selected columns as a Trellis plot of histograms. " + "Applies to two or three columns only.", }, selectedCount >= 2 && selectedCount <= 3 ); foldoutMenu.addItem({ text: "Trellis heatmaps", action: () => this.chart( this.meta.schema.getCheckedDescriptions(this.getSelectedColNames()), "TrellisHeatmap"), help: "Plot the data in the selected columns as a Trellis plot of heatmaps. " + "Applies to three columns only.", }, selectedCount === 3 && !this.isPrivate() ); foldoutMenu.addItem({ text: "Correlation", action: () => this.correlate(), help: "Compute pairwise corellation between a set of numeric columns" }, selectedCount > 1 && all(this.getSelectedColNames(), b => this.isNumericColumn(b))); foldoutMenu.addItem({ text: "Map", action: () => this.geo(this.meta.schema.find(this.getSelectedColNames()[0])!), help: "Plot the data in the selected columns on a map. " }, selectedCount === 1 && this.hasGeo(this.getSelectedColNames()[0]) ); this.contextMenu.showAtMouse(e); }; } protected doRenameColumn(from: string, to: string) { const rr = this.createRenameRequest(from, to); const schema = this.getSchema().renameColumn(from, to); if (schema == null) { this.page.reportError("Could not rename column '" + from + "' to '" + to + "'"); return; } const o = this.order.sortOrientationList.map( c => c.columnDescription.name == from ? { columnDescription: { name: to, kind: c.columnDescription.kind }, isAscending: c.isAscending } : c); let a: AggregateDescription[] | null = null if (this.aggregates != null) a = this.aggregates.map(a => a.cd.name == from ? { agkind: a.agkind, cd: { name: to, kind: a.cd.kind } } : a) const rec = new TableOperationCompleted(this.page, rr, { rowCount: this.meta.rowCount, schema, geoMetadata: this.meta.geoMetadata }, new RecordOrder(o), this.tableRowsDesired, a); rr.invoke(rec); } public createIntervalColumn(cols: string[]): void { if (cols.length != 2) { this.page.reportError("Only 2 columns expected"); return; } const dialog = new Dialog( "Create column of intervals", "Creates a column of intervals from two numeric columns."); const resultColumn = this.meta.schema.uniqueColumnName(cols[0] + ":" + cols[1]); dialog.addTextField("column", "Column", FieldKind.String, resultColumn, "Column to create"); dialog.addBooleanField("keep", "Keep original columns", false, "If selected the original columns are not removed"); dialog.setAction(() => { const col = dialog.getFieldValue("column"); const cd: IColumnDescription = { kind: "Interval", name: col }; const args: CreateIntervalColumnMapInfo = { startColName: cols[0], endColName: cols[1], columnIndex: -1, newColName: col }; const rr = this.createIntervalRequest(args); let schema = this.meta.schema.append(cd); let o = this.order.clone(); o.addColumn({columnDescription: cd, isAscending: true}); const keep = dialog.getBooleanValue("keep"); if (!keep) { schema = schema.filter((c) => cols.indexOf(c.name) < 0); o.hide(cols[0]); o.hide(cols[1]); } const rec = new TableOperationCompleted( this.page, rr, { rowCount: this.meta.rowCount, schema, geoMetadata: this.meta.geoMetadata }, o, this.tableRowsDesired, this.aggregates); rr.invoke(rec); }) dialog.show(); } public setCompareDialog(): void { const dialog = new Dialog( "Compare data from multiple views", "Select two other views; this will create a column that indicates for each row the views it belongs to"); const resultColumn = this.meta.schema.uniqueColumnName("Compare"); dialog.addTextField("column", "Column", FieldKind.String, resultColumn, "Column to create"); const pages = this.dataset.allPages .filter(p => p.dataView!.getRemoteObjectId() != null); if (pages.length < 2) { this.page.reportError("Not enough views to compare"); return; } const label = (p: FullPage) => p.pageId + ". " + p.title.getTextRepresentation(p) + "(" + p.title.provenance + ")"; dialog.addSelectFieldAsObject("view0", "First view", pages, label, "First view to compare"); dialog.addSelectFieldAsObject("view1", "Second view", pages, label,"Second view to compare"); dialog.setAction(() => { const page0 = dialog.getFieldValueAsObject<FullPage>("view0"); const page1 = dialog.getFieldValueAsObject<FullPage>("view1"); if (page0 == null || page1 == null || page0.dataView == null || page1.dataView == null || page0.dataView.getRemoteObjectId() == null || page1.dataView.getRemoteObjectId() == null) return; const newColumn = dialog.getFieldValue("column"); const args: CompareDatasetsInfo = { names: [page0.pageId.toString(), page1.pageId.toString()], otherIds: [page0.dataView.getRemoteObjectId()!, page1.dataView.getRemoteObjectId()!], outputName: newColumn }; const rr = this.createCompareDatasetsRequest(args); const cd: IColumnDescription = { name: newColumn, kind: "String" }; const schema = this.meta.schema.append(cd); const o = this.order.clone(); o.addColumn({columnDescription: cd, isAscending: true}); const rec = new TableOperationCompleted( this.page, rr, { rowCount: this.meta.rowCount, schema, geoMetadata: this.meta.geoMetadata }, o, this.tableRowsDesired, this.aggregates); rr.invoke(rec); }); dialog.show(); } public filterJSDialog(): void { const dialog = new Dialog( "Filter using JavaScript", "Specify a JavaScript function which filters each row."); dialog.addMultiLineTextField("function", "Function", "function filter(row) {", " return row['col'] != 0;", "}", "A JavaScript function that computes a Boolean value for each row." + "The function has a single argument 'row'. The row is a JavaScript map that can be indexed with " + "a column name (a string) and which produces a value. Rows where the function returns 'true' are keps."); dialog.setCacheTitle("FilterJSDialog"); dialog.setAction(() => { const fun = "function filter(row) {" + dialog.getFieldValue("function") + "}"; const selColumns = cloneToSet(this.getSelectedColNames()); const subSchema = this.meta.schema.filter((c) => selColumns.has(c.name)); const arg: JSFilterInfo = { jsCode: fun, schema: subSchema.schema, }; const rr = this.createJSFilterRequest(arg); const title = "Filtered using JS"; const newPage = this.dataset.newPage(new PageTitle(title, "Filter using JavaScript code\n" + fun), this.page); const rec = new TableOperationCompleted( newPage, rr, this.meta, this.order, this.tableRowsDesired, this.aggregates); rr.invoke(rec); }); dialog.show(); } public aggregateDialog(): void { const dialog = new Dialog("Aggregate", "Select columns to display in aggregate"); dialog.addSelectField("aggregation", "Operation", allAggregateKind, null, "Choose aggregation operation to perform"); const selected = this.getSelectedColNames(); dialog.setAction(() => { const operation = dialog.getFieldValue("aggregation"); if (this.aggregates == null) this.aggregates = []; for (const col of selected) { const cd = this.meta.schema.find(col); if (cd == null) { this.page.reportError("Column not found " + col); return; } const agg: AggregateDescription = { cd: cd, agkind: operation as AggregateKind }; if (find(agg, this.aggregates, sameAggregate) > 0) continue; this.aggregates.push(agg); } this.refresh(); }); dialog.show(); } public updateView(nextKList: NextKList, revert: boolean, order: RecordOrder, result: FindResult | null): void { this.cellsPerColumn = new Map<string, HTMLElement[]>(); this.headerPerColumn = new Map<string, HTMLElement>(); this.grid.prepareForUpdate(); this.selectedColumns.clear(); this.nextKList = nextKList; if (nextKList == null) return; this.dataRowsDisplayed = 0; this.startPosition = nextKList.startPosition; this.meta.rowCount = nextKList.rowsScanned; this.order = order.clone(); if (this.isPrivate()) this.page.setEpsilon(null, null); if (revert) { let rowsDisplayed = 0; if (nextKList.rows != null) { nextKList.rows.reverse(); rowsDisplayed = nextKList.rows.map((r) => r.count).reduce(add, 0); } if (nextKList.aggregates != null) nextKList.aggregates.reverse(); this.startPosition = this.meta.rowCount - this.startPosition - rowsDisplayed; this.order = this.order.invert(); } // These two columns are always shown const cds: IColumnDescription[] = []; const posCd: IColumnDescription = { kind: "Integer", name: "(position)", }; const ctCd: IColumnDescription = { kind: "Integer", name: "(count)", }; { // Create column headers let thd = this.addHeaderCell(posCd, posCd.name, "Position within sorted order.", DataRangeUI.width, true, false); thd.oncontextmenu = () => {}; thd = this.addHeaderCell(ctCd, ctCd.name, "Number of occurrences.", 75, true, false); thd.oncontextmenu = () => {}; if (this.meta.schema == null) return; } for (let i = 0; i < this.meta.schema.length; i++) { const cd = this.meta.schema.get(i); const visible = this.order.find(cd.name) >= 0; if (this.showHidden || visible) { cds.push(cd); const kindString = cd.kind.toString(); const name = cd.name; let title = name + "\nType is " + kindString + "\n"; if (this.isPrivate()) { const pm = this.dataset.privacySchema!.quantization.quantization[cd.name]; if (pm != null) { const eps = this.dataset.getEpsilon([cd.name]); title += "Epsilon=" + eps + "\n"; if (kindIsString(cd.kind)) { title += "Range is [" + pm.leftBoundaries![0] + ", " + pm.globalMax + "]\n"; title += "Divided in " + pm.leftBoundaries!.length + " intervals\n"; } else if (cd.kind === "Date") { title += "Range is [" + Converters.dateFromDouble(pm.globalMin as number) + ", " + Converters.dateFromDouble(pm.globalMax as number) + "]\n"; title += "Bucket size is " + Converters.durationFromDouble(pm.granularity!) + "\n"; } else if (cd.kind === "LocalDate") { title += "Range is [" + Converters.localDateFromDouble(pm.globalMin as number) + ", " + Converters.localDateFromDouble(pm.globalMax as number) + "]\n"; title += "Bucket size is " + Converters.durationFromDouble(pm.granularity!) + "\n"; } else if (cd.kind === "Time") { title += "Range is [" + Converters.timeFromDouble(pm.globalMin as number) + ", " + Converters.timeFromDouble(pm.globalMax as number) + "]\n"; title += "Bucket size is " + Converters.durationFromDouble(pm.granularity!) + "\n"; } else { title += "Range is [" + formatNumber(pm.globalMin as number) + ", " + formatNumber(pm.globalMax as number) + "]\n"; title += "Bucket size is " + pm.granularity + "\n"; } } } title += "Right mouse click opens a menu\n"; const thd = this.addHeaderCell(cd, cd.name, title, 0, visible, true); thd.classList.add("col" + i.toString()); thd.onclick = (e) => this.columnClick(i, e); thd.ondblclick = (e) => { e.preventDefault(); const o = this.order.clone(); if (visible) o.hide(cd.name); else o.addColumn({columnDescription: cd, isAscending: true}); this.setOrder(o, true); }; this.createContextMenu(thd, i, visible); } } if (this.aggregates != null) { for (let i = 0; i < this.aggregates.length; i++) { const ag = this.aggregates[i]; let name; const dn = ag.cd.name; name = ag.agkind + "(" + dn.toString() + ")"; const cd: IColumnDescription = { kind: ag.cd.kind, name: name }; const thd = this.addHeaderCell(cd, name, ag.agkind + " of values in column " + ag.cd.name, 0, true, false); const aggIndex = i; thd.oncontextmenu = (e: MouseEvent) => { this.contextMenu.clear(); this.contextMenu.addItem({ text: "Remove", action: () => { this.aggregates!.splice(aggIndex, 1); if (this.aggregates!.length === 0) this.aggregates = null; this.refresh(); }, help: "Remove aggregate from display.", }, true); this.contextMenu.showAtMouse(e); }; } } cds.forEach((cd) => this.cellsPerColumn.set(cd.name, [])); let tableRowCount = 0; // Add row data let previousRow: RowData | null = null; if (nextKList.rows != null) { tableRowCount = nextKList.rows.length; let index = 0; if (nextKList.aggregates != null) console.assert(nextKList.rows.length === nextKList.aggregates.length); for (let i = 0; i < nextKList.rows.length; i++) { const row = nextKList.rows[i]; const agg = nextKList.aggregates == null ? null : nextKList.aggregates[i]; this.addRow(nextKList.rows, previousRow, agg, cds, index); previousRow = row; index++; } } assert(this.summary != null); this.summary.set("table rows", tableRowCount); this.summary.set("displayed rows", this.dataRowsDisplayed, this.isPrivate()); this.standardSummary(); this.summary.set("% visible", percent(this.dataRowsDisplayed, this.meta.rowCount)); if (this.startPosition > 0) { this.summary.set("starting at %", percent(this.startPosition, this.meta.rowCount)); } this.summary.display(); if (result != null) { this.findBar.setCounts(result.before, result.after); } else { this.findBar.show(false); } this.updateScrollBar(); this.highlightSelectedColumns(); this.grid.updateCompleted(); } /** * Return true if this column is a column in a log file that has a contents * that is of the form of a key=value. */ private isKVColumn(col: string): boolean { const cd = this.meta.schema.find(col); if (cd == null) return false; return (cd.kind === "Json" || // This is a heuristic; this is tied to RFC5424 logs right now (this.dataset.isLog() && col === "StructuredData")); } public filterOnRowValue(row: RowValue[], comparison: Comparison): void { const filter: RowFilterDescription = { order: this.order, data: row, comparison: comparison }; const rr = this.createRowFilterRequest(filter); const title = "Filtered: " + filter.comparison + " to row."; const newPage = this.dataset.newPage(new PageTitle(title, Converters.rowFilterDescription(filter)), this.page); rr.invoke(new TableOperationCompleted(newPage, rr, this.meta, this.order, this.tableRowsDesired, this.aggregates)); } public filterAroundValue(cd: IColumnDescription, value: RowValue): void { const doubleValue = value as number; const display = Converters.valueToString(value, cd.kind, true); const dialog = new Dialog( "Interval size", "Interval size around " + display); switch (cd.kind) { case "Integer": case "Double": const nf = dialog.addTextField("interval", "interval", FieldKind.Double, "5", "Interval size."); nf.required = true; break; case "Date": case "Duration": case "LocalDate": case "Time": const df = dialog.addTextField("days", "days", FieldKind.Integer, "0", "Number of days"); df.required = true; const tf = dialog.addTextField("time", "[[HH:]MM:]SS[.msec]", FieldKind.Time, "2.5", "Time interval"); tf.required = true; break; } dialog.setAction(() => { let size: number | null = 0; if (kindIsNumeric(cd.kind)) size = dialog.getFieldValueAsNumber("interval"); else { const days = dialog.getFieldValueAsInt("days"); const ms = dialog.getFieldValueAsInterval("time"); if (days != null && ms != null) { size = ms + days * 86_400_000; } } if (size == null) { this.page.reportError("Could not parse interval"); return; } const filter: RangeFilterDescription = { min: doubleValue - size, max: doubleValue + size, minString: null, maxString: null, cd, includeMissing: false }; const filters: RangeFilterArrayDescription = { filters: [filter], complement: false }; const rr = this.createFilterRequest(filters); const title = "Filtered around " + display; const newPage = this.dataset.newPage(new PageTitle(title, this.defaultProvenance), this.page); rr.invoke(new TableOperationCompleted(newPage, rr, this.meta, this.order, this.tableRowsDesired, this.aggregates)); }); dialog.show(); } public filterOnValue(cd: IColumnDescription, value: RowValue, comparison: Comparison): void { const cfd = createComparisonFilter(cd, value, comparison); this.runComparisonFilter(cfd, this.order, this.tableRowsDesired, this.aggregates); } public dropColumns(): void { const selected = cloneToSet(this.getSelectedColNames()); const schema = this.meta.schema.filter((c) => !selected.has(c.name)); const so: ColumnSortOrientation[] = []; for (let i = 0; i < this.order.length(); i++) { const cso = this.order.get(i); if (!selected.has(cso.columnDescription.name)) so.push(cso); } const order = new RecordOrder(so); const rr = this.createProjectRequest(schema.schema); // Remove all aggregates that depend on these columns let aggregates: AggregateDescription[] | null = []; if (this.aggregates != null) { for (const a of this.aggregates) { if (!selected.has(a.cd.name)) aggregates.push(a); } } if (aggregates.length === 0) aggregates = null; const rec = new TableOperationCompleted(this.page, rr, { rowCount: this.meta.rowCount, schema, geoMetadata: this.meta.geoMetadata }, order, this.tableRowsDesired, aggregates); rr.invoke(rec); } /** * Mouse click on a column. * @param colNum column position in schema. * @param e mouse event */ private columnClick(colNum: number, e: MouseEvent): void { e.preventDefault(); if (e.ctrlKey || e.metaKey) this.selectedColumns.changeState("Ctrl", colNum); else if (e.shiftKey) this.selectedColumns.changeState("Shift", colNum); else { if (e.button === 2) { // right button if (this.selectedColumns.has(colNum)) // Do nothing if pressed on a selected column return; } this.selectedColumns.changeState("NoKey", colNum); } this.highlightSelectedColumns(); } // noinspection JSUnusedLocalSymbols private selectNumericColumns(): void { this.selectedColumns.clear(); let count = 0; for (let i = 0; i < this.meta.schema.length; i++) { const desc = this.meta.schema.get(i); if (!this.headerPerColumn.has(desc.name)) continue; const kind = desc.kind; if (kind === "Integer" || kind === "Double") { this.selectedColumns.add(i); count++; } } this.page.reportError(`Selected ${count} numeric columns.`); this.highlightSelectedColumns(); } public getSelectedColNames(): string[] { const colNames: string[] = []; this.selectedColumns.getStates().forEach((i) => colNames.push(this.meta.schema.get(i).name)); return colNames; } private isNumericColumn(colName: string): boolean { const kind = this.meta.schema.find(colName)!.kind; return kind === "Double" || kind === "Integer"; } private checkNumericColumns(colNames: string[], atLeast: number = 3): [boolean, string] { if (colNames.length < atLeast) { const msg = `\nNot enough columns. Need at least ${atLeast}. There are ${colNames.length}`; return [false, msg]; } let valid = true; let message = ""; colNames.forEach((colName) => { if (!this.isNumericColumn(colName)) { valid = false; message += "\n * Column '" + colName + "' is not numeric."; } }); return [valid, message]; } public correlate(): void { const colNames = this.getSelectedColNames(); const [valid, message] = this.checkNumericColumns(colNames, 2); if (!valid) { this.page.reportError("Not valid for correlation:" + message); return; } this.chart(this.meta.schema.getCheckedDescriptions(colNames), "CorrelationHeatmaps"); } public pca(toSample: boolean): void { const colNames = this.getSelectedColNames(); const [valid, message] = this.checkNumericColumns(colNames, 2); if (!valid) { this.page.reportError("Not valid for PCA:" + message); return; } const pcaDialog = new Dialog("Principal Component Analysis", "Projects a set of numeric columns to a smaller set of numeric columns while preserving the 'shape' " + " of the data as much as possible."); const components = pcaDialog.addTextField("numComponents", "Number of components", FieldKind.Integer, "2", "Number of dimensions to project to. Must be an integer bigger than 1 and " + "smaller than the number of selected columns"); components.required = true; components.min = "2"; components.max = colNames.length.toString(); const name = pcaDialog.addTextField("projectionName", "Name for Projected columns", FieldKind.String, "PCA", "The projected columns will appear with this name followed by a number starting from 0"); name.required = true; pcaDialog.setCacheTitle("PCADialog"); pcaDialog.setAction(() => { const numComponents: number | null = pcaDialog.getFieldValueAsInt("numComponents"); const projectionName: string = pcaDialog.getFieldValue("projectionName"); if (numComponents == null || numComponents < 1 || numComponents > colNames.length) { this.page.reportError("Number of components for PCA must be between 1 (incl.) " + "and the number of selected columns, " + colNames.length + " (incl.). (" + numComponents + " does not satisfy this.)"); return; } const rr = this.createCorrelationMatrixRequest(colNames, this.meta.rowCount, toSample); rr.invoke(new CorrelationMatrixReceiver(this.getPage(), this, rr, this.order, numComponents, projectionName)); }); pcaDialog.show(); } private spectrum(toSample: boolean): void { const colNames = this.getSelectedColNames(); const [valid, message] = this.checkNumericColumns(colNames, 2); if (valid) { const rr = this.createSpectrumRequest(colNames, this.meta.rowCount, toSample); rr.invoke(new SpectrumReceiver( this.getPage(), this, this.getRemoteObjectId()!, this.meta, colNames, rr, false)); } else { this.page.reportError("Not valid for PCA:" + message); } } private highlightSelectedColumns(): void { for (let i = 0; i < this.meta.schema.length; i++) { const name = this.meta.schema.get(i).name; if (!this.headerPerColumn.has(name)) continue; const cells = this.cellsPerColumn.get(name); const header = this.headerPerColumn.get(name); const selected = this.selectedColumns.has(i); if (selected) header.classList.add("selected"); else header.classList.remove("selected"); for (const cell of cells) { if (selected) cell.classList.add("selected"); else cell.classList.remove("selected"); } } } private updateScrollBar(): void { if (this.startPosition == null || this.meta.rowCount == null) return; if (this.meta.rowCount <= 0 || this.dataRowsDisplayed <= 0) // we show everything this.setScroll(0, 1); else this.setScroll(this.startPosition / this.meta.rowCount, (this.startPosition + this.dataRowsDisplayed) / this.meta.rowCount); } protected changeTableSize(): void { const dialog = new Dialog("Number of rows", "Choose number of rows to display"); const maxRows = 1000; const field = dialog.addTextField("rows", "Rows", FieldKind.Integer, Resolution.tableRowsOnScreen.toString(), "Number of rows to show (between 10 and " + maxRows.toString() + ")"); field.min = "10"; field.max = maxRows.toString(); field.required = true; dialog.setAction(() => { const rowCount = dialog.getFieldValueAsInt("rows"); if (rowCount == null || rowCount < 10 || rowCount > maxRows) { this.page.reportError("Row count must be between 10 and " + maxRows.toString()); return; } this.tableRowsDesired = rowCount; this.refresh(); }); dialog.show(); } public viewSchema(): void { const newPage = this.dataset.newPage(new PageTitle("Schema", this.defaultProvenance), this.page); const sv = new SchemaView(this.getRemoteObjectId()!, this.meta, newPage); newPage.setDataView(sv); sv.show(0); newPage.scrollIntoView(); } public moveRowToBoundary(row: RowData, top: boolean): void { const order = top ? this.order.clone() : this.order.invert(); const rr = this.createNextKRequest( order, row.values, this.tableRowsDesired, this.aggregates, null); rr.invoke(new NextKReceiver(this.page, this, rr, !top, order, null)); } protected centerRow(rows: RowData[], index: number): void { const mid = Math.floor(rows.length / 2); if (index == mid) return; if (index < mid) { if (this.startPosition <= 0) { this.page.reportError("Cannot move: already at the top"); return; } this.moveRowToBoundary(rows[index + mid], false); } else { if (this.startPosition + this.dataRowsDisplayed >= this.meta.rowCount - 1) { this.page.reportError("Cannot move: already at the bottom"); return; } this.moveRowToBoundary(rows[index - mid], true); } } public addRow(rows: RowData[], previousRow: RowData | null, agg: number[] | null, cds: IColumnDescription[], index: number): void { const last = index == rows.length - 1; const row = rows[index]; this.grid.newRow(); const position = this.startPosition + this.dataRowsDisplayed; const rowContextMenu = (e: MouseEvent) => { this.contextMenu.clear(); this.contextMenu.addItem({text: "Keep equal rows", action: () => this.filterOnRowValue(row.values, "=="), help: "Keep only the rows that are equal to this one." }, true); this.contextMenu.addItem({text: "Keep different rows", action: () => this.filterOnRowValue(row.values, "!="), help: "Keep only the rows that are different." }, true); this.contextMenu.addItem({text: "Keep rows before", action: () => this.filterOnRowValue(row.values, ">"), help: "Keep only the rows that come before this one in the sort order." }, true); this.contextMenu.addItem({text: "Keep rows after", action: () => this.filterOnRowValue(row.values, "<"), help: "Keep only the rows that come after this one in the sort order." }, true); this.contextMenu.addItem({text: "Keep all rows before and this one", action: () => this.filterOnRowValue(row.values, ">="), help: "Keep only this row and the rows that come before this one in the sort order." }, true); this.contextMenu.addItem({text: "Keep all rows after and this one", action: () => this.filterOnRowValue(row.values, "<="), help: "Keep only this rows and the rows that come after this one in the sort order." }, true); this.contextMenu.addItem({ text: "Move to top", action: () => this.moveRowToBoundary(row, true), help: "Move this row to the top of the view.", }, true); this.contextMenu.addItem({ text: "Center row", action: () => this.centerRow(rows, index), help: "Move this row to become the middle row.", }, true); this.contextMenu.showAtMouse(e); }; let cell = this.grid.newCell("all"); const dataRange = new DataRangeUI(position, row.count, this.meta.rowCount); cell.appendChild(dataRange.getDOMRepresentation()); cell.oncontextmenu = rowContextMenu; cell = this.grid.newCell("all"); cell.classList.add("meta"); cell.style.textAlign = "right"; cell.oncontextmenu = rowContextMenu; significantDigitsHtml(row.count).setInnerHtml(cell); cell.title = "Number of rows that have these values: " + formatNumber(row.count); // Maps a column name to a boolean indicating whether the // value is the same as in the previous row. Must be computed // in sorted order. const isSame = new Map<string, boolean>(); let previousSame = true; for (const o of this.order.sortOrientationList) { const name = o.columnDescription.name; if (!previousSame || previousRow == null) { isSame.set(name, false); } else { const index = this.order.find(name); if (previousRow.values[index] === row.values[index]) { isSame.set(name, true); } else { previousSame = false; isSame.set(name, false); } } } for (let i = 0; i < cds.length; i++) { const cd = cds[i]; const dataIndex = this.order.find(cd.name); let value: RowValue = null; let borders: string; if (this.isVisible(cd.name)) { value = row.values[dataIndex]; if (previousRow == null) { if (last) borders = "all"; else borders = "top"; } else if (last) { if (isSame.get(cd.name)) borders = "bottom"; else borders = "all"; } else { if (isSame.get(cd.name)) borders = "middle"; else borders = "top"; } } else { if (previousRow == null) { if (last) borders = "all"; else borders = "top"; } else { if (last) borders = "bottom"; else borders = "middle"; } } cell = this.grid.newCell(borders); let align = "right"; if (kindIsString(cd.kind)) align = "left"; cell.style.textAlign = align; this.cellsPerColumn.get(cd.name).push(cell); if (this.isVisible(cd.name)) { let shownValue: string; let exactValue: string; if (value == null) { cell.appendChild(makeMissing()); shownValue = "missing"; exactValue = ""; } else { shownValue = Converters.valueToString(row.values[dataIndex], cd.kind, true); exactValue = Converters.valueToString(row.values[dataIndex], cd.kind, false); const high = this.findBar.highlight(shownValue, this.strFilter); cell.appendChild(high); } cell.onclick = () => { this.page.reportError(exactValue); }; const shortValue = truncate(shownValue, 30); cell.title = exactValue + "\nRight click will popup a menu."; cell.oncontextmenu = (e) => { this.contextMenu.clear(); const sel = window.getSelection(); if (sel != null) { const selString = sel.toString(); this.contextMenu.addItem({ text: "Keep rows containing " + truncate(selString, 20), action: () => { const filter: StringFilterDescription = { compareValue: selString, asRegEx: false, asSubString: true, caseSensitive: false, complement: false }; const columns = this.order.getSchema().map((c) => c.name); const rr = this.createFilterColumnsRequest( {colNames: columns, stringFilterDescription: filter}); const title = "Filtered on: " + filter.compareValue; const newPage = this.dataset.newPage(new PageTitle(title, Converters.stringFilterDescription(filter)), this.page); rr.invoke(new TableOperationCompleted(newPage, rr, this.meta, this.order, this.tableRowsDesired, this.aggregates)) }, help: "Keep rows containing this string" }, true); } // This menu shows the value to the right, but the filter // takes the value to the left, so we have to flip all // comparison signs. this.contextMenu.addItem({text: "Keep " + shortValue, action: () => this.filterOnValue(cd, value, "=="), help: "Keep only the rows that have this value in this column." }, true); this.contextMenu.addItem({text: "Keep different from " + shortValue, action: () => this.filterOnValue(cd, value, "!="), help: "Keep only the rows that have a different value in this column." }, true); this.contextMenu.addItem({text: "Keep all < " + shortValue, action: () => this.filterOnValue(cd, value, ">"), help: "Keep only the rows that have a smaller value in this column." }, true); this.contextMenu.addItem({text: "Keep all > " + shortValue, action: () => this.filterOnValue(cd, value, "<"), help: "Keep only the rows that have a larger value in this column." }, true); this.contextMenu.addItem({text: "Keep all <= " + shortValue, action: () => this.filterOnValue(cd, value, ">="), help: "Keep only the rows that have a smaller or equal value in this column." }, true); this.contextMenu.addItem({text: "Keep all >= " + shortValue, action: () => this.filterOnValue(cd, value, "<="), help: "Keep only the rows that have a larger or equal in this column." }, true); this.contextMenu.addItem({text: "Keep around " + shortValue + "...", action: () => this.filterAroundValue(cd, value), help: "Keep values in this column close to this one." }, kindIsNumeric(cd.kind) || kindIsTemporal(cd.kind)); this.contextMenu.addItem({text: "Move to top", action: () => this.moveRowToBoundary(row, true), help: "Move this row to the top of the view." }, true); this.contextMenu.addItem({text: "Center row", action: () => this.centerRow(rows, index), help: "Move this row to become the middle row.", }, true); this.contextMenu.showAtMouse(e); }; } else { cell.classList.add("empty"); cell.innerHTML = "&nbsp;"; cell.oncontextmenu = rowContextMenu; } } if (agg != null) { console.assert(agg.length === this.aggregates!.length); for (let i = 0; i < agg.length; i++) { cell = this.grid.newCell("all"); cell.style.textAlign = "right"; const shownValue = significantDigits(agg[i]); const span = makeSpan(shownValue); cell.classList.add("meta"); cell.appendChild(span); cell.oncontextmenu = rowContextMenu; cell.title = formatNumber(agg[i]); } } this.dataRowsDisplayed += row.count; } public openLogView(): void { const ts = this.meta.schema.find(GenericLogs.timestampColumnName); if (ts == null) { this.page.reportError("Cannot identify timestamp column"); return; } const logWindow = window.open("log.html", "_blank"); if (logWindow == null) return; logWindow.onload = () => { const newPage = new FullPage(0, this.page.title, null, this.dataset); newPage.setSinglePage(); logWindow.document.title = this.page.title.format; logWindow.document.body.appendChild(newPage.getHTMLRepresentation()); let allColumns = this.meta.schema.schema.filter(c => c.name != ts.name); allColumns.unshift(ts); const order = new RecordOrder(allColumns.map(c => { return { columnDescription: c, isAscending: true }; })); let colsMinValue = null; const startRow = this.nextKList.rows.length > 0 ? this.nextKList.rows[0].values : null; let firstRow = null; if (startRow != null) { firstRow = []; colsMinValue = []; for (const c of order.sortOrientationList) { const index = this.order.find(c.columnDescription.name); if (index >= 0) { firstRow.push(startRow[index]); } else { firstRow.push(null); colsMinValue.push(c.columnDescription.name); } } } const viewer = new LogFileView(this.getRemoteObjectId()!, this.meta, order, ts, newPage); const rr = viewer.createNextKRequest(order, firstRow, LogFileView.increment, null, colsMinValue); rr.invoke(new LogFragmentReceiver(newPage, viewer, rr)); }; } public setScroll(top: number, bottom: number): void { this.scrollBar.setPosition(top, bottom); } public createKVColumnDialog(inputColumn: string, tableRowsDesired: number): void { const dialog = new Dialog( "Extract value", "Extract values associated with a specific key."); const kf = dialog.addTextField("key", "Key", FieldKind.String, null, "Key whose value is extracted."); kf.onchange = () => { dialog.setFieldValue("outColName", this.meta.schema.uniqueColumnName(dialog.getFieldValue("key"))); }; const name = dialog.addTextField( "outColName", "Column name", FieldKind.String, null, "Name to use for the generated column."); name.required = true; dialog.setCacheTitle("CreateKVDialog"); dialog.setAction(() => this.createKVColumn(dialog, inputColumn, tableRowsDesired)); dialog.show(); } private createKVColumn(dialog: Dialog, inputColumn: string, tableRowsDesired: number): void { const col = dialog.getFieldValue("outColName"); if (this.meta.schema.find(col) != null) { this.page.reportError("Column " + col + " already exists"); return; } const key = dialog.getFieldValue("key"); if (key === "") { this.page.reportError("Please specify a non-empty key"); return; } const ic = this.meta.schema.find(inputColumn); if (ic === null) return; const arg: ExtractValueFromKeyMapInfo = { key: key, inputColumn: ic, outputColumn: col, outputIndex: this.meta.schema.columnIndex(inputColumn) }; const rr = this.createKVCreateColumnRequest(arg); const cd: IColumnDescription = { kind: "String", name: col, }; const schema = this.meta.schema.append(cd); const o = this.order.clone(); o.addColumn({columnDescription: cd, isAscending: true}); const rec = new TableOperationCompleted( this.page, rr, { rowCount: this.meta.rowCount, schema, geoMetadata: this.meta.geoMetadata }, o, tableRowsDesired, this.aggregates); rr.invoke(rec); } public explodeKVColumnDialog(inputColumn: string, tableRowsDesired: number): void { const dialog = new Dialog( "Explode key-value", "Explode a key-value string into a set of columns."); dialog.addTextField("prefix", "Prefix", FieldKind.String, null, "Prefix to add to all generated column names."); dialog.setCacheTitle("ExplodeKVDialog"); dialog.setAction(() => this.explodeKVColumn(dialog.getFieldValue("prefix"), inputColumn, tableRowsDesired)); dialog.show(); } private explodeKVColumn(outColPrefix: string, inputColumn: string, tableRowsDesired: number): void { const ic = this.meta.schema.find(inputColumn); if (ic === null) return; const rr = this.createKVGetAllKeysRequest(inputColumn); const rec = new ExplodedKeyReceiver( this.page, rr, this, this.meta, this.order, tableRowsDesired, this.aggregates, inputColumn, outColPrefix); rr.invoke(rec); } } class ExplodedKeyReceiver extends OnCompleteReceiver<RemoteObjectId> { constructor(page: FullPage, operation: ICancellable<RemoteObjectId>, protected view: TableView, protected readonly meta: TableMeta, protected order: RecordOrder | null, protected tableRowsDesired: number, protected aggregates: AggregateDescription[] | null, protected column: string, protected outColPrefix: string) { super(page, operation, "Finding all keys"); } public run(value: RemoteObjectId): void { const args: ExplodeColumnsInfo = { column: this.column, prefix: this.outColPrefix, distinctColumnsObjectId: value }; const rr = this.view.createKVExplodeColumnsRequest(args); rr.chain(this.operation); const rec = new RemoteTableReceiver(this.page, rr, this.view.dataset.loaded, "Explode columns", false); rr.invoke(rec); } } /** * Receives the NextK rows from a table and displays them. */ export class NextKReceiver extends Receiver<NextKList> { constructor(page: FullPage, protected view: OnNextK, operation: ICancellable<NextKList>, protected reverse: boolean, protected order: RecordOrder | null, protected result: FindResult | null) { super(page, operation, "Getting table rows"); } public onNext(value: PartialResult<NextKList>): void { super.onNext(value); this.view.updateView(value.data, this.reverse, this.order, this.result); } public onCompleted(): void { super.onCompleted(); this.view.updateCompleted(this.elapsedMilliseconds()); } } /** * Receives a Schema and displays the resulting table. */ export class SchemaReceiver extends OnCompleteReceiver<TableMetadata> { /** * Create a schema receiver for a new table. * @param page Page where result should be displayed. * @param operation Operation that will bring the results. * @param remoteObject Table object. * @param dataset Dataset that this is a part of. * @param schema Schema that is used to display the data - if not null. * @param viewKind What view to use. If null we get to choose. */ constructor(page: FullPage, operation: ICancellable<TableMetadata>, protected remoteObject: TableTargetAPI, protected dataset: DatasetView, protected schema: SchemaClass | null, protected viewKind: ViewKind | null) { super(page, operation, "Get schema"); } protected createMetadata(m: TableMetadata): TableMeta { const schemaClass = this.schema == null ? new SchemaClass(m.schema) : this.schema; return { rowCount: m.rowCount, schema: schemaClass, geoMetadata: m.geoMetadata } } public run(ts: TableMetadata): void { if (ts.schema == null) { this.page.reportError("No schema received; empty dataset?"); return; } if (ts.privacyMetadata != null) this.dataset.setPrivate(ts.privacyMetadata); const meta = this.createMetadata(ts); const useSchema = this.viewKind === "Schema" || (this.viewKind === null && ts.schema.length > 20); if (useSchema) { const dataView = new SchemaView(this.remoteObject.getRemoteObjectId()!, meta, this.page); this.page.setDataView(dataView); dataView.show(this.elapsedMilliseconds()); } else { const nk: NextKList = { rowsScanned: ts.rowCount, startPosition: 0, rows: [], aggregates: null }; const order = new RecordOrder([]); const table = new TableView(this.remoteObject.getRemoteObjectId()!, meta, this.page); this.page.setDataView(table); table.updateView(nk, false, order, null); table.updateCompleted(this.elapsedMilliseconds()); } } } /** * Receives a row which is the result of an approximate quantile request and * initiates a request to get the NextK rows after this one. */ class QuantileReceiver extends OnCompleteReceiver<RowValue[]> { public constructor(page: FullPage, protected tv: TableView, operation: ICancellable<RowValue[]>, protected order: RecordOrder) { super(page, operation, "Compute quantiles"); } public run(firstRow: RowValue[]): void { const rr = this.tv.createNextKRequest( this.order, firstRow, this.tv.tableRowsDesired, this.tv.aggregates, null); rr.chain(this.operation); rr.invoke(new NextKReceiver(this.page, this.tv, rr, false, this.order, null)); } } /** * Receives the result of a PCA computation and initiates the request * to project the specified columns using the projection matrix. */ export class CorrelationMatrixReceiver extends BaseReceiver { public constructor(page: FullPage, protected tv: TableView, operation: ICancellable<RemoteObjectId>, protected order: RecordOrder, private numComponents: number, private projectionName: string) { super(page, operation, "Correlation matrix", tv.dataset); } public run(value: RemoteObjectId): void { super.run(value); const rr = this.tv.createProjectToEigenVectorsRequest( this.remoteObject, this.numComponents, this.projectionName); rr.chain(this.operation); rr.invoke(new PCATableReceiver( this.page, rr, "Data with PCA projection columns", "Reading", this.tv, this.order, this.numComponents, this.tv.tableRowsDesired)); } } // Receives the ID of a table that contains additional eigen vector projection columns. // Invokes a sketch to get the schema of this new table. class PCATableReceiver extends BaseReceiver { constructor(page: FullPage, operation: ICancellable<RemoteObjectId>, protected title: string, progressInfo: string, protected tv: TSViewBase, protected order: RecordOrder, protected numComponents: number, protected tableRowsDesired: number) { super(page, operation, progressInfo, tv.dataset); } public run(value: RemoteObjectId): void { super.run(value); const rr = this.remoteObject.createGetMetadataRequest(); rr.chain(this.operation); rr.invoke(new PCASchemaReceiver(this.page, rr, this.remoteObject, this.tv, this.title, this.order, this.numComponents, this.tableRowsDesired)); } } // Receives the schema after a PCA computation; computes the additional columns // and adds these to the previous view class PCASchemaReceiver extends OnCompleteReceiver<TableMetadata> { constructor(page: FullPage, operation: ICancellable<TableMetadata>, protected remoteObject: TableTargetAPI, protected tv: TSViewBase, protected title: string, protected order: RecordOrder, protected numComponents: number, protected tableRowsDesired: number) { super(page, operation, "Get schema"); } public run(ts: TableMetadata): void { if (ts.schema == null) { this.page.reportError("No schema received; empty dataset?"); return; } const newCols: IColumnDescription[] = []; const o = this.order.clone(); // we rely on the fact that the last numComponents columns are added by the PCA // computation. for (let i = 0; i < this.numComponents; i++) { const cd = ts.schema[ts.schema.length - this.numComponents + i]; newCols.push(cd); o.addColumn({ columnDescription: cd, isAscending: true }); } const schema = this.tv.meta.schema.concat(newCols); const table = new TableView( this.remoteObject.getRemoteObjectId()!, { rowCount: this.tv.meta.rowCount, schema, geoMetadata: ts.geoMetadata }, this.page); this.page.setDataView(table); const rr = table.createNextKRequest(o, null, this.tableRowsDesired, null, null); rr.chain(this.operation); rr.invoke(new NextKReceiver(this.page, table, rr, false, o, null)); } } /** * Receives the id of a remote table and initiates a request to display the table. */ export class TableOperationCompleted extends BaseReceiver { /** * @param page Page where the new view will be displayed * @param operation Operation that initiated this request. * @param meta Table metadata. * @param order Order desired for table rows. If this is null we will * actually display a SchemaView, otherwise we will display a TableView * @param tableRowsDesired Number of rows desired in table (for a table view). * @param aggregates Aggregations that are desired. */ public constructor(page: FullPage, operation: ICancellable<RemoteObjectId>, protected readonly meta: TableMeta, protected order: RecordOrder | null, protected tableRowsDesired: number, protected aggregates: AggregateDescription[] | null) { super(page, operation, "Table operation", page.dataset); } public run(value: RemoteObjectId): void { super.run(value); if (this.order == null) { const rr = this.remoteObject.createGetMetadataRequest(); rr.chain(this.operation); rr.invoke(new SchemaReceiver( this.page, rr, this.remoteObject, this.page.dataset!, this.meta.schema, "Schema")); } else { const table = new TableView( this.remoteObject.getRemoteObjectId()!, this.meta, this.page); table.aggregates = this.aggregates; this.page.setDataView(table); const rr = table.createNextKRequest( this.order, null, this.tableRowsDesired, this.aggregates, null); rr.chain(this.operation); rr.invoke(new NextKReceiver(this.page, table, rr, false, this.order, null)); } } } /** * Receives a result from a remote table and initiates a NextK sketch * if any result is found. */ export class FindReceiver extends OnCompleteReceiver<FindResult> { public constructor(page: FullPage, operation: ICancellable<FindResult>, protected tv: TableView, protected order: RecordOrder) { super(page, operation, "Searching for data"); } public run(result: FindResult): void { if (result.at === 0) { this.page.reportError("No other matches found."); return; } const rr = this.tv.createNextKRequest( this.order, result.firstMatchingRow, this.tv.tableRowsDesired, this.tv.aggregates, null); rr.chain(this.operation); rr.invoke(new NextKReceiver(this.page, this.tv, rr, false, this.order, result)); } }
the_stack
import { iif, patch } from '@ngxs/store/operators'; describe('[TEST]: the iif State Operator', () => { it('should return the correct implied null or undefined type', () => { iif(true, null); // $ExpectType StateOperator<null> iif(true, undefined); // $ExpectType StateOperator<undefined> iif(true, null, undefined); // $ExpectType StateOperator<null> iif(() => true, null); // $ExpectType StateOperator<null> iif(() => true, undefined); // $ExpectType StateOperator<undefined> iif(() => true, null, undefined); // $ExpectType StateOperator<null> }); it('should return the correct implied number type', () => { iif(null!, 10); // $ExpectType StateOperator<number> iif(null!, 10, 20); // $ExpectType StateOperator<number> iif(undefined!, 10); // $ExpectType StateOperator<number> iif(undefined!, 10, 20); // $ExpectType StateOperator<number> iif(true, 10); // $ExpectType StateOperator<number> iif(false, 10, 20); // $ExpectType StateOperator<number> iif(false, 10, null); // $ExpectType StateOperator<number | null> iif(false, null, 10); // $ExpectType StateOperator<number | null> iif(false, 10, undefined); // $ExpectType StateOperator<number> iif(false, undefined, 10); // $ExpectType StateOperator<number | undefined> iif(() => true, 10); // $ExpectType StateOperator<number> iif(() => false, 10, 20); // $ExpectType StateOperator<number> iif(() => false, 10, null); // $ExpectType StateOperator<number | null> iif(() => false, 10, undefined); // $ExpectType StateOperator<number> iif(val => val === 1, 10); // $ExpectType StateOperator<number> iif(val => val === 1, 10, 20); // $ExpectType StateOperator<number> iif(val => val === 1, 10, null); // $ExpectType StateOperator<number | null> iif(val => val === 1, null, 10); // $ExpectType StateOperator<number | null> iif(val => val === null, 10, null); // $ExpectType StateOperator<number | null> iif(val => val === 1, 10, undefined); // $ExpectType StateOperator<number> iif(val => val === 1, undefined, 10); // $ExpectType StateOperator<number | undefined> iif(val => val === undefined, 10, undefined); // $ExpectType StateOperator<number> }); it('should return the correct implied string type', () => { iif(null!, '10'); // $ExpectType StateOperator<string> iif(null!, '10', '20'); // $ExpectType StateOperator<string> iif(undefined!, '10'); // $ExpectType StateOperator<string> iif(undefined!, '10', '20'); // $ExpectType StateOperator<string> iif(true, '10'); // $ExpectType StateOperator<string> iif(false, '10', '20'); // $ExpectType StateOperator<string> iif(false, '10', null); // $ExpectType StateOperator<string | null> iif(false, null, '10'); // $ExpectType StateOperator<string | null> iif(false, '10', undefined); // $ExpectType StateOperator<string> iif(false, undefined, '10'); // $ExpectType StateOperator<string | undefined> iif(() => true, '10'); // $ExpectType StateOperator<string> iif(() => false, '10', '20'); // $ExpectType StateOperator<string> iif(() => false, '10', null); // $ExpectType StateOperator<string | null> iif(() => false, '10', undefined); // $ExpectType StateOperator<string> iif(val => val === '1', '10'); // $ExpectType StateOperator<string> iif(val => val === '1', '10', '20'); // $ExpectType StateOperator<string> iif(val => val === '1', '10', null); // $ExpectType StateOperator<string | null> iif(val => val === '1', null, '10'); // $ExpectType StateOperator<string | null> iif(val => val === null, '10', null); // $ExpectType StateOperator<string | null> iif(val => val === '1', '10', undefined); // $ExpectType StateOperator<string> iif(val => val === '1', undefined, '10'); // $ExpectType StateOperator<string | undefined> iif(val => val === undefined, '10', undefined); // $ExpectType StateOperator<string> }); it('should return the correct implied boolean type', () => { iif(null!, true); // $ExpectType StateOperator<boolean> iif(null!, true, false); // $ExpectType StateOperator<boolean> iif(undefined!, true); // $ExpectType StateOperator<boolean> iif(undefined!, true, false); // $ExpectType StateOperator<boolean> iif(true, true); // $ExpectType StateOperator<boolean> iif(false, true, false); // $ExpectType StateOperator<boolean> iif(false, true, null); // $ExpectType StateOperator<boolean | null> iif(false, null, true); // $ExpectType StateOperator<boolean | null> iif(false, true, undefined); // $ExpectType StateOperator<boolean> iif(false, undefined, true); // $ExpectType StateOperator<boolean | undefined> iif(() => true, true); // $ExpectType StateOperator<boolean> iif(() => false, true, false); // $ExpectType StateOperator<boolean> iif(() => false, true, null); // $ExpectType StateOperator<boolean | null> iif(() => false, true, undefined); // $ExpectType StateOperator<boolean> iif(val => val === true, true); // $ExpectType StateOperator<boolean> iif(val => val === true, true, false); // $ExpectType StateOperator<boolean> iif(val => val === true, true, null); // $ExpectType StateOperator<boolean | null> iif(val => val === true, null, true); // $ExpectType StateOperator<boolean | null> iif(val => val === null, true, null); // $ExpectType StateOperator<boolean | null> iif(val => val === true, true, undefined); // $ExpectType StateOperator<boolean> iif(val => val === true, undefined, true); // $ExpectType StateOperator<boolean | undefined> iif(val => val === undefined, true, undefined); // $ExpectType StateOperator<boolean> }); it('should return the correct implied object type', () => { iif(null!, { val: '10' }); // $ExpectType StateOperator<{ val: string; }> iif(null!, { val: '10' }, { val: '20' }); // $ExpectType StateOperator<{ val: string; }> iif(undefined!, { val: '10' }); // $ExpectType StateOperator<{ val: string; }> iif(undefined!, { val: '10' }, { val: '20' }); // $ExpectType StateOperator<{ val: string; }> iif(true, { val: '10' }); // $ExpectType StateOperator<{ val: string; }> iif(false, { val: '10' }, { val: '20' }); // $ExpectType StateOperator<{ val: string; }> iif(false, { val: '10' }, null); // $ExpectType StateOperator<{ val: string; } | null> iif(false, null, { val: '10' }); // $ExpectType StateOperator<{ val: string; } | null> iif(false, { val: '10' }, undefined); // $ExpectType StateOperator<{ val: string; }> iif(false, undefined, { val: '10' }); // $ExpectType StateOperator<{ val: string; } | undefined> iif(() => true, { val: '10' }); // $ExpectType StateOperator<{ val: string; }> iif(() => false, { val: '10' }, { val: '20' }); // $ExpectType StateOperator<{ val: string; }> iif(() => false, { val: '10' }, null); // $ExpectType StateOperator<{ val: string; } | null> iif(() => false, { val: '10' }, undefined); // $ExpectType StateOperator<{ val: string; }> iif(obj => obj!.val === '1', { val: '10' }); // $ExpectType StateOperator<{ val: string; }> iif(obj => obj!.val === '1', { val: '10' }, { val: '20' }); // $ExpectType StateOperator<{ val: string; }> iif(obj => obj!.val === '1', { val: '10' }, null); // $ExpectType StateOperator<{ val: string; } | null> iif(obj => obj!.val === '1', null, { val: '10' }); // $ExpectType StateOperator<{ val: string; } | null> iif(obj => obj === null, { val: '10' }, null); // $ExpectType StateOperator<{ val: string; } | null> iif(obj => obj!.val === '1', { val: '10' }, undefined); // $ExpectType StateOperator<{ val: string; }> iif(obj => obj!.val === '1', undefined, { val: '10' }); // $ExpectType StateOperator<{ val: string; } | undefined> iif(obj => obj === undefined, { val: '10' }, undefined); // $ExpectType StateOperator<{ val: string; }> }); it('should return the corrrect implied array type', () => { /* TODO: readonly array improvement with TS3.4 iif(null!, ['10']); // $/ExpectType (existing: string[]) => string[] iif(null!, ['10'], ['20']); // $/ExpectType (existing: string[]) => string[] iif(undefined!, ['10']); // $/ExpectType (existing: string[]) => string[] iif(undefined!, ['10'], ['20']); // $/ExpectType (existing: string[]) => string[] iif(true, ['10']); // $/ExpectType (existing: string[]) => string[] iif(false, ['10'], ['20']); // $/ExpectType (existing: string[]) => string[] iif(false, ['10'], null); // $/ExpectType (existing: string[] | null) => string[] | null iif(false, null, ['10']); // $/ExpectType (existing: string[] | null) => string[] | null iif(false, ['10'], undefined); // $/ExpectType (existing: string[] | undefined) => string[] | undefined iif(false, undefined, ['10']); // $/ExpectType (existing: string[] | undefined) => string[] | undefined iif(() => true, ['10']); // $/ExpectType (existing: string[]) => string[] iif(() => false, ['10'], ['20']); // $/ExpectType (existing: string[]) => string[] iif(() => false, ['10'], null); // $/ExpectType (existing: string[] | null) => string[] | null iif(() => false, ['10'], undefined); // $/ExpectType (existing: string[] | undefined) => string[] | undefined iif(arr => arr!.includes('1'), ['10']); // $/ExpectType (existing: string[]) => string[] iif(arr => arr!.includes('1'), ['10'], ['20']); // $/ExpectType (existing: string[]) => string[] iif(arr => arr!.includes('1'), ['10'], null); // $/ExpectType (existing: string[] | null) => string[] | null iif(arr => arr!.includes('1'), null, ['10']); // $/ExpectType (existing: string[] | null) => string[] | null iif(arr => arr === null, ['10'], null); // $/ExpectType (existing: string[] | null) => string[] | null iif(arr => arr!.includes('1'), ['10'], undefined); // $/ExpectType (existing: string[] | undefined) => string[] | undefined iif(arr => arr!.includes('1'), undefined, ['10']); // $/ExpectType (existing: string[] | undefined) => string[] | undefined iif(arr => arr === undefined, ['10'], undefined); // $/ExpectType (existing: string[] | undefined) => string[] | undefined */ }); it('should have the following valid number usages', () => { interface MyType { num: number; _num: number | null; __num?: number; } const original: MyType = { num: 1, _num: null }; patch<MyType>({ num: iif(null!, 1) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } patch<MyType>({ num: iif(null!, 2, 3) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } patch<MyType>({ num: iif(undefined!, 1) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } patch<MyType>({ num: iif(undefined!, 2, 3) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } patch<MyType>({ num: iif(() => true, 10) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } patch<MyType>({ num: iif(true, 10) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } patch<MyType>({ num: iif(val => val === 1, 10) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } patch<MyType>({ num: iif(() => false, 10, 20) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } patch<MyType>({ num: iif(false, 10, 20) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } patch<MyType>({ num: iif(val => val === 2, 10, 20) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } iif<number | null>(() => true, null)(100); // $ExpectType number | null iif<number | null>(() => false, 1)(100); // $ExpectType number | null iif<number | null>(() => false, 1, null)(100); // $ExpectType number | null // Commented out because they document an existing bug // patch<MyType>({ _num: iif(() => true, null) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } // patch<MyType>({ _num: iif(() => false, 123, null) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } iif<number | undefined>(() => true, undefined)(100); // $ExpectType number | undefined iif<number | undefined>(() => true, 1)(100); // $ExpectType number | undefined iif<number | undefined>(() => true, 1, undefined)(100); // $ExpectType number | undefined // Commented out because they document an existing bug // patch<MyType>({ __num: iif(() => true, undefined) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } // patch<MyType>({ __num: iif(() => false, 123, undefined) })(original); // $ExpectType { num: number; _num: number | null; __num?: number | undefined; } iif<MyType>(() => true, patch<MyType>({ num: 1 }))(original); // $ExpectType MyType iif<MyType>( () => true, patch<MyType>({ num: 3, _num: 4 }), patch<MyType>({ num: 5, __num: 6 }) )(original); // $ExpectType MyType patch<MyType>({ num: iif(() => false, 10, 30), _num: iif(() => true, 50, 100), __num: iif(() => true, 5, 10) })(original); // $ExpectType MyType }); it('should have the following valid string usages', () => { interface MyType { str: string; _str: string | null; __str?: string; } const original: MyType = { str: '1', _str: null }; patch<MyType>({ str: iif(null!, '1') })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } patch<MyType>({ str: iif(null!, '2', '3') })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } patch<MyType>({ str: iif(undefined!, '1') })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } patch<MyType>({ str: iif(undefined!, '2', '3') })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } patch<MyType>({ str: iif(() => true, '10') })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } patch<MyType>({ str: iif(true, '10') })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } patch<MyType>({ str: iif(val => val === '1', '10') })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } patch<MyType>({ str: iif(() => false, '10', '20') })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } patch<MyType>({ str: iif(false, '10', '20') })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } patch<MyType>({ str: iif(val => val === '2', '10', '20') })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } iif<string | null>(() => true, null)('100'); // $ExpectType string | null iif<string | null>(() => false, '1')('100'); // $ExpectType string | null iif<string | null>(() => false, '1', null)('100'); // $ExpectType string | null // Commented out because they document an existing bug // patch<MyType>({ _str: iif(() => true, null) })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } // patch<MyType>({ _str: iif(() => false, '123', null) })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } iif<string | undefined>(() => true, undefined)('100'); // $ExpectType string | undefined iif<string | undefined>(() => true, '1')('100'); // $ExpectType string | undefined iif<string | undefined>(() => true, '1', undefined)('100'); // $ExpectType string | undefined // Commented out because they document an existing bug // patch<MyType>({ __str: iif(() => true, undefined) })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } // patch<MyType>({ __str: iif(() => false, '123', undefined) })(original); // $ExpectType { str: string; _str: string | null; __str?: string | undefined; } iif<MyType>(() => true, patch<MyType>({ str: '1' }))(original); // $ExpectType MyType iif<MyType>( () => true, patch<MyType>({ str: '3', _str: '4' }), patch<MyType>({ str: '5', __str: '6' }) )(original); // $ExpectType MyType patch<MyType>({ str: iif(() => false, '10', '30'), _str: iif(() => true, '50', '100'), __str: iif(() => true, '5', '10') })(original); // $ExpectType MyType }); it('should have the following valid boolean usages', () => { interface MyType { bool: boolean; _bool: boolean | null; __bool?: boolean; } const original: MyType = { bool: true, _bool: null }; patch<MyType>({ bool: iif(null!, true) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } patch<MyType>({ bool: iif(null!, false, true) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } patch<MyType>({ bool: iif(undefined!, true) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } patch<MyType>({ bool: iif(undefined!, false, true) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } patch<MyType>({ bool: iif(() => true, true) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } patch<MyType>({ bool: iif(true, true) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } patch<MyType>({ bool: iif(val => val === true, true) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } patch<MyType>({ bool: iif(() => false, true, false) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } patch<MyType>({ bool: iif(false, true, false) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } patch<MyType>({ bool: iif(val => val === false, true, false) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } iif<boolean | null>(() => true, null)(true); // $ExpectType boolean | null iif<boolean | null>(() => false, true)(true); // $ExpectType boolean | null iif<boolean | null>(() => false, true, null)(true); // $ExpectType boolean | null // Commented out because they document an existing bug // patch<MyType>({ _bool: iif(() => true, null) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } // patch<MyType>({ _bool: iif(() => false, true, null) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } iif<boolean | undefined>(() => true, undefined)(true); // $ExpectType boolean | undefined iif<boolean | undefined>(() => true, true)(true); // $ExpectType boolean | undefined iif<boolean | undefined>(() => true, true, undefined)(true); // $ExpectType boolean | undefined // Commented out because they document an existing bug // patch<MyType>({ __bool: iif(() => true, undefined) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } // patch<MyType>({ __bool: iif(() => false, true, undefined) })(original); // $ExpectType { bool: boolean; _bool: boolean | null; __bool?: boolean | undefined; } iif<MyType>(() => true, patch<MyType>({ bool: true }))(original); // $ExpectType MyType iif<MyType>( () => true, patch<MyType>({ bool: true, _bool: false }), patch<MyType>({ bool: false, __bool: true }) )(original); // $ExpectType MyType patch<MyType>({ bool: iif(() => false, true, false), _bool: iif(() => true, false, true), __bool: iif(() => true, false, true) })(original); // $ExpectType MyType }); it('should have the following valid object usages', () => { interface MyObj { val: string; } interface MyType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj; } const original: MyType = { obj: { val: '1' }, _obj: null }; patch<MyType>({ obj: iif(null!, { val: '1' }) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } patch<MyType>({ obj: iif(null!, { val: '2' }, { val: '3' }) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } patch<MyType>({ obj: iif(undefined!, { val: '1' }) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } patch<MyType>({ obj: iif(undefined!, { val: '2' }, { val: '3' }) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } patch<MyType>({ obj: iif(() => true, { val: '10' }) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } patch<MyType>({ obj: iif(true, { val: '10' }) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } patch<MyType>({ obj: iif(obj => obj!.val === '1', { val: '10' }) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } patch<MyType>({ obj: iif(() => false, { val: '10' }, { val: '20' }) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } patch<MyType>({ obj: iif(false, { val: '10' }, { val: '20' }) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } patch<MyType>({ obj: iif(obj => obj!.val === '2', { val: '10' }, { val: '20' }) })(original); // $ExpectType MyType iif<MyObj | null>(() => true, null)({ val: '100' }); // $ExpectType MyObj | null iif<MyObj | null>(() => false, { val: '1' })({ val: '100' }); // $ExpectType MyObj | null iif<MyObj | null>(() => false, { val: '1' }, null)({ val: '100' }); // $ExpectType MyObj | null // Commented out because they document an existing bug // patch<MyType>({ _obj: iif(() => true, null) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } // patch<MyType>({ _obj: iif(() => false, { val: '123' }, null) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } iif<MyObj | undefined>(() => true, undefined)({ val: '100' }); // $ExpectType MyObj | undefined iif<MyObj | undefined>(() => true, { val: '1' })({ val: '100' }); // $ExpectType MyObj | undefined iif<MyObj | undefined>(() => true, { val: '1' }, undefined)({ val: '100' }); // $ExpectType MyObj | undefined // Commented out because they document an existing bug // patch<MyType>({ __obj: iif(() => true, undefined) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } // patch<MyType>({ __obj: iif(() => false, { val: '123' }, undefined) })(original); // $ExpectType { obj: MyObj; _obj: MyObj | null; __obj?: MyObj | undefined; } iif<MyType>(() => true, patch<MyType>({ obj: { val: '1' } }))(original); // $ExpectType MyType iif<MyType>( () => true, patch<MyType>({ obj: { val: '3' }, _obj: { val: '4' } }), patch<MyType>({ obj: { val: '5' }, __obj: { val: '6' } }) )(original); // $ExpectType MyType patch<MyType>({ obj: iif(() => false, { val: '10' }, { val: '30' }), _obj: iif(() => true, { val: '50' }, { val: '100' }), __obj: iif(() => true, { val: '5' }, { val: '10' }) })(original); // $ExpectType MyType }); it('should have the following valid complex usage', () => { interface Person { name: string; lastName?: string; nickname?: string; } interface Greeting { motivated?: boolean; person: Person; } interface Model { a: number; b: { hello?: Greeting; goodbye?: Greeting; greeting?: string; }; c?: number; } const original: Model = { a: 1, b: { hello: { person: { name: 'you' } }, goodbye: { person: { name: 'Artur' } } } }; /* !>TS3.4! patch<Model>({ b: iif<Model['b']>( b => typeof b!.hello === 'object', patch<Model['b']>({ hello: patch({ motivated: iif(motivated => motivated !== true, true), person: patch({ name: 'Artur', lastName: 'Androsovych' }) }), greeting: 'How are you?' }) ), c: iif(c => c !== 100, () => 0 + 100, 10) })(original); // $/ExpectType Model patch<Model>({ b: patch<Model['b']>({ hello: patch<Greeting>({ motivated: iif(motivated => motivated !== true, true), person: patch({ name: iif(name => name !== 'Mark', 'Artur'), lastName: iif(lastName => lastName !== 'Whitfeld', 'Androsovych') }) }), greeting: iif(greeting => !greeting, 'How are you?') }), c: iif(c => !c, 100, 10) })(original); // $/ExpectType Model */ }); it('should not accept the following usages', () => { interface MyType { num: number; _num: number | null; __num?: number; str: string; _str: string | null; __str?: string; bool: boolean; _bool: boolean | null; __bool?: boolean; } const original: MyType = { num: 1, _num: null, str: '2', _str: null, bool: true, _bool: null }; patch<MyType>({ num: iif(true, '1') })(original); // $ExpectError patch<MyType>({ num: iif(true, {}) })(original); // $ExpectError patch<MyType>({ _num: iif(true, '1') })(original); // $ExpectError patch<MyType>({ _num: iif(true, undefined) })(original); // $ExpectError patch<MyType>({ __num: iif(true, '1') })(original); // $ExpectError patch<MyType>({ __num: iif(true, null) })(original); // $ExpectError patch<MyType>({ str: iif(true, 1) })(original); // $ExpectError patch<MyType>({ str: iif(true, {}) })(original); // $ExpectError patch<MyType>({ _str: iif(true, 1) })(original); // $ExpectError patch<MyType>({ _str: iif(true, undefined) })(original); // $ExpectError patch<MyType>({ __str: iif(true, 1) })(original); // $ExpectError patch<MyType>({ __str: iif(true, null) })(original); // $ExpectError patch<MyType>({ bool: iif(true, '1') })(original); // $ExpectError patch<MyType>({ bool: iif(true, {}) })(original); // $ExpectError patch<MyType>({ _bool: iif(true, '1') })(original); // $ExpectError patch<MyType>({ _bool: iif(true, undefined) })(original); // $ExpectError patch<MyType>({ __bool: iif(true, '1') })(original); // $ExpectError patch<MyType>({ __bool: iif(true, null) })(original); // $ExpectError }); });
the_stack
import { DataFrame, DataQueryRequest, Field, FieldConfig, FieldDTO, FieldType, getTimeField, MISSING_VALUE, MutableDataFrame, MutableField, ScopedVars, } from '@grafana/data'; import { getTemplateSrv } from '@grafana/runtime'; import { every, isString, mapValues } from 'lodash'; import { Context, Indom, InstanceId, Metadata } from '../../../common/services/pmapi/types'; import { GenericError } from '../../../common/types/errors'; import { Labels, Semantics } from '../../../common/types/pcp'; import { TargetFormat } from '../types'; import { applyFieldTransformations } from './field_transformations'; import { Metric, QueryResult } from './poller/types'; import { MinimalPmapiQuery, PmapiQuery } from './types'; interface FrameCustom { context: Context; query: PmapiQuery; metric: Metric; } interface FieldCustom { instanceId: InstanceId | null; instance?: Indom; } function getFieldName(metric: Metric, instanceId: InstanceId | null) { const metricName = metric.metadata.name; if (!metric.instanceDomain || instanceId === null) { return metricName; } const instanceName = metric.instanceDomain.instances[instanceId]?.name ?? instanceId; return `${metricName}[${instanceName}]`; } const pcpNumberTypes = ['32', 'u32', '64', 'u64', 'float', 'double']; function getFieldType(metadata: Metadata): FieldType { if (pcpNumberTypes.includes(metadata.type)) { return FieldType.number; } else if (metadata.type === 'string') { return FieldType.string; } else { return FieldType.other; } } function getLabels(context: Context, metric: Metric, instanceId: InstanceId | null): Labels { let labels = { ...context.labels, ...metric.metadata.labels, ...metric.instanceDomain?.labels, }; if (metric.instanceDomain && instanceId != null && instanceId in metric.instanceDomain.instances) { Object.assign(labels, metric.instanceDomain.instances[instanceId]!.labels); } return labels; } function getFieldUnit(metadata: Metadata): string | undefined { // pcp/src/libpcp/src/units.c // grafana-data/src/valueFormats/categories.ts switch (metadata.units) { case 'nanosec': return 'ns'; case 'microsec': return 'µs'; case 'millisec': return 'ms'; case 'sec': return 's'; case 'min': return 'm'; case 'hour': return 'h'; } if (metadata.sem === Semantics.Counter) { switch (metadata.units) { case 'byte': return 'binBps'; case 'Kbyte': return 'KiBs'; case 'Mbyte': return 'MiBs'; case 'Gbyte': return 'GiBs'; case 'Tbyte': return 'TiBs'; case 'Pbyte': return 'PiBs'; } } else { switch (metadata.units) { case 'byte': return 'bytes'; case 'Kbyte': return 'kbytes'; case 'Mbyte': return 'mbytes'; case 'Gbyte': return 'gbytes'; case 'Tbyte': return 'tbytes'; case 'Pbyte': return 'pbytes'; } } return undefined; } function getFieldDisplayName( scopedVars: ScopedVars, context: Context, query: PmapiQuery, metric: Metric, instanceId: InstanceId | null ) { if (!query.legendFormat) { return ''; } const vars = getLabels(context, metric, instanceId); const spl = metric.metadata.name.split('.'); vars['expr'] = query.expr; vars['metric'] = metric.metadata.name; vars['metric0'] = spl[spl.length - 1]; if (metric.instanceDomain && instanceId != null && instanceId in metric.instanceDomain.instances) { vars['instance'] = metric.instanceDomain.instances[instanceId]!.name; } return getTemplateSrv().replace(query.legendFormat, { ...mapValues(vars, value => ({ text: value, value })), ...scopedVars, }); } function createField( scopedVars: ScopedVars, context: Context, query: PmapiQuery, metric: Metric, instanceId: InstanceId | null ): FieldDTO & { config: FieldConfig<FieldCustom> } { let instance: Indom | undefined; if (metric.instanceDomain && instanceId !== null) { instance = metric.instanceDomain.instances[instanceId]; } const config: FieldConfig<FieldCustom> = { displayNameFromDS: getFieldDisplayName(scopedVars, context, query, metric, instanceId), custom: { instanceId: instanceId, instance, }, }; const unit = getFieldUnit(metric.metadata); if (unit) { config.unit = unit; } return { name: getFieldName(metric, instanceId), type: getFieldType(metric.metadata), labels: getLabels(context, metric, instanceId), config, }; } function createDataFrame( request: DataQueryRequest<MinimalPmapiQuery>, context: Context, query: PmapiQuery, metric: Metric, sampleIntervalSec: number ) { // fill the graph by requesting more data (+/- 1 interval) let requestRangeFromMs = request.range.from.valueOf() - sampleIntervalSec * 1000; let requestRangeToMs = request.range.to.valueOf() + sampleIntervalSec * 1000; // the first value of a counter metric is lost due to rate conversion if (metric.metadata.sem === Semantics.Counter) { requestRangeFromMs -= sampleIntervalSec * 1000; } const frame = new MutableDataFrame(); frame.meta = { custom: { context, query, metric, }, }; const timeField = frame.addField({ name: 'Time', type: FieldType.time }); const instanceIdToField = new Map<InstanceId | null, MutableField>(); for (const snapshot of metric.values) { if (!(requestRangeFromMs <= snapshot.timestampMs && snapshot.timestampMs <= requestRangeToMs)) { continue; } // create all dataFrame fields in one go, because Grafana automatically matches // the vector length of newly created fields with already existing fields by adding empty data for (const instanceValue of snapshot.values) { if (instanceIdToField.has(instanceValue.instance)) { continue; } const field = frame.addField( createField(request.scopedVars, context, query, metric, instanceValue.instance) ); instanceIdToField.set(instanceValue.instance, field); } timeField.values.add(snapshot.timestampMs); for (const instanceValue of snapshot.values) { let field = instanceIdToField.get(instanceValue.instance)!; // make sure a field doesn't grow larger than the time field // in case an instance has two values for the same timestamp (should not happen) if (field.values.length < timeField.values.length) { field.values.add(instanceValue.value); } } // some instance existed previously but disappeared -> fill field with MISSING_VALUE for (const field of instanceIdToField.values()) { if (timeField.values.length > field.values.length) { field.values.add(MISSING_VALUE); } } } if (frame.fields.length < 2) { // no actual data available, only time field return null; } applyFieldTransformations(query, metric.metadata, frame); return frame; } function getHeatMapDisplayName(field: Field) { // target name is the upper bound const instanceName = (field.config.custom as FieldCustom).instance?.name; if (instanceName) { // instance name can be -1024--512, -512-0, 512-1024, ... const match = instanceName.match(/^(.+?)\-(.+?)$/); if (match) { return match[2]; } } return '0-0'; } function transformToHeatMap(frame: MutableDataFrame) { const { timeField } = getTimeField(frame) as { timeField?: MutableField }; if (!timeField) { return; } for (const field of frame.fields) { if (field.type === FieldType.number) { field.config.displayNameFromDS = getHeatMapDisplayName(field); } } for (let i = 0; i < timeField.values.length; i++) { // round timestamps to one second, the heatmap panel calculates the x-axis size accordingly timeField.values.set(i, Math.floor(timeField.values.get(i) / 1000) * 1000); } } /** * transform a list of data frames to a table with metric names as columns and instances as rows * instances are grouped over multiple metrics */ function transformToMetricsTable(scopedVars: ScopedVars, frames: DataFrame[]) { const tableFrame = new MutableDataFrame(); tableFrame.addField({ name: 'instance', type: FieldType.string, }); let instanceColumn: Map<InstanceId | null, string> = new Map(); for (const frame of frames) { const { context, query, metric } = frame.meta!.custom as FrameCustom; const metricSpl = metric.metadata.name.split('.'); const newField = createField(scopedVars, context, query, metric, null); if (!newField.config.displayNameFromDS) { newField.config.displayNameFromDS = metricSpl[metricSpl.length - 1]; } tableFrame.addField(newField); if (frame.length === 0) { continue; } for (const field of frame.fields) { const lastValue = field.values.get(field.values.length - 1); if (field.type === FieldType.time || lastValue === MISSING_VALUE) { continue; } const instanceId = (field.config.custom as FieldCustom).instanceId; const instance = (field.config.custom as FieldCustom).instance; if (!instanceColumn.has(instanceId)) { instanceColumn.set(instanceId, instance?.name ?? ''); } } } /** * table is filled row-by-row * outer loop loops over table rows (instances) * inner loop loops over table columns (metrics), and writes the last value of the specific instance of a metric */ for (const [instanceId, instanceName] of instanceColumn.entries()) { let fieldIdx = 0; tableFrame.fields[fieldIdx].values.add(instanceName); fieldIdx++; for (const frame of frames) { const field = frame.fields.find( field => field.type !== FieldType.time && (field.config.custom as FieldCustom).instanceId === instanceId ); if (field) { const lastValue = field.values.get(field.values.length - 1); tableFrame.fields[fieldIdx].values.add(lastValue); } else { tableFrame.fields[fieldIdx].values.add(MISSING_VALUE); } fieldIdx++; } } return tableFrame; } function* parseCsvLine(line: string) { let quote = ''; let record = ''; for (const char of line) { // no quotation if (quote.length === 0) { if (char === '"' || char === "'") { // start quotation quote = char; } else if (char === ',') { yield record; record = ''; } else { record += char; } } // inside quotation else { if (char === quote) { // end quotation quote = ''; } else { record += char; } } } if (record.length > 0) { yield record; } } function transformToCsvTable(frames: DataFrame[]) { let tableText = ''; if (frames.length === 1 && frames[0].length > 0) { for (const field of frames[0].fields) { if (field.type !== FieldType.time) { const lastValue = field.values.get(field.values.length - 1); if (isString(lastValue) && lastValue.includes(',')) { tableText = lastValue; } } } } const tableFrame = new MutableDataFrame(); const lines = tableText.split('\n'); for (let line of lines) { line = line.trim(); if (line.length === 0) { continue; } if (tableFrame.fields.length === 0) { const header = Array.from(parseCsvLine(line)); for (const title of header) { tableFrame.addField({ name: title, type: FieldType.string }); } } else { const row = Array.from(parseCsvLine(line)); for (let i = 0; i < tableFrame.fields.length; i++) { tableFrame.fields[i].values.add(row[i]); } } } return tableFrame; } export function processQueries( request: DataQueryRequest<MinimalPmapiQuery>, queryResults: QueryResult[], sampleIntervalSec: number ): DataFrame[] { if (queryResults.length === 0) { return []; } const format = queryResults[0].query.format; if (!every(queryResults, result => result.query.format === format)) { throw new GenericError('Format must be the same for all queries of a panel.'); } const frames = queryResults.flatMap( queryResult => queryResult.metrics .map(metric => createDataFrame(request, queryResult.endpoint.context, queryResult.query, metric, sampleIntervalSec) ) .filter(frame => frame !== null) as MutableDataFrame[] ); switch (format) { case TargetFormat.TimeSeries: case TargetFormat.FlameGraph: return frames; case TargetFormat.Heatmap: frames.forEach(transformToHeatMap); return frames; case TargetFormat.MetricsTable: return [transformToMetricsTable(request.scopedVars, frames)]; case TargetFormat.CsvTable: return [transformToCsvTable(frames)]; default: throw new GenericError(`Invalid target format '${format}'`); } }
the_stack
import * as React from 'react'; import { FixedSizeList as List, ListOnScrollProps } from 'react-window'; import ResizeObserver from 'rc-resize-observer'; import classNames from 'classnames'; import { compact } from 'lodash'; import { useIntl } from 'react-intl'; import Button from '@synerise/ds-button'; import { ScrollbarProps } from '@synerise/ds-scrollbar/dist/Scrollbar.types'; import Tooltip from '@synerise/ds-tooltip'; import Scrollbar from '@synerise/ds-scrollbar'; import { infiniteLoaderItemHeight } from '../InfiniteScroll/constants'; import BackToTopButton from '../InfiniteScroll/BackToTopButton'; import DSTable from '../Table'; import { RowType, DSTableProps } from '../Table.types'; import VirtualTableRow from './VirtualTableRow'; import { RelativeContainer } from './VirtualTable.styles'; import { Props } from './VirtualTable.types'; import useRowStar from '../hooks/useRowStar'; import { useTableLocale } from '../utils/locale'; import { calculatePixels } from '../utils/calculatePixels'; export const EXPANDED_ROW_PROPERTY = 'expandedChild'; const relativeInlineStyle: React.CSSProperties = { position: 'relative' }; const CustomScrollbar = (containerRef: React.RefObject<HTMLDivElement>): React.FC => React.forwardRef<HTMLElement, React.HTMLAttributes<Element>>( ({ onScroll, children, style }, ref): React.ReactElement => { const [header, setHeader] = React.useState<HTMLDivElement | null>(null); React.useEffect(() => { if (containerRef?.current) { const headerElement = containerRef.current.querySelector<HTMLDivElement>('.ant-table-header'); headerElement && setHeader(headerElement); } }, []); const onScrollHandler: ScrollbarProps['onScroll'] = React.useCallback( e => { if (header) { header.scrollTo({ left: e.currentTarget.scrollLeft }); } onScroll && onScroll(e); }, [onScroll, header] ); return ( <Scrollbar ref={ref} onScroll={onScrollHandler} absolute maxHeight={style?.height}> {children} </Scrollbar> ); } ); // eslint-disable-next-line @typescript-eslint/no-explicit-any function VirtualTable<T extends any & RowType<T> & { [EXPANDED_ROW_PROPERTY]?: boolean }>( props: Props<T> ): React.ReactElement { const { columns = [], scroll, className, cellHeight = 52, infiniteScroll, selection, onRowClick, rowKey, rowStar, initialWidth = 0, dataSource = [], expandable, locale, onListRefChange, } = props; const intl = useIntl(); const tableLocale = useTableLocale(intl, locale); const listRef = React.useRef<List>(null); const containerRef = React.useRef<HTMLDivElement>(null); const [tableWidth, setTableWidth] = React.useState(initialWidth); const { getRowStarColumn } = useRowStar(rowStar?.starredRowKeys || []); React.useEffect(() => { onListRefChange && onListRefChange(listRef); }, [listRef, onListRefChange]); const propsForRowStar = { ...props, rowStar: { ...rowStar, onClick: (e): void => { e.stopPropagation(); if (typeof rowStar?.onClick === 'function') { rowStar.onClick(e); } }, }, locale: tableLocale, } as Props<T>; const rowStarColumn = getRowStarColumn(propsForRowStar); const getRowKey = React.useCallback( (row: T): React.ReactText | undefined => { if (typeof rowKey === 'function') return rowKey(row); if (typeof rowKey === 'string') return row[rowKey]; return undefined; }, [rowKey] ); // eslint-disable-next-line @typescript-eslint/no-explicit-any const virtualColumns = React.useMemo((): any[] => { return compact([ !!selection && { width: 64, key: 'key', dataIndex: 'key', render: (key: string, record: T): React.ReactNode => { const recordKey = getRowKey(record); const allChildsChecked = // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) Array.isArray(record.children) && // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) record.children?.filter((child: T) => { const childKey = getRowKey(child); return childKey && selection?.selectedRowKeys.indexOf(childKey) < 0; }).length === 0; const checkedChilds = // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) record.children?.filter((child: T) => { const childKey = getRowKey(child); return childKey && selection?.selectedRowKeys.indexOf(childKey) >= 0; }) || []; const isIndeterminate = // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) Array.isArray(record.children) && checkedChilds.length > 0 && // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) checkedChilds.length < (record.children?.length || 0); const checked = (recordKey !== undefined && selection.selectedRowKeys && selection.selectedRowKeys.indexOf(recordKey) >= 0) || allChildsChecked; return ( recordKey !== undefined && ( <Tooltip title={tableLocale?.selectRowTooltip} mouseLeaveDelay={0}> <Button.Checkbox key={`checkbox-${recordKey}`} checked={checked} disabled={!checked && Boolean(selection.limit && selection.limit <= selection.selectedRowKeys.length)} indeterminate={isIndeterminate} onClick={(e): void => { e.stopPropagation(); }} onChange={(isChecked): void => { const { selectedRowKeys, onChange } = selection; let selectedRows: T[] = []; dataSource && dataSource.forEach((row: T): void => { // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) if (row.children !== undefined && Array.isArray(row.children)) { // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) row.children.forEach((child: T) => { const k = getRowKey(child); if (k && selectedRowKeys.indexOf(k) >= 0) { selectedRows = [...selectedRows, child]; } }); } else { const k = getRowKey(row); if (k && selectedRowKeys.indexOf(k) >= 0) { selectedRows = [...selectedRows, row]; } } }); if (isChecked) { // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) if (Array.isArray(record.children)) { // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) selectedRows = [...selectedRows, ...record.children]; } else { selectedRows = [...selectedRows, record]; } // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) } else if (Array.isArray(record.children)) { // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) const childsKeys = record.children.map((child: T) => getRowKey(child)); selectedRows = selectedRows.filter(child => childsKeys.indexOf(getRowKey(child)) < 0); } else { selectedRows = selectedRows.filter(row => getRowKey(row) !== recordKey); } selectedRows = [...new Set(selectedRows)]; onChange && onChange( selectedRows.map(selected => getRowKey(selected) as React.ReactText), selectedRows ); }} /> </Tooltip> ) ); }, }, !!rowStar && rowStarColumn, ...columns, ]); }, [columns, selection, rowStar, rowStarColumn, getRowKey, dataSource, tableLocale]); const mergedColumns = React.useMemo(() => { const widthColumnCount = virtualColumns.filter(({ width }) => !width).length; const rowWidth = tableWidth || initialWidth; const definedWidth = virtualColumns .filter(({ width }) => width) .reduce((total: number, { width }): number => total + width, 0); return virtualColumns?.map(column => { if (column.width) { return { ...column, width: calculatePixels(column.width), }; } return { ...column, width: Math.floor((rowWidth - definedWidth) / widthColumnCount), }; }); }, [virtualColumns, tableWidth, initialWidth]); const listInnerElementType = React.forwardRef<HTMLDivElement>( ({ style, ...rest }: React.HTMLAttributes<HTMLDivElement>, ref) => ( <div ref={ref} style={{ ...style, height: `${Number(style?.height) + infiniteLoaderItemHeight}px`, }} {...rest} /> ) ); const handleBackToTopClick = (): void => { if (!listRef.current) { return; } listRef.current.scrollTo(0); }; const outerElement = React.useMemo(() => CustomScrollbar(containerRef), [containerRef]); const renderBody = (rawData: T[], meta: unknown, defaultTableProps?: DSTableProps<T>): React.ReactNode => { const renderVirtualList = (data: T[]): React.ReactNode => { const listHeight = data.length * cellHeight - scroll.y + infiniteLoaderItemHeight; const handleListScroll = ({ scrollOffset, scrollDirection }: ListOnScrollProps): void => { if ( scrollDirection === 'forward' && scrollOffset >= listHeight && typeof infiniteScroll?.onScrollEndReach === 'function' ) { infiniteScroll.onScrollEndReach(); } if ( scrollDirection === 'backward' && scrollOffset === 0 && typeof infiniteScroll?.onScrollTopReach === 'function' ) { infiniteScroll.onScrollTopReach(); } }; return ( <List ref={listRef} onScroll={handleListScroll} className="virtual-grid" height={scroll.y} itemCount={data.length} itemSize={cellHeight} width="100%" itemData={{ mergedColumns, selection, onRowClick, dataSource: data, infiniteScroll, cellHeight, defaultTableProps, }} itemKey={(index): string => { return String(getRowKey(data[index])); }} outerElementType={outerElement} overscanCount={1} innerElementType={infiniteScroll && listInnerElementType} > {VirtualTableRow} </List> ); }; if (expandable?.expandedRowKeys?.length) { const expandedRows = rawData.reduce((result: T[], currentRow: T) => { const key = getRowKey(currentRow); if ( key !== undefined && expandable?.expandedRowKeys?.includes(key) && // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) Array.isArray(currentRow.children) && // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) currentRow.children.length ) { return [ ...result, currentRow, // @ts-expect-error: Property 'children' does not exist on type 'T'.ts(2339) ...currentRow.children.map((child: T) => ({ ...child, [EXPANDED_ROW_PROPERTY]: true })), ]; } return [...result, currentRow]; }, []); return renderVirtualList(expandedRows); } return renderVirtualList(rawData); }; const columnsSliceStartIndex = Number(!!selection) + Number(!!rowStar); return ( <RelativeContainer key="relative-container" ref={containerRef} style={relativeInlineStyle}> <ResizeObserver onResize={({ offsetWidth }): void => { setTableWidth(offsetWidth); }} > <DSTable {...props} className={classNames(className, 'virtual-table', !!infiniteScroll && 'virtual-table-infinite-scroll')} // Remove columns which cause header columns indent columns={mergedColumns.slice(columnsSliceStartIndex)} pagination={false} components={{ body: renderBody, }} locale={tableLocale} /> </ResizeObserver> {!!infiniteScroll?.showBackToTopButton && ( <BackToTopButton onClick={handleBackToTopClick}>{tableLocale.infiniteScrollBackToTop}</BackToTopButton> )} </RelativeContainer> ); } export default VirtualTable;
the_stack
import { ref } from '@vue/composition-api'; import { StrictEventEmitter, addEventListener } from '@/lib/events'; import { getLogger } from '@/lib/log'; export type Direction = 'horizontal' | 'vertical'; export const isSplit = (vue: any): vue is { i: Section } => { return vue.$options.name === 'Split'; }; // tslint:disable-next-line:interface-over-type-literal type SplitEvents = { height: [number]; width: [number]; resize: [number]; collapsed: [boolean]; }; export type SectionMode = 'low' | 'high' | 'fixed'; export interface SectionOpts { name?: string; collapsible?: boolean; minSize?: number; collapsePixels?: number; direction?: Direction; initial?: number; mode?: SectionMode; collapsed?: boolean; } const logger = getLogger('split'); export class Section { public static DEBUG = false; public parent: null | Section = null; public direction: Direction | undefined; public readonly name?: string; private gutter = ref(false); private disabled = false; private width = 0; private height = 0; private minSize: number; private children: Section[] = []; private toDispose: Array<{ dispose: () => void }> = []; private mode: SectionMode; private collapsible: boolean; private collapsed: boolean; private collapsePixels: number; private initial: number | undefined; private events = new StrictEventEmitter<SplitEvents>(); // tslint:disable-next-line:member-ordering public addListeners = this.events.addListeners.bind(this.events); constructor(o: SectionOpts = {}) { this.minSize = o.minSize || 15; this.collapsible = !!o.collapsible; this.name = o.name; this.collapsePixels = o.collapsePixels || 10; this.direction = o.direction; this.initial = o.initial; this.mode = o.mode || 'high'; this.collapsed = !!o.collapsed; } get sizes() { return { height: this.height, width: this.width, }; } get isCollapsed() { return this.collapsed; } get isGutter() { return this.gutter.value; } public setParent(parent: Section) { this.parent = parent; parent.children.push(this); } public siblings() { if (!this.parent) { return { before: [], after: [], }; } const i = this.parent.children.indexOf(this); const before = this.parent.children.slice(0, i).reverse(); const after = this.parent.children.slice(i); if (i === -1) { return { before: [], after: [], }; } return { before, after, }; } public move(px: number) { if (!this.parent || !this.parent.direction || px === 0) { return; } const i = this.parent.children.indexOf(this); if (i === -1) { return; } const attr = this.parent.direction === 'horizontal' ? 'width' : 'height' as const; const { before, after } = this.siblings(); let shrinking: Section[]; let growing: Section[]; if (px < 0) { shrinking = before; growing = after; } else { shrinking = after; growing = before; } const move = (sections: Section[], toMoveInner: number) => { let totalMoved = 0; totalMoved += this.iterate(sections, attr, toMoveInner, 'high'); totalMoved += this.iterate(sections, attr, toMoveInner - totalMoved, 'low'); totalMoved += this.iterate(sections, attr, toMoveInner - totalMoved, 'collapse'); return totalMoved; }; // When growing, if something un-collapses, then we need to run everything again const shrunk = move(shrinking, -Math.abs(px)); let toMove = -shrunk; while (true) { const change = move(growing, toMove); toMove -= change; if (change === 0 || toMove <= 0) { break; } } // A bit of a hack but this works for now move(shrinking, toMove); } public collapse() { this.collapseHelper({ mode: 'collapse' }); } public unCollapse(size: number) { this.collapseHelper({ mode: 'un-collapse', size }); } public init(sizes?: { height: number, width: number }) { if (!sizes) { if (this.parent) { return; } sizes = { height: window.innerHeight, width: window.innerWidth, }; } // tslint:disable-next-line:no-unused-expression Section.DEBUG && logger.debug( `[INIT${this.direction ? ', ' + this.direction.padEnd(10) : ''}] ${this.name ? this.name.padEnd(5) : 'None '}| ` + `height -> ${sizes.height.toString().padEnd(4)}, width -> ${sizes.width.toString().padEnd(4)}`, ); this.set('height', sizes.height, false); this.set('width', sizes.width, false); // There will never be a gutter for the first element // This logic may not be right but we are putting a gutter on any divider that doesn't touch a "fixed" split this.children.slice(1).forEach((_, i) => { this.children[i + 1].gutter.value = this.children[i].mode !== 'fixed' && this.children[i + 1].mode !== 'fixed'; }); const initialSum = this.children.reduce((sum, curr) => { return sum + (curr.collapsed ? 0 : curr.initial ? curr.initial : 0); }, 0); const total = this.direction === 'horizontal' ? this.width : this.height; const remaining = total - initialSum; const notFixed = this.children.filter((child) => child.initial === undefined && child.collapsed === false); const size = remaining / notFixed.length; this.children.forEach((split) => { const splitSize = split.collapsed ? 0 : split.initial !== undefined ? split.initial : size; // Set the opposite values // e.g. if the direction is "horizontal" set the height if (this.direction === 'horizontal') { split.init({ height: this.height, width: splitSize, }); } else { split.init({ height: splitSize, width: this.width, }); } }); this.toDispose.push(this.addListeners({ height: () => this.resize({ direction: 'vertical' }), width: () => this.resize({ direction: 'horizontal' }), })); if (this.parent === null) { this.toDispose.push(addEventListener('resize', () => { this.set('width', window.innerWidth); this.set('height', window.innerHeight); })); } } public resize({ direction }: { direction: Direction }) { const attr = direction === 'horizontal' ? 'width' : 'height' as const; const oldSize = this.children.reduce((sum, child) => sum + child[attr], 0); let px = this[attr] - oldSize; if (this.direction !== direction) { this.children.forEach((child) => { const newSize = this[attr]; // tslint:disable-next-line:no-unused-expression Section.DEBUG && logger.debug( `[PROP, ${attr}] ${child.name} ` + `from ${child[attr].toString().padEnd(3)} -> ${newSize.toString().padEnd(3)}`, ); child.set(attr, newSize); }); return; } px -= this.iterate(this.children, attr, px, 'high'); px -= this.iterate(this.children, attr, px, 'low'); // this.iterate(this.children, attr, px, 'fixed'); } public dispose() { this.toDispose.forEach(({ dispose }) => dispose()); this.toDispose = []; } /** * Just a helper method which emits the appropriate events. * * @param attr * @param value * @param emit Whether to emit the "resize" event. We set this to false during initialization. */ public set(attr: 'height' | 'width', value: number, emit: boolean = true) { this[attr] = value; this.events.emit(attr, value); if ( !this.parent || !this.parent.direction || this.disabled ) { return; } if (!emit) { return; } if (attr === 'height' && this.parent.direction === 'vertical') { this.events.emit('resize', value); } else if (attr === 'width' && this.parent.direction === 'horizontal') { this.events.emit('resize', value); } } private setCollapsed(value: boolean) { this.collapsed = value; this.events.emit('collapsed', value); } private collapseHelper(opts: { mode: 'collapse' } | { mode: 'un-collapse', size: number }) { const mode = opts.mode; if ( (mode === 'collapse' && this.collapsed) || (mode === 'un-collapse' && !this.collapsed) || !this.parent ) { return; } const { before, after } = this.siblings(); if (before.length === 0 && after.length === 0) { return; } const attr = this.parent.direction === 'horizontal' ? 'width' : 'height' as const; const noBeforeMultiple = mode === 'collapse' ? -1 : 1; const hasBeforeMultiple = mode === 'un-collapse' ? -1 : 1; this.withDisabled(() => { const amount = Math.max(this[attr], this.minSize, opts.mode === 'un-collapse' ? opts.size : 0); // after.length will never be 0 if (after.length === 1) { this.move(amount * hasBeforeMultiple); } else { const rightAfter = after[1]; rightAfter.move(amount * noBeforeMultiple); } }); } private withDisabled(cb: () => void) { this.disabled = true; try { cb(); } finally { this.disabled = false; } } private iterate( sections: Section[], attr: 'height' | 'width', toMove: number, mode: 'low' | 'high' | 'fixed' | 'collapse', ) { let moved = 0; for (const section of sections) { if ( (mode === 'high' || mode === 'low' || mode === 'fixed') && (mode !== section.mode || section.collapsed)) { continue; } if (toMove === 0) { break; } let newSize = section[attr]; if (mode === 'high' || mode === 'low' || mode === 'fixed') { newSize = Math.max(section.minSize, section[attr] + toMove); if (newSize === section[attr]) { continue; } } else { if ( section.collapsible && !section.collapsed && toMove < -section.collapsePixels ) { section.setCollapsed(true); newSize = 0; } else if ( section.collapsible && section.collapsed && toMove >= section.minSize ) { section.setCollapsed(false); newSize = section.minSize; } else { continue; } } // tslint:disable-next-line:no-unused-expression Section.DEBUG && logger.debug( `[${mode.padEnd(6)}][${attr}] ${section.name} ` + `from ${section[attr].toString().padEnd(3)} -> ${newSize.toString().padEnd(3)}`, ); const diff = newSize - section[attr]; section.set(attr, newSize); toMove -= diff; moved += diff; } return moved; } }
the_stack
* This file contains lots of methods for accessing the remote TableTarget.java class. */ import {DatasetView, IViewSerialization} from "./datasetView"; import { AggregateDescription, BasicColStats, BucketsInfo, CombineOperators, CompareDatasetsInfo, ComparisonFilterDescription, CountWithConfidence, EigenVal, FindResult, Groups, HeavyHittersFilterInfo, HistogramRequestInfo, IColumnDescription, CreateColumnJSMapInfo, JSFilterInfo, kindIsString, ExtractValueFromKeyMapInfo, NextKArgs, NextKList, QuantilesMatrixInfo, QuantilesVectorInfo, RangeFilterArrayDescription, RecordOrder, RemoteObjectId, RowFilterDescription, SampleSet, Schema, StringColumnFilterDescription, StringColumnsFilterDescription, StringFilterDescription, TopList, CreateIntervalColumnMapInfo, HeatmapRequestInfo, RowValue, MapAndColumnRepresentation, FilterListDescription, TableMetadata, RenameArgs, ExplodeColumnsInfo } from "./javaBridge"; import {OnCompleteReceiver, RemoteObject, RpcRequest} from "./rpc"; import {FullPage, PageTitle} from "./ui/fullPage"; import {HtmlString, PointSet, Resolution, SpecialChars, ViewKind} from "./ui/ui"; import { assert, assertNever, ICancellable, Pair, Seed, significantDigitsHtml, Two, zip } from "./util"; import {IDataView} from "./ui/dataview"; import {SchemaClass} from "./schemaClass"; import {PlottingSurface} from "./ui/plottingSurface"; import {CommonArgs, TableMeta} from "./ui/receiver"; import {SubMenu, TopMenuItem} from "./ui/menu"; /** * An interface which has a function that is called when all updates are completed. */ export interface CompletedWithTime { updateCompleted(timeInMs: number): void; } export interface OnNextK extends CompletedWithTime { updateView(nextKList: NextKList, revert: boolean, order: RecordOrder | null, result: FindResult | null): void; } /** * This class has methods that correspond directly to TableTarget.java methods. */ export class TableTargetAPI extends RemoteObject { /** * Create a reference to a remote table target. * @param remoteObjectId Id of remote table on the web server. */ constructor(remoteObjectId: RemoteObjectId) { super(remoteObjectId); } public createMergeRequest(r: RemoteObjectId): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("mergeWith", [r]); } public createSetRequest(r: RemoteObjectId, c: CombineOperators): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("setOperation", { otherId: r, op: CombineOperators[c] }); } public createFindRequest( order: RecordOrder, topRow: RowValue[] | null, strFilter: StringFilterDescription, excludeTopRow: boolean, next: boolean): RpcRequest<FindResult> { return this.createStreamingRpcRequest<FindResult>("find", { order: order, topRow: topRow, stringFilterDescription: strFilter, excludeTopRow: excludeTopRow, next: next, }); } public createQuantileRequest(rowCount: number, o: RecordOrder, position: number): RpcRequest<RowValue[]> { return this.createStreamingRpcRequest<RowValue[]>("quantile", { precision: 100, tableSize: rowCount, order: o, position: position, seed: Seed.instance.get(), }); } /** * Computes the maximum resolution at which a data range request must be made. * @param page Page - used to compute the screen size. * @param viewKind Desired view for the data. * @param cds Columns analyzed. */ private static rangesResolution(page: FullPage, viewKind: ViewKind, cds: IColumnDescription[]): number[] { const width = page.getWidthInPixels(); const size = PlottingSurface.getDefaultCanvasSize(width); const maxWindows = Math.floor(width / Resolution.minTrellisWindowSize) * Math.floor(size.height / Resolution.minTrellisWindowSize); const maxBuckets = Resolution.maxBuckets(page.getWidthInPixels()); switch (viewKind) { case "QuartileVector": return [maxBuckets, maxBuckets]; case "Histogram": // Always get the window size; we integrate the CDF to draw the actual histogram. return [size.width]; case "2DHistogram": // On the horizontal axis we get the maximum resolution, which we will use for // deriving the CDF curve. On the vertical axis we use a smaller number. return [width, Resolution.max2DBucketCount]; case "Heatmap": return [Math.floor(size.width / Resolution.minDotSize), Math.floor(size.height / Resolution.minDotSize)]; case "CorrelationHeatmaps": const dots = Math.floor(size.width / (cds.length - 1) / Resolution.minDotSize); return cds.map(_ => dots); case "Trellis2DHistogram": return [width, maxBuckets, maxWindows]; case "TrellisHeatmap": return [width, maxBuckets, maxWindows]; case "TrellisQuartiles": return [maxBuckets, maxBuckets, maxWindows]; case "TrellisHistogram": return [width, maxWindows]; case "LogFile": return [page.getHeightInPixels()]; case "Table": case "Schema": case "Load": case "HeavyHitters": case "SVD Spectrum": case "Map": // Shoudld not occur assert(false); return []; default: assertNever(viewKind); } } /** * Create a request to find quantiles of a set of columns for a specific screen resolution. * @param cds Columns whose quantiles are computed. * @param page Current page. * @param viewKind How data will be displayed. */ public createDataQuantilesRequest(cds: IColumnDescription[], page: FullPage, viewKind: ViewKind): RpcRequest<BucketsInfo[]> { // Determine the resolution of the ranges request based on the plot kind. const bucketCounts: number[] = TableTargetAPI.rangesResolution(page, viewKind, cds); assert(bucketCounts.length === cds.length); const args = zip(cds, bucketCounts, (c, b) => { return { cd: c, seed: kindIsString(c.kind) ? Seed.instance.get() : 0, stringsToSample: b }}); return this.createStreamingRpcRequest<BucketsInfo[]>("getDataQuantiles", args); } public createCorrelationHeatmapRequest(args: HistogramRequestInfo): RpcRequest<Groups<Groups<number>>[]> { return this.createStreamingRpcRequest<Groups<Groups<number>>[]>("correlationHeatmaps", args); } public createQuantilesVectorRequest(args: QuantilesVectorInfo): RpcRequest<Groups<SampleSet>> { return this.createStreamingRpcRequest<Groups<SampleSet>>("getQuantilesVector", args); } public createQuantilesMatrixRequest(args: QuantilesMatrixInfo): RpcRequest<Groups<Groups<SampleSet>>> { return this.createStreamingRpcRequest<Groups<Groups<SampleSet>>>("getQuantilesMatrix", args); } /** * Create a request for a nextK sketch * @param order Sorting order. * @param firstRow Values in the smallest row (may be null). * @param rowsOnScreen How many rows to bring. * @param aggregates List of aggregates to compute. * @param columnsMinimumValue List of columns in the firstRow for which we want to specify * "minimum possible value" instead of "null". */ public createNextKRequest(order: RecordOrder, firstRow: RowValue[] | null, rowsOnScreen: number, aggregates: AggregateDescription[] | null, columnsMinimumValue: string[] | null): RpcRequest<NextKList> { const nextKArgs: NextKArgs = { toFind: null, order, firstRow, rowsOnScreen, columnsMinimumValue, aggregates }; return this.createStreamingRpcRequest<NextKList>("getNextK", nextKArgs); } public createGetMetadataRequest(): RpcRequest<TableMetadata> { return this.createStreamingRpcRequest<TableMetadata>("getMetadata", null); } public createGeoRequest(column: IColumnDescription): RpcRequest<MapAndColumnRepresentation> { return this.createStreamingRpcRequest<MapAndColumnRepresentation>("getGeo", column); } public createHLogLogRequest(colName: string): RpcRequest<CountWithConfidence> { return this.createStreamingRpcRequest<CountWithConfidence>("hLogLog", { columnName: colName, seed: Seed.instance.get() }); } public createBasicColStatsRequest(cols: string[]): RpcRequest<Pair<BasicColStats, CountWithConfidence>[]> { return this.createStreamingRpcRequest<Pair<BasicColStats, CountWithConfidence>[]>( "basicColStats", { cols: cols, seed: Seed.instance.get()}); } public createHeavyHittersRequest(columns: IColumnDescription[], percent: number, totalRows: number, threshold: number): RpcRequest<TopList> { if (percent < threshold) { return this.createStreamingRpcRequest<TopList>("heavyHittersMG", { columns: columns, amount: percent, totalRows: totalRows, seed: 0 }); // no randomness needed } else { return this.createStreamingRpcRequest<TopList>("heavyHittersSampling", { columns: columns, amount: percent, totalRows: totalRows, seed: Seed.instance.get() }); } } public createCheckHeavyRequest(r: RemoteObject, schema: Schema): RpcRequest<TopList> { return this.createStreamingRpcRequest<TopList>("checkHeavy", { hittersId: r.getRemoteObjectId(), schema: schema } as HeavyHittersFilterInfo); } public createFilterHeavyRequest(rid: RemoteObjectId, schema: Schema, includeSet: boolean): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("filterHeavy", { hittersId: rid, schema: schema, includeSet: includeSet }); } public createFilterListHeavy(rid: RemoteObjectId, schema: Schema, includeSet: boolean, rowIndices: number[]): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("filterListHeavy", { hittersId: rid, schema: schema, includeSet: includeSet, rowIndices: rowIndices }); } public createProjectToEigenVectorsRequest(r: RemoteObject, dimension: number, projectionName: string): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("projectToEigenVectors", { id: r.getRemoteObjectId(), numComponents: dimension, projectionName: projectionName }); } public createJSFilterRequest(filter: JSFilterInfo): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("jsFilter", filter); } public createIntervalRequest(args: CreateIntervalColumnMapInfo): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("createIntervalColumn", args); } public createCompareDatasetsRequest(args: CompareDatasetsInfo): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("compareDatasets", args); } public createRowFilterRequest(filter: RowFilterDescription): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("filterOnRow", filter); } public createFilterColumnRequest(filter: StringColumnFilterDescription): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("filterColumn", filter); } public createFilterColumnsRequest(filter: StringColumnsFilterDescription): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("filterColumns", filter); } public createFilterComparisonRequest(filter: ComparisonFilterDescription): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("filterComparison", filter); } public createCorrelationMatrixRequest(columnNames: string[], totalRows: number, toSample: boolean): RpcRequest<RemoteObjectId> { const args = { columnNames: columnNames, totalRows: totalRows, seed: Seed.instance.get(), toSample: toSample }; return this.createStreamingRpcRequest<RemoteObjectId>("correlationMatrix", args); } public createRenameRequest(from: string, to: string): RpcRequest<RemoteObjectId> { const a: RenameArgs = { fromName: from, toName: to }; return this.createStreamingRpcRequest<RemoteObjectId>("renameColumn", a); } public createProjectRequest(schema: Schema): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("project", schema); } public createSpectrumRequest(columnNames: string[], totalRows: number, toSample: boolean): RpcRequest<EigenVal> { return this.createStreamingRpcRequest<EigenVal>("spectrum", { columnNames: columnNames, totalRows: totalRows, seed: Seed.instance.get(), toSample: toSample }); } public createJSCreateColumnRequest(c: CreateColumnJSMapInfo): RpcRequest<string> { return this.createStreamingRpcRequest<string>("jsCreateColumn", c); } public createKVCreateColumnRequest(c: ExtractValueFromKeyMapInfo): RpcRequest<string> { return this.createStreamingRpcRequest<string>("kvCreateColumn", c); } public createKVGetAllKeysRequest(c: string): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<string>("kvGetAllKeys", c); } public createKVExplodeColumnsRequest(e: ExplodeColumnsInfo): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("kvExplodeColumn", e); } public createFilterRequest(f: RangeFilterArrayDescription): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("filterRanges", f); } public createFilterListRequest(f: FilterListDescription): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("filterList", f); } public createHistogramRequest(info: HistogramRequestInfo): RpcRequest<Groups<number>> { return this.createStreamingRpcRequest<Groups<number>>("histogram", info); } public createHistogram2DAndCDFRequest(info: HistogramRequestInfo): RpcRequest<Pair<Groups<Groups<number>>, Groups<number>>> { return this.createStreamingRpcRequest<Pair<Groups<Groups<number>>, Groups<number>>>("histogram2DAndCDF", info); } public createHistogram2DRequest(info: HistogramRequestInfo): RpcRequest<Two<Groups<Groups<number>>>> { return this.createStreamingRpcRequest<Two<Groups<Groups<number>>>>("histogram2D", info); } public createHeatmapRequest(info: HeatmapRequestInfo): RpcRequest<Pair<Groups<Groups<number>>, Groups<Groups<RowValue[]>>>> { return this.createStreamingRpcRequest<Pair<Groups<Groups<number>>, Groups<Groups<RowValue[]>>>>( "heatmap", info); } public createHistogram3DRequest(info: HistogramRequestInfo): RpcRequest<Groups<Groups<Groups<number>>>> { return this.createStreamingRpcRequest<Groups<Groups<Groups<number>>>>("histogram3D", info); } public createHistogramAndCDFRequest(info: HistogramRequestInfo): RpcRequest<Two<Two<Groups<number>>>> { return this.createStreamingRpcRequest<Two<Two<Groups<number>>>>( "histogramAndCDF", info); } public createSampledControlPointsRequest(rowCount: number, numSamples: number, columnNames: string[]): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("sampledControlPoints", {rowCount: rowCount, numSamples: numSamples, columnNames: columnNames, seed: Seed.instance.get() }); } public createCategoricalCentroidsControlPointsRequest( categoricalColumnName: string, numericalColumnNames: string[]): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("categoricalCentroidsControlPoints", { categoricalColumnName: categoricalColumnName, numericalColumnNames: numericalColumnNames } ); } public createMDSProjectionRequest(id: RemoteObjectId): RpcRequest<PointSet> { return this.createStreamingRpcRequest<PointSet>( "makeMDSProjection", { id: id, seed: Seed.instance.get() }); } public createLAMPMapRequest(controlPointsId: RemoteObjectId, colNames: string[], controlPoints: PointSet, newColNames: string[]): RpcRequest<RemoteObjectId> { return this.createStreamingRpcRequest<RemoteObjectId>("lampMap", {controlPointsId: controlPointsId, colNames: colNames, newLowDimControlPoints: controlPoints, newColNames: newColNames }); } } export class SummaryMessage { data: Map<string, HtmlString>; constructor(protected parent: HTMLDivElement) { this.data = new Map(); } set(s: string, n: number, approx?: boolean): void { let summary = new HtmlString(""); if (approx != null && approx) summary.appendSafeString(SpecialChars.approx); summary.append(significantDigitsHtml(n)); this.data.set(s, summary); } setString(s: string, v: HtmlString): void { this.data.set(s, v); } public display(): void { let summary = new HtmlString(""); let first = true; this.data.forEach((v, k) => { if (!first) summary.appendSafeString(", "); first = false; summary.appendSafeString(k + ": "); summary.append(v); }); summary.setInnerHtml(this.parent); } } /** * These kinds of plots show up repeatedly. */ type CommonPlots = "chart" // Contains the chart (or charts for trellis views) | "summary" // summary of the data displayed | "legend"; // legend /** * This is an IDataView that is also a TableTargetAPI. * "Big" tables are table-shaped remote datasets, represented * in Java by IDataSet<ITable>. * This is a base class for most views that are rendering * information from a big table. * A BigTableView view is always part of a DatasetView. */ export abstract class BigTableView extends TableTargetAPI implements IDataView, CompletedWithTime { protected topLevel: HTMLElement; public readonly dataset: DatasetView; protected chartDiv: HTMLDivElement | null; protected summaryDiv: HTMLDivElement | null; protected legendDiv: HTMLDivElement | null; protected summary: SummaryMessage | null; /** * Create a view for a big table. * @param remoteObjectId Id of remote table on the web server. * @param meta Table metadata. * @param page Page where the view is displayed. * @param viewKind Kind of view displayed. */ protected constructor( remoteObjectId: RemoteObjectId, public meta: TableMeta, public page: FullPage, public readonly viewKind: ViewKind) { super(remoteObjectId); this.topLevel = document.createElement("div"); this.topLevel.classList.add("bigTableView"); this.setPage(page); page.setDataView(this); this.dataset = page.dataset!; this.chartDiv = null; this.summaryDiv = null; this.legendDiv = null; this.summary = null; } protected makeToplevelDiv(cls: string): HTMLDivElement { const div = document.createElement("div"); this.topLevel.appendChild(div); div.className = cls; return div; } public getSchema(): SchemaClass { return this.meta.schema; } protected createDiv(b: CommonPlots): HTMLDivElement { const div = this.makeToplevelDiv(b.toString()); switch (b) { case "chart": div.style.display = "flex"; div.style.flexDirection = "column"; this.chartDiv = div; break; case "summary": this.summaryDiv = div; this.summary = new SummaryMessage(this.summaryDiv); break; case "legend": this.legendDiv = div; break; } return div; } protected abstract export(): void; protected exportMenu(): TopMenuItem { return { text: "Export", help: "Save the information in this view in a local file.", subMenu: new SubMenu([{ text: "As CSV", help: "Saves the data in this view in a CSV file.", action: () => this.export() }])}; } /** * Save the information needed to (re)create this view. */ public serialize(): IViewSerialization { return { viewKind: this.viewKind, pageId: this.page.pageId, sourcePageId: this.page.sourcePageId, title: this.page.title.format, provenance: this.page.title.provenance, remoteObjectId: this.getRemoteObjectId()!, rowCount: this.meta.rowCount, schema: this.meta.schema.serialize(), geoMetadata: this.meta.geoMetadata }; } protected standardSummary(): void { this.summary!.set("row count", this.meta.rowCount, this.isPrivate()); } /** * Validate the serialization. Returns null on failure. * @param ser Serialization of a view. */ public static validateSerialization(ser: IViewSerialization): CommonArgs | null { if (ser.schema == null || ser.rowCount == null || ser.remoteObjectId == null || ser.provenance == null || ser.title == null || ser.viewKind == null || ser.pageId == null || ser.geoMetadata == null) return null; const schema = new SchemaClass([]).deserialize(ser.schema); if (schema == null) return null; return { title: new PageTitle(ser.title, ser.provenance), remoteObject: new TableTargetAPI(ser.remoteObjectId), rowCount: ser.rowCount, schema: schema, geoMetadata: ser.geoMetadata }; } public setPage(page: FullPage): void { assert(page != null); this.page = page; if (this.topLevel != null) { this.topLevel.ondragover = (e) => e.preventDefault(); this.topLevel.ondrop = (e) => this.drop(e); } } // noinspection JSMethodCanBeStatic public drop(e: DragEvent): void { console.log(e); } public getPage(): FullPage { if (this.page == null) throw new Error(("Page not set")); return this.page; } public selectCurrent(): void { this.dataset.select(this.page.pageId); } public abstract resize(): void; /** * The refresh method should be able to execute based solely on * the state serialized by calling "serialize", which is * reloaded by "reconstruct". */ public abstract refresh(): void; public getHTMLRepresentation(): HTMLElement { return this.topLevel; } /** * This method is called by the zip receiver after combining two datasets. * It should return a renderer which will handle the newly received object * after the set operation has been performed. */ protected abstract getCombineRenderer(title: PageTitle): (page: FullPage, operation: ICancellable<RemoteObjectId>) => BaseReceiver; public combine(how: CombineOperators): void { const pageId = this.dataset.getSelected(); if (pageId == null) { this.page.reportError("No original dataset selected"); return; } const renderer = this.getCombineRenderer( new PageTitle(this.page.title.format, CombineOperators[how] + " between " + this.page.pageId + " and " + pageId)); if (renderer == null) return; const view = this.dataset.findPage(pageId)?.dataView; if (view == null) return; const rid = view.getRemoteObjectId(); if (rid === null) return; const rr = this.createSetRequest(rid, how); const receiver = renderer(this.getPage(), rr); rr.invoke(receiver); } /** * This method is called when all the data has been received. */ public updateCompleted(timeInMs: number): void { this.page.reportTime(timeInMs); } public isPrivate(): boolean { return this.dataset.isPrivate(); } } /** * A receiver that receives a remoteObjectId for a big table. */ export abstract class BaseReceiver extends OnCompleteReceiver<RemoteObjectId> { protected remoteObject: TableTargetAPI; protected constructor(public page: FullPage, public operation: ICancellable<RemoteObjectId> | null, public description: string, protected dataset: DatasetView | null) { // may be null for the first table super(page, operation, description); } public run(value: RemoteObjectId): void { this.remoteObject = new TableTargetAPI(value); } }
the_stack
import {mat4, vec2, vec3, vec4} from 'gl-matrix'; // @ts-ignore import * as Stats from 'stats-js'; import * as DAT from 'dat-gui'; import Square from './geometry/Square'; import Plane from './geometry/Plane'; import OpenGLRenderer from './rendering/gl/OpenGLRenderer'; import Camera from './Camera'; import {gl, setGL} from './globals'; import ShaderProgram, {Shader} from './rendering/gl/ShaderProgram'; var mouseChange = require('mouse-change'); // static variables var clientWidth : number; var clientHeight : number; var lastX = 0; var lastY = 0; const simresolution = 1024; const shadowMapResolution = 4096; const enableBilateralBlur = false; var gl_context : WebGL2RenderingContext; let speed = 3; let SimFramecnt = 0; let TerrainGeometryDirty = true; let PauseGeneration = false; let HightMapCpuBuf = new Float32Array(simresolution * simresolution * 4); // height map CPU read back buffer, for CPU raycast & collision physics let HightMapBufCounter = 0; let MaxHightMapBufCounter = 200; // determine how many frame to update CPU buffer of terrain hight map for ray casting on CPU let simres : number = simresolution; // (for backup) const controlscomp = { tesselations: 5, pipelen: 0.8,// Kc : 0.10, Ks : 0.020, Kd : 0.013, timestep : 0.05, pipeAra : 0.6, RainErosion : false, // RainErosionStrength : 1.0, RainErosionDropSize : 1.0, EvaporationConstant : 0.005, VelocityMultiplier : 1, RainDegree : 4.5, AdvectionSpeedScaling : 1.0, spawnposx : 0.5, spawnposy : 0.5, posTemp : vec2.fromValues(0.0,0.0), posPerm : vec2.fromValues(0.0,0.0), 'Load Scene': loadScene, // A function pointer, essentially 'Start/Resume' :StartGeneration, 'ResetTerrain' : Reset, 'setTerrainRandom':setTerrainRandom, SimulationSpeed : 3, TerrainBaseMap : 0, TerrainBaseType : 0,//0 ordinary fbm, 1 domain warping, 2 terrace, 3 voroni TerrainBiomeType : 1, TerrainScale : 3.2, TerrainHeight : 2.0, TerrainMask : 0,//0 off, 1 sphere TerrainDebug : 0, WaterTransparency : 0.50, SedimentTrace : 0, // 0 on, 1 off TerrainPlatte : 1, // 0 normal alphine mtn, 1 desert, 2 jungle SnowRange : 0, ForestRange : 0, brushType : 2, // 0 : no brush, 1 : terrain, 2 : water brushSize : 4, brushStrenth : 0.40, brushOperation : 0, // 0 : add, 1 : subtract brushPressed : 0, // 0 : not pressed, 1 : pressed pbrushOn : 0, pbrushData : vec2.fromValues(5.0, 0.4), // size & strength thermalRate : 0.5, thermalErosionScale : 1.0, lightPosX : 0.4, lightPosY : 0.2, lightPosZ : -1.0, showScattering : true, enableBilateralBlur : true, AdvectionMethod : 1, SimulationResolution : simres, }; const controls = { tesselations: 5, pipelen: 0.8,// Kc : 0.1, Ks : 0.02, Kd : 0.013, timestep : 0.05, pipeAra : 0.6, ErosionMode : 0, // 0 river erosion, 1 : mountain erosion, 2 : polygonal mode RainErosion : false, // RainErosionStrength : 1.0, RainErosionDropSize : 2.0, EvaporationConstant : 0.005, VelocityMultiplier : 1, RainDegree : 4.5, AdvectionSpeedScaling : 1.0, spawnposx : 0.5, spawnposy : 0.5, posTemp : vec2.fromValues(0.0,0.0), posPerm : vec2.fromValues(0.0,0.0), 'Load Scene': loadScene, // A function pointer, essentially 'Pause/Resume' :StartGeneration, 'ResetTerrain' : Reset, 'setTerrainRandom':setTerrainRandom, SimulationSpeed : 3, TerrainBaseMap : 0, TerrainBaseType : 0,//0 ordinary fbm, 1 domain warping, 2 terrace, 3 voroni TerrainBiomeType : 1, TerrainScale : 3.2, TerrainHeight : 2.0, TerrainMask : 0,//0 off, 1 sphere TerrainDebug : 0, WaterTransparency : 0.50, SedimentTrace : true, // 0 on, 1 off ShowFlowTrace : true, TerrainPlatte : 1, // 0 normal alphine mtn, 1 desert, 2 jungle SnowRange : 0, ForestRange : 0, brushType : 2, // 0 : no brush, 1 : terrain, 2 : water brushSize : 4, brushStrenth : 0.40, brushOperation : 0, // 0 : add, 1 : subtract brushPressed : 0, // 0 : not pressed, 1 : pressed pbrushOn : 0, pbrushData : vec2.fromValues(5.0, 0.4), // size & strength thermalTalusAngleScale : 8.0, thermalRate : 0.5, thermalErosionScale : 1.0, lightPosX : 0.4, lightPosY : 0.2, lightPosZ : -1.0, showScattering : true, enableBilateralBlur : true, AdvectionMethod : 1, SimulationResolution : simres, }; // ================ geometries ============ // ============================================================= let square: Square; let plane : Plane; let waterPlane : Plane; // ================ frame buffers ============ // ============================================================= let frame_buffer : WebGLFramebuffer; let shadowMap_frame_buffer : WebGLFramebuffer; let deferred_frame_buffer : WebGLFramebuffer; // ================ render buffers ============ // ============================================================= let render_buffer : WebGLRenderbuffer; let shadowMap_render_buffer : WebGLRenderbuffer; let deferred_render_buffer : WebGLRenderbuffer; // ================ muti-renderpasses used textures ============ // ============================================================= let shadowMap_tex : WebGLTexture; let scene_depth_tex : WebGLTexture; let bilateral_filter_horizontal_tex : WebGLTexture; let bilateral_filter_vertical_tex : WebGLTexture; let color_pass_tex : WebGLTexture; let color_pass_reflection_tex : WebGLTexture; let scatter_pass_tex : WebGLTexture; // ================ simulation textures =================== // ======================================================== let read_terrain_tex : WebGLTexture; let write_terrain_tex : WebGLTexture; let read_flux_tex : WebGLTexture; let write_flux_tex : WebGLTexture; let read_terrain_flux_tex : WebGLTexture;// thermal let write_terrain_flux_tex : WebGLTexture; let read_maxslippage_tex : WebGLTexture; let write_maxslippage_tex : WebGLTexture; let read_vel_tex : WebGLTexture; let write_vel_tex : WebGLTexture; let read_sediment_tex : WebGLTexture; let write_sediment_tex : WebGLTexture; let terrain_nor : WebGLTexture; let read_sediment_blend : WebGLTexture; let write_sediment_blend : WebGLTexture; let sediment_advect_a : WebGLTexture; let sediment_advect_b : WebGLTexture; // ================ dat gui button call backs ============ // ============================================================= function loadScene() { square = new Square(vec3.fromValues(0, 0, 0)); square.create(); plane = new Plane(vec3.fromValues(0,0,0), vec2.fromValues(1,1), 18); plane.create(); waterPlane = new Plane(vec3.fromValues(0,0,0), vec2.fromValues(1,1), 18); waterPlane.create(); } function StartGeneration(){ PauseGeneration = !PauseGeneration; } function Reset(){ SimFramecnt = 0; TerrainGeometryDirty = true; if(controls.SimulationResolution!=simres){ simres = controls.SimulationResolution; resizeTextures4Simulation(gl_context); } //PauseGeneration = true; } function setTerrainRandom() { } function Render2Texture(renderer:OpenGLRenderer, gl_context:WebGL2RenderingContext,camera:Camera,shader:ShaderProgram,cur_texture:WebGLTexture){ gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,render_buffer); gl_context.renderbufferStorage(gl_context.RENDERBUFFER,gl_context.DEPTH_COMPONENT16, simres,simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,cur_texture,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT1,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT2,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT3,gl_context.TEXTURE_2D,null,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0]); let status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); gl_context.viewport(0,0,simres,simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); renderer.clear(); shader.use(); renderer.render(camera,shader,[square]); // if(cur_texture == read_terrain_tex){ // HightMapCpuBuf = new Float32Array(simres * simres * 4); // gl_context.readPixels(0,0,simres,simres, gl_context.RGBA, gl_context.FLOAT, HightMapCpuBuf); // //console.log(HightMapCpuBuf); // } gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); } function SimulatePerStep(renderer:OpenGLRenderer, gl_context:WebGL2RenderingContext, camera:Camera, shader:ShaderProgram, waterhight:ShaderProgram, sedi:ShaderProgram, advect:ShaderProgram, macCormack : ShaderProgram, rains:ShaderProgram, eva:ShaderProgram, ave:ShaderProgram, thermalterrainflux:ShaderProgram, thermalapply:ShaderProgram, maxslippageheight:ShaderProgram) { ////////////////////////////////////////////////////////////////// //rain precipitation //0---use hight map to derive hight map : hight map -----> hight map ////////////////////////////////////////////////////////////////// gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,write_terrain_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT1,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT2,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT3,gl_context.TEXTURE_2D,null,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0]); let status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); gl_context.viewport(0,0,simres,simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); renderer.clear(); rains.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(rains.prog,"readTerrain"),0); gl_context.uniform1f(gl_context.getUniformLocation(rains.prog,'raindeg'),controls.RainDegree); renderer.render(camera,rains,[square]); if(HightMapBufCounter % MaxHightMapBufCounter == 0) { gl_context.readPixels(0, 0, simres, simres, gl_context.RGBA, gl_context.FLOAT, HightMapCpuBuf); } HightMapBufCounter ++; gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); //swap terrain tex----------------------------------------------- let tmp = read_terrain_tex; read_terrain_tex = write_terrain_tex; write_terrain_tex = tmp; //swap terrain tex----------------------------------------------- ////////////////////////////////////////////////////////////////// //1---use hight map to derive flux map : hight map -----> flux map ////////////////////////////////////////////////////////////////// gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,write_flux_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT1,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT2,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT3,gl_context.TEXTURE_2D,null,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); gl_context.viewport(0,0,simres,simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); renderer.clear(); shader.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(shader.prog,"readTerrain"),0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D,read_flux_tex); gl_context.uniform1i(gl_context.getUniformLocation(shader.prog,"readFlux"),1); gl_context.activeTexture(gl_context.TEXTURE2); gl_context.bindTexture(gl_context.TEXTURE_2D,read_sediment_tex); gl_context.uniform1i(gl_context.getUniformLocation(shader.prog,"readSedi"),2); renderer.render(camera,shader,[square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); //-----swap flux ping and pong tmp = read_flux_tex; read_flux_tex = write_flux_tex; write_flux_tex = tmp; //-----swap flux ping and pong ////////////////////////////////////////////////////////////////// //2---use flux map and hight map to derive velocity map and new hight map : // hight map + flux map -----> velocity map + hight map ////////////////////////////////////////////////////////////////// gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,write_terrain_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT1,gl_context.TEXTURE_2D,write_vel_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT2,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT3,gl_context.TEXTURE_2D,null,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0,gl_context.COLOR_ATTACHMENT1]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); gl_context.viewport(0,0,simres,simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); renderer.clear(); waterhight.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(waterhight.prog,"readTerrain"),0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D,read_flux_tex); gl_context.uniform1i(gl_context.getUniformLocation(waterhight.prog,"readFlux"),1); gl_context.activeTexture(gl_context.TEXTURE2); gl_context.bindTexture(gl_context.TEXTURE_2D,read_sediment_tex); gl_context.uniform1i(gl_context.getUniformLocation(waterhight.prog,"readSedi"),2); gl_context.activeTexture(gl_context.TEXTURE3); gl_context.bindTexture(gl_context.TEXTURE_2D,read_vel_tex); gl_context.uniform1i(gl_context.getUniformLocation(waterhight.prog,"readVel"),3); renderer.render(camera,waterhight,[square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); //-----swap terrain ping and pong and velocity ping pong tmp = read_terrain_tex; read_terrain_tex = write_terrain_tex; write_terrain_tex = tmp; tmp = read_vel_tex; read_vel_tex = write_vel_tex; write_vel_tex = tmp; //-----swap flux ping and pong and velocity ping pong ////////////////////////////////////////////////////////////////// //3---use velocity map, sediment map and hight map to derive sediment map and new hight map and velocity map : // hight map + velocity map + sediment map -----> sediment map + hight map + terrain normal map + velocity map ////////////////////////////////////////////////////////////////// gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,write_terrain_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT1,gl_context.TEXTURE_2D,write_sediment_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT2,gl_context.TEXTURE_2D,terrain_nor,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT3,gl_context.TEXTURE_2D,write_vel_tex,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0,gl_context.COLOR_ATTACHMENT1,gl_context.COLOR_ATTACHMENT2, gl_context.COLOR_ATTACHMENT3]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); gl_context.viewport(0,0,simres,simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); renderer.clear(); sedi.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(sedi.prog,"readTerrain"),0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D,read_vel_tex); gl_context.uniform1i(gl_context.getUniformLocation(sedi.prog,"readVelocity"),1); gl_context.activeTexture(gl_context.TEXTURE2); gl_context.bindTexture(gl_context.TEXTURE_2D,read_sediment_tex); gl_context.uniform1i(gl_context.getUniformLocation(sedi.prog,"readSediment"),2); renderer.render(camera,sedi,[square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); //----------swap terrain and sediment map--------- tmp = read_sediment_tex; read_sediment_tex = write_sediment_tex; write_sediment_tex = tmp; tmp = read_terrain_tex; read_terrain_tex = write_terrain_tex; write_terrain_tex = tmp; tmp = read_vel_tex; read_vel_tex = write_vel_tex; write_vel_tex = tmp; //----------swap terrain and sediment map--------- ////////////////////////////////////////////////////////////////// // semi-lagrangian advection for sediment transportation // 4---use velocity map, sediment map to derive new sediment map : // velocity map + sediment map -----> sediment map ////////////////////////////////////////////////////////////////// if(controls.AdvectionMethod == 1) { //4.1 first subpass writing to the intermidiate sediment advection texture a { gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT0, gl_context.TEXTURE_2D, sediment_advect_a, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT1, gl_context.TEXTURE_2D, write_vel_tex, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT2, gl_context.TEXTURE_2D, write_sediment_blend, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT3, gl_context.TEXTURE_2D, null, 0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER, gl_context.DEPTH_ATTACHMENT, gl_context.RENDERBUFFER, render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0, gl_context.COLOR_ATTACHMENT1, gl_context.COLOR_ATTACHMENT2]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log("frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D, null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER, null); gl_context.viewport(0, 0, simres, simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, frame_buffer); renderer.clear(); advect.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D, read_vel_tex); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "vel"), 0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D, read_sediment_tex); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "sedi"), 1); gl_context.activeTexture(gl_context.TEXTURE2); gl_context.bindTexture(gl_context.TEXTURE_2D, read_sediment_blend); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "sediBlend"), 2); gl_context.activeTexture(gl_context.TEXTURE3); gl_context.bindTexture(gl_context.TEXTURE_2D, read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "terrain"), 3); advect.setFloat(1, "unif_advectMultiplier"); renderer.render(camera, advect, [square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, null); } //4.2 second subpass writing to the intermidiate sediment advection texture b using a { gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT0, gl_context.TEXTURE_2D, sediment_advect_b, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT1, gl_context.TEXTURE_2D, write_vel_tex, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT2, gl_context.TEXTURE_2D, write_sediment_blend, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT3, gl_context.TEXTURE_2D, null, 0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER, gl_context.DEPTH_ATTACHMENT, gl_context.RENDERBUFFER, render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0, gl_context.COLOR_ATTACHMENT1, gl_context.COLOR_ATTACHMENT2]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log("frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D, null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER, null); gl_context.viewport(0, 0, simres, simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, frame_buffer); renderer.clear(); advect.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D, read_vel_tex); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "vel"), 0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D, sediment_advect_a); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "sedi"), 1); gl_context.activeTexture(gl_context.TEXTURE2); gl_context.bindTexture(gl_context.TEXTURE_2D, read_sediment_blend); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "sediBlend"), 2); gl_context.activeTexture(gl_context.TEXTURE3); gl_context.bindTexture(gl_context.TEXTURE_2D, read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "terrain"), 3); advect.setFloat(-1, "unif_advectMultiplier"); renderer.render(camera, advect, [square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, null); } //4.3 thrid subpass : mac cormack advection writing to actual sediment using intermidiate advection textures { gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT0, gl_context.TEXTURE_2D, write_sediment_tex, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT1, gl_context.TEXTURE_2D, null, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT2, gl_context.TEXTURE_2D, null, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT3, gl_context.TEXTURE_2D, null, 0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER, gl_context.DEPTH_ATTACHMENT, gl_context.RENDERBUFFER, render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0, gl_context.COLOR_ATTACHMENT1, gl_context.COLOR_ATTACHMENT2]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log("frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D, null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER, null); gl_context.viewport(0, 0, simres, simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, frame_buffer); renderer.clear(); macCormack.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D, read_vel_tex); gl_context.uniform1i(gl_context.getUniformLocation(macCormack.prog, "vel"), 0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D, read_sediment_tex); gl_context.uniform1i(gl_context.getUniformLocation(macCormack.prog, "sedi"), 1); gl_context.activeTexture(gl_context.TEXTURE2); gl_context.bindTexture(gl_context.TEXTURE_2D, sediment_advect_a); gl_context.uniform1i(gl_context.getUniformLocation(macCormack.prog, "sediadvecta"), 2); gl_context.activeTexture(gl_context.TEXTURE3); gl_context.bindTexture(gl_context.TEXTURE_2D, sediment_advect_b); gl_context.uniform1i(gl_context.getUniformLocation(macCormack.prog, "sediadvectb"), 3); renderer.render(camera, macCormack, [square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, null); } }else{ gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT0, gl_context.TEXTURE_2D, write_sediment_tex, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT1, gl_context.TEXTURE_2D, write_vel_tex, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT2, gl_context.TEXTURE_2D, write_sediment_blend, 0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT3, gl_context.TEXTURE_2D, null, 0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER, gl_context.DEPTH_ATTACHMENT, gl_context.RENDERBUFFER, render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0, gl_context.COLOR_ATTACHMENT1, gl_context.COLOR_ATTACHMENT2]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log("frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D, null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER, null); gl_context.viewport(0, 0, simres, simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, frame_buffer); renderer.clear(); advect.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D, read_vel_tex); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "vel"), 0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D, read_sediment_tex); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "sedi"), 1); gl_context.activeTexture(gl_context.TEXTURE2); gl_context.bindTexture(gl_context.TEXTURE_2D, read_sediment_blend); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "sediBlend"), 2); gl_context.activeTexture(gl_context.TEXTURE3); gl_context.bindTexture(gl_context.TEXTURE_2D, read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(advect.prog, "terrain"), 3); advect.setFloat(1, "unif_advectMultiplier"); renderer.render(camera, advect, [square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, null); } //----------swap sediment map--------- tmp = read_sediment_blend; read_sediment_blend = write_sediment_blend; write_sediment_blend = tmp; tmp = read_sediment_tex; read_sediment_tex = write_sediment_tex; write_sediment_tex = tmp; tmp = read_vel_tex; read_vel_tex = write_vel_tex; write_vel_tex = tmp; //----------swap sediment map--------- ////////////////////////////////////////////////////////////////// // maxslippage map generation // 4.5---use terrain map to derive new maxslippage map : // hight map -----> max slippage map ////////////////////////////////////////////////////////////////// gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,write_maxslippage_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT1,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT2,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT3,gl_context.TEXTURE_2D,null,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); gl_context.viewport(0,0,simres,simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); renderer.clear(); maxslippageheight.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(maxslippageheight.prog,"readTerrain"),0); renderer.render(camera,maxslippageheight,[square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); //--------------------------------- //swap maxslippage maps tmp = read_maxslippage_tex; read_maxslippage_tex = write_maxslippage_tex; write_maxslippage_tex = tmp; //-------------------------------- ////////////////////////////////////////////////////////////////// // thermal terrain flux map generation // 5---use velocity map, sediment map to derive new sediment map : // hight map -----> terrain flux map ////////////////////////////////////////////////////////////////// gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,write_terrain_flux_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT1,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT2,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT3,gl_context.TEXTURE_2D,null,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); gl_context.viewport(0,0,simres,simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); renderer.clear(); thermalterrainflux.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); gl_context.uniform1i( gl_context.getUniformLocation(thermalterrainflux.prog,"readTerrain"),0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D,read_maxslippage_tex); gl_context.uniform1i(gl_context.getUniformLocation(thermalterrainflux.prog,"readMaxSlippage"),1); renderer.render(camera,thermalterrainflux,[square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); //--------------------------------- //swap terrain flux maps tmp = read_terrain_flux_tex; read_terrain_flux_tex = write_terrain_flux_tex; write_terrain_flux_tex = tmp; ////////////////////////////////////////////////////////////////// // thermal erosion apply // 6---use terrain flux map to derive new terrain map : // terrain flux map -----> terrain map ////////////////////////////////////////////////////////////////// gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,write_terrain_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT1,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT2,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT3,gl_context.TEXTURE_2D,null,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); gl_context.viewport(0,0,simres,simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); renderer.clear(); thermalapply.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_flux_tex); gl_context.uniform1i(gl_context.getUniformLocation(thermalapply.prog,"readTerrainFlux"),0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(thermalapply.prog,"readTerrain"),1); renderer.render(camera,thermalapply,[square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); //---------------swap terrain mao---------------------------- tmp = read_terrain_tex; read_terrain_tex = write_terrain_tex; write_terrain_tex = tmp; ////////////////////////////////////////////////////////////////// // water level evaporation at end of each iteration // 7---use terrain map to derive new terrain map : // terrain map -----> terrain map ////////////////////////////////////////////////////////////////// gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,write_terrain_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT1,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT2,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT3,gl_context.TEXTURE_2D,null,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); gl_context.viewport(0,0,simres,simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); renderer.clear(); eva.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(eva.prog,"terrain"),0); gl_context.uniform1f(gl_context.getUniformLocation(eva.prog,'evapod'),controls.EvaporationConstant); renderer.render(camera,eva,[square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); //---------------swap terrain mao---------------------------- tmp = read_terrain_tex; read_terrain_tex = write_terrain_tex; write_terrain_tex = tmp; //---------------swap terrain mao---------------------------- ////////////////////////////////////////////////////////////////// // final average step : average terrain to avoid extremly sharp ridges or ravines // 6---use terrain map to derive new terrain map : // terrain map -----> terrain map ////////////////////////////////////////////////////////////////// gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,write_terrain_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT1,gl_context.TEXTURE_2D,terrain_nor,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT2,gl_context.TEXTURE_2D,null,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT3,gl_context.TEXTURE_2D,null,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0,gl_context.COLOR_ATTACHMENT1]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); gl_context.viewport(0,0,simres,simres); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,frame_buffer); renderer.clear(); ave.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(ave.prog,"readTerrain"),0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D,read_sediment_tex); gl_context.uniform1i(gl_context.getUniformLocation(ave.prog,"readSedi"),1); renderer.render(camera,ave,[square]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); //---------------swap terrain mao---------------------------- tmp = read_terrain_tex; read_terrain_tex = write_terrain_tex; write_terrain_tex = tmp; //---------------swap terrain mao---------------------------- } function LE_create_texture(w : number, h : number, samplingType : number){ let new_tex = gl_context.createTexture(); gl_context.bindTexture(gl_context.TEXTURE_2D,new_tex); gl_context.texImage2D(gl_context.TEXTURE_2D,0,gl_context.RGBA32F,w,h,0, gl_context.RGBA,gl_context.FLOAT,null); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MIN_FILTER, samplingType); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MAG_FILTER, samplingType); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_S, gl_context.CLAMP_TO_EDGE); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_T, gl_context.CLAMP_TO_EDGE); return new_tex; } function LE_recreate_texture(w : number, h : number, samplingType : number, texHandle : WebGLTexture){ gl_context.bindTexture(gl_context.TEXTURE_2D,texHandle); gl_context.texImage2D(gl_context.TEXTURE_2D,0,gl_context.RGBA32F,w,h,0, gl_context.RGBA,gl_context.FLOAT,null); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MIN_FILTER, samplingType); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MAG_FILTER, samplingType); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_S, gl_context.CLAMP_TO_EDGE); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_T, gl_context.CLAMP_TO_EDGE); } function LE_create_screen_texture(w : number, h : number, samplingType : number){ let new_tex = gl_context.createTexture(); gl_context.bindTexture(gl_context.TEXTURE_2D,new_tex); gl_context.texImage2D(gl_context.TEXTURE_2D,0,gl_context.RGBA32F,w,h,0, gl_context.RGBA,gl_context.FLOAT,null); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MIN_FILTER, samplingType); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MAG_FILTER, samplingType); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_S, gl_context.CLAMP_TO_EDGE); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_T, gl_context.CLAMP_TO_EDGE); return new_tex; } function resizeTextures4Simulation(gl_context:WebGL2RenderingContext){ let simulationTextureSampler = gl_context.LINEAR; // reacreate all textures related to simulation LE_recreate_texture(simres,simres,simulationTextureSampler, read_terrain_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, write_terrain_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, read_flux_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, write_flux_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, read_terrain_flux_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, write_terrain_flux_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, read_maxslippage_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, write_maxslippage_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, read_vel_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, write_vel_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, read_sediment_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, write_sediment_tex); LE_recreate_texture(simres,simres,simulationTextureSampler, terrain_nor); LE_recreate_texture(simres,simres,simulationTextureSampler, read_sediment_blend); LE_recreate_texture(simres,simres,simulationTextureSampler, write_sediment_blend); LE_recreate_texture(simres,simres,simulationTextureSampler, sediment_advect_a); LE_recreate_texture(simres,simres,simulationTextureSampler, sediment_advect_b); // recreate all framebuffer/renderbuffer related to simulation gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,render_buffer); gl_context.renderbufferStorage(gl_context.RENDERBUFFER,gl_context.DEPTH_COMPONENT16, simres,simres); gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); // recreate CPU read texture buffer for simulation & User interaction HightMapCpuBuf = new Float32Array(simres * simres * 4); } function setupFramebufferandtextures(gl_context:WebGL2RenderingContext) { let simulationTextureSampler = gl_context.LINEAR; //Noise generated data from GPU texture, include population density, water distribution, terrain elevation... read_terrain_tex = LE_create_texture(simres,simres,simulationTextureSampler); write_terrain_tex = LE_create_texture(simres,simres,simulationTextureSampler); read_flux_tex = LE_create_texture(simres,simres,simulationTextureSampler); write_flux_tex = LE_create_texture(simres,simres,simulationTextureSampler); read_terrain_flux_tex = LE_create_texture(simres,simres,simulationTextureSampler); write_terrain_flux_tex = LE_create_texture(simres,simres,simulationTextureSampler); read_maxslippage_tex =LE_create_texture(simres,simres,simulationTextureSampler); write_maxslippage_tex = LE_create_texture(simres,simres,simulationTextureSampler); read_vel_tex = LE_create_texture(simres,simres,simulationTextureSampler); write_vel_tex = LE_create_texture(simres,simres,simulationTextureSampler); read_sediment_tex = LE_create_texture(simres,simres,simulationTextureSampler); write_sediment_tex = LE_create_texture(simres,simres,simulationTextureSampler); terrain_nor = LE_create_texture(simres,simres,simulationTextureSampler); read_sediment_blend = LE_create_texture(simres,simres,simulationTextureSampler); write_sediment_blend = LE_create_texture(simres,simres,simulationTextureSampler); sediment_advect_a = LE_create_texture(simres,simres,simulationTextureSampler); sediment_advect_b = LE_create_texture(simres,simres,simulationTextureSampler); shadowMap_tex = LE_create_screen_texture(shadowMapResolution, shadowMapResolution,gl_context.LINEAR); scene_depth_tex = LE_create_screen_texture(window.innerWidth,window.innerHeight,gl_context.LINEAR); bilateral_filter_horizontal_tex = LE_create_screen_texture(window.innerWidth,window.innerHeight,gl_context.LINEAR); bilateral_filter_vertical_tex = LE_create_screen_texture(window.innerWidth,window.innerHeight,gl_context.LINEAR); color_pass_tex = LE_create_screen_texture(window.innerWidth,window.innerHeight,gl_context.LINEAR); color_pass_reflection_tex = LE_create_screen_texture(window.innerWidth,window.innerHeight,gl_context.LINEAR); scatter_pass_tex = LE_create_screen_texture(window.innerWidth,window.innerHeight,gl_context.LINEAR); shadowMap_frame_buffer = gl_context.createFramebuffer(); shadowMap_render_buffer = gl_context.createRenderbuffer(); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,shadowMap_render_buffer); gl_context.renderbufferStorage(gl_context.RENDERBUFFER,gl_context.DEPTH_COMPONENT16, shadowMapResolution,shadowMapResolution); deferred_frame_buffer = gl_context.createFramebuffer(); deferred_render_buffer = gl_context.createRenderbuffer(); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,deferred_render_buffer); gl_context.renderbufferStorage(gl_context.RENDERBUFFER,gl_context.DEPTH_COMPONENT16, window.innerWidth,window.innerHeight); frame_buffer = gl_context.createFramebuffer(); render_buffer = gl_context.createRenderbuffer(); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,render_buffer); gl_context.renderbufferStorage(gl_context.RENDERBUFFER,gl_context.DEPTH_COMPONENT16, simres,simres); gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); } function SimulationStep(curstep:number, flow:ShaderProgram, waterhight : ShaderProgram, sediment : ShaderProgram, advect:ShaderProgram, macCormack : ShaderProgram, rains:ShaderProgram, evapo:ShaderProgram, average:ShaderProgram, thermalterrainflux:ShaderProgram, thermalapply:ShaderProgram, maxslippageheight : ShaderProgram, renderer:OpenGLRenderer, gl_context:WebGL2RenderingContext,camera:Camera){ if(PauseGeneration) return true; else{ SimulatePerStep(renderer, gl_context,camera,flow,waterhight,sediment,advect, macCormack,rains,evapo,average,thermalterrainflux,thermalapply, maxslippageheight); } return false; } function handleInteraction (buttons : number, x : number, y : number){ lastX = x; lastY = y; //console.log(x + ' ' + y); } function onKeyDown(event : KeyboardEvent){ if(event.key == 'c'){ controls.brushPressed = 1; }else{ controls.brushPressed = 0; } if(event.key == 'r'){ controls.pbrushOn = controls.pbrushOn == 0 ? 1 : 0; controls.posPerm = controls.posTemp; controls.pbrushData = vec2.fromValues(controls.brushSize, controls.brushStrenth); } if(event.key == 'p'){ controls.pbrushOn = 0; } } function onKeyUp(event : KeyboardEvent){ if(event.key == 'c'){ controls.brushPressed = 0; } } function main() { // Initial display for framerate const stats = Stats(); stats.setMode(0); stats.domElement.style.position = 'absolute'; stats.domElement.style.left = '0px'; stats.domElement.style.top = '0px'; document.body.appendChild(stats.domElement); //HightMapCpuBuf = new Float32Array(simresolution * simresolution * 4); // Add controls to the gui const gui = new DAT.GUI(); var simcontrols = gui.addFolder('Simulation Controls'); simcontrols.add(controls,'Pause/Resume'); simcontrols.add(controls,'SimulationSpeed',{fast:3,medium : 2, slow : 1}); simcontrols.open(); var terrainParameters = gui.addFolder('Terrain Parameters'); terrainParameters.add(controls,'SimulationResolution',{256 : 256 , 512 : 512, 1024 : 1024, 2048 : 2048} ); terrainParameters.add(controls,'TerrainScale', 0.1, 4.0); terrainParameters.add(controls,'TerrainHeight', 1.0, 5.0); terrainParameters.add(controls,'TerrainMask',{OFF : 0 ,Sphere : 1, slope : 2}); terrainParameters.add(controls,'TerrainBaseType', {ordinaryFBM : 0, domainWarp : 1, terrace : 2, voroni : 3, ridgeNoise : 4}); terrainParameters.add(controls,'ResetTerrain'); terrainParameters.open(); var erosionpara = gui.addFolder('Erosion Parameters'); erosionpara.add(controls, 'ErosionMode', {RiverMode : 0, MountainMode : 1, PolygonalMode : 2}); var RainErosionPara = erosionpara.addFolder('Rain Erosion Parameters'); RainErosionPara.add(controls,'RainErosion'); RainErosionPara.add(controls, 'RainErosionStrength', 0.1,3.0); RainErosionPara.add(controls,'RainErosionDropSize', 0.1, 3.0); RainErosionPara.close(); erosionpara.add(controls, 'EvaporationConstant', 0.0001, 0.08); erosionpara.add(controls,'Kc', 0.01,0.5); erosionpara.add(controls,'Ks', 0.001,0.2); erosionpara.add(controls,'Kd', 0.0001,0.1); //erosionpara.add(controls,'AdvectionSpeedScaling', 0.1, 1.0); erosionpara.add(controls, 'TerrainDebug', {noDebugView : 0, sediment : 1, velocity : 2, velocityHeatmap : 9, terrain : 3, flux : 4, terrainflux : 5, maxslippage : 6, flowMap : 7, spikeDiffusion : 8}); erosionpara.add(controls, 'AdvectionMethod', {Semilagrangian : 0, MacCormack : 1}); erosionpara.add(controls, 'VelocityMultiplier',1.0,5.0); erosionpara.open(); var thermalerosionpara = gui.addFolder("Thermal Erosion Parameters"); thermalerosionpara.add(controls, 'thermalTalusAngleScale', 2.0, 10.0); thermalerosionpara.add(controls,'thermalErosionScale',0.0, 5.0 ); //thermalerosionpara.open(); var terraineditor = gui.addFolder('Terrain Editor'); terraineditor.add(controls,'brushType',{NoBrush : 0, TerrainBrush : 1, WaterBrush : 2}); terraineditor.add(controls,'brushSize',0.1, 20.0); terraineditor.add(controls,'brushStrenth',0.1,2.0); terraineditor.add(controls,'brushOperation', {Add : 0, Subtract : 1}); terraineditor.open(); var renderingpara = gui.addFolder('Rendering Parameters'); renderingpara.add(controls, 'WaterTransparency', 0.0, 1.0); renderingpara.add(controls, 'TerrainPlatte', {AlpineMtn : 0, Desert : 1, Jungle : 2}); renderingpara.add(controls, 'SnowRange', 0.0, 100.0); renderingpara.add(controls, 'ForestRange', 0.0, 50.0); renderingpara.add(controls,'ShowFlowTrace'); renderingpara.add(controls,'SedimentTrace'); renderingpara.add(controls,'showScattering'); renderingpara.add(controls,'enableBilateralBlur'); var renderingparalightpos = renderingpara.addFolder('sunPos/Dir'); renderingparalightpos.add(controls,'lightPosX',-1.0,1.0); renderingparalightpos.add(controls,'lightPosY',0.0,1.0); renderingparalightpos.add(controls,'lightPosZ',-1.0,1.0); renderingparalightpos.open(); renderingpara.open(); // get canvas and webgl context const canvas = <HTMLCanvasElement> document.getElementById('canvas'); gl_context = <WebGL2RenderingContext> canvas.getContext('webgl2'); clientWidth = canvas.clientWidth; clientHeight = canvas.clientHeight; mouseChange(canvas, handleInteraction); document.addEventListener('keydown', onKeyDown, false); document.addEventListener('keyup', onKeyUp, false); if (!gl_context) { alert('WebGL 2 not supported!'); } var extensions = gl_context.getSupportedExtensions(); for(let e in extensions){ console.log(e); } if(!gl_context.getExtension('OES_texture_float_linear')){ console.log("float texture not supported"); } if(!gl_context.getExtension('OES_texture_float')){ console.log("no float texutre!!!?? y am i here?"); } if(!gl_context.getExtension('EXT_color_buffer_float')) { console.log("cant render to float texture "); } // `setGL` is a function imported above which sets the value of `gl_context` in the `globals.ts` module. // Later, we can import `gl_context` from `globals.ts` to access it setGL(gl_context); // Initial call to load scene loadScene(); const camera = new Camera(vec3.fromValues(-0.18, 0.3, 0.6), vec3.fromValues(0, 0, 0)); const renderer = new OpenGLRenderer(canvas); renderer.setClearColor(0.0, 0.0, 0.0, 0); gl_context.enable(gl_context.DEPTH_TEST); setupFramebufferandtextures(gl_context); //================================================================= //load in the shaders const lambert = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/terrain-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/terrain-frag.glsl')), ]); const flat = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/flat-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/flat-frag.glsl')), ]); const noiseterrain = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/initial-frag.glsl')), ]); const flow = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/flow-frag.glsl')), ]); const waterhight = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/alterwaterhight-frag.glsl')), ]); const sediment = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/sediment-frag.glsl')), ]); const sediadvect = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/sediadvect-frag.glsl')), ]); const macCormack = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/maccormack-frag.glsl')), ]); const rains = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/rain-frag.glsl')), ]); const evaporation = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/eva-frag.glsl')), ]); const average = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/average-frag.glsl')), ]); const clean = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/clean-frag.glsl')), ]); const water = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/water-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/water-frag.glsl')), ]); const thermalterrainflux = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/thermalterrainflux-frag.glsl')), ]); const thermalapply = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/thermalapply-frag.glsl')), ]); const maxslippageheight = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/maxslippageheight-frag.glsl')), ]); const shadowMapShader = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/shadowmap-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/shadowmap-frag.glsl')), ]); const sceneDepthShader = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/terrain-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/sceneDepth-frag.glsl')), ]); const combinedShader = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/combine-frag.glsl')), ]); const bilateralBlur = new ShaderProgram([ new Shader(gl_context.VERTEX_SHADER, require('./shaders/quad-vert.glsl')), new Shader(gl_context.FRAGMENT_SHADER, require('./shaders/bilateralBlur-frag.glsl')), ]); let timer = 0; function cleanUpTextures(){ Render2Texture(renderer, gl_context, camera, clean, read_terrain_tex); Render2Texture(renderer, gl_context, camera, clean, read_vel_tex); Render2Texture(renderer, gl_context, camera, clean, read_flux_tex); Render2Texture(renderer, gl_context, camera, clean, read_terrain_flux_tex); Render2Texture(renderer, gl_context, camera, clean, write_terrain_flux_tex); Render2Texture(renderer, gl_context, camera, clean, read_maxslippage_tex); Render2Texture(renderer, gl_context, camera, clean, write_maxslippage_tex); Render2Texture(renderer, gl_context, camera, clean, read_sediment_tex); Render2Texture(renderer, gl_context, camera, clean, write_terrain_tex); Render2Texture(renderer, gl_context, camera, clean, write_vel_tex); Render2Texture(renderer, gl_context, camera, clean, write_flux_tex); Render2Texture(renderer, gl_context, camera, clean, write_sediment_tex); Render2Texture(renderer, gl_context, camera, clean, terrain_nor); Render2Texture(renderer, gl_context, camera, clean, read_sediment_blend); Render2Texture(renderer, gl_context, camera, clean, write_sediment_blend); Render2Texture(renderer, gl_context, camera, clean, sediment_advect_a); Render2Texture(renderer, gl_context, camera, clean, sediment_advect_b); } function rayCast(ro : vec3, rd : vec3){ let res = vec2.fromValues(-10.0, -10.0); let cur = ro; let step = 0.01; for(let i = 0;i<100;++i){ let curTexSpace = vec2.fromValues((cur[0] + .50)/1.0, (cur[2] + .50)/1.0); let scaledTexSpace = vec2.fromValues(curTexSpace[0] * simres, curTexSpace[1] * simres); vec2.floor(scaledTexSpace,scaledTexSpace); let hvalcoordinate = scaledTexSpace[1] * simres * 4 + scaledTexSpace[0] * 4 + 0; let hval = HightMapCpuBuf[hvalcoordinate]; if(cur[1] < hval/simres){ res = curTexSpace; //console.log(curTexSpace); break; } let rdscaled = vec3.fromValues(rd[0] * step, rd[1] * step, rd[2] * step); vec3.add(cur,cur,rdscaled); } return res; } function tick() { // ================ ray casting =================== //=================================================== let iclientWidth = window.innerWidth; let iclientHeight = window.innerHeight; var screenMouseX = lastX / iclientWidth; var screenMouseY = lastY / iclientHeight; //console.log(screenMouseX + ' ' + screenMouseY); //console.log(clientHeight + ' ' + clientWidth); let viewProj = mat4.create(); let invViewProj = mat4.create(); mat4.multiply(viewProj, camera.projectionMatrix, camera.viewMatrix); mat4.invert(invViewProj,viewProj); let mousePoint = vec4.fromValues(2.0 * screenMouseX - 1.0, 1.0 - 2.0 * screenMouseY, -1.0, 1.0); let mousePointEnd = vec4.fromValues(2.0 * screenMouseX - 1.0, 1.0 - 2.0 * screenMouseY, -0.0, 1.0); vec4.transformMat4(mousePoint,mousePoint,invViewProj); vec4.transformMat4(mousePointEnd,mousePointEnd,invViewProj); mousePoint[0] /= mousePoint[3]; mousePoint[1] /= mousePoint[3]; mousePoint[2] /= mousePoint[3]; mousePoint[3] /= mousePoint[3]; mousePointEnd[0] /= mousePointEnd[3]; mousePointEnd[1] /= mousePointEnd[3]; mousePointEnd[2] /= mousePointEnd[3]; mousePointEnd[3] /= mousePointEnd[3]; let dir = vec3.fromValues(mousePointEnd[0] - mousePoint[0], mousePointEnd[1] - mousePoint[1], mousePointEnd[2] - mousePoint[2]); vec3.normalize(dir,dir); let ro = vec3.fromValues(mousePoint[0], mousePoint[1], mousePoint[2]); //==========set initial terrain uniforms================= timer++; noiseterrain.setTime(timer); noiseterrain.setTerrainHeight(controls.TerrainHeight); noiseterrain.setTerrainScale(controls.TerrainScale); noiseterrain.setInt(controls.TerrainMask,"u_TerrainMask"); gl_context.uniform1i(gl_context.getUniformLocation(noiseterrain.prog,"u_terrainBaseType"),controls.TerrainBaseType); if(TerrainGeometryDirty){ //=============clean up all simulation textures=================== cleanUpTextures(); //=============recreate base terrain textures===================== Render2Texture(renderer,gl_context,camera,noiseterrain,read_terrain_tex); Render2Texture(renderer,gl_context,camera,noiseterrain,write_terrain_tex); TerrainGeometryDirty = false; } //ray cast happens here let pos = vec2.fromValues(0.0, 0.0); pos = rayCast(ro, dir); controls.posTemp = pos; //===================per tick uniforms================== flat.setTime(timer); gl_context.uniform1f(gl_context.getUniformLocation(flat.prog,"u_far"),camera.far); gl_context.uniform1f(gl_context.getUniformLocation(flat.prog,"u_near"),camera.near); gl_context.uniform3fv(gl_context.getUniformLocation(flat.prog,"unif_LightPos"),vec3.fromValues(controls.lightPosX,controls.lightPosY,controls.lightPosZ)); water.setWaterTransparency(controls.WaterTransparency); water.setSimres(simres); gl_context.uniform1f(gl_context.getUniformLocation(water.prog,"u_far"),camera.far); gl_context.uniform1f(gl_context.getUniformLocation(water.prog,"u_near"),camera.near); gl_context.uniform3fv(gl_context.getUniformLocation(water.prog,"unif_LightPos"),vec3.fromValues(controls.lightPosX,controls.lightPosY,controls.lightPosZ)); lambert.setTerrainDebug(controls.TerrainDebug); lambert.setMouseWorldPos(mousePoint); lambert.setMouseWorldDir(dir); lambert.setBrushSize(controls.brushSize); lambert.setBrushType(controls.brushType); lambert.setBrushPos(pos); lambert.setSimres(simres); lambert.setFloat(controls.SnowRange, "u_SnowRange"); lambert.setFloat(controls.ForestRange, "u_ForestRange"); lambert.setInt(controls.TerrainPlatte, "u_TerrainPlatte"); lambert.setInt(controls.ShowFlowTrace ? 0 : 1,"u_FlowTrace"); lambert.setInt(controls.SedimentTrace ? 0 : 1,"u_SedimentTrace"); lambert.setVec2(controls.posPerm,'u_permanentPos'); lambert.setInt(controls.pbrushOn, "u_pBrushOn"); lambert.setVec2(controls.pbrushData,"u_PBrushData"); gl_context.uniform3fv(gl_context.getUniformLocation(lambert.prog,"unif_LightPos"),vec3.fromValues(controls.lightPosX,controls.lightPosY,controls.lightPosZ)); sceneDepthShader.setSimres(simres); rains.setMouseWorldPos(mousePoint); rains.setMouseWorldDir(dir); rains.setBrushSize(controls.brushSize); rains.setBrushStrength(controls.brushStrenth); rains.setBrushType(controls.brushType); rains.setBrushPressed(controls.brushPressed); rains.setInt(controls.pbrushOn, "u_pBrushOn"); rains.setVec2(controls.pbrushData,"u_PBrushData"); rains.setBrushPos(pos); rains.setBrushOperation(controls.brushOperation); rains.setSpawnPos(vec2.fromValues(controls.spawnposx, controls.spawnposy)); rains.setVec2(controls.posPerm,'u_permanentPos'); rains.setTime(timer); gl_context.uniform1i(gl_context.getUniformLocation(rains.prog,"u_RainErosion"),controls.RainErosion ? 1 : 0); rains.setFloat(controls.RainErosionStrength,'u_RainErosionStrength'); rains.setFloat(controls.RainErosionDropSize,'u_RainErosionDropSize'); flow.setPipeLen(controls.pipelen); flow.setSimres(simres); flow.setTimestep(controls.timestep); flow.setPipeArea(controls.pipeAra); waterhight.setPipeLen(controls.pipelen); waterhight.setSimres(simres); waterhight.setTimestep(controls.timestep); waterhight.setPipeArea(controls.pipeAra); waterhight.setFloat(controls.VelocityMultiplier, 'u_VelMult'); waterhight.setTime(timer); sediment.setSimres(simres); sediment.setPipeLen(controls.pipelen); sediment.setKc(controls.Kc); sediment.setKs(controls.Ks); sediment.setKd(controls.Kd); sediment.setTimestep(controls.timestep); sediment.setTime(timer); sediadvect.setSimres(simres); sediadvect.setPipeLen(controls.pipelen); sediadvect.setKc(controls.Kc); sediadvect.setKs(controls.Ks); sediadvect.setKd(controls.Kd); sediadvect.setTimestep(controls.timestep); sediadvect.setFloat(controls.AdvectionSpeedScaling, "unif_advectionSpeedScale"); macCormack.setSimres(simres); macCormack.setPipeLen(controls.pipelen); macCormack.setKc(controls.Kc); macCormack.setKs(controls.Ks); macCormack.setKd(controls.Kd); macCormack.setTimestep(controls.timestep); macCormack.setFloat(controls.AdvectionSpeedScaling, "unif_advectionSpeedScale"); thermalterrainflux.setSimres(simres); thermalterrainflux.setPipeLen(controls.pipelen); thermalterrainflux.setTimestep(controls.timestep); thermalterrainflux.setPipeArea(controls.pipeAra); gl_context.uniform1f(gl_context.getUniformLocation(thermalterrainflux.prog,"unif_thermalRate"),controls.thermalRate); thermalapply.setSimres(simres); thermalapply.setPipeLen(controls.pipelen); thermalapply.setTimestep(controls.timestep); thermalapply.setPipeArea(controls.pipeAra); gl_context.uniform1f(gl_context.getUniformLocation(thermalapply.prog,"unif_thermalErosionScale"),controls.thermalErosionScale); maxslippageheight.setSimres(simres); maxslippageheight.setPipeLen(controls.pipelen); maxslippageheight.setTimestep(controls.timestep); maxslippageheight.setPipeArea(controls.pipeAra); maxslippageheight.setFloat(controls.thermalTalusAngleScale, "unif_TalusScale"); average.setSimres(simres); average.setInt(controls.ErosionMode,'unif_ErosionMode'); camera.update(); stats.begin(); //========================== we begin simulation from now =========================================== for(let i = 0;i<controls.SimulationSpeed;i++) { SimulationStep(SimFramecnt, flow, waterhight, sediment, sediadvect, macCormack,rains,evaporation,average,thermalterrainflux, thermalapply, maxslippageheight, renderer, gl_context, camera); SimFramecnt++; } gl_context.viewport(0, 0, window.innerWidth, window.innerHeight); renderer.clear(); //========================== we enter a series of render pass from now ================================ //========================== pass 1 : render shadow map pass===================================== gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,shadowMap_frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,shadowMap_tex,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,shadowMap_render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0]); let status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } gl_context.bindTexture(gl_context.TEXTURE_2D,null); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,null); gl_context.viewport(0,0,shadowMapResolution,shadowMapResolution); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,shadowMap_frame_buffer); renderer.clear();// clear when attached to shadow map shadowMapShader.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); gl_context.uniform1i(gl_context.getUniformLocation(shadowMapShader.prog,"hightmap"),0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D, read_sediment_tex); gl_context.uniform1i(gl_context.getUniformLocation(shadowMapShader.prog, "sedimap"), 1); let lightViewMat = mat4.create(); let lightProjMat = mat4.create(); lightProjMat = mat4.ortho(lightProjMat,-1.6,1.6,-1.6,1.6,0,100); lightViewMat = mat4.lookAt(lightViewMat, [controls.lightPosX,controls.lightPosY,controls.lightPosZ],[0,0,0],[0,1,0]); gl_context.uniformMatrix4fv(gl_context.getUniformLocation(shadowMapShader.prog,'u_proj'),false,lightProjMat); gl_context.uniformMatrix4fv(gl_context.getUniformLocation(shadowMapShader.prog,'u_view'),false,lightViewMat); shadowMapShader.setSimres(simres); renderer.render(camera,shadowMapShader,[plane]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); //=========================== pass 2 : render scene depth tex ================================ sceneDepthShader.use(); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,deferred_frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,scene_depth_tex,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,deferred_render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } renderer.clear();// clear when attached to scene depth map gl_context.viewport(0,0,window.innerWidth, window.innerHeight); renderer.render(camera, sceneDepthShader, [ plane, ]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); //============================= pass 3 : render terrain and water geometry ================================================ //============ terrain geometry ========= gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,deferred_frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,color_pass_tex,0); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT1,gl_context.TEXTURE_2D,color_pass_reflection_tex,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,deferred_render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0, gl_context.COLOR_ATTACHMENT1]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } renderer.clear(); lambert.use(); gl_context.viewport(0,0,window.innerWidth, window.innerHeight); //plane.setDrawMode(gl_context.LINE_STRIP); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); let PingUniform = gl_context.getUniformLocation(lambert.prog,"hightmap"); gl_context.uniform1i(PingUniform,0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D,terrain_nor); let norUniform = gl_context.getUniformLocation(lambert.prog,"normap"); gl_context.uniform1i(norUniform,1); gl_context.activeTexture(gl_context.TEXTURE2); gl_context.bindTexture(gl_context.TEXTURE_2D, read_sediment_tex); let sediUniform = gl_context.getUniformLocation(lambert.prog, "sedimap"); gl_context.uniform1i(sediUniform, 2); gl_context.activeTexture(gl_context.TEXTURE3); gl_context.bindTexture(gl_context.TEXTURE_2D, read_vel_tex); let velUniform = gl_context.getUniformLocation(lambert.prog, "velmap"); gl_context.uniform1i(velUniform, 3); gl_context.activeTexture(gl_context.TEXTURE4); gl_context.bindTexture(gl_context.TEXTURE_2D, read_flux_tex); let fluxUniform = gl_context.getUniformLocation(lambert.prog, "fluxmap"); gl_context.uniform1i(fluxUniform, 4); gl_context.activeTexture(gl_context.TEXTURE5); gl_context.bindTexture(gl_context.TEXTURE_2D, read_terrain_flux_tex); let terrainfluxUniform = gl_context.getUniformLocation(lambert.prog, "terrainfluxmap"); gl_context.uniform1i(terrainfluxUniform, 5); gl_context.activeTexture(gl_context.TEXTURE6); gl_context.bindTexture(gl_context.TEXTURE_2D, read_maxslippage_tex); let terrainslippageUniform = gl_context.getUniformLocation(lambert.prog, "maxslippagemap"); gl_context.uniform1i(terrainslippageUniform, 6); gl_context.activeTexture(gl_context.TEXTURE7); gl_context.bindTexture(gl_context.TEXTURE_2D, read_sediment_blend); gl_context.uniform1i(gl_context.getUniformLocation(lambert.prog, "sediBlend"), 7); gl_context.activeTexture(gl_context.TEXTURE8); gl_context.bindTexture(gl_context.TEXTURE_2D, shadowMap_tex); gl_context.uniform1i(gl_context.getUniformLocation(lambert.prog, "shadowMap"), 8); gl_context.activeTexture(gl_context.TEXTURE9); gl_context.bindTexture(gl_context.TEXTURE_2D, scene_depth_tex); gl_context.uniform1i(gl_context.getUniformLocation(lambert.prog, "sceneDepth"), 9); gl_context.uniformMatrix4fv(gl_context.getUniformLocation(lambert.prog,'u_sproj'),false,lightProjMat); gl_context.uniformMatrix4fv(gl_context.getUniformLocation(lambert.prog,'u_sview'),false,lightViewMat); renderer.render(camera, lambert, [ plane, ]); // =============== water ===================== gl_context.enable(gl_context.BLEND); gl_context.blendFunc(gl_context.SRC_ALPHA, gl_context.ONE_MINUS_SRC_ALPHA); water.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D,read_terrain_tex); PingUniform = gl_context.getUniformLocation(water.prog,"hightmap"); gl_context.uniform1i(PingUniform,0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D,terrain_nor); norUniform = gl_context.getUniformLocation(water.prog,"normap"); gl_context.uniform1i(norUniform,1); gl_context.activeTexture(gl_context.TEXTURE2); gl_context.bindTexture(gl_context.TEXTURE_2D,read_sediment_tex); sediUniform = gl_context.getUniformLocation(water.prog,"sedimap"); gl_context.uniform1i(sediUniform,2); gl_context.activeTexture(gl_context.TEXTURE3); gl_context.bindTexture(gl_context.TEXTURE_2D,scene_depth_tex); gl_context.uniform1i(gl_context.getUniformLocation(water.prog,"sceneDepth"),3); gl_context.activeTexture(gl_context.TEXTURE4); gl_context.bindTexture(gl_context.TEXTURE_2D,color_pass_reflection_tex); gl_context.uniform1i(gl_context.getUniformLocation(water.prog,"colorReflection"),4); renderer.render(camera, water, [ plane, ]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,null); gl_context.blendFunc(gl_context.SRC_ALPHA, gl_context.ONE_MINUS_SRC_ALPHA); // ======================== pass 4 : back ground & post processing & rayleigh mie scattering ================================== gl_context.bindFramebuffer(gl_context.FRAMEBUFFER,deferred_frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER,gl_context.COLOR_ATTACHMENT0,gl_context.TEXTURE_2D,scatter_pass_tex,0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER,gl_context.DEPTH_ATTACHMENT,gl_context.RENDERBUFFER,deferred_render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log( "frame buffer status:" + status.toString()); } renderer.clear();// clear when attached to scene depth map gl_context.viewport(0,0,window.innerWidth, window.innerHeight); flat.use(); gl_context.enable(gl_context.DEPTH_TEST); gl_context.depthFunc(gl_context.LESS); gl_context.enable(gl_context.BLEND); gl_context.blendFunc(gl_context.SRC_ALPHA, gl_context.ONE_MINUS_SRC_ALPHA); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D, read_sediment_tex); gl_context.uniform1i(gl_context.getUniformLocation(flat.prog,"hightmap"),0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D, scene_depth_tex); gl_context.uniform1i(gl_context.getUniformLocation(flat.prog,"sceneDepth"),1); gl_context.activeTexture(gl_context.TEXTURE2); gl_context.bindTexture(gl_context.TEXTURE_2D, shadowMap_tex); gl_context.uniform1i(gl_context.getUniformLocation(flat.prog,"shadowMap"),2); gl_context.uniformMatrix4fv(gl_context.getUniformLocation(flat.prog,'u_sproj'),false,lightProjMat); gl_context.uniformMatrix4fv(gl_context.getUniformLocation(flat.prog,'u_sview'),false,lightViewMat); gl_context.uniform1i(gl_context.getUniformLocation(flat.prog,"u_showScattering"),controls.showScattering ? 1 : 0); renderer.render(camera, flat, [ square, ]); gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, null); // ======================== pass 5 : bilateral blurring pass ================================== if(controls.enableBilateralBlur) { let NumBlurPass = 4; for (let i = 0; i < NumBlurPass; ++i) { gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, deferred_frame_buffer); gl_context.framebufferTexture2D(gl_context.FRAMEBUFFER, gl_context.COLOR_ATTACHMENT0, gl_context.TEXTURE_2D, bilateral_filter_horizontal_tex, 0); gl_context.framebufferRenderbuffer(gl_context.FRAMEBUFFER, gl_context.DEPTH_ATTACHMENT, gl_context.RENDERBUFFER, deferred_render_buffer); gl_context.drawBuffers([gl_context.COLOR_ATTACHMENT0]); status = gl_context.checkFramebufferStatus(gl_context.FRAMEBUFFER); if (status !== gl_context.FRAMEBUFFER_COMPLETE) { console.log("frame buffer status:" + status.toString()); } renderer.clear();// clear when attached to scene depth map bilateralBlur.use(); gl_context.activeTexture(gl_context.TEXTURE0); if (i == 0) { gl_context.bindTexture(gl_context.TEXTURE_2D, scatter_pass_tex); } else { gl_context.bindTexture(gl_context.TEXTURE_2D, bilateral_filter_vertical_tex); } gl_context.uniform1i(gl_context.getUniformLocation(bilateralBlur.prog, "scatter_tex"), 0); gl_context.activeTexture(gl_context.TEXTURE1); gl_context.bindTexture(gl_context.TEXTURE_2D, scene_depth_tex); gl_context.uniform1i(gl_context.getUniformLocation(bilateralBlur.prog, "scene_depth"), 1); gl_context.uniform1f(gl_context.getUniformLocation(bilateralBlur.prog, "u_far"), camera.far); gl_context.uniform1f(gl_context.getUniformLocation(bilateralBlur.prog, "u_near"), camera.near); gl_context.uniform1i(gl_context.getUniformLocation(bilateralBlur.prog, "u_isHorizontal"), i % 2); renderer.render(camera, bilateralBlur, [ square, ]); let tmp = bilateral_filter_horizontal_tex; bilateral_filter_horizontal_tex = bilateral_filter_vertical_tex; bilateral_filter_vertical_tex = tmp; gl_context.bindFramebuffer(gl_context.FRAMEBUFFER, null); } } // ===================================== pass 6 : combination pass ===================================================================== combinedShader.use(); gl_context.activeTexture(gl_context.TEXTURE0); gl_context.bindTexture(gl_context.TEXTURE_2D, color_pass_tex); gl_context.uniform1i(gl_context.getUniformLocation(combinedShader.prog,"color_tex"),0); gl_context.activeTexture(gl_context.TEXTURE1); if(controls.enableBilateralBlur) gl_context.bindTexture(gl_context.TEXTURE_2D, bilateral_filter_horizontal_tex); else gl_context.bindTexture(gl_context.TEXTURE_2D, scatter_pass_tex); gl_context.uniform1i(gl_context.getUniformLocation(combinedShader.prog,"bi_tex"),1); gl_context.activeTexture(gl_context.TEXTURE2); gl_context.bindTexture(gl_context.TEXTURE_2D, scene_depth_tex); gl_context.uniform1i(gl_context.getUniformLocation(combinedShader.prog,"sceneDepth_tex"),2); renderer.clear(); renderer.render(camera, combinedShader, [ square, ]); gl_context.disable(gl_context.BLEND); //gl_context.disable(gl_context.DEPTH_TEST); stats.end(); // Tell the browser to call `tick` again whenever it renders a new frame requestAnimationFrame(tick); } window.addEventListener('resize', function() { gl_context.bindRenderbuffer(gl_context.RENDERBUFFER,deferred_render_buffer); gl_context.renderbufferStorage(gl_context.RENDERBUFFER,gl_context.DEPTH_COMPONENT16, window.innerWidth,window.innerHeight); gl_context.bindTexture(gl_context.TEXTURE_2D,color_pass_reflection_tex); gl_context.texImage2D(gl_context.TEXTURE_2D,0,gl_context.RGBA32F,window.innerWidth,window.innerHeight,0, gl_context.RGBA,gl_context.FLOAT,null); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MIN_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MAG_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_S, gl_context.CLAMP_TO_EDGE); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_T, gl_context.CLAMP_TO_EDGE); gl_context.bindTexture(gl_context.TEXTURE_2D,scatter_pass_tex); gl_context.texImage2D(gl_context.TEXTURE_2D,0,gl_context.RGBA32F,window.innerWidth,window.innerHeight,0, gl_context.RGBA,gl_context.FLOAT,null); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MIN_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MAG_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_S, gl_context.CLAMP_TO_EDGE); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_T, gl_context.CLAMP_TO_EDGE); gl_context.bindTexture(gl_context.TEXTURE_2D,color_pass_tex); gl_context.texImage2D(gl_context.TEXTURE_2D,0,gl_context.RGBA32F,window.innerWidth,window.innerHeight,0, gl_context.RGBA,gl_context.FLOAT,null); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MIN_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MAG_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_S, gl_context.CLAMP_TO_EDGE); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_T, gl_context.CLAMP_TO_EDGE); gl_context.bindTexture(gl_context.TEXTURE_2D,bilateral_filter_vertical_tex); gl_context.texImage2D(gl_context.TEXTURE_2D,0,gl_context.RGBA32F,window.innerWidth,window.innerHeight,0, gl_context.RGBA,gl_context.FLOAT,null); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MIN_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MAG_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_S, gl_context.CLAMP_TO_EDGE); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_T, gl_context.CLAMP_TO_EDGE); gl_context.bindTexture(gl_context.TEXTURE_2D,bilateral_filter_horizontal_tex); gl_context.texImage2D(gl_context.TEXTURE_2D,0,gl_context.RGBA32F,window.innerWidth,window.innerHeight,0, gl_context.RGBA,gl_context.FLOAT,null); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MIN_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MAG_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_S, gl_context.CLAMP_TO_EDGE); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_T, gl_context.CLAMP_TO_EDGE); gl_context.bindTexture(gl_context.TEXTURE_2D,scene_depth_tex); gl_context.texImage2D(gl_context.TEXTURE_2D,0,gl_context.RGBA32F,window.innerWidth,window.innerHeight,0, gl_context.RGBA,gl_context.FLOAT,null); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MIN_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MAG_FILTER, gl_context.LINEAR); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_S, gl_context.CLAMP_TO_EDGE); gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_T, gl_context.CLAMP_TO_EDGE); renderer.setSize(window.innerWidth, window.innerHeight); camera.setAspectRatio(window.innerWidth / window.innerHeight); camera.updateProjectionMatrix(); }, false); renderer.setSize(window.innerWidth, window.innerHeight); camera.setAspectRatio(window.innerWidth / window.innerHeight); camera.updateProjectionMatrix(); // Start the render loop tick(); } main();
the_stack
import { HTMLAttributes } from 'react'; import { Story } from '../../../../lib/@types/storybook-emotion-10-fixes'; import { asChromaticStory, asPlayground } from '../../../../lib/story-intents'; import { Container } from '../Container/Container'; import { Column } from './Column'; import { Columns, ColumnsProps } from './Columns'; const style = { backgroundColor: 'rgba(255, 0, 0, 0.25)' }; const Code = (args: HTMLAttributes<HTMLElement>) => ( <code style={{ whiteSpace: 'nowrap' }} {...args} /> ); export default { title: 'Source/src-layout/Columns', component: Columns, subcomponents: { Column }, }; const Template: Story<ColumnsProps> = (args) => ( <Columns {...args} style={style}> <Column style={style}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut faucibus nibh erat, eget rutrum ligula vehicula sit amet. Etiam scelerisque dapibus pulvinar. Integer non accumsan justo. Duis et vehicula risus. Nulla ligula eros, consequat sodales lectus eget, eleifend venenatis neque. </Column> <Column style={style}> Interdum et malesuada fames ac ante ipsum primis in faucibus. Nulla facilisi. Phasellus id aliquam odio. Aliquam tempus eu enim in fermentum. Donec ut velit vel purus rutrum vulputate ut scelerisque lacus. </Column> <Column style={style}> Pellentesque id ornare turpis. Aliquam laoreet aliquet pharetra. Donec nec erat ac libero interdum sollicitudin. Nullam imperdiet ut dolor non cursus. Integer et ante fringilla, luctus magna nec, consequat est. </Column> <Column style={style}> Nunc nec dapibus quam. Praesent nec neque vel velit mollis tempor. Suspendisse justo eros, pharetra et elit sit amet, hendrerit laoreet dui. Curabitur ut libero nibh. Duis finibus sollicitudin tortor, ac viverra urna commodo et. </Column> <Column style={style}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Non igitur potestis voluptate omnia dirigentes aut tueri aut retinere virtutem. Hoc Hieronymus summum bonum esse dixit. </Column> </Columns> ); // ***************************************************************************** export const Playground = Template.bind({}); asPlayground(Playground); // ***************************************************************************** export const Default = Template.bind({}); Default.parameters = { viewport: { defaultViewport: 'tablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(Default); // ***************************************************************************** export const CollapseUntilTabletWithNoSpacing = Template.bind({}); CollapseUntilTabletWithNoSpacing.args = { collapseUntil: 'tablet', }; CollapseUntilTabletWithNoSpacing.parameters = { viewport: { defaultViewport: 'phablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(CollapseUntilTabletWithNoSpacing); // ***************************************************************************** export const CollapseUntilTabletWithSpace1 = Template.bind({}); CollapseUntilTabletWithSpace1.args = { collapseUntil: 'tablet', spaceY: '1', }; CollapseUntilTabletWithSpace1.parameters = { viewport: { defaultViewport: 'phablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(CollapseUntilTabletWithSpace1); // ***************************************************************************** export const CollapseUntilTabletWithSpace2 = Template.bind({}); CollapseUntilTabletWithSpace2.args = { collapseUntil: 'tablet', spaceY: '2', }; CollapseUntilTabletWithSpace2.parameters = { viewport: { defaultViewport: 'phablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(CollapseUntilTabletWithSpace2); // ***************************************************************************** export const CollapseUntilTabletWithSpace3 = Template.bind({}); CollapseUntilTabletWithSpace3.args = { collapseUntil: 'tablet', spaceY: '3', }; CollapseUntilTabletWithSpace3.parameters = { viewport: { defaultViewport: 'phablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(CollapseUntilTabletWithSpace3); // ***************************************************************************** export const CollapseUntilTabletWithSpace4 = Template.bind({}); CollapseUntilTabletWithSpace4.args = { collapseUntil: 'tablet', spaceY: '4', }; CollapseUntilTabletWithSpace4.parameters = { viewport: { defaultViewport: 'phablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(CollapseUntilTabletWithSpace4); // ***************************************************************************** export const CollapseUntilTabletWithSpace5 = Template.bind({}); CollapseUntilTabletWithSpace5.args = { collapseUntil: 'tablet', spaceY: '5', }; CollapseUntilTabletWithSpace5.parameters = { viewport: { defaultViewport: 'phablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(CollapseUntilTabletWithSpace5); // ***************************************************************************** export const CollapseUntilTabletWithSpace6 = Template.bind({}); CollapseUntilTabletWithSpace6.args = { collapseUntil: 'tablet', spaceY: '6', }; CollapseUntilTabletWithSpace6.parameters = { viewport: { defaultViewport: 'phablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(CollapseUntilTabletWithSpace6); // ***************************************************************************** export const CollapseUntilTabletWithSpace9 = Template.bind({}); CollapseUntilTabletWithSpace9.args = { collapseUntil: 'tablet', spaceY: '9', }; CollapseUntilTabletWithSpace9.parameters = { viewport: { defaultViewport: 'phablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(CollapseUntilTabletWithSpace9); // ***************************************************************************** export const CollapseUntilTabletWithSpace12 = Template.bind({}); CollapseUntilTabletWithSpace12.args = { collapseUntil: 'tablet', spaceY: '12', }; CollapseUntilTabletWithSpace12.parameters = { viewport: { defaultViewport: 'phablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(CollapseUntilTabletWithSpace12); // ***************************************************************************** export const CollapseUntilTabletWithSpace24 = Template.bind({}); CollapseUntilTabletWithSpace24.args = { collapseUntil: 'tablet', spaceY: '24', }; CollapseUntilTabletWithSpace24.parameters = { viewport: { defaultViewport: 'phablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(CollapseUntilTabletWithSpace24); // ***************************************************************************** export const WithContainer: Story<ColumnsProps> = (args) => ( <Container style={style}>{Template(args)}</Container> ); WithContainer.parameters = { layout: 'fullscreen', }; asChromaticStory(WithContainer); // ***************************************************************************** export const ResponsiveAtPhablet: Story<ColumnsProps> = (args) => ( <Container style={style}> <Columns {...args}> <Column width={[1 / 2, 1 / 4]} style={style}> <p>default 50% wide, 25% from tablet</p> <Code>{'width={[1 / 2, 1 / 4]}'}</Code> </Column> <Column width={[1 / 2, 3 / 4]} style={style}> <p>default 50% wide, 75% from tablet</p> <Code>{'width={[1 / 2, 3 / 4]}'}</Code> </Column> </Columns> </Container> ); ResponsiveAtPhablet.parameters = { viewport: { defaultViewport: 'phablet' }, layout: 'fullscreen', outline: true, }; asChromaticStory(ResponsiveAtPhablet); // ***************************************************************************** export const ResponsiveAtTablet: Story<ColumnsProps> = (args) => ( <Container style={style}> <Columns {...args}> <Column width={[1 / 2, 1 / 4]} style={style}> <p>default 50% wide, 25% from tablet</p> <Code>{'width={[1 / 2, 1 / 4]}'}</Code> </Column> <Column width={[1 / 2, 3 / 4]} style={style}> <p>default 50% wide, 75% from tablet</p> <Code>{'width={[1 / 2, 3 / 4]}'}</Code> </Column> </Columns> </Container> ); ResponsiveAtTablet.parameters = { viewport: { defaultViewport: 'tablet' }, layout: 'fullscreen', }; asChromaticStory(ResponsiveAtTablet); // ***************************************************************************** export const ResponsiveHideAtTablet: Story<ColumnsProps> = (args) => ( <Container style={style}> <Columns {...args}> <Column width={[0, 1 / 4]} style={style}> <p>hidden at mobile, 25% from tablet</p> <Code>{'width={[0, 1 / 4]}'}</Code> </Column> <Column width={[1, 3 / 4]} style={style}> <p>default 100% wide, 75% from tablet</p> <Code>{'width={[1, 3 / 4]}'}</Code> </Column> </Columns> </Container> ); ResponsiveHideAtTablet.parameters = { viewport: { defaultViewport: 'tablet' }, layout: 'fullscreen', }; asChromaticStory(ResponsiveHideAtTablet); // ***************************************************************************** export const ResponsiveHideAtMobile: Story<ColumnsProps> = (args) => ( <Container style={style}> <Columns {...args}> <Column width={[0, 1 / 4]} style={style}> <p>hidden at mobile, 25% from tablet</p> <Code>{'width={[0, 1 / 4]}'}</Code> </Column> <Column width={[1, 3 / 4]} style={style}> <p>default 100% wide, 75% from tablet</p> <Code>{'width={[1, 3 / 4]}'}</Code> </Column> </Columns> </Container> ); ResponsiveHideAtMobile.parameters = { viewport: { defaultViewport: 'mobile' }, layout: 'fullscreen', }; asChromaticStory(ResponsiveHideAtMobile); // ***************************************************************************** export const WithSpan: Story<ColumnsProps> = (args) => ( <> <p> Elements with a <Code>{'span'}</Code> prop will scale at our{' '} <a href="https://theguardian.design/2a1e5182b/p/41be19-grids"> established breakpoints </a> : </p> <Container style={style}> <Columns> <Column style={style} span={1}> <Code>{'span={1}'}</Code> </Column> <Column style={style} span={1}> <Code>{'span={1}'}</Code> </Column> <Column style={style} span={2}> <Code>{'span={2}'}</Code> </Column> </Columns> </Container> <p></p> <Container style={style}> <Columns> <Column style={style} span={2}> <Code>{'span={2}'}</Code> </Column> <Column style={style} /> <Column style={style} span={1}> <Code>{'span={1}'}</Code> </Column> </Columns> </Container> <p> An array of <Code>{'span'}</Code> values can be specified for relevant breakpoints: </p> <Container style={style}> <Columns> <Column style={style} span={4}> <Code>{'span={4}'}</Code> </Column> <Column style={style} span={[0, 4, 4]}> <Code>{'span={[0, 4]}'}</Code> </Column> <Column style={style} span={[0, 4, 4, 6, 8]}> <Code>{'span={[0, 0, 4, 6, 8]}'}</Code> </Column> </Columns> </Container> <p> An element with a <Code>{'span'}</Code> will not extend beyond 100% of the browser width: </p> <Container style={style}> <Columns> <Column style={style} span={12}> <Code>{'span={12}'}</Code> </Column> </Columns> </Container> <p> A <Code>{'span'}</Code> of 0 will cause the element not to be displayed. </p> <Container style={style}> <Columns> <Column style={style}>*</Column> <Column style={style} span={[0, 0, 2]}> <Code>{'span={[0, 0, 2]}'}</Code> </Column> <Column style={style} span={[0, 0, 2]}> <Code>{'span={[0, 0, 2]}'}</Code> </Column> </Columns> </Container> <p> <Code>{'span'}</Code> is overruled by <Code>{'width'}</Code> prop: </p> <Container style={style}> <Columns> <Column style={style} span={2} width={3 / 4}> <Code>{'span={2} width={3 / 4}'}</Code> </Column> <Column style={style} width={1 / 4}> <Code>{'width={1 / 4}'}</Code> </Column> </Columns> </Container> </> ); WithSpan.parameters = { layout: 'fullscreen', }; asChromaticStory(WithSpan); // ***************************************************************************** export const WithWidth: Story<ColumnsProps> = (args) => ( <> <Container style={style}> <Columns> <Column width={1 / 4} style={style}> <Code>{'width={1 / 4}'}</Code> </Column> <Column style={style} /> <Column style={style} /> </Columns> </Container> <p></p> <Container style={style}> <Columns> <Column width={1 / 3} style={style}> <Code>{'width={1 / 3}'}</Code> </Column> <Column style={style} /> <Column style={style} /> </Columns> </Container> <p></p> <Container style={style}> <Columns> <Column width={1 / 2} style={style}> <Code>{'width={1 / 2}'}</Code> </Column> <Column style={style} /> <Column style={style} /> </Columns> </Container> <p></p> <Container style={style}> <Columns> <Column width={3 / 4} style={style}> <Code>{'width={3 / 4}'}</Code> </Column> <Column style={style} /> <Column style={style} /> </Columns> </Container> </> ); WithWidth.parameters = { layout: 'fullscreen', }; asChromaticStory(WithWidth);
the_stack
import { animate, timeline } from '../../src/main'; import * as chai from 'chai'; import { getEffects } from '../../src/lib/model/effects'; import { getState } from '../../src/lib/store'; const { assert } = chai; describe('basic', () => { it('resolves single target', () => { /* Test code */ const target1 = {}; const t1 = animate({ easing: 'linear', duration: 1000, targets: target1, props: { opacity: [0, 1] } }); const actual = getEffects(getState(t1.id))[0]; assert.deepEqual(actual, { target: target1, from: 0, to: 1000, plugin: 'props', prop: 'opacity', keyframes: [ { offset: 0, value: 0, easing: 'linear', interpolate: undefined }, { offset: 1, value: 1, easing: 'linear', interpolate: undefined } ] }); t1.destroy(); }); it('decomposes and then re-composes a single set of keyframes', () => { /* Test code */ const target = {}; const t1 = animate().add({ duration: 1000, easing: 'linear', targets: target, props: { opacity: [0, 1] } }); const actual = getEffects(getState(t1.id)); assert.deepEqual<{}>(actual, [ { target, from: 0, to: 1000, plugin: 'props', prop: 'opacity', keyframes: [ { offset: 0, value: 0, easing: 'linear', interpolate: undefined }, { offset: 1, value: 1, easing: 'linear', interpolate: undefined } ] } ]); t1.destroy(); }); it('decomposes and then re-composes a single set of keyframes for multiple targets', () => { /* Test code */ const target1 = { id: 'element1' }; const target2 = { id: 'element2' }; const t1 = animate() .add({ easing: 'linear', duration: 1000, targets: [target1], props: { opacity: [0, 1] } }) .add({ easing: 'linear', duration: 1000, targets: [target2], props: { number: [0, 200] } }); const actual = getEffects(getState(t1.id)); assert.deepEqual<{}>(actual, [ { target: target1, from: 0, to: 1000, plugin: 'props', prop: 'opacity', keyframes: [ { offset: 0, value: 0, easing: 'linear', interpolate: undefined }, { offset: 1, value: 1, easing: 'linear', interpolate: undefined } ] }, { target: target2, from: 1000, to: 2000, plugin: 'props', prop: 'number', keyframes: [ { offset: 0, value: 0, easing: 'linear', interpolate: undefined }, { offset: 1, value: 200, easing: 'linear', interpolate: undefined } ] } ]); t1.destroy(); }); it('functions on properties resolve target', () => { /* Test code */ const target1 = { opacity: 0.1 }; const target2 = { opacity: 0.2 }; const opacityFromTarget = (target: {}) => { return (target as any).opacity; }; const t1 = animate({ duration: 1000, easing: 'linear', targets: [target1, target2], props: { opacity: [opacityFromTarget, 1] } }); const actual = getEffects(getState(t1.id)); assert.deepEqual<{}>(actual, [ { target: { opacity: 0.1 }, from: 0, to: 1000, plugin: 'props', prop: 'opacity', keyframes: [ { offset: 0, value: 0.1, easing: 'linear', interpolate: undefined }, { offset: 1, value: 1, easing: 'linear', interpolate: undefined } ] }, { target: { opacity: 0.2 }, from: 0, to: 1000, plugin: 'props', prop: 'opacity', keyframes: [ { offset: 0, value: 0.2, easing: 'linear', interpolate: undefined }, { offset: 1, value: 1, easing: 'linear', interpolate: undefined } ] } ]); t1.destroy(); }); it('functions on properties resolve index', () => { /* Test code */ const target1 = {}; const target2 = {}; const opacityFromIndex = (_target: {}, index: number) => { return 0.1 * (index + 1); }; const t1 = animate({ duration: 1000, easing: 'linear', targets: [target1, target2], props: { opacity: [opacityFromIndex, 1] } }); const actual = getEffects(getState(t1.id)); assert.deepEqual<{}>(actual, [ { target: {}, from: 0, to: 1000, plugin: 'props', prop: 'opacity', keyframes: [ { offset: 0, value: 0.1, easing: 'linear', interpolate: undefined }, { offset: 1, value: 1, easing: 'linear', interpolate: undefined } ] }, { target: {}, from: 0, to: 1000, plugin: 'props', prop: 'opacity', keyframes: [ { offset: 0, value: 0.2, easing: 'linear', interpolate: undefined }, { offset: 1, value: 1, easing: 'linear', interpolate: undefined } ] } ]); t1.destroy(); }); it('only last value for opacity at an offset is kept, others are ignored', () => { /* Test code */ const target1 = {}; const t1 = animate({ easing: 'linear', duration: 1000, targets: [target1], props: { opacity: [ { value: 0, offset: 0 }, { value: 1, offset: 0 }, { value: 1, offset: 1 }, { value: 0, offset: 1 } ] } }); const actual = getEffects(getState(t1.id)); assert.deepEqual<{}>(actual, [ { target: {}, from: 0, to: 1000, plugin: 'props', prop: 'opacity', keyframes: [ { offset: 0, value: 1, easing: 'linear', interpolate: undefined }, { offset: 1, value: 0, easing: 'linear', interpolate: undefined } ] } ]); t1.destroy(); }); it('add() accepts an array', () => { /* Test code */ const target1 = { id: 'element1' }; const target2 = { id: 'element2' }; const t1 = timeline(); t1.add([ { easing: 'linear', duration: 1000, targets: target1, props: { opacity: [0, 1] } }, { easing: 'linear', duration: 1000, targets: target2, props: { number: [0, 200] } } ]); const actual = getEffects(getState(t1.id)); assert.deepEqual<{}>(actual, [ { target: target1, from: 0, to: 1000, plugin: 'props', prop: 'opacity', keyframes: [ { offset: 0, value: 0, easing: 'linear', interpolate: undefined }, { offset: 1, value: 1, easing: 'linear', interpolate: undefined } ] }, { target: target2, from: 0, to: 1000, plugin: 'props', prop: 'number', keyframes: [ { offset: 0, value: 0, easing: 'linear', interpolate: undefined }, { offset: 1, value: 200, easing: 'linear', interpolate: undefined } ] } ]); t1.destroy(); }); it('fromTo() accepts an array', () => { /* Test code */ const target1 = { id: 'element1' }; const target2 = { id: 'element2' }; const t1 = timeline(); t1.fromTo(200, 800, [ { easing: 'linear', targets: target1, props: { opacity: [0, 1] } }, { easing: 'linear', targets: target2, props: { number: [0, 200] } } ]); const actual = getEffects(getState(t1.id)); assert.deepEqual<{}>(actual, [ { target: target1, from: 200, to: 800, plugin: 'props', prop: 'opacity', keyframes: [ { offset: 0, value: 0, easing: 'linear', interpolate: undefined }, { offset: 1, value: 1, easing: 'linear', interpolate: undefined } ] }, { target: target2, from: 200, to: 800, plugin: 'props', prop: 'number', keyframes: [ { offset: 0, value: 0, easing: 'linear', interpolate: undefined }, { offset: 1, value: 200, easing: 'linear', interpolate: undefined } ] } ]); t1.destroy(); }); it('sets props at specific times', () => { /* Test code */ const target = { opacity: -1 }; const t1 = timeline(); t1.set({ easing: 'linear', targets: target, props: { opacity: 0 } }); t1.set({ at: 1000, easing: 'linear', targets: target, props: { opacity: 1 } }); t1.pause(); t1.currentTime = 0; assert.equal(target.opacity, 0); t1.currentTime = 999; assert.equal(target.opacity, 0); t1.currentTime = 1000; assert.equal(target.opacity, 1); t1.destroy(); }); it('sets props dynamically at the current time', () => { /* Test code */ const target = { opacity: -1, transformOrigin: 'inherit' }; const t1 = timeline(); t1.add({ duration: 1000, easing: 'linear', targets: target, props: { opacity: [1, 0] } }); t1.set({ targets: target, props: { transformOrigin: 'center center' } }); t1.pause(); t1.currentTime = 999; assert.equal(target.transformOrigin, 'inherit'); t1.currentTime = 1000; assert.equal(target.transformOrigin, 'center center'); t1.destroy(); }); xit('player actually plays', done => { /* Test code */ const target = { x: 0 }; const t1 = animate({ targets: target, duration: 1000, easing: 'linear', props: { x: 1000 } }); t1.play({ destroy: true }); setTimeout(() => { assert.approximately(target.x, 500, 50); t1.destroy(); done(); }, 500); }); it('accessing a destroyed animation throws an error', done => { const t1 = animate({ targets: { x: 200 }, duration: 1000, props: { x: 0 } }); t1.play().destroy(); setTimeout(() => { assert.throws(function() { t1.duration; }); assert.throws(function() { t1.currentTime; }); assert.throws(function() { t1.playbackRate; }); assert.throws(function() { t1.play(); }); done(); }); }); it('auto-destroy removes an animation after it finished playing', done => { const t1 = animate({ targets: { x: 200 }, duration: 200, props: { x: 0 } }); t1.on('finish', function() { setTimeout(() => { assert.throws(function() { t1.duration; }); assert.throws(function() { t1.currentTime; }); assert.throws(function() { t1.playbackRate; }); assert.throws(function() { t1.play(); }); done(); }); }); t1.play({ destroy: true }); }); it('once() only handles the event one time', done => { var iterations = 0; const t1 = timeline() .animate({ targets: { x: 200 }, duration: 200, props: { x: 0 } }) .once('update', () => { iterations++; }) .on('finish', () => { assert.equal(iterations, 1); t1.destroy(); done(); }); t1.play(); }); });
the_stack
import * as chai from 'chai'; import 'mocha'; import { AbiEncoder, BigNumber } from '../../src/'; import { chaiSetup } from '../utils/chai_setup'; import * as ReturnValueAbis from './abi_samples/return_value_abis'; chaiSetup.configure(); const expect = chai.expect; describe('ABI Encoder: Return Value Encoding/Decoding', () => { const DECODE_BEYOND_CALL_DATA_ERROR = 'Tried to decode beyond the end of calldata'; const encodingRules: AbiEncoder.EncodingRules = { shouldOptimize: false }; // optimizer is tested separately. const nullEncodedReturnValue = '0x'; describe('Standard encoding/decoding', () => { it('No Return Value', async () => { // Decode return value const method = new AbiEncoder.Method(ReturnValueAbis.noReturnValues); const returnValue = '0x'; const decodedReturnValue = method.decodeReturnValues(returnValue, { shouldConvertStructsToObjects: false }); const expectedDecodedReturnValue: any[] = []; expect(decodedReturnValue).to.be.deep.equal(expectedDecodedReturnValue); }); it('Single static return value', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.singleStaticReturnValue); const returnValue = ['0x01020304']; const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); const decodedReturnValue = method.decodeReturnValues(encodedReturnValue, { shouldConvertStructsToObjects: false, }); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue); }); it('Multiple static return values', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.multipleStaticReturnValues); const returnValue = ['0x01020304', '0x05060708']; const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); const decodedReturnValue = method.decodeReturnValues(encodedReturnValue, { shouldConvertStructsToObjects: false, }); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue); }); it('Single dynamic return value', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.singleDynamicReturnValue); const returnValue = ['0x01020304']; const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); const decodedReturnValue = method.decodeReturnValues(encodedReturnValue, { shouldConvertStructsToObjects: false, }); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue); }); it('Multiple dynamic return values', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.multipleDynamicReturnValues); const returnValue = ['0x01020304', '0x05060708']; const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); const decodedReturnValue = method.decodeReturnValues(encodedReturnValue, { shouldConvertStructsToObjects: false, }); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue); }); it('Mixed static/dynamic return values', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.mixedStaticAndDynamicReturnValues); const returnValue = ['0x01020304', '0x05060708']; const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); const decodedReturnValue = method.decodeReturnValues(encodedReturnValue, { shouldConvertStructsToObjects: false, }); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue); }); it('Should decode NULL as default value (single; static)', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.singleStaticReturnValue); const returnValue = ['0x00000000']; const decodedReturnValue = method.decodeReturnValues(nullEncodedReturnValue, { shouldConvertStructsToObjects: false, }); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue); }); it('Should decode NULL as default value (multiple; static)', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.multipleStaticReturnValues); const returnValue = ['0x00000000', '0x00000000']; const decodedReturnValue = method.decodeReturnValues(nullEncodedReturnValue, { shouldConvertStructsToObjects: false, }); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue); }); it('Should decode NULL as default value (single; dynamic)', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.singleDynamicReturnValue); const returnValue = ['0x']; const decodedReturnValue = method.decodeReturnValues(nullEncodedReturnValue, { shouldConvertStructsToObjects: false, }); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue); }); }); describe('Strict encoding/decoding', () => { it('No Return Value', async () => { // Decode return value const method = new AbiEncoder.Method(ReturnValueAbis.noReturnValues); const returnValue = '0x'; const decodedReturnValue = method.strictDecodeReturnValue<void>(returnValue); const expectedDecodedReturnValue = undefined; expect(decodedReturnValue).to.be.deep.equal(expectedDecodedReturnValue); }); it('Single static return value', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.singleStaticReturnValue); const returnValue = ['0x01020304']; const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); const decodedReturnValue = method.strictDecodeReturnValue<string>(encodedReturnValue); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue[0]); }); it('Multiple static return values', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.multipleStaticReturnValues); const returnValue = ['0x01020304', '0x05060708']; const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); const decodedReturnValue = method.strictDecodeReturnValue<[string, string]>(encodedReturnValue); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue); }); it('Single dynamic return value', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.singleDynamicReturnValue); const returnValue = ['0x01020304']; const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); const decodedReturnValue = method.strictDecodeReturnValue<string>(encodedReturnValue); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue[0]); }); it('Multiple dynamic return values', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.multipleDynamicReturnValues); const returnValue = ['0x01020304', '0x05060708']; const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); const decodedReturnValue = method.strictDecodeReturnValue<[string, string]>(encodedReturnValue); // Validate decoded return value expect(decodedReturnValue).to.be.deep.equal(returnValue); }); it('Struct should include fields', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.structuredReturnValue); const returnValue = { fillResults: { makerAssetFilledAmount: new BigNumber(50), takerAssetFilledAmount: new BigNumber(40), }, }; const encodedReturnValue = method.encodeReturnValues(returnValue, encodingRules); const decodedReturnValue = method.strictDecodeReturnValue<{ makerAssetFilledAmount: BigNumber; takerAssetFilledAmount: BigNumber; }>(encodedReturnValue); // Validate decoded return value // Note that only the contents of `fillResults`, not the key itself, is decoded. // This is by design, as only a struct's contents are encoded and returned by a funciton call. expect(decodedReturnValue).to.be.deep.equal(returnValue.fillResults); }); it('Should fail to decode NULL (single; static)', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.singleStaticReturnValue); const encodedReturnValue = '0x'; const decodeReturnValue = () => method.strictDecodeReturnValue<string>(encodedReturnValue); // Validate decoded return value expect(decodeReturnValue).to.throws(DECODE_BEYOND_CALL_DATA_ERROR); }); it('Should fail to decode NULL (multiple; static)', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.multipleStaticReturnValues); const encodedReturnValue = '0x'; const decodeReturnValue = () => method.strictDecodeReturnValue<[string, string]>(encodedReturnValue); // Validate decoded return value expect(decodeReturnValue).to.throws(DECODE_BEYOND_CALL_DATA_ERROR); }); it('Should fail to decode NULL (single; dynamic)', async () => { // Generate Return Value const method = new AbiEncoder.Method(ReturnValueAbis.singleDynamicReturnValue); const encodedReturnValue = '0x'; const decodeReturnValue = () => method.strictDecodeReturnValue<string>(encodedReturnValue); // Validate decoded return value expect(decodeReturnValue).to.throws(DECODE_BEYOND_CALL_DATA_ERROR); }); }); });
the_stack
import { AffectedTaskOccurrence } from "../../Enumerations/AffectedTaskOccurrence"; import { DeleteMode } from "../../Enumerations/DeleteMode"; import { EwsLogging } from "../EwsLogging"; import { EwsServiceXmlReader } from "../EwsServiceXmlReader"; import { EwsServiceXmlWriter } from "../EwsServiceXmlWriter"; import { ExchangeService } from "../ExchangeService"; import { ExchangeVersion } from "../../Enumerations/ExchangeVersion"; import { ExtendedPropertyCollection } from "../../ComplexProperties/ExtendedPropertyCollection"; import { ExtendedPropertyDefinition } from "../../PropertyDefinitions/ExtendedPropertyDefinition"; import { InvalidOperationException } from "../../Exceptions/InvalidOperationException"; import { IOutParam } from "../../Interfaces/IOutParam"; import { NotSupportedException } from "../../Exceptions/NotSupportedException"; import { Promise } from "../../Promise"; import { PropertyBag } from "../PropertyBag"; import { PropertyDefinition } from "../../PropertyDefinitions/PropertyDefinition"; import { PropertyDefinitionBase } from "../../PropertyDefinitions/PropertyDefinitionBase"; import { PropertySet } from "../PropertySet"; import { SendCancellationsMode } from "../../Enumerations/SendCancellationsMode"; import { ServiceId } from "../../ComplexProperties/ServiceId"; import { ServiceObjectChangedDelegate } from "../../Misc/DelegateTypes"; import { ServiceObjectPropertyException } from "../../Exceptions/ServiceObjectPropertyException"; import { ServiceObjectSchema } from "./Schemas/ServiceObjectSchema"; import { StringHelper } from "../../ExtensionMethods"; import { Strings } from "../../Strings"; import { XmlElementNames } from "../../Core/XmlElementNames"; /** * Represents the base abstract class for all item and folder types. */ export abstract class ServiceObject { private lockObject: any = {}; //private service: ExchangeService; /** workaround for service variable exposer in console.log */ private getService: () => ExchangeService; private setService: (service: ExchangeService) => void; private propertyBag: PropertyBag; private xmlElementName: string; /** * @internal The property bag holding property values for this object. */ get PropertyBag(): PropertyBag { return this.propertyBag; } /** * Gets the schema associated with this type of object. */ get Schema(): ServiceObjectSchema { return this.GetSchema(); } /** * Gets the ExchangeService the object is bound to. */ get Service(): ExchangeService { return this.getService(); } /**@internal set*/ set Service(value: ExchangeService) { this.setService(value); } /** * Indicates whether this object is a real store item, or if it's a local object that has yet to be saved. */ get IsNew(): boolean { var id = this.GetId(); return id == null ? true : !id.IsValid; } /** * Gets a value indicating whether the object has been modified and should be saved. */ get IsDirty(): boolean { return this.PropertyBag.IsDirty; } /** * Defines an event that is triggered when the service object changes. */ private OnChange: ServiceObjectChangedDelegate[] = []; /** * @internal Internal constructor. * * @param {ExchangeService} service EWS service to which this object belongs. */ constructor(service: ExchangeService) { //EwsUtilities.ValidateParam(service, "service"); //EwsUtilities.ValidateServiceObjectVersion(this, service.RequestedServerVersion); //this.Service = service; var innerService = service; this.setService = (service) => { innerService = service; } this.getService = () => { return innerService; } this.propertyBag = new PropertyBag(this); } /** * Gets the value of specified property in this instance. * This Indexer of c# * * @param {PropertyDefinitionBase} propertyDefinition Definition of the property to get. */ _getItem(propertyDefinition: PropertyDefinitionBase): any { var propertyValue: any; var propDef: PropertyDefinition = <PropertyDefinition>propertyDefinition; if (propDef instanceof PropertyDefinition) { return this.PropertyBag._getItem(propDef); } else { var extendedPropDef: ExtendedPropertyDefinition = <ExtendedPropertyDefinition>propertyDefinition; if (extendedPropDef instanceof ExtendedPropertyDefinition) { if (this.TryGetExtendedProperty(extendedPropDef, propertyValue)) { return propertyValue; } else { throw new ServiceObjectPropertyException(Strings.MustLoadOrAssignPropertyBeforeAccess, propertyDefinition); } } else { // Other subclasses of PropertyDefinitionBase are not supported. let constructorName = "Chile of ServiceObject"; if ((<any>propertyDefinition.constructor).name) { constructorName = (<any>propertyDefinition.constructor).name; } throw new NotSupportedException(StringHelper.Format( Strings.OperationNotSupportedForPropertyDefinitionType, constructorName)); } } } /** * @internal Triggers dispatch of the change event. */ Changed(): void { if (this.OnChange != null) { for (var changeDelegate of this.OnChange) { changeDelegate(this); } } } /** * @internal Clears the object's change log. */ ClearChangeLog(): void { this.PropertyBag.ClearChangeLog(); } /** * @internal Gets the name of the change XML element. * * @return {string} XML element name, */ GetChangeXmlElementName(): string { return XmlElementNames.ItemChange; } /** * @internal Gets the name of the delete field XML element. * * @return {string} XML element name, */ GetDeleteFieldXmlElementName(): string { return XmlElementNames.DeleteItemField; } /** * @internal Gets the extended properties collection. * * @return {ExtendedPropertyCollection} Extended properties collection. */ GetExtendedProperties(): ExtendedPropertyCollection { return null; } /** * @internal The unique Id of this object. * * @return {ServiceId} A ServiceId instance.. */ GetId(): ServiceId { var idPropertyDefinition = this.GetIdPropertyDefinition(); var serviceId: IOutParam<any> = { outValue: null }; if (idPropertyDefinition != null) { this.PropertyBag.TryGetValue(idPropertyDefinition, serviceId); } return <ServiceId>serviceId.outValue; } /** * @internal The property definition for the Id of this object. * * @return {PropertyDefinition} A PropertyDefinition instance. */ GetIdPropertyDefinition(): PropertyDefinition { return null; } /** * @internal Determines whether properties defined with ScopedDateTimePropertyDefinition require custom time zone scoping. * * @return {boolean} true if this item type requires custom scoping for scoped date/time properties; otherwise, false. */ GetIsCustomDateTimeScopingRequired(): boolean { return false; } /** * @internal Gets a value indicating whether a time zone SOAP header should be emitted in a CreateItem or UpdateItem request so this item can be property saved or updated. * * @param {boolean} isUpdateOperation Indicates whether the operation being petrformed is an update operation. * @return {boolean} true if a time zone SOAP header should be emitted; otherwise, false. */ GetIsTimeZoneHeaderRequired(isUpdateOperation: boolean): boolean { return false; } /** * Gets the collection of loaded property definitions. * * @return {PropertyDefinitionBase[]} Collection of property definitions. */ GetLoadedPropertyDefinitions(): PropertyDefinitionBase[] /*System.Collections.ObjectModel.Collection<PropertyDefinitionBase>*/ { var propDefs: PropertyDefinitionBase[] = []; for (var propDef of this.PropertyBag.Properties.Keys) { propDefs.push(propDef); } if (this.GetExtendedProperties() != null) { for (var extProp of this.GetExtendedProperties().Items) { propDefs.push(extProp.PropertyDefinition); } } return propDefs; } /** * @internal Gets the minimum required server version. * * @return {ExchangeVersion} Earliest Exchange version in which this service object type is supported. */ abstract GetMinimumRequiredServerVersion(): ExchangeVersion; /** * @internal Internal method to return the schema associated with this type of object. * * @return {ServiceObjectSchema} The schema associated with this type of object. */ abstract GetSchema(): ServiceObjectSchema; /** * @internal Gets the name of the set field XML element. * * @return {string} XML element name, */ GetSetFieldXmlElementName(): string { return XmlElementNames.SetItemField; } /** * @internal GetXmlElementName retrieves the XmlElementName of this type based on the EwsObjectDefinition attribute that decorates it, if present. * * @return {string} The XML element name associated with this type. */ GetXmlElementName(): string { throw new Error("ServiceObject.ts - GetXmlElementName - this must be overridden by derived class - can not use reflection to get class attribute in javascript"); if (StringHelper.IsNullOrEmpty(this.xmlElementName)) { this.xmlElementName = this.GetXmlElementNameOverride(); EwsLogging.Assert( !StringHelper.IsNullOrEmpty(this.xmlElementName), "EwsObject.GetXmlElementName", StringHelper.Format("The class {0} does not have an associated XML element name.", "unknown decendent of ServiceObject - in serviceObject.GetXmlElementname")); } return this.xmlElementName; } /** * @internal This methods lets subclasses of ServiceObject override the default mechanism by which the XML element name associated with their type is retrieved. * * @return {string} The XML element name associated with this type. If this method returns null or empty, the XML element name associated with this type is determined by the EwsObjectDefinition attribute that decorates the type, if present. */ GetXmlElementNameOverride(): string { return null; } /** * @internal Deletes the object. * * @param {DeleteMode} deleteMode The deletion mode. * @param {SendCancellationsMode} sendCancellationsMode Indicates whether meeting cancellation messages should be sent. * @param {AffectedTaskOccurrence} affectedTaskOccurrences Indicate which occurrence of a recurring task should be deleted. */ abstract InternalDelete(deleteMode: DeleteMode, sendCancellationsMode: SendCancellationsMode, affectedTaskOccurrences: AffectedTaskOccurrence): Promise<void>; /** * @internal Loads the specified set of properties on the object. * * @param {PropertySet} propertySet The properties to load. */ abstract InternalLoad(propertySet: PropertySet): Promise<void>; /** * Loads the first class properties. Calling this method results in a call to EWS. */ Load(): Promise<void>; /** * Loads the specified set of properties. Calling this method results in a call to EWS. * * @param {PropertySet} propertySet The properties to load. */ Load(propertySet?: PropertySet): Promise<void>; Load(propertySet?: PropertySet): Promise<void> { return this.InternalLoad(propertySet || PropertySet.FirstClassProperties); } /** * @internal Loads service object from XML. * * @param {any} jsObject Json Object converted from XML. * @param {ExchangeService} service The service. * @param {boolean} clearPropertyBag if set to true [clear property bag]. * @param {PropertySet} requestedPropertySet The property set. * @param {boolean} summaryPropertiesOnly if set to true [summary props only]. */ LoadFromXmlJsObject(jsObject: any, service: ExchangeService, clearPropertyBag: boolean, requestedPropertySet: PropertySet = null, summaryPropertiesOnly: boolean = false): void { this.PropertyBag.LoadFromXmlJsObject( jsObject, service, clearPropertyBag, requestedPropertySet, summaryPropertiesOnly); } /** * @internal Throws exception if this is a new service object. */ ThrowIfThisIsNew(): void { if (this.IsNew) { throw new InvalidOperationException(Strings.ServiceObjectDoesNotHaveId); } } /** * @internal Throws exception if this is not a new service object. */ ThrowIfThisIsNotNew(): void { if (!this.IsNew) { throw new InvalidOperationException(Strings.ServiceObjectAlreadyHasId); } } /** * @internal Try to get the value of a specified extended property in this instance. * * @param {ExtendedPropertyDefinition} propertyDefinition The property definition. * @param {IOutParam<T>} propertyValue The property value. * @return {boolean} True if property retrieved, false otherwise. */ TryGetExtendedProperty<T>(propertyDefinition: ExtendedPropertyDefinition, propertyValue: IOutParam<T>): boolean { var propertyCollection: ExtendedPropertyCollection = this.GetExtendedProperties(); if ((propertyCollection != null) && propertyCollection.TryGetValue<T>(propertyDefinition, propertyValue)) { return true; } else { propertyValue.outValue = null;//default(T); return false; } } //todo:fix - implement type casting on specific type request version. //TryGetProperty<T>(propertyDefinition: PropertyDefinitionBase, propertyValue: any): boolean { throw new Error("Need implementation."); } //TryGetProperty(propertyDefinition: PropertyDefinitionBase, propertyValue: any): boolean { throw new Error("ServiceObject.ts - TryGetProperty : Not implemented."); } /** * Try to get the value of a specified property in this instance. * * @param {PropertyDefinitionBase} propertyDefinition The property definition. * @param {IOutParam<T>} propertyValue The property value. * @return {boolean} True if property retrieved, false otherwise. */ TryGetProperty<T>(propertyDefinition: PropertyDefinitionBase, propertyValue: IOutParam<T>): boolean { var propDef: PropertyDefinition = <PropertyDefinition>propertyDefinition;// as PropertyDefinition; //info: fix for compatibility checking, if this is propertydefinition or extendedpropertydefinitionbase if (propDef instanceof PropertyDefinition) { return this.PropertyBag.TryGetPropertyAs<T>(propDef, propertyValue); } else { //info: fix for compatibility of extendedpropertydefition or propertydefition type. var extPropDef: ExtendedPropertyDefinition = <ExtendedPropertyDefinition>propertyDefinition;// as ExtendedPropertyDefinition; if (extPropDef instanceof ExtendedPropertyDefinition) { return this.TryGetExtendedProperty<T>(extPropDef, propertyValue); } else { // Other subclasses of PropertyDefinitionBase are not supported. let constructorName = "Child of ServiceObject"; if ((<any>propertyDefinition.constructor).name) { constructorName = (<any>propertyDefinition.constructor).name; } throw new NotSupportedException(StringHelper.Format( Strings.OperationNotSupportedForPropertyDefinitionType, propertyDefinition.Type)); } } } /** * @internal Validates this instance. */ Validate(): void { this.PropertyBag.Validate(); } /** * @internal Writes service object as XML. * * @param {EwsServiceXmlWriter} writer The writer. */ WriteToXml(writer: EwsServiceXmlWriter): void { this.PropertyBag.WriteToXml(writer); } /** * @internal Writes service object for update as XML. * * @param {EwsServiceXmlWriter} writer The writer. */ WriteToXmlForUpdate(writer: EwsServiceXmlWriter): void { this.PropertyBag.WriteToXmlForUpdate(writer); } }
the_stack
import * as d3Hierarchy from 'd3-hierarchy' import * as d3Interpolate from 'd3-interpolate' import * as d3Path from 'd3-path' import * as d3Selection from 'd3-selection' import * as d3Transition from 'd3-transition' import * as _ from 'lodash' import { debounceAndThrottle } from '../rxjs/operators' import { Maybe } from 'tsmonad' import { commonAncestor } from './common-ancestor' import { FakeNode } from './fakenode' import { GoalNode } from './goalnode' import * as HierarchyNodeUtils from './hierarchy-node-utils' import * as LinkSelection from './link-selection' import * as RectSelection from './rect-selection' import { TacticGroupNode } from './tacticgroupnode' import * as TextSelection from './text-selection' import { Strictly } from '../peacoq/strictly' import * as ProofTreeUtils from './utils' type HTMLElementSelection = ProofTreeTypes.HTMLElementSelection d3Transition // forces the import function byNodeId(d : ProofTreeTypes.Node) : string { return d.data.id } function byLinkId(d : ProofTreeTypes.Link) : string { return `${d.source.data.id}, ${d.target.data.id}` } /* Globals to be configured */ const animationDuration = 800 // const diffBlue = '#8888EE' // const diffGreen = '#88EE88' // const diffOrange = '#FFB347' // const diffOpacity = 0.75 // const diffRed = '#EE8888' const goalBodyPadding = 4 const verticalSpacingBetweenNodes = 10 function pairwise<T>(a : T[]) : [T, T][] { const zipped = _.zip( a, a.slice(1) ) zipped.pop() // removes [last, undefined] at the end return _.flatMap<[T | undefined, T | undefined][], [T, T]>( zipped, ([a, b] : [T | undefined, T | undefined]) : [T, T][] => { if (!a || !b) { return [] } return [ [a, b] ] } ) } export class ProofTree implements IProofTree { public descendantsOffset : number public readonly curNode$ : Rx.Subject<IGoalNode> public rootNode : IGoalNode public tacticWaiting : Maybe<string> public xFactor : number public yFactor : number private anchor : ProofTreeTypes.HTMLElementSelection private _curNode : IGoalNode private paused : boolean private svgId : string private tactics : () => TacticGroup[] private tacticsWorklist : WorklistItem[] private hierarchyRoot : d3Hierarchy.HierarchyNode<IProofTreeNode> private treeRoot : d3Hierarchy.HierarchyPointNode<IProofTreeNode> private updateSubject : Rx.Subject<{}> private usingKeyboard : boolean /* true until the user uses their mouse */ private viewportX : number private viewportY : number private div : HTMLElementSelection private svg : HTMLElementSelection private viewport : HTMLElementSelection private linkLayer : HTMLElementSelection private rectLayer : HTMLElementSelection private diffLayer : HTMLElementSelection private textLayer : HTMLElementSelection private tipsLayer : HTMLElementSelection constructor( public name : string, anchor : HTMLElement, private width : number, private height : number, parent : Maybe<ITacticGroupNode>, public context : PeaCoqContext, public index : number, public document : ICoqDocument ) { width = Math.max(0, width) this.width = width height = Math.max(0, height) this.height = height this.anchor = d3Selection.select(anchor) this.paused = false this.svgId = _.uniqueId() this.xFactor = this.width this.yFactor = this.height this.usingKeyboard = true // true until the user moves their mouse this.tacticWaiting = nothing<string>() this.rootNode = new GoalNode(this, parent, context, index) this._curNode = this.rootNode this.curNode$ = new Rx.BehaviorSubject(this.rootNode) // debugger this.treeRoot = ProofTreeUtils.makeHierarchyTree(this) d3Selection.select('body') .on('keydown', () => { // capture events only if we are in proof mode if ($(' :focus').length === 0) { this.keydownHandler() } }) this.div = this.anchor .insert('div', ' :first-child') .attr('id', 'pt-' + this.svgId) .classed('prooftree', true) .style('overflow', 'hidden') this.svg = this.div .insert('svg', ' :first-child') .classed('svg', true) .attr('id', 'svg-' + this.svgId) // necessary for the height to be exactly what we set .attr('display', 'block') .style('width', this.width + 'px') .style('height', this.height + 'px') // also need these as attributes for svg_todataurl .attr('width', this.width + 'px') .attr('height', this.height + 'px') // .attr('focusable', true) // this creates a blue outline that changes the width weirdly // .attr('tabindex', 0) // for debugging, this is useful // .attr('viewBox', '0 -100 1000 400') // debugger this.viewport = this.svg .append('g') .attr('id', 'viewport') // for SVGPan.js .attr('class', 'viewport') .attr( 'transform', 'translate(' + this.getGoalWidth() + ', 0)' ) // note : the order of these influence the display // from bottom layers this.linkLayer = this.viewport.append('g').attr('id', 'link-layer') this.rectLayer = this.viewport.append('g').attr('id', 'rect-layer') this.diffLayer = this.viewport.append('g').attr('id', 'diff-layer') this.textLayer = this.viewport.append('g').attr('id', 'text-layer') this.tipsLayer = this.viewport.append('g').attr('id', 'tips-layer') // to top layers // if (svgPanEnabled) { // this.svg.insert('script', ' :first-child').attr('xlink :href', 'SVGPan.js') // } this.updateSubject = new Rx.Subject() // Why? Rx.Observable.interval(2000).subscribe(() => this.updateSubject.onNext({})) // TODO : figure out why I was doing this and whether I can avoid it // this updates the display every second this.updateSubject .let(debounceAndThrottle(1000)) .subscribe(() => this.updateAndWait()) } public cleanup() { this.curNode$.onCompleted() } public getAllGoals() : IGoalNode[] { return ([] as IGoalNode[]).concat( [this.rootNode], this.rootNode.getAllGoalDescendants() ) } get curNode() : IGoalNode { return this._curNode } set curNode(n : IGoalNode) { if (n.id !== this._curNode.id) { // debugger // console.log('Switching current node to', n) this._curNode = n n.focus() this.curNode$.onNext(n) } } public getGoalWidth() { const goalShare = 15 / 20 return Math.floor(this.width * (goalShare / 2)) } public getHierarchyCurNode() : ProofTreeTypes.Node { const found = this.treeRoot.descendants().find(d => d.data.id === this.curNode.id) if (found === undefined) { debugger throw tantrum } return found } public getTacticWidth() { const tacticShare = 4 / 20 return Math.floor(this.width * (tacticShare / 2)) } public isCurNode(n : IProofTreeNode) : boolean { return n.id === this.curNode.id } public isCurNodeAncestor(strictly : Strictly, n : IProofTreeNode) : boolean { const common = commonAncestor(n, this.curNode) const commonAncestorIsNode = common.id === n.id switch (strictly) { case Strictly.Yes : return commonAncestorIsNode && !this.isCurNode(n) case Strictly.No : return commonAncestorIsNode } throw 'ProofTree.isCurNodeAncestor' } public requestNext() : void { this.document.next() } public resize(width : number, height : number) { this.width = Math.floor(width) this.height = Math.floor(height) this.svg .style('width', `${this.width}px`) .style('height', `${this.height}px`) // also need these as attributes for svg_todataurl .attr('width', `${this.width}px`) .attr('height', `${this.height}px`) this.scheduleUpdate() } public scheduleUpdate() : void { this.updateSubject.onNext({}) } public updateAndWait() : Promise<{}> { // console.trace(new Date()) return new Promise((onFulfilled, onRejected) => { this.updatePromise( () => { // console.log('UPDATE : DONE') onFulfilled() }, onRejected ) }) } // public xOffset(d : ProofTreeTypes.Node) : number { // return - d.data.getWidth() / 2 // position the center // } // public yOffset(d : ProofTreeTypes.Node) : number { // const offset = - d.data.getHeight() / 2 // for the center // const focusedChild = this.curNode.getFocusedChild() // // all tactic nodes are shifted such that the current tactic is centered // // assert(isGoal(this.curNode), 'yOffset assumes the current node is a goal!') // if (this.isCurGoalChild(d.data)) { // // assert(focusedChild !== undefined, 'yOffset : focusedChild === undefined') // return offset + ( // ProofTreeUtils.nodeY(d.parent) - ProofTreeUtils.nodeY(fromJust(focusedChild)) // ) * this.yFactor // } // // all goal grandchildren are shifted such that the context line of the // // current goal and the current suboal align // if (this.isCurGoalGrandChild(d.data)) { // return offset + this.descendantsOffset // } // // we center the curNode parent to its focused child // if (this.isCurNodeParent(d.data)) { // if (d instanceof TacticGroupNode) { // return offset + ( // ProofTreeUtils.nodeY(this.curNode) - ProofTreeUtils.nodeY(d) // ) * this.yFactor // } else { // // This should not happen anymore (should not be a GoalNode) // debugger // } // } // // the other nodes (current goal and its ancestors) stay where they need // return offset // } private findNodeInTree<T extends IProofTreeNode>(n : T) : d3Hierarchy.HierarchyPointNode<T> { if (n.id === undefined) { debugger } // this happened before... const found = this.treeRoot.descendants().find(d => d.data.id === n.id) if (found === undefined) { debugger throw 'findNodeInTree' } return found as any } /* here we are looking for the descendant which should align with the current node. it used to be at the top of the view, now it's centered. */ private computeDescendantsOffset() { const curNode = this.findNodeInTree(this.curNode) const centeredDescendant : Maybe<IProofTreeNode> = this.curNode.getViewFocusedChild().caseOf<Maybe<IProofTreeNode>>({ nothing : () => nothing<IProofTreeNode>(), just : fc => fc.getFocusedChild().caseOf<Maybe<IProofTreeNode>>({ nothing : () => just(fc), just : (fgc : IProofTreeNode) => just(fgc), }) }) centeredDescendant.caseOf({ nothing : () => { this.descendantsOffset = 0 }, just : d => { const treeD = this.findNodeInTree(d) if (d instanceof GoalNode) { // computing the difference in height between the <hr> is not // obvious... const hrDelta = curNode.data.html[0].offsetTop - d.html[0].offsetTop this.descendantsOffset = ( this.yFactor * (ProofTreeUtils.nodeY(curNode) - ProofTreeUtils.nodeY(treeD)) - (curNode.data.getHeight() - d.getHeight()) / 2 + hrDelta ) } else { this.descendantsOffset = this.yFactor * (ProofTreeUtils.nodeY(curNode) - ProofTreeUtils.nodeY(treeD)) } } }) } private computeXYFactors() { const curGoal = this.getHierarchyCurNode() // huh cf. https ://github.com/DefinitelyTyped/DefinitelyTyped/issues/11365 const visibleChildren = curGoal.children || [] const visibleGrandChildren = visibleChildren.reduce<ProofTreeTypes.Node[]>( (acc, elt) => acc.concat(elt.children || []), [] ) const visibleNodes = ([] as ProofTreeTypes.Node[]).concat( (curGoal.parent !== null) ? [curGoal.parent] : [], [curGoal], visibleChildren, visibleGrandChildren ) // xFactor is now fixed, so that the user experience is more stable const rootViewChildren = this.rootNode.getViewChildren() if (rootViewChildren.length === 0) { this.xFactor = this.width } else { const treeFirstChildren = this.findNodeInTree(rootViewChildren[0]) const treeRootNode = this.findNodeInTree(this.rootNode) const xDistance = ProofTreeUtils.nodeX(treeFirstChildren) - ProofTreeUtils.nodeX(treeRootNode) if (xDistance === 0) { debugger } /* width = 4 * xDistance * xFactor */ this.xFactor = this.width / (4 * xDistance) } /* we want all visible grand children to be apart from each other i.e. ∀ a b, yFactor * | a.y - b.y | > a.height/2 + b.height/2 + nodeVSpacing we also want all visible children to be apart from each other (especially when they don't have their own children to separate them) */ const gcSiblings = pairwise(visibleGrandChildren) const cSiblings = pairwise(visibleChildren) // also, the current node should not overlap its siblings let currentSiblings : [ProofTreeTypes.Node, ProofTreeTypes.Node][] = [] const curParent = curGoal.parent if (this.curNode instanceof GoalNode && curParent !== null) { const curNodeSiblings = curParent.children || [] currentSiblings = pairwise(curNodeSiblings) } const siblings = _(gcSiblings.concat(cSiblings, currentSiblings)) // debugger const yFactors = siblings .map(e => { const a = e[0], b = e[1] const yDistance = ProofTreeUtils.nodeY(b) - ProofTreeUtils.nodeY(a) if (yDistance === 0) { debugger return 1 } const wantedSpacing = ((a.data.getHeight() + b.data.getHeight()) / 2) + verticalSpacingBetweenNodes return wantedSpacing / yDistance }) .value() const newYFactor = _.isEmpty(yFactors) ? this.height : _.max(yFactors) if (newYFactor !== undefined) { this.yFactor = newYFactor } else { console.log('Not updating yFactor, check this out...') } // This has happened many times!!! if (!Number.isFinite(this.xFactor)) { debugger } if (!Number.isFinite(this.yFactor)) { debugger } } private getAllNodes() : IProofTreeNode[] { return this.rootNode.getAllDescendants() } private getCurrentGoal() : IGoalNode { assert(this.curNode instanceof GoalNode, 'getCurrentGoal : curNode instanceof GoalNode') return this.curNode } private getFocus() { $(' :focus').blur() } private getCurrentScale() { return (<any>this.svg[0][0]).currentScale } /* getFocusedGoal() : GoalNode { const focusedChild = this.curNode.getFocusedChild() if (focusedChild !== undefined) { //if (focusedChild instanceof GoalNode) { return focusedChild } const focusedGrandChild = focusedChild.getFocusedChild() if (focusedGrandChild !== undefined) { return focusedGrandChild } } return undefined } */ private isCurGoal(n : IProofTreeNode) : boolean { return n.id === this.curNode.id } private isCurGoalChild(n : IProofTreeNode) : boolean { return n.hasParentSuchThat(p => this.isCurGoal(p)) } private isCurGoalGrandChild(n : IProofTreeNode) : boolean { return n.hasParentSuchThat(p => this.isCurGoalChild(p)) } private isCurNodeChild(n : IProofTreeNode) : boolean { return n.hasParentSuchThat(p => this.isCurNode(p)) } private isCurNodeDescendant(strictly : Strictly, n : IProofTreeNode) : boolean { const common = commonAncestor(n, this.curNode) const commonAncestorIsCurNode = common.id === this.curNode.id switch (strictly) { case Strictly.Yes : return commonAncestorIsCurNode && !this.isCurNode(n) case Strictly.No : return commonAncestorIsCurNode } throw 'ProofTree.isCurNodeDescendant' } private isCurNodeGrandChild(n : IProofTreeNode) : boolean { return n.hasParentSuchThat(p => this.isCurNodeChild(p)) } private isCurNodeParent(n : IProofTreeNode) : boolean { return this.curNode.hasParentSuchThat(p => p.id === n.id) } // isCurNodeSibling(n : ProofTreeNode) : boolean { // return !this.isCurNode(n) && hasParent(n) && this.isCurNodeParent(n.getParent()) // } private isRootNode(n : IProofTreeNode) : boolean { return n.id === this.rootNode.id } private keydownHandler() { debugger // how does this work in D3 4.0? // const ev : any = d3.event // // don't interact while typing // if (ev.target.type === 'textarea') { return } // const curNode = this.curNode // const children = curNode.getViewChildren() // this.usingKeyboard = true // // console.log(d3.event.keyCode) // switch (ev.keyCode) { // case 37 : // Left // // case 65 : // a // ev.preventDefault() // curNode.getParent().caseOf({ // nothing : () => { // // when at the root node, undo the last action (usually Proof.) // // onCtrlUp(false) // }, // just : parent => { // // asyncLog('LEFT ' + nodeString(curNode.parent)) // parent.click() // }, // }) // break // case 39 : // Right // // case 68 : // d // ev.preventDefault() // curNode.getFocusedChild().fmap(dest => { // // asyncLog('RIGHT ' + nodeString(dest)) // dest.click() // }) // break // // case 38 : // Up // // //case 87 : // w // // ev.preventDefault() // // if (ev.shiftKey) { // // //this.shiftPrevGoal(curNode.getFocusedChild()) // // } else { // // this.shiftPrevByTacticGroup(curNode) // // } // // break // // // // case 40 : // Down // // //case 83 : // s // // ev.preventDefault() // // if (ev.shiftKey) { // // //this.shiftNextGoal(curNode.getFocusedChild()) // // } else { // // this.shiftNextByTacticGroup(curNode) // // } // // break // // // // case 219 : // [ // // var focusedChild = curNode.getFocusedChild() // // focusedChild.fmap((c) => (<TacticGroupNode>c).shiftPrevInGroup()) // // break // // // // case 221 : // ] // // var focusedChild = curNode.getFocusedChild() // // focusedChild.fmap((c) => (<TacticGroupNode>c).shiftNextInGroup()) // // break // default : // console.log('Unhandled event', (d3.event as any).keyCode) // return // } // // EDIT : now that we integrate the proof tree, it's best to const stuff bubble up // // if we haven't returned, we don't want the normal key behavior // // d3.event.preventDefault() } public linkWidth(d : ProofTreeTypes.Link) : string { const src = d.source const tgt = d.target const thin = '2px' const thick = '5px' // if the user uses his mouse, highlight the path under hover /* if (!this.usingKeyboard) { if (this.hoveredNode === undefined) { return thin } else { if (this.isCurNode(src)) { if (sameNode(tgt, this.hoveredNode)) { return thick } else if (!hasParent(this.hoveredNode)) { return thin } else if (sameNode(tgt, this.hoveredNode.parent)) { return thick } else { return thin } } else if (this.isCurNodeChild(src)) { if (sameNode(tgt, this.hoveredNode)) { return thick } else { return thin } } else { return thin } } } */ const curNode = this.curNode // if the user uses his keyboard, highlight the focused path // if (curNode instanceof GoalNode) { return this.curNode.getFocusedChild().caseOf({ nothing : () => thin, just : (focusedChild) => { if (this.isCurNode(src.data) && focusedChild.id === tgt.id) { return thick } return focusedChild.getFocusedChild().caseOf({ nothing : () => thin, just : (focusedGrandChild) => { return ( focusedChild.id === src.id && focusedGrandChild.id === tgt.id ? thick : thin ) }, }) }, }) // // } else if (curNode instanceof TacticGroupNode) { // const focusedChild = this.curNode.getFocusedChild() // if (focusedChild !== undefined && tgt.id === focusedChild.id) { // return thick // } // return thin // } else { // throw this.curNode // } } private processTactics() : Promise<any> { /* every time curNode is changed, the tacticsWorklist should be flushed, so that [runTactic] can reliably add the results of running the tactic to the current node */ const promiseSpark = this.tacticsWorklist.shift() if (promiseSpark === undefined) { return Promise.resolve() } return promiseSpark() // delay for testing purposes // .then(delayPromise(0)) .then(this.processTactics.bind(this)) .catch(outputError) } private refreshTactics() : void { // if (focusedOnEditor) { return } const self = this const curNode = this.curNode const tacticsAndGroups = this.tactics() /* _(this.tactics()) .groupBy(function(elt) { if ($.type(elt) === 'string') { return 'tactics' } else { return 'groups' } }) .value() // TODO : there should be no tactics! const groups = tacticsAndGroups.groups */ /* const groupSparks = _(tacticsAndGroups) .map(function(group) { const groupNode : TacticGroupNode = self.findOrCreateGroup(curNode, group.name) return ( _(group.tactics) .filter( tactic => { return ( !_(groupNode.tactics) .some(function(node) { return (node.tactic === tactic) }) ) }) .map( tactic => { return function() { return self.runTactic(tactic, groupNode) } }) .flatten(true) .value() ) }) .flatten<() => Promise<any>>(true) .value() // flushes the worklist and add the new sparks this.tacticsWorklist = groupSparks */ // console.log('REPOPULATING TACTICS WORKLIST', this.tacticsWorklist) this.processTactics() } private resetSVGTransform() : void { const transform = this.viewport.attr('transform') if (transform.length === 0) { return } let m = parseSVGTransform(transform) if (m.hasOwnProperty('matrix')) { m = m.matrix this.viewport.attr( 'transform', `matrix(1, ${m[1]}, ${m[2]}, 1, ${m[4]}, ${m[5]})` ) } } // private runTactic(t : string, groupToAttachTo) { // /* // const self = this // const parentGoal = getClosestGoal(groupToAttachTo) // const parentGoalRepr = goalNodeUnicityRepr(parentGoal) // // if we correctly stored the last response in [parentGoal], we don't need // // to query for status at this moment // const beforeResponse = parentGoal.response // $('#loading-text').text(nbsp + nbsp + 'Trying ' + t) // return asyncQueryAndUndo(t) // //.then(delayPromise(0)) // .then(function(response) { // if (isGood(response)) { // //const unfocusedBefore = getResponseUnfocused(beforeResponse) // //const unfocusedAfter = getResponseUnfocused(response) // const newChild = new Tactic( // t, // groupToAttachTo, // response // ) // // only attach the newChild if it produces something // // unique from existing children // const newChildRepr = tacticUnicityRepr(newChild) // const resultAlreadyExists = // _(parentGoal.getTactics()).some(function(t) { // return t.tactic === newChild.tactic // //return (tacticUnicityRepr(t) === newChildRepr) // }) // const tacticIsUseless = // (newChild.goals.length === 1) // && (goalNodeUnicityRepr(newChild.goals[0]) // === parentGoalRepr) // if (!resultAlreadyExists && !tacticIsUseless) { // groupToAttachTo.addTactic(newChild) // self.update() // } // } else { // //console.log('Bad response for', t, response) // } // }) // .catch(outputError) // */ // } private shiftNextByTacticGroup(n : IGoalNode) : void { if (this.paused) { return } if (n.isSolved()) { return } const viewChildren = n.getViewChildren() if (n.tacticIndex + 1 < viewChildren.length) { n.tacticIndex++ // asyncLog('DOWNGROUP ' + nodeString(viewChildren[n.tacticIndex])) this.scheduleUpdate() } } private shiftPrevByTacticGroup(n : IGoalNode) : void { if (this.paused) { return } if (n.isSolved()) { return } if (n.tacticIndex > 0) { n.tacticIndex-- // asyncLog('UPGROUP ' + nodeString(n.getViewChildren()[n.tacticIndex])) this.scheduleUpdate() } } private updatePromise<T>(onFulfilled : () => void, onRejected : () => void) : void { console.trace('updatePromise') const curNode = this.curNode this.resetSVGTransform() // cancel view transformations this.treeRoot = ProofTreeUtils.makeHierarchyTree(this) const allNodes = this.treeRoot.descendants() const allLinks = this.treeRoot.links() // now remove all fake nodes const nodes = allNodes .filter(node => !(node instanceof FakeNode)) const links = allLinks .filter(link => !(link.source instanceof FakeNode || link.target instanceof FakeNode)) const nodeArray = nodes.entries // we build the foreignObject first, as its dimensions will guide the others const textSelection = this.textLayer .selectAll<Element, ProofTreeTypes.Node>((d, i, nodes) => { return (nodes[i] as Element).getElementsByTagName('foreignObject') }) .data(nodes, d => d.data.id) // Here we need select({}) because d3 transitions are exclusive and // without it, concurrent selections will not each call their 'end' // callback. // See. https ://bl.ocks.org/mbostock/5348789 d3Selection.select({} as any) .transition() .duration(animationDuration) .each(() => { const textEnter = textSelection.enter().append('foreignObject') const rectSelection = this.rectLayer.selectAll('rect').data<ProofTreeTypes.Node>(nodes, byNodeId) const linkSelection = this.linkLayer.selectAll('path').data<ProofTreeTypes.Link>(links, byLinkId) /* Here, we must rely on the DOM to compute the height of nodes, so that we can position them accordingly. However, the height is dictated by how the HTML will render for the given width of the nodes. Therefore, we must initially include the HTML within the yet-to-be-placed nodes, and we must set their width so that the renderer computes their height. Once nodes have a height, we can query it, compute the zooming and translating factors, offset the descendant nodes to center the focused one, and start positioning nodes. */ textEnter .append('xhtml :body') .each((d, i, nodes) => { const self = nodes[i] // debugger const body = d3Selection.select(self as Element).node() if (body === null) { debugger return thisShouldNotHappen() } d.data.setHTMLElement(<HTMLElement><any>body) const node = d.data // debugger if (node instanceof GoalNode) { $(body).append(node.html) } if (node instanceof TacticGroupNode) { node.updateNode() } // $(body).prepend(d.id) }) textEnter.attr('width', d => d.data.getWidth()) // nodes now have a size, we can compute zooming factors this.computeXYFactors() // compute how much descendants must be moved to center current this.computeDescendantsOffset() // console.log('FIXME!!!') TextSelection.onTextEnter(textEnter) RectSelection.onRectEnter(rectSelection.enter()) LinkSelection.onLinkEnter(linkSelection.enter()) RectSelection.onRectUpdatePostMerge(rectSelection) TextSelection.onTextUpdatePostMerge(textSelection) LinkSelection.onLinkUpdatePostMerge(linkSelection) TextSelection.onTextExit(textSelection.exit<ProofTreeTypes.Node>()) RectSelection.onRectExit(rectSelection.exit<ProofTreeTypes.Node>()) LinkSelection.onLinkExit(linkSelection.exit<ProofTreeTypes.Link>()) const hierarchyCurNode = nodes.find(n => n.data.id === curNode.id) if (hierarchyCurNode === undefined) { return thisShouldNotHappen() } const hierarchyCurNodeParent = hierarchyCurNode.parent this.viewportX = - ( (hierarchyCurNodeParent === null) ? HierarchyNodeUtils.getDestinationScaledX(hierarchyCurNode) : HierarchyNodeUtils.getDestinationScaledX(hierarchyCurNodeParent) ) this.viewportY = - ( HierarchyNodeUtils.getDestinationScaledY(hierarchyCurNode) + curNode.getHeight() / 2 - this.height / 2 ) this.viewport .transition() .attr( 'transform', 'translate(' + this.viewportX + ', ' + this.viewportY + ')' ) }) .on('end', onFulfilled) } }
the_stack
require('module-alias/register'); import * as _ from 'lodash'; import * as ABIDecoder from 'abi-decoder'; import * as chai from 'chai'; import * as setProtocolUtils from 'set-protocol-utils'; import { Address } from 'set-protocol-utils'; import { BigNumber } from 'bignumber.js'; import ChaiSetup from '@utils/chaiSetup'; import { BigNumberSetup } from '@utils/bigNumberSetup'; import { CoreMockContract, FixedFeeCalculatorContract, LiquidatorMockContract, SetTokenContract, RebalanceAuctionModuleContract, RebalancingSetTokenV2Contract, RebalancingSetTokenV2FactoryContract, SetTokenFactoryContract, TransferProxyContract, VaultContract, WhiteListContract, } from '@utils/contracts'; import { Blockchain } from '@utils/blockchain'; import { ether } from '@utils/units'; import { DEFAULT_GAS, ONE_DAY_IN_SECONDS, DEFAULT_UNIT_SHARES, DEFAULT_REBALANCING_NATURAL_UNIT, ZERO, } from '@utils/constants'; import { getExpectedTransferLog, getExpectedEntryFeePaidLog, } from '@utils/contract_logs/rebalancingSetTokenV2'; import { expectRevertError, assertTokenBalanceAsync } from '@utils/tokenAssertions'; import { getWeb3 } from '@utils/web3Helper'; import { CoreHelper } from '@utils/helpers/coreHelper'; import { ERC20Helper } from '@utils/helpers/erc20Helper'; import { FeeCalculatorHelper } from '@utils/helpers/feeCalculatorHelper'; import { LiquidatorHelper } from '@utils/helpers/liquidatorHelper'; import { OracleHelper } from 'set-protocol-oracles'; import { RebalancingSetV2Helper } from '@utils/helpers/rebalancingSetV2Helper'; import { ValuationHelper } from '@utils/helpers/valuationHelper'; BigNumberSetup.configure(); ChaiSetup.configure(); const web3 = getWeb3(); const { SetProtocolTestUtils: SetTestUtils, SetProtocolUtils: SetUtils } = setProtocolUtils; const setTestUtils = new SetTestUtils(web3); const { expect } = chai; const blockchain = new Blockchain(web3); const { NULL_ADDRESS } = SetUtils.CONSTANTS; contract('Issuance', accounts => { const [ deployerAccount, managerAccount, feeRecipient, ] = accounts; let rebalancingSetToken: RebalancingSetTokenV2Contract; let coreMock: CoreMockContract; let transferProxy: TransferProxyContract; let vault: VaultContract; let rebalanceAuctionModule: RebalanceAuctionModuleContract; let factory: SetTokenFactoryContract; let rebalancingFactory: RebalancingSetTokenV2FactoryContract; let rebalancingComponentWhiteList: WhiteListContract; let liquidatorWhitelist: WhiteListContract; let liquidatorMock: LiquidatorMockContract; let fixedFeeCalculator: FixedFeeCalculatorContract; let feeCalculatorWhitelist: WhiteListContract; const coreHelper = new CoreHelper(deployerAccount, deployerAccount); const erc20Helper = new ERC20Helper(deployerAccount); const rebalancingHelper = new RebalancingSetV2Helper( deployerAccount, coreHelper, erc20Helper, blockchain ); const oracleHelper = new OracleHelper(deployerAccount); const valuationHelper = new ValuationHelper(deployerAccount, coreHelper, erc20Helper, oracleHelper); const liquidatorHelper = new LiquidatorHelper(deployerAccount, erc20Helper, valuationHelper); const feeCalculatorHelper = new FeeCalculatorHelper(deployerAccount); before(async () => { ABIDecoder.addABI(CoreMockContract.getAbi()); ABIDecoder.addABI(RebalancingSetTokenV2Contract.getAbi()); }); after(async () => { ABIDecoder.removeABI(CoreMockContract.getAbi()); ABIDecoder.removeABI(RebalancingSetTokenV2Contract.getAbi()); }); beforeEach(async () => { blockchain.saveSnapshotAsync(); transferProxy = await coreHelper.deployTransferProxyAsync(); vault = await coreHelper.deployVaultAsync(); coreMock = await coreHelper.deployCoreMockAsync(transferProxy, vault); rebalanceAuctionModule = await coreHelper.deployRebalanceAuctionModuleAsync(coreMock, vault); await coreHelper.addModuleAsync(coreMock, rebalanceAuctionModule.address); factory = await coreHelper.deploySetTokenFactoryAsync(coreMock.address); rebalancingComponentWhiteList = await coreHelper.deployWhiteListAsync(); liquidatorWhitelist = await coreHelper.deployWhiteListAsync(); feeCalculatorWhitelist = await coreHelper.deployWhiteListAsync(); rebalancingFactory = await coreHelper.deployRebalancingSetTokenV2FactoryAsync( coreMock.address, rebalancingComponentWhiteList.address, liquidatorWhitelist.address, feeCalculatorWhitelist.address ); await coreHelper.setDefaultStateAndAuthorizationsAsync(coreMock, vault, transferProxy, factory); await coreHelper.addFactoryAsync(coreMock, rebalancingFactory); liquidatorMock = await liquidatorHelper.deployLiquidatorMockAsync(); await coreHelper.addAddressToWhiteList(liquidatorMock.address, liquidatorWhitelist); fixedFeeCalculator = await feeCalculatorHelper.deployFixedFeeCalculatorAsync(); await coreHelper.addAddressToWhiteList(fixedFeeCalculator.address, feeCalculatorWhitelist); }); afterEach(async () => { blockchain.revertAsync(); }); describe('#mint: Called from CoreMock', async () => { let subjectIssuer: Address; let subjectQuantity: BigNumber; let subjectCaller: Address; let rebalancingSetToken: RebalancingSetTokenV2Contract; let nextSetToken: SetTokenContract; let currentSetToken: SetTokenContract; let entryFee: BigNumber; let customEntryFee: BigNumber; beforeEach(async () => { const setTokensToDeploy = 2; const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, setTokensToDeploy, ); currentSetToken = setTokens[0]; nextSetToken = setTokens[1]; const liquidator = liquidatorMock.address; const failPeriod = ONE_DAY_IN_SECONDS; entryFee = customEntryFee || ZERO; const { timestamp: lastRebalanceTimestamp } = await web3.eth.getBlock('latest'); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async( coreMock, rebalancingFactory.address, managerAccount, liquidator, feeRecipient, fixedFeeCalculator.address, currentSetToken.address, failPeriod, lastRebalanceTimestamp, entryFee, ); subjectIssuer = deployerAccount, subjectQuantity = ether(5); subjectCaller = managerAccount; }); async function subject(): Promise<string> { return coreMock.mint.sendTransactionAsync( rebalancingSetToken.address, subjectIssuer, subjectQuantity, { from: subjectCaller, gas: DEFAULT_GAS} ); } it('updates the balances of the user correctly', async () => { const existingBalance = await rebalancingSetToken.balanceOf.callAsync(subjectIssuer); await subject(); const expectedNewBalance = existingBalance.add(subjectQuantity); await assertTokenBalanceAsync(rebalancingSetToken, expectedNewBalance, subjectIssuer); }); it('updates the totalSupply_ correctly', async () => { const existingTokenSupply = await rebalancingSetToken.totalSupply.callAsync(); await subject(); const expectedTokenSupply = existingTokenSupply.add(subjectQuantity); const newTokenSupply = await rebalancingSetToken.totalSupply.callAsync(); expect(newTokenSupply).to.be.bignumber.equal(expectedTokenSupply); }); it('emits a Transfer log denoting a minting', async () => { const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = getExpectedTransferLog( NULL_ADDRESS, subjectIssuer, subjectQuantity, rebalancingSetToken.address ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('when there is a 1% entry fee', async () => { before(async () => { customEntryFee = new BigNumber(10 ** 16); }); after(async () => { customEntryFee = undefined; }); it('mints the correct Rebalncing Set quantity to the issuer', async () => { const entryFee = await rebalancingHelper.calculateEntryFee( rebalancingSetToken, subjectQuantity ); await subject(); const issuerBalance = await rebalancingSetToken.balanceOf.callAsync(subjectIssuer); const expectedIssueQuantity = subjectQuantity.sub(entryFee); expect(issuerBalance).to.bignumber.equal(expectedIssueQuantity); }); it('mints the Rebalancing Set fee to the feeRecipient', async () => { const entryFee = await rebalancingHelper.calculateEntryFee( rebalancingSetToken, subjectQuantity ); await subject(); const feeRecipientSetBalance = await rebalancingSetToken.balanceOf.callAsync(feeRecipient); expect(feeRecipientSetBalance).to.bignumber.equal(entryFee); }); it('emits the EntryFeePaid log', async () => { const txHash = await subject(); const entryFee = await rebalancingHelper.calculateEntryFee( rebalancingSetToken, subjectQuantity ); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = getExpectedEntryFeePaidLog( feeRecipient, entryFee, rebalancingSetToken.address ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); }); describe('Post-Rebalance stage', async () => { beforeEach(async () => { // Issue currentSetToken await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(8), {from: deployerAccount}); await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address); // Use issued currentSetToken to issue rebalancingSetToken const rebalancingSetQuantityToIssue = ether(7); await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, rebalancingSetQuantityToIssue); }); describe('when mint is called from Rebalance state', async () => { beforeEach(async () => { await rebalancingHelper.transitionToRebalanceV2Async( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, managerAccount ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when mint is called from Drawdown State', async () => { beforeEach(async () => { await rebalancingHelper.transitionToDrawdownV2Async( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, rebalanceAuctionModule, liquidatorMock, nextSetToken, managerAccount, ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); }); describe('#mint: Called on Rebalancing Token', async () => { let subjectIssuer: Address; let subjectQuantity: BigNumber; let subjectCaller: Address; beforeEach(async () => { const setTokensToDeploy = 1; const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, setTokensToDeploy, ); const currentSetToken = setTokens[0]; const manager = managerAccount; const liquidator = liquidatorMock.address; const initialSet = currentSetToken.address; const feeCalculator = fixedFeeCalculator.address; const initialUnitShares = DEFAULT_UNIT_SHARES; const initialNaturalUnit = DEFAULT_REBALANCING_NATURAL_UNIT; const rebalanceInterval = ONE_DAY_IN_SECONDS; const failPeriod = ONE_DAY_IN_SECONDS; const { timestamp: lastRebalanceTimestamp } = await web3.eth.getBlock('latest'); const entryFee = ZERO; const rebalancingFactory = await coreHelper.deployRebalancingSetTokenV2FactoryAsync( coreMock.address, rebalancingComponentWhiteList.address, liquidatorWhitelist.address, feeCalculatorWhitelist.address, ); await coreHelper.addFactoryAsync(coreMock, rebalancingFactory); rebalancingSetToken = await rebalancingHelper.deployRebalancingSetTokenV2Async( [ rebalancingFactory.address, manager, liquidator, initialSet, rebalancingComponentWhiteList.address, liquidatorWhitelist.address, feeRecipient, feeCalculator, ], [ initialUnitShares, initialNaturalUnit, rebalanceInterval, failPeriod, new BigNumber(lastRebalanceTimestamp), entryFee, ], '0x00' ); subjectIssuer = deployerAccount, subjectQuantity = ether(5); subjectCaller = deployerAccount; }); async function subject(): Promise<string> { return rebalancingSetToken.mint.sendTransactionAsync( subjectIssuer, subjectQuantity, { from: subjectCaller, gas: DEFAULT_GAS} ); } it('should revert since call is not from core', async () => { await expectRevertError(subject()); }); }); describe('#burn: Called by Module', async () => { let subjectBurner: Address; let subjectQuantity: BigNumber; let subjectCaller: Address; let currentSetToken: SetTokenContract; let nextSetToken: SetTokenContract; beforeEach(async () => { await coreHelper.addModuleAsync(coreMock, managerAccount); const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, 2 ); currentSetToken = setTokens[0]; nextSetToken = setTokens[1]; const liquidator = liquidatorMock.address; const failPeriod = ONE_DAY_IN_SECONDS; const { timestamp: lastRebalanceTimestamp } = await web3.eth.getBlock('latest'); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async( coreMock, rebalancingFactory.address, managerAccount, liquidator, feeRecipient, fixedFeeCalculator.address, currentSetToken.address, failPeriod, lastRebalanceTimestamp, ); const mintedQuantity = ether(5); subjectBurner = deployerAccount, subjectQuantity = ether(5); subjectCaller = managerAccount; // Issue currentSetToken await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(5), {from: deployerAccount}); await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address); // Use issued currentSetToken to issue rebalancingSetToken await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, mintedQuantity); }); async function subject(): Promise<string> { return rebalancingSetToken.burn.sendTransactionAsync( subjectBurner, subjectQuantity, { from: subjectCaller, gas: DEFAULT_GAS} ); } it('should revert because its not called through core during non-Drawdown state', async () => { await expectRevertError(subject()); }); describe('when Module calls burn from Drawdown State', async () => { beforeEach(async () => { await rebalancingHelper.transitionToDrawdownV2Async( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, rebalanceAuctionModule, liquidatorMock, nextSetToken, managerAccount, ); }); it('updates the totalSupply_ correctly', async () => { const existingTokenSupply = await rebalancingSetToken.totalSupply.callAsync(); await subject(); const expectedTokenSupply = existingTokenSupply.sub(subjectQuantity); const newTokenSupply = await rebalancingSetToken.totalSupply.callAsync(); expect(newTokenSupply).to.be.bignumber.equal(expectedTokenSupply); }); }); }); describe('#burn: Called from CoreMock', async () => { let rebalancingSetToken: RebalancingSetTokenV2Contract; let subjectBurner: Address; let subjectQuantity: BigNumber; let subjectCaller: Address; let nextSetToken: SetTokenContract; let currentSetToken: SetTokenContract; beforeEach(async () => { const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, 2 ); currentSetToken = setTokens[0]; nextSetToken = setTokens[1]; const liquidator = liquidatorMock.address; const failPeriod = ONE_DAY_IN_SECONDS; const { timestamp: lastRebalanceTimestamp } = await web3.eth.getBlock('latest'); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async( coreMock, rebalancingFactory.address, managerAccount, liquidator, feeRecipient, fixedFeeCalculator.address, currentSetToken.address, failPeriod, lastRebalanceTimestamp, ); const mintedQuantity = ether(5); subjectBurner = deployerAccount, subjectQuantity = ether(5); subjectCaller = managerAccount; // Issue currentSetToken await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(5), {from: deployerAccount}); await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address); // Use issued currentSetToken to issue rebalancingSetToken await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, mintedQuantity); }); async function subject(): Promise<string> { return coreMock.burn.sendTransactionAsync( rebalancingSetToken.address, subjectBurner, subjectQuantity, { from: subjectCaller, gas: DEFAULT_GAS} ); } it('updates the balances of the user correctly', async () => { const existingBalance = await rebalancingSetToken.balanceOf.callAsync(subjectBurner); await subject(); const expectedNewBalance = existingBalance.sub(subjectQuantity); await assertTokenBalanceAsync(rebalancingSetToken, expectedNewBalance, subjectBurner); }); it('updates the totalSupply_ correctly', async () => { const existingTokenSupply = await rebalancingSetToken.totalSupply.callAsync(); await subject(); const expectedTokenSupply = existingTokenSupply.sub(subjectQuantity); const newTokenSupply = await rebalancingSetToken.totalSupply.callAsync(); expect(newTokenSupply).to.be.bignumber.equal(expectedTokenSupply); }); it('emits a Transfer log denoting a burn', async () => { const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = getExpectedTransferLog( subjectBurner, NULL_ADDRESS, subjectQuantity, rebalancingSetToken.address ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('when the user does not have enough shares to burn', async () => { beforeEach(async () => { subjectQuantity = ether(10); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('during Rebalance state', async () => { beforeEach(async () => { await rebalancingHelper.transitionToRebalanceV2Async( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, nextSetToken, managerAccount ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when Core calls burn from Drawdown State', async () => { beforeEach(async () => { await rebalancingHelper.transitionToDrawdownV2Async( coreMock, rebalancingComponentWhiteList, rebalancingSetToken, rebalanceAuctionModule, liquidatorMock, nextSetToken, managerAccount, ); }); it('should revert', async () => { await expectRevertError(subject()); }); }); }); describe('#burn: Called on Rebalancing Token', async () => { let subjectBurner: Address; let subjectQuantity: BigNumber; let subjectCaller: Address; let currentSetToken: SetTokenContract; beforeEach(async () => { const setTokens = await rebalancingHelper.createSetTokensAsync( coreMock, factory.address, transferProxy.address, 2 ); currentSetToken = setTokens[0]; const liquidator = liquidatorMock.address; const failPeriod = ONE_DAY_IN_SECONDS; const { timestamp: lastRebalanceTimestamp } = await web3.eth.getBlock('latest'); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV2Async( coreMock, rebalancingFactory.address, managerAccount, liquidator, feeRecipient, fixedFeeCalculator.address, currentSetToken.address, failPeriod, lastRebalanceTimestamp, ); const mintedQuantity = ether(5); subjectBurner = deployerAccount, subjectQuantity = ether(5); subjectCaller = managerAccount; // Issue currentSetToken await coreMock.issue.sendTransactionAsync(currentSetToken.address, ether(5), {from: deployerAccount}); await erc20Helper.approveTransfersAsync([currentSetToken], transferProxy.address); // Use issued currentSetToken to issue rebalancingSetToken await coreMock.issue.sendTransactionAsync(rebalancingSetToken.address, mintedQuantity); }); async function subject(): Promise<string> { return rebalancingSetToken.burn.sendTransactionAsync( subjectBurner, subjectQuantity, { from: subjectCaller, gas: DEFAULT_GAS} ); } it('should revert because its not called through core', async () => { await expectRevertError(subject()); }); }); });
the_stack
import { AST_NODE_TYPES, TSESLint, TSESTree, } from '@typescript-eslint/experimental-utils'; import * as tsutils from 'tsutils'; import * as ts from 'typescript'; import * as util from '../util'; export type Options = [ { ignoreArrowShorthand?: boolean; ignoreVoidOperator?: boolean; }, ]; export type MessageId = | 'invalidVoidExpr' | 'invalidVoidExprWrapVoid' | 'invalidVoidExprArrow' | 'invalidVoidExprArrowWrapVoid' | 'invalidVoidExprReturn' | 'invalidVoidExprReturnLast' | 'invalidVoidExprReturnWrapVoid' | 'voidExprWrapVoid'; export default util.createRule<Options, MessageId>({ name: 'no-confusing-void-expression', meta: { docs: { description: 'Requires expressions of type void to appear in statement position', recommended: false, requiresTypeChecking: true, }, messages: { invalidVoidExpr: 'Placing a void expression inside another expression is forbidden. ' + 'Move it to its own statement instead.', invalidVoidExprWrapVoid: 'Void expressions used inside another expression ' + 'must be moved to its own statement ' + 'or marked explicitly with the `void` operator.', invalidVoidExprArrow: 'Returning a void expression from an arrow function shorthand is forbidden. ' + 'Please add braces to the arrow function.', invalidVoidExprArrowWrapVoid: 'Void expressions returned from an arrow function shorthand ' + 'must be marked explicitly with the `void` operator.', invalidVoidExprReturn: 'Returning a void expression from a function is forbidden. ' + 'Please move it before the `return` statement.', invalidVoidExprReturnLast: 'Returning a void expression from a function is forbidden. ' + 'Please remove the `return` statement.', invalidVoidExprReturnWrapVoid: 'Void expressions returned from a function ' + 'must be marked explicitly with the `void` operator.', voidExprWrapVoid: 'Mark with an explicit `void` operator.', }, schema: [ { type: 'object', properties: { ignoreArrowShorthand: { type: 'boolean' }, ignoreVoidOperator: { type: 'boolean' }, }, additionalProperties: false, }, ], type: 'problem', fixable: 'code', hasSuggestions: true, }, defaultOptions: [{}], create(context, [options]) { return { 'AwaitExpression, CallExpression, TaggedTemplateExpression'( node: | TSESTree.AwaitExpression | TSESTree.CallExpression | TSESTree.TaggedTemplateExpression, ): void { const parserServices = util.getParserServices(context); const checker = parserServices.program.getTypeChecker(); const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node); const type = util.getConstrainedTypeAtLocation(checker, tsNode); if (!tsutils.isTypeFlagSet(type, ts.TypeFlags.VoidLike)) { // not a void expression return; } const invalidAncestor = findInvalidAncestor(node); if (invalidAncestor == null) { // void expression is in valid position return; } const sourceCode = context.getSourceCode(); const wrapVoidFix = (fixer: TSESLint.RuleFixer): TSESLint.RuleFix => { const nodeText = sourceCode.getText(node); const newNodeText = `void ${nodeText}`; return fixer.replaceText(node, newNodeText); }; if (invalidAncestor.type === AST_NODE_TYPES.ArrowFunctionExpression) { // handle arrow function shorthand if (options.ignoreVoidOperator) { // handle wrapping with `void` return context.report({ node, messageId: 'invalidVoidExprArrowWrapVoid', fix: wrapVoidFix, }); } // handle wrapping with braces const arrowFunction = invalidAncestor; return context.report({ node, messageId: 'invalidVoidExprArrow', fix(fixer) { const arrowBody = arrowFunction.body; const arrowBodyText = sourceCode.getText(arrowBody); const newArrowBodyText = `{ ${arrowBodyText}; }`; if (util.isParenthesized(arrowBody, sourceCode)) { const bodyOpeningParen = sourceCode.getTokenBefore( arrowBody, util.isOpeningParenToken, )!; const bodyClosingParen = sourceCode.getTokenAfter( arrowBody, util.isClosingParenToken, )!; return fixer.replaceTextRange( [bodyOpeningParen.range[0], bodyClosingParen.range[1]], newArrowBodyText, ); } return fixer.replaceText(arrowBody, newArrowBodyText); }, }); } if (invalidAncestor.type === AST_NODE_TYPES.ReturnStatement) { // handle return statement if (options.ignoreVoidOperator) { // handle wrapping with `void` return context.report({ node, messageId: 'invalidVoidExprReturnWrapVoid', fix: wrapVoidFix, }); } const returnStmt = invalidAncestor; if (isFinalReturn(returnStmt)) { // remove the `return` keyword return context.report({ node, messageId: 'invalidVoidExprReturnLast', fix(fixer) { const returnValue = returnStmt.argument!; const returnValueText = sourceCode.getText(returnValue); let newReturnStmtText = `${returnValueText};`; if (isPreventingASI(returnValue, sourceCode)) { // put a semicolon at the beginning of the line newReturnStmtText = `;${newReturnStmtText}`; } return fixer.replaceText(returnStmt, newReturnStmtText); }, }); } // move before the `return` keyword return context.report({ node, messageId: 'invalidVoidExprReturn', fix(fixer) { const returnValue = returnStmt.argument!; const returnValueText = sourceCode.getText(returnValue); let newReturnStmtText = `${returnValueText}; return;`; if (isPreventingASI(returnValue, sourceCode)) { // put a semicolon at the beginning of the line newReturnStmtText = `;${newReturnStmtText}`; } if (returnStmt.parent?.type !== AST_NODE_TYPES.BlockStatement) { // e.g. `if (cond) return console.error();` // add braces if not inside a block newReturnStmtText = `{ ${newReturnStmtText} }`; } return fixer.replaceText(returnStmt, newReturnStmtText); }, }); } // handle generic case if (options.ignoreVoidOperator) { // this would be reported by this rule btw. such irony return context.report({ node, messageId: 'invalidVoidExprWrapVoid', suggest: [{ messageId: 'voidExprWrapVoid', fix: wrapVoidFix }], }); } context.report({ node, messageId: 'invalidVoidExpr', }); }, }; /** * Inspects the void expression's ancestors and finds closest invalid one. * By default anything other than an ExpressionStatement is invalid. * Parent expressions which can be used for their short-circuiting behavior * are ignored and their parents are checked instead. * @param node The void expression node to check. * @returns Invalid ancestor node if it was found. `null` otherwise. */ function findInvalidAncestor(node: TSESTree.Node): TSESTree.Node | null { const parent = util.nullThrows( node.parent, util.NullThrowsReasons.MissingParent, ); if (parent.type === AST_NODE_TYPES.ExpressionStatement) { // e.g. `{ console.log("foo"); }` // this is always valid return null; } if (parent.type === AST_NODE_TYPES.LogicalExpression) { if (parent.right === node) { // e.g. `x && console.log(x)` // this is valid only if the next ancestor is valid return findInvalidAncestor(parent); } } if (parent.type === AST_NODE_TYPES.ConditionalExpression) { if (parent.consequent === node || parent.alternate === node) { // e.g. `cond ? console.log(true) : console.log(false)` // this is valid only if the next ancestor is valid return findInvalidAncestor(parent); } } if (parent.type === AST_NODE_TYPES.ArrowFunctionExpression) { // e.g. `() => console.log("foo")` // this is valid with an appropriate option if (options.ignoreArrowShorthand) { return null; } } if (parent.type === AST_NODE_TYPES.UnaryExpression) { if (parent.operator === 'void') { // e.g. `void console.log("foo")` // this is valid with an appropriate option if (options.ignoreVoidOperator) { return null; } } } if (parent.type === AST_NODE_TYPES.ChainExpression) { // e.g. `console?.log('foo')` return findInvalidAncestor(parent); } // any other parent is invalid return parent; } /** Checks whether the return statement is the last statement in a function body. */ function isFinalReturn(node: TSESTree.ReturnStatement): boolean { // the parent must be a block const block = util.nullThrows( node.parent, util.NullThrowsReasons.MissingParent, ); if (block.type !== AST_NODE_TYPES.BlockStatement) { // e.g. `if (cond) return;` (not in a block) return false; } // the block's parent must be a function const blockParent = util.nullThrows( block.parent, util.NullThrowsReasons.MissingParent, ); if ( ![ AST_NODE_TYPES.FunctionDeclaration, AST_NODE_TYPES.FunctionExpression, AST_NODE_TYPES.ArrowFunctionExpression, ].includes(blockParent.type) ) { // e.g. `if (cond) { return; }` // not in a top-level function block return false; } // must be the last child of the block if (block.body.indexOf(node) < block.body.length - 1) { // not the last statement in the block return false; } return true; } /** * Checks whether the given node, if placed on its own line, * would prevent automatic semicolon insertion on the line before. * * This happens if the line begins with `(`, `[` or `` ` `` */ function isPreventingASI( node: TSESTree.Expression, sourceCode: Readonly<TSESLint.SourceCode>, ): boolean { const startToken = util.nullThrows( sourceCode.getFirstToken(node), util.NullThrowsReasons.MissingToken('first token', node.type), ); return ['(', '[', '`'].includes(startToken.value); } }, });
the_stack
import { ethers, network, upgrades, waffle } from "hardhat"; import { Signer } from "ethers"; import chai from "chai"; import { solidity } from "ethereum-waffle"; import "@openzeppelin/test-helpers"; import { MockERC20, MockERC20__factory, MdexFactory, MdexFactory__factory, MdexPair, MdexPair__factory, MdexRouter, MdexRouter__factory, MdexRestrictedStrategyAddBaseTokenOnly, MdexRestrictedStrategyAddBaseTokenOnly__factory, WETH, WETH__factory, MockMdexWorker, MockMdexWorker__factory, MdxToken, MdxToken__factory, SwapMining, SwapMining__factory, Oracle, Oracle__factory, } from "../../../../../typechain"; import { assertAlmostEqual } from "../../../../helpers/assert"; import { formatEther } from "ethers/lib/utils"; import * as TimeHelpers from "../../../../helpers/time"; chai.use(solidity); const { expect } = chai; describe("MdexRestrictedStrategyAddBaseTokenOnly", () => { const FOREVER = "2000000000"; const mdxPerBlock = "51600000000000000000"; /// Mdex-related instance(s) let factory: MdexFactory; let router: MdexRouter; let lp: MdexPair; let oracle: Oracle; let swapMining: SwapMining; /// MockMdexWorker-related instance(s) let mockMdexWorker: MockMdexWorker; let mockMdexEvilWorker: MockMdexWorker; /// Token-related instance(s) let wbnb: WETH; let baseToken: MockERC20; let farmingToken: MockERC20; let mdxToken: MdxToken; /// Strategy instance(s) let strat: MdexRestrictedStrategyAddBaseTokenOnly; // Accounts let deployer: Signer; let alice: Signer; let bob: Signer; // Contract Signer let baseTokenAsAlice: MockERC20; let baseTokenAsBob: MockERC20; let farmingTokenAsAlice: MockERC20; let routerAsAlice: MdexRouter; let stratAsBob: MdexRestrictedStrategyAddBaseTokenOnly; let mockMdexWorkerAsBob: MockMdexWorker; let mockMdexEvilWorkerAsBob: MockMdexWorker; async function fixture() { [deployer, alice, bob] = await ethers.getSigners(); // Setup Mdex const MdexFactory = (await ethers.getContractFactory("MdexFactory", deployer)) as MdexFactory__factory; factory = await MdexFactory.deploy(await deployer.getAddress()); await factory.deployed(); const WBNB = (await ethers.getContractFactory("WETH", deployer)) as WETH__factory; wbnb = await WBNB.deploy(); await wbnb.deployed(); const MdxToken = (await ethers.getContractFactory("MdxToken", deployer)) as MdxToken__factory; mdxToken = await MdxToken.deploy(); await mdxToken.deployed(); await mdxToken.addMinter(await deployer.getAddress()); await mdxToken.mint(await deployer.getAddress(), ethers.utils.parseEther("100")); const MdexRouter = (await ethers.getContractFactory("MdexRouter", deployer)) as MdexRouter__factory; router = await MdexRouter.deploy(factory.address, wbnb.address); await router.deployed(); const Oracle = (await ethers.getContractFactory("Oracle", deployer)) as Oracle__factory; oracle = await Oracle.deploy(factory.address); await oracle.deployed(); /// Setup token stuffs const MockERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory; baseToken = (await upgrades.deployProxy(MockERC20, ["BTOKEN", "BTOKEN", 18])) as MockERC20; await baseToken.deployed(); await baseToken.mint(await alice.getAddress(), ethers.utils.parseEther("100")); await baseToken.mint(await bob.getAddress(), ethers.utils.parseEther("100")); farmingToken = (await upgrades.deployProxy(MockERC20, ["FTOKEN", "FTOKEN", 18])) as MockERC20; await farmingToken.deployed(); await farmingToken.mint(await alice.getAddress(), ethers.utils.parseEther("10")); await farmingToken.mint(await bob.getAddress(), ethers.utils.parseEther("10")); await factory.createPair(baseToken.address, farmingToken.address); lp = MdexPair__factory.connect(await factory.getPair(farmingToken.address, baseToken.address), deployer); await factory.addPair(lp.address); // Mdex SwapMinig const blockNumber = await TimeHelpers.latestBlockNumber(); const SwapMining = (await ethers.getContractFactory("SwapMining", deployer)) as SwapMining__factory; swapMining = await SwapMining.deploy( mdxToken.address, factory.address, oracle.address, router.address, farmingToken.address, mdxPerBlock, blockNumber ); await swapMining.deployed(); // set swapMining to router await router.setSwapMining(swapMining.address); await mdxToken.addMinter(swapMining.address); await swapMining.addPair(100, lp.address, false); await swapMining.addWhitelist(baseToken.address); await swapMining.addWhitelist(farmingToken.address); /// Setup MockMdexWorker const MockMdexWorker = (await ethers.getContractFactory("MockMdexWorker", deployer)) as MockMdexWorker__factory; mockMdexWorker = (await MockMdexWorker.deploy( lp.address, baseToken.address, farmingToken.address )) as MockMdexWorker; await mockMdexWorker.deployed(); mockMdexEvilWorker = (await MockMdexWorker.deploy( lp.address, baseToken.address, farmingToken.address )) as MockMdexWorker; await mockMdexEvilWorker.deployed(); const MdexRestrictedStrategyAddBaseTokenOnly = (await ethers.getContractFactory( "MdexRestrictedStrategyAddBaseTokenOnly", deployer )) as MdexRestrictedStrategyAddBaseTokenOnly__factory; strat = (await upgrades.deployProxy(MdexRestrictedStrategyAddBaseTokenOnly, [ router.address, mdxToken.address, ])) as MdexRestrictedStrategyAddBaseTokenOnly; await strat.deployed(); await strat.setWorkersOk([mockMdexWorker.address], true); // Assign contract signer baseTokenAsAlice = MockERC20__factory.connect(baseToken.address, alice); baseTokenAsBob = MockERC20__factory.connect(baseToken.address, bob); farmingTokenAsAlice = MockERC20__factory.connect(farmingToken.address, alice); routerAsAlice = MdexRouter__factory.connect(router.address, alice); stratAsBob = MdexRestrictedStrategyAddBaseTokenOnly__factory.connect(strat.address, bob); mockMdexWorkerAsBob = MockMdexWorker__factory.connect(mockMdexWorker.address, bob); mockMdexEvilWorkerAsBob = MockMdexWorker__factory.connect(mockMdexEvilWorker.address, bob); // Adding liquidity to the pool // Alice adds 0.1 FTOKEN + 1 BTOKEN await farmingTokenAsAlice.approve(router.address, ethers.utils.parseEther("0.1")); await baseTokenAsAlice.approve(router.address, ethers.utils.parseEther("1")); // // Add liquidity to the BTOKEN-FTOKEN pool on Mdex await routerAsAlice.addLiquidity( baseToken.address, farmingToken.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("0.1"), "0", "0", await alice.getAddress(), FOREVER ); // refer to MdexFactory line: 842 // totalSupply = sqrt(amount0 * amount1) - 0.000000000000001000 // totalSupply = sqrt(1 * 0.1) - 0.000000000000001000 = 0.316227766016836933 await network.provider.send("hardhat_setNextBlockBaseFeePerGas", ["0x0"]); } beforeEach(async () => { await waffle.loadFixture(fixture); }); context("When bad calldata", async () => { it("should revert", async () => { // Bob passes some bad calldata that can't be decoded await expect(stratAsBob.execute(await bob.getAddress(), "0", "0x1234")).to.be.reverted; }); }); context("When the setOkWorkers caller is not an owner", async () => { it("should be reverted", async () => { await expect(stratAsBob.setWorkersOk([mockMdexEvilWorkerAsBob.address], true)).to.reverted; }); }); context("When non-worker call the strat", async () => { it("should revert", async () => { await expect( stratAsBob.execute(await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])) ).to.be.reverted; }); }); context("When contract get LP < minLP", async () => { it("should revert", async () => { // Bob uses AddBaseTokenOnly strategy yet again, but now with an unreasonable min LP request await baseTokenAsBob.transfer(mockMdexWorker.address, ethers.utils.parseEther("0.1")); await expect( mockMdexWorkerAsBob.work( 0, await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0.05")])] ) ) ).to.be.revertedWith("MdexRestrictedStrategyAddBaseTokenOnly::execute:: insufficient LP tokens received"); }); }); context("When caller worker hasn't been whitelisted", async () => { it("should revert as bad worker", async () => { await baseTokenAsBob.transfer(mockMdexEvilWorkerAsBob.address, ethers.utils.parseEther("0.05")); await expect( mockMdexEvilWorkerAsBob.work( 0, await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0.05")])] ) ) ).to.be.revertedWith("MdexRestrictedStrategyAddBaseTokenOnly::onlyWhitelistedWorkers:: bad worker"); }); }); context("when revoking whitelist workers", async () => { it("should revert as bad worker", async () => { await strat.setWorkersOk([mockMdexWorker.address], false); await expect( mockMdexWorkerAsBob.work( 0, await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], [ethers.utils.parseEther("0.05")])] ) ) ).to.be.revertedWith("MdexRestrictedStrategyAddBaseTokenOnly::onlyWhitelistedWorkers:: bad worker"); }); }); it("should convert all BTOKEN to LP tokens at best rate (trading fee 25)", async () => { await factory.setPairFees(lp.address, 25); // Bob transfer 0.1 BTOKEN to StrategyAddBaseTokenOnly first await baseTokenAsBob.transfer(mockMdexWorker.address, ethers.utils.parseEther("0.1")); // Bob uses AddBaseTokenOnly strategy to add 0.1 BTOKEN await mockMdexWorkerAsBob.work( 0, await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // // actualLpAmount = 0.015415396042372718 expect(await lp.balanceOf(mockMdexWorker.address)).to.be.eq(ethers.utils.parseEther("0.015415396042372718")); expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); expect(await farmingToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); expect(await baseToken.balanceOf(strat.address)).to.be.eq(ethers.BigNumber.from("0")); // // Bob uses AddBaseTokenOnly strategy to add another 0.1 BTOKEN await baseTokenAsBob.transfer(mockMdexWorker.address, ethers.utils.parseEther("0.1")); await mockMdexWorkerAsBob.work( 0, await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); expect(await lp.balanceOf(mockMdexWorker.address)).to.be.eq(ethers.utils.parseEther("0.030143763464109982")); expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); expect(await farmingToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); expect(await baseToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); }); it("should convert all BTOKEN to LP tokens at best rate (trading fee 20)", async () => { await factory.setPairFees(lp.address, 20); // Bob transfer 0.1 BTOKEN to StrategyAddBaseTokenOnly first await baseTokenAsBob.transfer(mockMdexWorker.address, ethers.utils.parseEther("0.1")); // Bob uses AddBaseTokenOnly strategy to add 0.1 BTOKEN await mockMdexWorkerAsBob.work( 0, await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Adding 0.1 BTOKEN // amountIn of BTOKEN that will be swapped // amountIn = [ sqrt(reserveIn * (amountBTOKEN * 3992000 + (reserveIn * 3992004))) - (reserveIn * 1998) ] / 1996 // amountIn = [ sqrt(1 * ((0.1 * 3992000) + (1 * 3992004))) - (1 * 1998) ] / 1996 // amountIn = 0.048857707015160316... BTOKEN // amountOut = (amountIn * fee * reserveOut) / ((reserveIn * feeDenom) + (amountIn * fee)) // amountOut = (0.048857707015160316 * 998 * 0.1) / ((1 * 1000) + (0.048857707015160316 * 998 )) // amountOut = 0.004649299362258152... FTOKEN // after swap // reserveIn = 1 + 0.048857707015160316 = 1.048857707015160316 BTOKEN // reserveOut = 0.1 - 0.004649299362258152 = 0.095350700637741848 FTOKEN // totalSupply = 0.316227766016836933 (from first adding liquidity in the setup) // so adding both BTOKEN and FTOKEN as liquidity will result in an amount of lp // amountBTOKEN = 0.1 - 0.048857707015160316 = 0.051142292984839684 // amountFTOKEN = 0.004649299362258152 // refer to MdexFactory line: 846 // lpAmount = min of [ totalSupply * (amountF / reserveF) or totalSupply * (amountB / reserveB) ] // lpAmount = 0.316227766016837933 * (0.004649299362258152 / 0.095350700637741848) ~= 0.015419263215025115... // lpAmount = 0.316227766016837933 * (0.051142292984839684 / 1.048857707015160316) ~= 0.015419263215025119... // actualLpAmount = 0.015419263215025115 expect(await lp.balanceOf(mockMdexWorker.address)).to.be.eq(ethers.utils.parseEther("0.015419263215025115")); expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); expect(await farmingToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); // there is a very small remaining amount of base token left expect(await baseToken.balanceOf(strat.address)).to.be.lte(ethers.BigNumber.from("13")); // Bob uses AddBaseTokenOnly strategy to add another 0.1 BTOKEN await baseTokenAsBob.transfer(mockMdexWorker.address, ethers.utils.parseEther("0.1")); await mockMdexWorkerAsBob.work( 0, await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); expect(await lp.balanceOf(mockMdexWorker.address)).to.be.eq(ethers.utils.parseEther("0.030151497260262730")); expect(await lp.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); expect(await farmingToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); expect(await baseToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0")); }); describe("#withdrawTradingRewards", async () => { context("When the withdrawTradingRewards caller is not an owner", async () => { it("should be reverted", async () => { await expect(stratAsBob.withdrawTradingRewards(await bob.getAddress())).to.reverted; }); }); context("When withdrawTradingRewards caller is the owner", async () => { it("should be able to withdraw trading rewards", async () => { // set lp pair fee await factory.setPairFees(lp.address, 25); // Bob transfer 0.1 BTOKEN to StrategyAddBaseTokenOnly first await baseTokenAsBob.transfer(mockMdexWorker.address, ethers.utils.parseEther("0.1")); // Bob uses AddBaseTokenOnly strategy to add 0.1 BTOKEN await mockMdexWorkerAsBob.work( 0, await bob.getAddress(), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [strat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); const deployerAddress = await deployer.getAddress(); const mdxBefore = await mdxToken.balanceOf(deployerAddress); // withdraw trading reward to deployer const withDrawTx = await strat.withdrawTradingRewards(deployerAddress); const mdxAfter = await mdxToken.balanceOf(deployerAddress); // get trading reward of the previos block const pIds = [0]; const totalRewardPrev = await strat.getMiningRewards(pIds, { blockTag: Number(withDrawTx.blockNumber) - 1 }); const withDrawBlockReward = await swapMining["reward()"]({ blockTag: withDrawTx.blockNumber }); const totalReward = totalRewardPrev.add(withDrawBlockReward); expect(mdxAfter.sub(mdxBefore)).to.eq(totalReward); }); }); }); });
the_stack
import { Trans } from "@lingui/macro"; import { MountService } from "foundation-ui"; import * as React from "react"; import { Hooks } from "PluginSDK"; import { Route, hashHistory } from "react-router"; import ApplicationUtil from "#SRC/js/utils/ApplicationUtil"; import AuthStore from "#SRC/js/stores/AuthStore"; import Authenticated from "#SRC/js/components/Authenticated"; import AccessDeniedPage from "#SRC/js/components/AccessDeniedPage"; import Config from "#SRC/js/config/Config"; import CookieUtils from "#SRC/js/utils/CookieUtils"; import * as EventTypes from "#SRC/js/constants/EventTypes"; import MetadataStore from "#SRC/js/stores/MetadataStore"; import MesosStateStore from "#SRC/js/stores/MesosStateStore"; import RequestErrorMsg from "#SRC/js/components/RequestErrorMsg"; import RouterUtil from "#SRC/js/utils/RouterUtil"; import { ACL_AUTH_USER_PERMISSIONS_CHANGED } from "./constants/EventTypes"; import ACLAuthenticatedUserStoreFactory from "./stores/ACLAuthenticatedUserStore"; import AuthenticatedClusterDropdown from "./components/AuthenticatedClusterDropdown"; import AuthenticatedUserAccountDropdown from "./components/AuthenticatedUserAccountDropdown"; import LoginPage from "./components/LoginPage"; const API_PERMISSIONS = { acsAPI: "dcos:adminrouter:acs", metronomeAPI: "dcos:adminrouter:service:metronome", metadataAPI: "dcos:adminrouter:ops:metadata", marathonAPI: "dcos:adminrouter:service:marathon", mesosAPI: "dcos:adminrouter:ops:mesos", networkingAPI: "dcos:adminrouter:ops:networking", packageAPI: "dcos:adminrouter:package", secretsAPI: "dcos:adminrouter:secrets", systemHealthAPI: "dcos:adminrouter:ops:system-health", uiUpdate: "dcos:adminrouter:ops:dcos-ui-update-service", }; const SIDEBAR_MENU_MAP = { "/dashboard": ["marathonAPI", "systemHealthAPI"], "/services": ["marathonAPI"], "/jobs": ["metronomeAPI"], "/catalog": ["packageAPI"], "/nodes": ["mesosAPI"], "/networking": ["networkingAPI"], "/secrets": ["none"], "/cluster": ["superadmin"], "/components": ["systemHealthAPI"], "/settings": ["superadmin", "acsAPI", "none"], "/organization": ["acsAPI"], }; const MESOS_ACCESS_DENIED_MOUNTS = [ "ServiceInstancesContainer:TasksContainer", "DeclinedOffersTable", ]; export default (SDK) => { const ACLAuthenticatedUserStore = ACLAuthenticatedUserStoreFactory(SDK); return { arePluginsConfigured: false, configuration: { enabled: false, }, actions: [ { id: "AJAXRequestError" }, { id: "pluginsConfigured" }, { id: "redirectToLogin" }, { id: "userLoginSuccess" }, { id: "userLogoutSuccess", priority: 10 }, ], filters: [ { id: "applicationRoutes" }, { id: "applicationRedirectRoute" }, { id: "pluginsLoadedCheck" }, { id: "shouldIdentifyLoggedInUser" }, { id: "serverErrorModalListeners" }, { id: "hasAuthorization" }, { id: "hasCapability", priority: 15 }, { id: "sidebarNavigation", priority: 999999 }, { id: "secondaryNavigation", priority: 999999 }, ], initialize() { this.filters.forEach(({ id, priority }) => { Hooks.addFilter(id, this[id].bind(this), priority); }); this.actions.forEach(({ id, priority }) => { Hooks.addAction(id, this[id].bind(this), priority); }); this.configure(SDK.config); this.unregisterMesosDeniedAccess = this.unregisterMesosDeniedAccess.bind( this ); this.registerMesosDeniedAccess = this.registerMesosDeniedAccess.bind( this ); MesosStateStore.addChangeListener( EventTypes.MESOS_STATE_REQUEST_ERROR, this.registerMesosDeniedAccess ); this.registerHeaderDropdowns(); hashHistory.listen(this.handleRouteChange.bind(this)); }, configure(configuration) { // Only merge keys that have a non-null value Object.keys(configuration).forEach((key) => { if (configuration[key] != null) { this.configuration[key] = configuration[key]; } }); }, isEnabled() { return this.configuration.enabled; }, pluginsConfigured() { this.arePluginsConfigured = true; }, redirectToLogin(nextState, replace) { const redirectTo = RouterUtil.getRedirectTo(); // Ignores relative path if redirect is present if (redirectTo) { replace(`/login?redirect=${redirectTo}`); } else { replace(`/login?relativePath=${nextState.location.pathname}`); } }, registerMesosDeniedAccess(xhr) { if (xhr.status === 403) { MESOS_ACCESS_DENIED_MOUNTS.forEach((type) => { MountService.MountService.registerComponent( this.getMesosAccessDeniedMessage, type ); }); // Listen for success to unregister in case permissions change MesosStateStore.addChangeListener( EventTypes.MESOS_STATE_CHANGE, this.unregisterMesosDeniedAccess ); // Unregister access-denied since we've already acted MesosStateStore.removeChangeListener( EventTypes.MESOS_STATE_REQUEST_ERROR, this.registerMesosDeniedAccess ); } }, unregisterMesosDeniedAccess() { MESOS_ACCESS_DENIED_MOUNTS.forEach((type) => { MountService.MountService.unregisterComponent( this.getMesosAccessDeniedMessage, type ); }); // Stop listening for success since we've already acted MesosStateStore.removeChangeListener( EventTypes.MESOS_STATE_CHANGE, this.unregisterMesosDeniedAccess ); // Listen for errors again in case permissions change MesosStateStore.addChangeListener( EventTypes.MESOS_STATE_REQUEST_ERROR, this.registerMesosDeniedAccess ); }, getMesosAccessDeniedMessage() { const message = ( <Trans render="div"> You do not have access to this resource. Please contact your{" "} {Config.productName} administrator or see{" "} <a href={MetadataStore.buildDocsURI("/security/ent/iam-api/")} target="_blank" > security documentation </a>{" "} for more information. </Trans> ); return <RequestErrorMsg header="Access Denied" message={message} />; }, locationIsAccessDeniedPage(location) { return /^\/access-denied/.test(location); }, locationIsLoginPage(location) { return /^\/login/.test(location); }, AJAXRequestError(xhr) { if (xhr.status !== 401 && xhr.status !== 403) { return; } const location = window.location.hash.replace(/^#/, ""); const onAccessDeniedPage = this.locationIsAccessDeniedPage(location); const onLoginPage = this.locationIsLoginPage(location); // Unauthorized if (xhr.status === 401 && !onLoginPage && !onAccessDeniedPage) { document.cookie = CookieUtils.emptyCookieWithExpiry(new Date(1970)); window.location.href = "#/login"; } // TODO: foundation refactor needed // If you: // 1) Log in with an Identity Provider // 2) Have a user with access only to "/services" // 3) And access the root path "/" // // You receive an "Access Denied" page although you should be redirected // to the "/services" path. This happens because in the secrets/hooks.js // there is a SecretStore.fetchStores(); request that returns a 403 that // triggers this AjaxRequestError and shows the access denied page although // we're located in the root page "/" that would eventually redirect us to // the services page. // // This area is a patch for: DCOS-19914 // Reference foundation task: DCOS-19926 const findFirstAccessibleRoute = this.findFirstAccessibleRoute(); const isRootPath = location && location.split("?")[0] === "/"; if (isRootPath && findFirstAccessibleRoute) { return; } // Check if user has access to any of the APIs for the route const hasSomeCapabilities = this.authorizedToAccessLocation(location); // Forbidden if (xhr.status === 403 && !hasSomeCapabilities) { window.location.href = "#/access-denied"; } }, authorizedToAccessLocation(location) { const onAccessDeniedPage = this.locationIsAccessDeniedPage(location); const onLoginPage = this.locationIsLoginPage(location); if (onAccessDeniedPage || onLoginPage) { return true; } const currentRoutePath = Object.keys(SIDEBAR_MENU_MAP).find((route) => location.startsWith(route) ); if (!currentRoutePath) { return false; } return SIDEBAR_MENU_MAP[currentRoutePath].some((api) => Hooks.applyFilter("hasCapability", false, api) ); }, shouldIdentifyLoggedInUser() { return false; }, serverErrorModalListeners(listeners) { listeners.push({ name: "auth", events: ["logoutError"] }); return listeners; }, applicationRoutes(routes) { if (this.isEnabled() === true) { // Override handler of index to be 'authenticated' routes[0].children.forEach((child) => { if (child.id === "index") { child.component = new Authenticated(child.component); child.onEnter = child.component.willTransitionTo; } }); // Add access denied and login pages routes[0].children.unshift( { component: AccessDeniedPage, path: "/access-denied", type: Route, }, { component: LoginPage, path: "/login", type: Route, } ); } return routes; }, pluginsLoadedCheck(promiseArray) { const permissions = ACLAuthenticatedUserStore.getPermissions(); // If there's no permissions if (Object.keys(permissions).length === 0) { const user = AuthStore.getUser(); if (user) { // Create a new promise that needs to be resolved before the app loads const promise = new Promise((resolve) => { this.fetchPermissionsForUserID(user.uid, resolve); }); promiseArray.push(promise); } } return promiseArray; }, fetchPermissionsForUserID(userID, callback) { // Listen to event once, we only care if it was received ACLAuthenticatedUserStore.once(ACL_AUTH_USER_PERMISSIONS_CHANGED, () => { callback(); Hooks.doAction("userCapabilitiesFetched"); }); // Make request to API ACLAuthenticatedUserStore.fetchPermissions(userID); }, applicationRedirectRoute() { return this.findFirstAccessibleRoute(); }, findFirstAccessibleRoute() { const routableItems = { "/dashboard": SIDEBAR_MENU_MAP["/dashboard"], "/services": SIDEBAR_MENU_MAP["/services"], "/jobs": SIDEBAR_MENU_MAP["/jobs"], "/nodes": SIDEBAR_MENU_MAP["/nodes"], "/catalog": SIDEBAR_MENU_MAP["/catalog"], "/networking": SIDEBAR_MENU_MAP["/networking"], "/components": ["systemHealthAPI"], "/organization": ["acsAPI"], "/secrets": ["secretsAPI"], }; const items = this.filterViewableItems( routableItems, Object.keys(routableItems) ); if (items.length) { return items[0]; } // This ensures we route to access denied after login return "/access-denied"; }, userLoginSuccess() { const redirectTo = RouterUtil.getRedirectTo(); const isValidRedirect = RouterUtil.isValidRedirect(redirectTo); if (isValidRedirect) { window.location.href = redirectTo; } else { const user = AuthStore.getUser(); // We need to fetch permissions before mesos so that // we know which endpoint to poll first this.fetchPermissionsForUserID(user.uid, () => { ApplicationUtil.beginTemporaryPolling(() => { const relativePath = RouterUtil.getRelativePath(); const loginRedirectRoute = AuthStore.get("loginRedirectRoute"); if (loginRedirectRoute && !relativePath) { // Go to redirect route if it is present hashHistory.push(loginRedirectRoute); return; } if (relativePath) { window.location.replace( `${window.location.origin}/#${relativePath}` ); return; } hashHistory.push(this.findFirstAccessibleRoute()); }); }); } }, userLogoutSuccess() { hashHistory.push("/login"); window.location.reload(); }, handleRouteChange({ pathname }) { // We can't validate users access if we don't have their permissions yet if (!this.arePluginsConfigured) { return; } if (this.locationIsLoginPage(pathname)) { return; } if (!AuthStore.isLoggedIn()) { Hooks.doAction( "redirectToLogin", { location: { pathname } }, hashHistory.replace ); return; } const isAuthorized = Hooks.applyFilter( "hasAuthorization", false, pathname ); if (!isAuthorized) { hashHistory.push(this.findFirstAccessibleRoute()); } }, /** * Checks if user is authorized to access a path * @param {boolean} bool The previous value of this filter * @param {String} location The path to check * @return {boolean} is authorized to access location */ hasAuthorization(bool, location) { return this.authorizedToAccessLocation(location); }, hasCapability(bool, capability) { if (!capability) { return false; } if (capability === "none") { return true; } const permissions = ACLAuthenticatedUserStore.getPermissions(); // Super users have access to everything if (permissions["dcos:superuser"]) { return true; } return ( capability in API_PERMISSIONS && !!permissions[API_PERMISSIONS[capability]] ); }, filterViewableItems(constraintMap, filterableArray) { const hasCapability = Hooks.applyFilter.bind( Hooks, "hasCapability", false ); // Filter out any menu items that don't exist // This will happen when some plugins aren't enabled constraintMap = Object.keys(constraintMap).reduce((memo, constraint) => { if (filterableArray.indexOf(constraint) === -1) { if (Config.environment === "development") { console.warn(`${constraint} doesn't exist.`); } } else { memo[constraint] = constraintMap[constraint]; } return memo; }, {}); return Object.keys(constraintMap).reduce((filteredItems, constraint) => { // Only need to match one of the permissions if (constraintMap[constraint].some(hasCapability)) { filteredItems.push(constraint); } return filteredItems; }, []); }, registerHeaderDropdowns() { MountService.MountService.registerComponent( AuthenticatedUserAccountDropdown, "Header:UserAccountDropdown", 100 ); MountService.MountService.registerComponent( AuthenticatedClusterDropdown, "Header:ClusterDropdown", 100 ); }, // Menu Handling sidebarNavigation(menuItems) { const filteredMenu = this.filterViewableItems( SIDEBAR_MENU_MAP, menuItems ); if (filteredMenu.length === 0) { // This will ensure we redirect on reload of page setTimeout(() => { window.location.href = "/#/access-denied"; }); } return filteredMenu; }, secondaryNavigation(tabs, parentPath) { if (parentPath === "/settings") { const tabMap = { "/settings/ui-settings": ["none"], "/settings/repositories": ["superadmin"], "/settings/stores": ["superadmin"], "/settings/identity-providers": ["acsAPI"], "/settings/directory": ["acsAPI"], }; return this.filterViewableItems(tabMap, tabs); } return tabs; }, }; };
the_stack
import moment from "moment"; import type { KubeJsonApiData, KubeJsonApiDataList, KubeJsonApiListMetadata } from "./kube-json-api"; import { autoBind, formatDuration, hasOptionalTypedProperty, hasTypedProperty, isObject, isString, isNumber, bindPredicate, isTypedArray, isRecord, json } from "../utils"; import type { ItemObject } from "../item.store"; import { apiKube } from "./index"; import * as resourceApplierApi from "./endpoints/resource-applier.api"; import type { Patch } from "rfc6902"; import assert from "assert"; import type { JsonObject } from "type-fest"; export type KubeJsonApiDataFor<K> = K extends KubeObject<infer Status, infer Spec, infer Scope> ? KubeJsonApiData<KubeObjectMetadata<Scope>, Status, Spec> : never; export interface KubeObjectConstructorData { readonly kind?: string; readonly namespaced?: boolean; readonly apiBase?: string; } export type KubeObjectConstructor<K extends KubeObject<any, any, KubeObjectScope>, Data> = (new (data: Data) => K) & KubeObjectConstructorData; export interface OwnerReference { apiVersion: string; kind: string; name: string; uid: string; controller?: boolean; blockOwnerDeletion?: boolean; } export type KubeTemplateObjectMetadata<Namespaced extends KubeObjectScope> = Pick<KubeJsonApiObjectMetadata<KubeObjectScope>, "annotations" | "finalizers" | "generateName" | "labels" | "ownerReferences"> & { name?: string; namespace?: ScopedNamespace<Namespaced>; }; export interface BaseKubeJsonApiObjectMetadata<Namespaced extends KubeObjectScope> { /** * Annotations is an unstructured key value map stored with a resource that may be set by * external tools to store and retrieve arbitrary metadata. They are not queryable and should be * preserved when modifying objects. * * More info: http://kubernetes.io/docs/user-guide/annotations */ annotations?: Partial<Record<string, string>>; /** * The name of the cluster which the object belongs to. This is used to distinguish resources * with same name and namespace in different clusters. This field is not set anywhere right now * and apiserver is going to ignore it if set in create or update request. */ clusterName?: string; /** * CreationTimestamp is a timestamp representing the server time when this object was created. It * is not guaranteed to be set in happens-before order across separate operations. Clients may * not set this value. It is represented in RFC3339 form and is in UTC. Populated by the system. * * More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */ readonly creationTimestamp?: string; /** * Number of seconds allowed for this object to gracefully terminate before it will be removed * from the system. Only set when deletionTimestamp is also set. May only be shortened. */ readonly deletionGracePeriodSeconds?: number; /** * DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This field * is set by the server when a graceful deletion is requested by the user, and is not directly * settable by a client. The resource is expected to be deleted (no longer visible from resource * lists, and not reachable by name) after the time in this field, once the finalizers list is * empty. As long as the finalizers list contains items, deletion is blocked. Once the * `deletionTimestamp` is set, this value may not be unset or be set further into the future, * although it may be shortened or the resource may be deleted prior to this time. For example, * a user may request that a pod is deleted in 30 seconds. The Kubelet will react by sending a * graceful termination signal to the containers in the pod. After that 30 seconds, the Kubelet * will send a hard termination signal (SIGKILL) to the container and after cleanup, remove the * pod from the API. In the presence of network partitions, this object may still exist after * this timestamp, until an administrator or automated process can determine the resource is * fully terminated. If not set, graceful deletion of the object has not been requested. * Populated by the system when a graceful deletion is requested. * * More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata */ readonly deletionTimestamp?: string; /** * Must be empty before the object is deleted from the registry. Each entry is an identifier for * the responsible component that will remove the entry from the list. If the deletionTimestamp * of the object is non-nil, entries in this list can only be removed. Finalizers may be * processed and removed in any order. Order is NOT enforced because it introduces significant * risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder * it. If the finalizer list is processed in order, then this can lead to a situation in which * the component responsible for the first finalizer in the list is waiting for a signal (field * value, external system, or other) produced by a component responsible for a finalizer later in * the list, resulting in a deadlock. Without enforced ordering finalizers are free to order * amongst themselves and are not vulnerable to ordering changes in the list. */ finalizers?: string[]; /** * GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the * Name field has not been provided. If this field is used, the name returned to the client will * be different than the name passed. This value will also be combined with a unique suffix. The * provided value has the same validation rules as the Name field, and may be truncated by the * length of the suffix required to make the value unique on the server. If this field is * specified and the generated name exists, the server will NOT return a 409 - instead, it will * either return 201 Created or 500 with Reason ServerTimeout indicating a unique name could not * be found in the time allotted, and the client should retry (optionally after the time indicated * in the Retry-After header). Applied only if Name is not specified. * * More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency */ generateName?: string; /** * A sequence number representing a specific generation of the desired state. Populated by the * system. */ readonly generation?: number; /** * Map of string keys and values that can be used to organize and categorize (scope and select) * objects. May match selectors of replication controllers and services. * * More info: http://kubernetes.io/docs/user-guide/labels */ labels?: Partial<Record<string, string>>; /** * ManagedFields maps workflow-id and version to the set of fields that are managed by that * workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set * or understand this field. A workflow can be the user's name, a controller's name, or the name * of a specific apply path like "ci-cd". The set of fields is always in the version that the * workflow used when modifying the object. */ managedFields?: unknown[]; /** * Name must be unique within a namespace. Is required when creating resources, although some * resources may allow a client to request the generation of an appropriate name automatically. * Name is primarily intended for creation idempotence and configuration definition. * * More info: http://kubernetes.io/docs/user-guide/identifiers#names */ readonly name: string; /** * Namespace defines the space within which each name must be unique. An empty namespace is * equivalent to the "default" namespace, but "default" is the canonical representation. Not all * objects are required to be scoped to a namespace - the value of this field for those objects * will be empty. Must be a DNS_LABEL. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/namespaces */ readonly namespace?: ScopedNamespace<Namespaced>; /** * List of objects depended by this object. If ALL objects in the list have been deleted, this * object will be garbage collected. If this object is managed by a controller, then an entry in * this list will point to this controller, with the controller field set to true. There cannot * be more than one managing controller. */ ownerReferences?: OwnerReference[]; /** * An opaque value that represents the internal version of this object that can be used by * clients to determine when objects have changed. May be used for optimistic concurrency, change * detection, and the watch operation on a resource or set of resources. Clients must treat these * values as opaque and passed unmodified back to the server. They may only be valid for a * particular resource or set of resources. Populated by the system. Value must be treated as * opaque by clients. * * More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency */ readonly resourceVersion?: string; /** * SelfLink is a URL representing this object. Populated by the system. */ readonly selfLink?: string; /** * UID is the unique in time and space value for this object. It is typically generated by the * server on successful creation of a resource and is not allowed to change on PUT operations. * Populated by the system. * * More info: http://kubernetes.io/docs/user-guide/identifiers#uids */ readonly uid?: string; [key: string]: unknown; } export type KubeJsonApiObjectMetadata<Namespaced extends KubeObjectScope = KubeObjectScope> = Namespaced extends KubeObjectScope.Namespace ? BaseKubeJsonApiObjectMetadata<KubeObjectScope.Namespace> & { readonly namespace: string } : BaseKubeJsonApiObjectMetadata<Namespaced>; export type KubeObjectMetadata<Namespaced extends KubeObjectScope = KubeObjectScope> = KubeJsonApiObjectMetadata<Namespaced> & { readonly selfLink: string; readonly uid: string; readonly name: string; readonly resourceVersion: string; }; export interface KubeStatusData { kind: string; apiVersion: string; code: number; message?: string; reason?: string; } export function isKubeStatusData(object: unknown): object is KubeStatusData { return isObject(object) && hasTypedProperty(object, "kind", isString) && hasTypedProperty(object, "apiVersion", isString) && hasTypedProperty(object, "code", isNumber) && hasOptionalTypedProperty(object, "message", isString) && hasOptionalTypedProperty(object, "reason", isString) && object.kind === "Status"; } export class KubeStatus { public readonly kind = "Status"; public readonly apiVersion: string; public readonly code: number; public readonly message: string; public readonly reason: string; constructor(data: KubeStatusData) { this.apiVersion = data.apiVersion; this.code = data.code; this.message = data.message || ""; this.reason = data.reason || ""; } } export interface BaseKubeObjectCondition { /** * Last time the condition transit from one status to another. * * @type Date */ lastTransitionTime?: string; /** * A human readable message indicating details about last transition. */ message?: string; /** * brief (usually one word) readon for the condition's last transition. */ reason?: string; /** * Status of the condition */ status: "True" | "False" | "Unknown"; /** * Type of the condition */ type: string; } export interface KubeObjectStatus { conditions?: BaseKubeObjectCondition[]; } export type KubeMetaField = keyof KubeJsonApiObjectMetadata; export class KubeCreationError extends Error { constructor(message: string, public data: any) { super(message); } } export type LabelMatchExpression = { /** * The label key that the selector applies to. */ key: string; } & ( { /** * This represents the key's relationship to a set of values. */ operator: "Exists" | "DoesNotExist"; values?: undefined; } | { operator: "In" | "NotIn"; /** * The set of values for to match according to the operator for the label. */ values: string[]; } ); export interface Toleration { key?: string; operator?: string; effect?: string; value?: string; tolerationSeconds?: number; } export interface ObjectReference { apiVersion?: string; fieldPath?: string; kind?: string; name: string; namespace?: string; resourceVersion?: string; uid?: string; } export interface LocalObjectReference { name: string; } export interface TypedLocalObjectReference { apiGroup?: string; kind: string; name: string; } export interface NodeAffinity { nodeSelectorTerms?: LabelSelector[]; weight: number; preference: LabelSelector; } export interface PodAffinity { labelSelector: LabelSelector; topologyKey: string; } export interface SpecificAffinity<T> { requiredDuringSchedulingIgnoredDuringExecution?: T[]; preferredDuringSchedulingIgnoredDuringExecution?: T[]; } export interface Affinity { nodeAffinity?: SpecificAffinity<NodeAffinity>; podAffinity?: SpecificAffinity<PodAffinity>; podAntiAffinity?: SpecificAffinity<PodAffinity>; } export interface LabelSelector { matchLabels?: Partial<Record<string, string>>; matchExpressions?: LabelMatchExpression[]; } export enum KubeObjectScope { Namespace, Cluster, } export type ScopedNamespace<Namespaced extends KubeObjectScope> = ( Namespaced extends KubeObjectScope.Namespace ? string : Namespaced extends KubeObjectScope.Cluster ? undefined : string | undefined ); export class KubeObject< Status = unknown, Spec = unknown, Namespaced extends KubeObjectScope = KubeObjectScope, > implements ItemObject { static readonly kind?: string; static readonly namespaced?: boolean; static readonly apiBase?: string; apiVersion!: string; kind!: string; metadata!: KubeObjectMetadata<Namespaced>; status?: Status; spec!: Spec; static create< Metadata extends KubeObjectMetadata = KubeObjectMetadata, Status = unknown, Spec = unknown, >(data: KubeJsonApiData<Metadata, Status, Spec>) { return new KubeObject(data); } static isNonSystem(item: KubeJsonApiData | KubeObject<unknown, unknown, KubeObjectScope>) { return !item.metadata.name?.startsWith("system:"); } static isJsonApiData(object: unknown): object is KubeJsonApiData { return ( isObject(object) && hasTypedProperty(object, "kind", isString) && hasTypedProperty(object, "apiVersion", isString) && hasTypedProperty(object, "metadata", KubeObject.isKubeJsonApiMetadata) ); } static isKubeJsonApiListMetadata(object: unknown): object is KubeJsonApiListMetadata { return ( isObject(object) && hasOptionalTypedProperty(object, "resourceVersion", isString) && hasOptionalTypedProperty(object, "selfLink", isString) ); } static isKubeJsonApiMetadata(object: unknown): object is KubeJsonApiObjectMetadata { return ( isObject(object) && hasTypedProperty(object, "uid", isString) && hasTypedProperty(object, "name", isString) && hasTypedProperty(object, "resourceVersion", isString) && hasOptionalTypedProperty(object, "selfLink", isString) && hasOptionalTypedProperty(object, "namespace", isString) && hasOptionalTypedProperty(object, "creationTimestamp", isString) && hasOptionalTypedProperty(object, "continue", isString) && hasOptionalTypedProperty(object, "finalizers", bindPredicate(isTypedArray, isString)) && hasOptionalTypedProperty(object, "labels", bindPredicate(isRecord, isString, isString)) && hasOptionalTypedProperty(object, "annotations", bindPredicate(isRecord, isString, isString)) ); } static isPartialJsonApiMetadata(object: unknown): object is Partial<KubeJsonApiObjectMetadata> { return ( isObject(object) && hasOptionalTypedProperty(object, "uid", isString) && hasOptionalTypedProperty(object, "name", isString) && hasOptionalTypedProperty(object, "resourceVersion", isString) && hasOptionalTypedProperty(object, "selfLink", isString) && hasOptionalTypedProperty(object, "namespace", isString) && hasOptionalTypedProperty(object, "creationTimestamp", isString) && hasOptionalTypedProperty(object, "continue", isString) && hasOptionalTypedProperty(object, "finalizers", bindPredicate(isTypedArray, isString)) && hasOptionalTypedProperty(object, "labels", bindPredicate(isRecord, isString, isString)) && hasOptionalTypedProperty(object, "annotations", bindPredicate(isRecord, isString, isString)) ); } static isPartialJsonApiData(object: unknown): object is Partial<KubeJsonApiData> { return ( isObject(object) && hasOptionalTypedProperty(object, "kind", isString) && hasOptionalTypedProperty(object, "apiVersion", isString) && hasOptionalTypedProperty(object, "metadata", KubeObject.isPartialJsonApiMetadata) ); } static isJsonApiDataList<T>(object: unknown, verifyItem: (val: unknown) => val is T): object is KubeJsonApiDataList<T> { return ( isObject(object) && hasTypedProperty(object, "kind", isString) && hasTypedProperty(object, "apiVersion", isString) && hasTypedProperty(object, "metadata", KubeObject.isKubeJsonApiListMetadata) && hasTypedProperty(object, "items", bindPredicate(isTypedArray, verifyItem)) ); } static stringifyLabels(labels?: Partial<Record<string, string>>): string[] { if (!labels) return []; return Object.entries(labels).map(([name, value]) => `${name}=${value}`); } /** * These must be RFC6902 compliant paths */ private static readonly nonEditablePathPrefixes = [ "/metadata/managedFields", "/status", ]; private static readonly nonEditablePaths = new Set([ "/apiVersion", "/kind", "/metadata/name", "/metadata/selfLink", "/metadata/resourceVersion", "/metadata/uid", ...KubeObject.nonEditablePathPrefixes, ]); constructor(data: KubeJsonApiData<KubeObjectMetadata<Namespaced>, Status, Spec>) { if (typeof data !== "object") { throw new TypeError(`Cannot create a KubeObject from ${typeof data}`); } if (!data.metadata || typeof data.metadata !== "object") { throw new KubeCreationError(`Cannot create a KubeObject from an object without metadata`, data); } Object.assign(this, data); autoBind(this); } get selfLink() { return this.metadata.selfLink; } getId() { return this.metadata.uid; } getResourceVersion() { return this.metadata.resourceVersion; } getScopedName() { const ns = this.getNs(); const res = ns ? `${ns}/` : ""; return res + this.getName(); } getName() { return this.metadata.name; } getNs(): ScopedNamespace<Namespaced> { // avoid "null" serialization via JSON.stringify when post data return (this.metadata.namespace || undefined) as never; } /** * This function computes the number of milliseconds from the UNIX EPOCH to the * creation timestamp of this object. */ getCreationTimestamp() { if (!this.metadata.creationTimestamp) { return Date.now(); } return new Date(this.metadata.creationTimestamp).getTime(); } /** * @deprecated This function computes a new "now" on every call which might cause subtle issues if called multiple times * * NOTE: Generally you can use `getCreationTimestamp` instead. */ getTimeDiffFromNow(): number { if (!this.metadata.creationTimestamp) { return 0; } return Date.now() - new Date(this.metadata.creationTimestamp).getTime(); } /** * @deprecated This function computes a new "now" on every call might cause subtle issues if called multiple times * * NOTE: this function also is not reactive to updates in the current time so it should not be used for renderering */ getAge(humanize = true, compact = true, fromNow = false): string | number { if (fromNow) { return moment(this.metadata.creationTimestamp).fromNow(); // "string", getTimeDiffFromNow() cannot be used } const diff = this.getTimeDiffFromNow(); if (humanize) { return formatDuration(diff, compact); } return diff; } getFinalizers(): string[] { return this.metadata.finalizers || []; } getLabels(): string[] { return KubeObject.stringifyLabels(this.metadata.labels); } getAnnotations(filter = false): string[] { const labels = KubeObject.stringifyLabels(this.metadata.annotations); return filter ? labels.filter(label => { const skip = resourceApplierApi.annotations.some(key => label.startsWith(key)); return !skip; }) : labels; } getOwnerRefs() { const refs = this.metadata.ownerReferences || []; const namespace = this.getNs(); return refs.map(ownerRef => ({ ...ownerRef, namespace })); } getSearchFields() { const { getName, getId, getNs, getAnnotations, getLabels } = this; return [ getName(), getNs(), getId(), ...getLabels(), ...getAnnotations(true), ]; } toPlainObject() { return json.parse(JSON.stringify(this)) as JsonObject; } /** * @deprecated use KubeApi.patch instead */ async patch(patch: Patch): Promise<KubeJsonApiData | null> { for (const op of patch) { if (KubeObject.nonEditablePaths.has(op.path)) { throw new Error(`Failed to update ${this.kind}: JSON pointer ${op.path} has been modified`); } for (const pathPrefix of KubeObject.nonEditablePathPrefixes) { if (op.path.startsWith(`${pathPrefix}/`)) { throw new Error(`Failed to update ${this.kind}: Child JSON pointer of ${op.path} has been modified`); } } } return resourceApplierApi.patch(this.getName(), this.kind, this.getNs(), patch); } /** * Perform a full update (or more specifically a replace) * * Note: this is brittle if `data` is not actually partial (but instead whole). * As fields such as `resourceVersion` will probably out of date. This is a * common race condition. * * @deprecated use KubeApi.update instead */ async update(data: Partial<this>): Promise<KubeJsonApiData | null> { // use unified resource-applier api for updating all k8s objects return resourceApplierApi.update({ ...this.toPlainObject(), ...data, }); } /** * @deprecated use KubeApi.delete instead */ delete(params?: object) { assert(this.selfLink, "selfLink must be present to delete self"); return apiKube.del(this.selfLink, params); } }
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the ManagedServiceIdentityClient. */ export interface Operations { /** * Lists available operations for the Microsoft.ManagedIdentity provider * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists available operations for the Microsoft.ManagedIdentity provider * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; list(callback: ServiceCallback<models.OperationListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; /** * Lists available operations for the Microsoft.ManagedIdentity provider * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists available operations for the Microsoft.ManagedIdentity provider * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; } /** * @class * UserAssignedIdentities * __NOTE__: An instance of this class is automatically created for an * instance of the ManagedServiceIdentityClient. */ export interface UserAssignedIdentities { /** * Lists all the userAssignedIdentities available under the specified * subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UserAssignedIdentitiesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UserAssignedIdentitiesListResult>>; /** * Lists all the userAssignedIdentities available under the specified * subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UserAssignedIdentitiesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UserAssignedIdentitiesListResult} [result] - The deserialized result object if an error did not occur. * See {@link UserAssignedIdentitiesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscription(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UserAssignedIdentitiesListResult>; listBySubscription(callback: ServiceCallback<models.UserAssignedIdentitiesListResult>): void; listBySubscription(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UserAssignedIdentitiesListResult>): void; /** * Lists all the userAssignedIdentities available under the specified * ResourceGroup. * * @param {string} resourceGroupName The name of the Resource Group to which * the identity belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UserAssignedIdentitiesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UserAssignedIdentitiesListResult>>; /** * Lists all the userAssignedIdentities available under the specified * ResourceGroup. * * @param {string} resourceGroupName The name of the Resource Group to which * the identity belongs. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UserAssignedIdentitiesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UserAssignedIdentitiesListResult} [result] - The deserialized result object if an error did not occur. * See {@link UserAssignedIdentitiesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UserAssignedIdentitiesListResult>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.UserAssignedIdentitiesListResult>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UserAssignedIdentitiesListResult>): void; /** * Create or update an identity in the specified subscription and resource * group. * * @param {string} resourceGroupName The name of the Resource Group to which * the identity belongs. * * @param {string} resourceName The name of the identity resource. * * @param {object} parameters Parameters to create or update the identity * * @param {string} [parameters.location] The Azure region where the identity * lives. * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Identity>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, parameters: models.Identity, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Identity>>; /** * Create or update an identity in the specified subscription and resource * group. * * @param {string} resourceGroupName The name of the Resource Group to which * the identity belongs. * * @param {string} resourceName The name of the identity resource. * * @param {object} parameters Parameters to create or update the identity * * @param {string} [parameters.location] The Azure region where the identity * lives. * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Identity} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Identity} [result] - The deserialized result object if an error did not occur. * See {@link Identity} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, resourceName: string, parameters: models.Identity, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Identity>; createOrUpdate(resourceGroupName: string, resourceName: string, parameters: models.Identity, callback: ServiceCallback<models.Identity>): void; createOrUpdate(resourceGroupName: string, resourceName: string, parameters: models.Identity, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Identity>): void; /** * Update an identity in the specified subscription and resource group. * * @param {string} resourceGroupName The name of the Resource Group to which * the identity belongs. * * @param {string} resourceName The name of the identity resource. * * @param {object} parameters Parameters to update the identity * * @param {string} [parameters.location] The Azure region where the identity * lives. * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Identity>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, resourceName: string, parameters: models.Identity, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Identity>>; /** * Update an identity in the specified subscription and resource group. * * @param {string} resourceGroupName The name of the Resource Group to which * the identity belongs. * * @param {string} resourceName The name of the identity resource. * * @param {object} parameters Parameters to update the identity * * @param {string} [parameters.location] The Azure region where the identity * lives. * * @param {object} [parameters.tags] Resource tags * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Identity} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Identity} [result] - The deserialized result object if an error did not occur. * See {@link Identity} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, resourceName: string, parameters: models.Identity, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Identity>; update(resourceGroupName: string, resourceName: string, parameters: models.Identity, callback: ServiceCallback<models.Identity>): void; update(resourceGroupName: string, resourceName: string, parameters: models.Identity, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Identity>): void; /** * Gets the identity. * * @param {string} resourceGroupName The name of the Resource Group to which * the identity belongs. * * @param {string} resourceName The name of the identity resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Identity>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Identity>>; /** * Gets the identity. * * @param {string} resourceGroupName The name of the Resource Group to which * the identity belongs. * * @param {string} resourceName The name of the identity resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Identity} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Identity} [result] - The deserialized result object if an error did not occur. * See {@link Identity} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Identity>; get(resourceGroupName: string, resourceName: string, callback: ServiceCallback<models.Identity>): void; get(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Identity>): void; /** * Deletes the identity. * * @param {string} resourceGroupName The name of the Resource Group to which * the identity belongs. * * @param {string} resourceName The name of the identity resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the identity. * * @param {string} resourceGroupName The name of the Resource Group to which * the identity belongs. * * @param {string} resourceName The name of the identity resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, resourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, resourceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, resourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists all the userAssignedIdentities available under the specified * subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UserAssignedIdentitiesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UserAssignedIdentitiesListResult>>; /** * Lists all the userAssignedIdentities available under the specified * subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UserAssignedIdentitiesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UserAssignedIdentitiesListResult} [result] - The deserialized result object if an error did not occur. * See {@link UserAssignedIdentitiesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscriptionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UserAssignedIdentitiesListResult>; listBySubscriptionNext(nextPageLink: string, callback: ServiceCallback<models.UserAssignedIdentitiesListResult>): void; listBySubscriptionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UserAssignedIdentitiesListResult>): void; /** * Lists all the userAssignedIdentities available under the specified * ResourceGroup. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UserAssignedIdentitiesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UserAssignedIdentitiesListResult>>; /** * Lists all the userAssignedIdentities available under the specified * ResourceGroup. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UserAssignedIdentitiesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UserAssignedIdentitiesListResult} [result] - The deserialized result object if an error did not occur. * See {@link UserAssignedIdentitiesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UserAssignedIdentitiesListResult>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.UserAssignedIdentitiesListResult>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UserAssignedIdentitiesListResult>): void; }
the_stack
import * as ABIDecoder from "abi-decoder"; import * as compact from "lodash.compact"; import * as moment from "moment"; import * as Web3 from "web3"; import { BigNumber } from "../../../utils/bignumber"; // Wrappers import { DebtKernelContract, DebtOrderDataWrapper, DummyTokenContract, RepaymentRouterContract, SimpleInterestTermsContractContract, TokenRegistryContract, TokenTransferProxyContract, } from "../../../src/wrappers"; // APIs import { AdaptersAPI, ContractsAPI, OrderAPI, SignerAPI } from "../../../src/apis"; // Scenarios import { FillScenario, IssuanceCancellationScenario, OrderCancellationScenario, OrderGenerationScenario, UnpackTermsScenario, } from "./scenarios/"; // Types import { Adapter } from "../../../src/adapters"; import { DebtOrderData } from "../../../src/types"; // Utils import { CollateralizedSimpleInterestLoanOrder } from "../../../src/adapters/collateralized_simple_interest_loan_adapter"; import { SimpleInterestLoanOrder } from "../../../src/adapters/simple_interest_loan_adapter"; import * as Units from "../../../utils/units"; import { Web3Utils } from "../../../utils/web3_utils"; import { ACCOUNTS } from "../../accounts"; const TX_DEFAULTS = { from: ACCOUNTS[0].address, gas: 4712388 }; export class OrderScenarioRunner { public web3Utils: Web3Utils; public debtKernel: DebtKernelContract; public repaymentRouter: RepaymentRouterContract; public tokenTransferProxy: TokenTransferProxyContract; public principalToken: DummyTokenContract; public termsContract: SimpleInterestTermsContractContract; public orderApi: OrderAPI; public contractsApi: ContractsAPI; public orderSigner: SignerAPI; public adaptersApi: AdaptersAPI; private currentSnapshotId: number; private readonly web3: Web3; constructor(web3: Web3) { this.web3Utils = new Web3Utils(web3); this.web3 = web3; this.testCheckOrderFilledScenario = this.testCheckOrderFilledScenario.bind(this); this.testFillScenario = this.testFillScenario.bind(this); this.testAssertFillable = this.testAssertFillable.bind(this); this.testAssertReadyToFill = this.testAssertReadyToFill.bind(this); this.testOrderCancelScenario = this.testOrderCancelScenario.bind(this); this.testIssuanceCancelScenario = this.testIssuanceCancelScenario.bind(this); this.testOrderGenerationScenario = this.testOrderGenerationScenario.bind(this); this.testUnpackTermsScenario = this.testUnpackTermsScenario.bind(this); this.saveSnapshotAsync = this.saveSnapshotAsync.bind(this); this.revertToSavedSnapshot = this.revertToSavedSnapshot.bind(this); } public testCheckOrderFilledScenario(scenario: FillScenario) { describe(scenario.description, () => { let debtOrderData: DebtOrderData; beforeAll(() => { ABIDecoder.addABI(this.debtKernel.abi); }); afterAll(() => { ABIDecoder.removeABI(this.debtKernel.abi); }); beforeEach(async () => { debtOrderData = await this.setUpFillScenario(scenario); }); test("returns false if order has not been filled", async () => { expect(await this.orderApi.checkOrderFilledAsync(debtOrderData)).toEqual(false); }); test("returns true if order has been filled", async () => { await this.orderApi.fillAsync(debtOrderData, { from: scenario.filler, }); expect(await this.orderApi.checkOrderFilledAsync(debtOrderData)).toEqual(true); }); describe("when validating the loan order", () => { const validateMock = jest.fn(); let originalValidate: ( loanOrder: SimpleInterestLoanOrder | CollateralizedSimpleInterestLoanOrder, ) => void; let adapter: Adapter; beforeAll(async () => { adapter = await this.adaptersApi.getAdapterByTermsContractAddress( debtOrderData.termsContract, ); originalValidate = adapter.validateAsync; // Mock the validate function, to count the number of times it was called, // and to spy on the given arguments. adapter.validateAsync = validateMock; }); afterAll(() => { // Replace the adapter's validate function. adapter.validateAsync = validateMock; }); test("it calls validate on the appropriate adapter once", async () => { await this.orderApi.fillAsync(debtOrderData, { from: scenario.filler, }); expect(validateMock).toHaveBeenCalledTimes(1); }); test("it calls validate with a loan order adapted from the debt order", async () => { const loanOrder = await adapter.fromDebtOrder(debtOrderData); await this.orderApi.fillAsync(debtOrderData, { from: scenario.filler, }); // Assert the expected input, which is a loan order. expect(validateMock).toHaveBeenCalledWith(loanOrder); }); }); }); } public testAssertReadyToFill(scenario: FillScenario) { describe(scenario.description, () => { let debtOrderData: DebtOrderData; beforeEach(async () => { debtOrderData = await this.setUpFillScenario(scenario); }); if (scenario.successfullyFills) { test("does not throw", async () => { await expect( this.orderApi.assertReadyToFill(debtOrderData, { from: scenario.filler, }), ).resolves.not.toThrow(); }); } else { test(`throws ${scenario.errorType} error`, async () => { await expect( this.orderApi.assertReadyToFill(debtOrderData, { from: scenario.filler }), ).rejects.toThrow(scenario.errorMessage); }); } }); } public testAssertFillable(scenario: FillScenario) { describe(scenario.description, () => { let debtOrderData: DebtOrderData; beforeAll(() => { ABIDecoder.addABI(this.debtKernel.abi); }); afterAll(() => { ABIDecoder.removeABI(this.debtKernel.abi); }); beforeEach(async () => { debtOrderData = await this.setUpFillScenario(scenario); }); if (scenario.successfullyFills) { test("does not throw", async () => { await expect( this.orderApi.assertFillableAsync(debtOrderData, { from: scenario.filler, }), ).resolves.not.toThrow(); }); } else { test(`throws ${scenario.errorType} error`, async () => { await expect( this.orderApi.assertFillableAsync(debtOrderData, { from: scenario.filler }), ).rejects.toThrow(scenario.errorMessage); }); } }); } public testFillScenario(scenario: FillScenario) { describe(scenario.description, () => { let debtOrderData: DebtOrderData; beforeAll(() => { ABIDecoder.addABI(this.debtKernel.abi); }); afterAll(() => { ABIDecoder.removeABI(this.debtKernel.abi); }); beforeEach(async () => { debtOrderData = await this.setUpFillScenario(scenario); }); if (scenario.successfullyFills) { test("emits log indicating successful fill", async () => { const txHash = await this.orderApi.fillAsync(debtOrderData, { from: scenario.filler, }); const receipt = await this.web3Utils.getTransactionReceiptAsync(txHash); const [debtOrderFilledLog] = compact(ABIDecoder.decodeLogs(receipt.logs)); expect(debtOrderFilledLog.name).toBe("LogDebtOrderFilled"); }); } else { test(`throws ${scenario.errorType} error`, async () => { await expect( this.orderApi.fillAsync(debtOrderData, { from: scenario.filler }), ).rejects.toThrow(scenario.errorMessage); }); } }); } public async testOrderCancelScenario(scenario: OrderCancellationScenario) { describe(scenario.description, () => { let debtOrderData: DebtOrderData; beforeAll(() => { ABIDecoder.addABI(this.debtKernel.abi); }); afterAll(() => { ABIDecoder.removeABI(this.debtKernel.abi); }); beforeEach(async () => { debtOrderData = scenario.generateDebtOrderData( this.debtKernel, this.repaymentRouter, this.principalToken, ); if (scenario.orderAlreadyCancelled) { await this.orderApi.cancelOrderAsync(debtOrderData, { from: debtOrderData.debtor, }); } if (scenario.issuanceAlreadyCancelled) { const debtOrderDataWrapped = new DebtOrderDataWrapper(debtOrderData); await this.orderApi.cancelIssuanceAsync( debtOrderDataWrapped.getIssuanceCommitment(), { from: debtOrderData.debtor }, ); } }); if (scenario.successfullyCancels) { test("emits log indicating successful fill", async () => { const txHash = await this.orderApi.cancelOrderAsync(debtOrderData, { from: scenario.canceller, }); const receipt = await this.web3Utils.getTransactionReceiptAsync(txHash); const [debtOrderCancelledLog] = compact(ABIDecoder.decodeLogs(receipt.logs)); expect(debtOrderCancelledLog.name).toBe("LogDebtOrderCancelled"); }); test("isCancelled returns false before cancel", async () => { const isCancelled = await this.orderApi.isCancelled(debtOrderData); expect(isCancelled).toEqual(false); }); test("isCancelled returns true after cancel", async () => { await this.orderApi.cancelOrderAsync(debtOrderData, { from: scenario.canceller, }); const isCancelled = await this.orderApi.isCancelled(debtOrderData); expect(isCancelled).toEqual(true); }); } else { test(`throws ${scenario.errorType} error`, async () => { await expect( this.orderApi.cancelOrderAsync(debtOrderData, { from: scenario.canceller }), ).rejects.toThrow(scenario.errorMessage); }); } }); } public async testIssuanceCancelScenario(scenario: IssuanceCancellationScenario) { describe(scenario.description, () => { let debtOrderData: DebtOrderData; beforeAll(() => { ABIDecoder.addABI(this.debtKernel.abi); }); afterAll(() => { ABIDecoder.removeABI(this.debtKernel.abi); }); beforeEach(async () => { debtOrderData = scenario.generateDebtOrderData( this.debtKernel, this.repaymentRouter, this.principalToken, ); if (scenario.orderAlreadyCancelled) { await this.orderApi.cancelOrderAsync(debtOrderData, { from: debtOrderData.debtor, }); } if (scenario.issuanceAlreadyCancelled) { const debtOrderDataWrapped = new DebtOrderDataWrapper(debtOrderData); await this.orderApi.cancelIssuanceAsync( debtOrderDataWrapped.getIssuanceCommitment(), { from: debtOrderData.debtor }, ); } }); if (scenario.successfullyCancels) { test("emits log indicating successful fill", async () => { const debtOrderDataWrapped = new DebtOrderDataWrapper(debtOrderData); const txHash = await this.orderApi.cancelIssuanceAsync( debtOrderDataWrapped.getIssuanceCommitment(), { from: scenario.canceller }, ); const receipt = await this.web3Utils.getTransactionReceiptAsync(txHash); const [debtIssuanceCancelledLog] = compact(ABIDecoder.decodeLogs(receipt.logs)); expect(debtIssuanceCancelledLog.name).toBe("LogIssuanceCancelled"); }); } else { test(`throws ${scenario.errorType} error`, async () => { const debtOrderDataWrapped = new DebtOrderDataWrapper(debtOrderData); await expect( this.orderApi.cancelIssuanceAsync( debtOrderDataWrapped.getIssuanceCommitment(), { from: scenario.canceller }, ), ).rejects.toThrow(scenario.errorMessage); }); } }); } public testOrderGenerationScenario(scenario: OrderGenerationScenario) { describe(scenario.description, () => { let adapter: Adapter; beforeEach(() => { adapter = scenario.adapter(this.adaptersApi); }); if (!scenario.throws) { test("returns order translated by adapter from input parameters", async () => { const expectedDebtOrderData = await adapter.toDebtOrder( scenario.inputParameters, ); await expect( this.orderApi.generate(adapter, scenario.inputParameters), ).resolves.toEqual(expectedDebtOrderData); }); } else { test(`should throw ${scenario.errorType}`, async () => { await expect( this.orderApi.generate(adapter, scenario.inputParameters), ).rejects.toThrow(scenario.errorMessage); }); } }); } public testUnpackTermsScenario(scenario: UnpackTermsScenario) { describe(scenario.description, () => { let debtOrderData: DebtOrderData; beforeEach(async () => { const simpleInterestTermsContract = this.termsContract; const collateralizedSimpleInterestTermsContract = await this.contractsApi.loadCollateralizedSimpleInterestTermsContract(); const otherTermsContractAddress = ACCOUNTS[4].address; debtOrderData = { kernelVersion: this.debtKernel.address, issuanceVersion: this.repaymentRouter.address, principalAmount: Units.ether(1), principalToken: this.principalToken.address, debtor: ACCOUNTS[1].address, debtorFee: Units.ether(0.001), creditor: ACCOUNTS[2].address, creditorFee: Units.ether(0.001), relayer: ACCOUNTS[3].address, relayerFee: Units.ether(0.002), termsContract: scenario.termsContract( simpleInterestTermsContract.address, collateralizedSimpleInterestTermsContract.address, otherTermsContractAddress, ), termsContractParameters: scenario.termsContractParameters, expirationTimestampInSec: new BigNumber( moment() .add(7, "days") .unix(), ), salt: new BigNumber(0), }; }); if (!scenario.throws) { test("returns correctly unpacked parameters", async () => { await expect(this.orderApi.unpackTerms(debtOrderData)).resolves.toEqual( scenario.expectedParameters, ); }); } else { test(`throws ${scenario.errorType}`, async () => { await expect(this.orderApi.unpackTerms(debtOrderData)).rejects.toThrow( scenario.errorMessage, ); }); } }); } public async saveSnapshotAsync() { this.currentSnapshotId = await this.web3Utils.saveTestSnapshot(); } public async revertToSavedSnapshot() { await this.web3Utils.revertToSnapshot(this.currentSnapshotId); } private async setUpFillScenario(scenario: FillScenario): Promise<DebtOrderData> { let debtOrderData; if (scenario.isCollateralized) { const collateralizedTC = await this.contractsApi.loadCollateralizedSimpleInterestTermsContract(); debtOrderData = scenario.generateDebtOrderData( this.debtKernel, this.repaymentRouter, this.principalToken, collateralizedTC, ); /* Set up balances and allowances for collateral. */ const dummyTokenRegistry = await TokenRegistryContract.deployed(this.web3, TX_DEFAULTS); const collateralTokenAddress = await dummyTokenRegistry.getTokenAddressByIndex.callAsync( scenario.collateralTokenIndex, ); const collateralToken = await DummyTokenContract.at( collateralTokenAddress, this.web3, TX_DEFAULTS, ); await collateralToken.setBalance.sendTransactionAsync( debtOrderData.debtor, new BigNumber(scenario.collateralBalance), ); await collateralToken.approve.sendTransactionAsync( this.tokenTransferProxy.address, new BigNumber(scenario.collateralAllowance), { from: debtOrderData.debtor }, ); } else { debtOrderData = scenario.generateDebtOrderData( this.debtKernel, this.repaymentRouter, this.principalToken, this.termsContract, ); } // We dynamically set the creditor's balance and // allowance of a given principal token to either // their assigned values in the fill scenario, or // to a default amount (i.e sufficient balance / allowance // necessary for order fill) const creditorBalance = scenario.creditorBalance || debtOrderData.principalAmount.times(2); const creditorAllowance = scenario.creditorAllowance || debtOrderData.principalAmount.times(2); await this.principalToken.setBalance.sendTransactionAsync( debtOrderData.creditor, creditorBalance, ); await this.principalToken.approve.sendTransactionAsync( this.tokenTransferProxy.address, creditorAllowance, { from: debtOrderData.creditor }, ); // We dynamically attach signatures based on whether the // the scenario specifies that a signature from a signatory // ought to be attached. debtOrderData.debtorSignature = scenario.signatories.debtor ? await this.orderSigner.asDebtor(debtOrderData, false) : null; debtOrderData.creditorSignature = scenario.signatories.creditor ? await this.orderSigner.asCreditor(debtOrderData, false) : null; debtOrderData.underwriterSignature = scenario.signatories.underwriter ? await this.orderSigner.asUnderwriter(debtOrderData, false) : null; if (scenario.beforeBlock) { await scenario.beforeBlock(debtOrderData, this.debtKernel); } return debtOrderData; } }
the_stack
import { App as AppCore } from './core'; import { AppStore, defaultAppStore } from './lifecycle'; import { app, appCheck, auth, messaging, machineLearning, storage, firestore, database, instanceId, installations, projectManagement, securityRules , remoteConfig, AppOptions, } from '../firebase-namespace-api'; import { cert, refreshToken, applicationDefault } from './credential-factory'; import { getSdkVersion } from '../utils/index'; import App = app.App; import AppCheck = appCheck.AppCheck; import Auth = auth.Auth; import Database = database.Database; import Firestore = firestore.Firestore; import Installations = installations.Installations; import InstanceId = instanceId.InstanceId; import MachineLearning = machineLearning.MachineLearning; import Messaging = messaging.Messaging; import ProjectManagement = projectManagement.ProjectManagement; import RemoteConfig = remoteConfig.RemoteConfig; import SecurityRules = securityRules.SecurityRules; import Storage = storage.Storage; export interface FirebaseServiceNamespace <T> { (app?: App): T; [key: string]: any; } /** * Internals of a FirebaseNamespace instance. */ export class FirebaseNamespaceInternals { constructor(private readonly appStore: AppStore) {} /** * Initializes the App instance. * * @param options - Optional options for the App instance. If none present will try to initialize * from the FIREBASE_CONFIG environment variable. If the environment variable contains a string * that starts with '{' it will be parsed as JSON, otherwise it will be assumed to be pointing * to a file. * @param appName - Optional name of the FirebaseApp instance. * * @returns A new App instance. */ public initializeApp(options?: AppOptions, appName?: string): App { const app = this.appStore.initializeApp(options, appName); return extendApp(app); } /** * Returns the App instance with the provided name (or the default App instance * if no name is provided). * * @param appName - Optional name of the FirebaseApp instance to return. * @returns The App instance which has the provided name. */ public app(appName?: string): App { const app = this.appStore.getApp(appName); return extendApp(app); } /* * Returns an array of all the non-deleted App instances. */ public get apps(): App[] { return this.appStore.getApps().map((app) => extendApp(app)); } } const firebaseCredential = { cert, refreshToken, applicationDefault }; /** * Global Firebase context object. */ export class FirebaseNamespace { // Hack to prevent Babel from modifying the object returned as the default admin namespace. /* tslint:disable:variable-name */ public __esModule = true; /* tslint:enable:variable-name */ public credential = firebaseCredential; public SDK_VERSION = getSdkVersion(); public INTERNAL: FirebaseNamespaceInternals; /* tslint:disable */ // TODO(jwenger): Database is the only consumer of firebase.Promise. We should update it to use // use the native Promise and then remove this. public Promise: any = Promise; /* tslint:enable */ constructor(appStore?: AppStore) { this.INTERNAL = new FirebaseNamespaceInternals(appStore ?? new AppStore()); } /** * Gets the `Auth` service namespace. The returned namespace can be used to get the * `Auth` service for the default app or an explicitly specified app. */ get auth(): FirebaseServiceNamespace<Auth> { const fn: FirebaseServiceNamespace<Auth> = (app?: App) => { return this.ensureApp(app).auth(); }; const auth = require('../auth/auth').Auth; return Object.assign(fn, { Auth: auth }); } /** * Gets the `Database` service namespace. The returned namespace can be used to get the * `Database` service for the default app or an explicitly specified app. */ get database(): FirebaseServiceNamespace<Database> { const fn: FirebaseServiceNamespace<Database> = (app?: App) => { return this.ensureApp(app).database(); }; // eslint-disable-next-line @typescript-eslint/no-var-requires return Object.assign(fn, require('@firebase/database-compat/standalone')); } /** * Gets the `Messaging` service namespace. The returned namespace can be used to get the * `Messaging` service for the default app or an explicitly specified app. */ get messaging(): FirebaseServiceNamespace<Messaging> { const fn: FirebaseServiceNamespace<Messaging> = (app?: App) => { return this.ensureApp(app).messaging(); }; const messaging = require('../messaging/messaging').Messaging; return Object.assign(fn, { Messaging: messaging }); } /** * Gets the `Storage` service namespace. The returned namespace can be used to get the * `Storage` service for the default app or an explicitly specified app. */ get storage(): FirebaseServiceNamespace<Storage> { const fn: FirebaseServiceNamespace<Storage> = (app?: App) => { return this.ensureApp(app).storage(); }; const storage = require('../storage/storage').Storage; return Object.assign(fn, { Storage: storage }); } /** * Gets the `Firestore` service namespace. The returned namespace can be used to get the * `Firestore` service for the default app or an explicitly specified app. */ get firestore(): FirebaseServiceNamespace<Firestore> { let fn: FirebaseServiceNamespace<Firestore> = (app?: App) => { return this.ensureApp(app).firestore(); }; // eslint-disable-next-line @typescript-eslint/no-var-requires const firestore = require('@google-cloud/firestore'); fn = Object.assign(fn, firestore.Firestore); // `v1beta1` and `v1` are lazy-loaded in the Firestore SDK. We use the same trick here // to avoid triggering this lazy-loading upon initialization. Object.defineProperty(fn, 'v1beta1', { get: () => { return firestore.v1beta1; }, }); Object.defineProperty(fn, 'v1', { get: () => { return firestore.v1; }, }); return fn; } /** * Gets the `MachineLearning` service namespace. The returned namespace can be * used to get the `MachineLearning` service for the default app or an * explicityly specified app. */ get machineLearning(): FirebaseServiceNamespace<MachineLearning> { const fn: FirebaseServiceNamespace<MachineLearning> = (app?: App) => { return this.ensureApp(app).machineLearning(); }; const machineLearning = require('../machine-learning/machine-learning').MachineLearning; return Object.assign(fn, { MachineLearning: machineLearning }); } /** * Gets the `Installations` service namespace. The returned namespace can be used to get the * `Installations` service for the default app or an explicitly specified app. */ get installations(): FirebaseServiceNamespace<Installations> { const fn: FirebaseServiceNamespace<Installations> = (app?: App) => { return this.ensureApp(app).installations(); }; const installations = require('../installations/installations').Installations; return Object.assign(fn, { Installations: installations }); } /** * Gets the `InstanceId` service namespace. The returned namespace can be used to get the * `Instance` service for the default app or an explicitly specified app. */ get instanceId(): FirebaseServiceNamespace<InstanceId> { const fn: FirebaseServiceNamespace<InstanceId> = (app?: App) => { return this.ensureApp(app).instanceId(); }; const instanceId = require('../instance-id/instance-id').InstanceId; return Object.assign(fn, { InstanceId: instanceId }); } /** * Gets the `ProjectManagement` service namespace. The returned namespace can be used to get the * `ProjectManagement` service for the default app or an explicitly specified app. */ get projectManagement(): FirebaseServiceNamespace<ProjectManagement> { const fn: FirebaseServiceNamespace<ProjectManagement> = (app?: App) => { return this.ensureApp(app).projectManagement(); }; const projectManagement = require('../project-management/project-management').ProjectManagement; return Object.assign(fn, { ProjectManagement: projectManagement }); } /** * Gets the `SecurityRules` service namespace. The returned namespace can be used to get the * `SecurityRules` service for the default app or an explicitly specified app. */ get securityRules(): FirebaseServiceNamespace<SecurityRules> { const fn: FirebaseServiceNamespace<SecurityRules> = (app?: App) => { return this.ensureApp(app).securityRules(); }; const securityRules = require('../security-rules/security-rules').SecurityRules; return Object.assign(fn, { SecurityRules: securityRules }); } /** * Gets the `RemoteConfig` service namespace. The returned namespace can be used to get the * `RemoteConfig` service for the default app or an explicitly specified app. */ get remoteConfig(): FirebaseServiceNamespace<RemoteConfig> { const fn: FirebaseServiceNamespace<RemoteConfig> = (app?: App) => { return this.ensureApp(app).remoteConfig(); }; const remoteConfig = require('../remote-config/remote-config').RemoteConfig; return Object.assign(fn, { RemoteConfig: remoteConfig }); } /** * Gets the `AppCheck` service namespace. The returned namespace can be used to get the * `AppCheck` service for the default app or an explicitly specified app. */ get appCheck(): FirebaseServiceNamespace<AppCheck> { const fn: FirebaseServiceNamespace<AppCheck> = (app?: App) => { return this.ensureApp(app).appCheck(); }; const appCheck = require('../app-check/app-check').AppCheck; return Object.assign(fn, { AppCheck: appCheck }); } // TODO: Change the return types to app.App in the following methods. /** * Initializes the FirebaseApp instance. * * @param options - Optional options for the FirebaseApp instance. * If none present will try to initialize from the FIREBASE_CONFIG environment variable. * If the environment variable contains a string that starts with '{' it will be parsed as JSON, * otherwise it will be assumed to be pointing to a file. * @param appName - Optional name of the FirebaseApp instance. * * @returns A new FirebaseApp instance. */ public initializeApp(options?: AppOptions, appName?: string): App { return this.INTERNAL.initializeApp(options, appName); } /** * Returns the FirebaseApp instance with the provided name (or the default FirebaseApp instance * if no name is provided). * * @param appName - Optional name of the FirebaseApp instance to return. * @returns The FirebaseApp instance which has the provided name. */ public app(appName?: string): App { return this.INTERNAL.app(appName); } /* * Returns an array of all the non-deleted FirebaseApp instances. */ public get apps(): App[] { return this.INTERNAL.apps; } private ensureApp(app?: App): App { if (typeof app === 'undefined') { app = this.app(); } return app; } } /** * In order to maintain backward compatibility, we instantiate a default namespace instance in * this module, and delegate all app lifecycle operations to it. In a future implementation where * the old admin namespace is no longer supported, we should remove this. * * @internal */ export const defaultNamespace = new FirebaseNamespace(defaultAppStore); function extendApp(app: AppCore): App { const result: App = app as App; if ((result as any).__extended) { return result; } result.auth = () => { const fn = require('../auth/index').getAuth; return fn(app); }; result.appCheck = () => { const fn = require('../app-check/index').getAppCheck; return fn(app); }; result.database = (url?: string) => { const fn = require('../database/index').getDatabaseWithUrl; return fn(url, app); }; result.messaging = () => { const fn = require('../messaging/index').getMessaging; return fn(app); }; result.storage = () => { const fn = require('../storage/index').getStorage; return fn(app); }; result.firestore = () => { const fn = require('../firestore/index').getFirestore; return fn(app); }; result.instanceId = () => { const fn = require('../instance-id/index').getInstanceId; return fn(app); } result.installations = () => { const fn = require('../installations/index').getInstallations; return fn(app); }; result.machineLearning = () => { const fn = require('../machine-learning/index').getMachineLearning; return fn(app); } result.projectManagement = () => { const fn = require('../project-management/index').getProjectManagement; return fn(app); }; result.securityRules = () => { const fn = require('../security-rules/index').getSecurityRules; return fn(app); }; result.remoteConfig = () => { const fn = require('../remote-config/index').getRemoteConfig; return fn(app); }; (result as any).__extended = true; return result; }
the_stack
import * as fc from '../../../../lib/fast-check'; import { floatNext, FloatNextConstraints } from '../../../../src/arbitrary/_next/floatNext'; import { floatNextConstraints, float32raw, isNotNaN32bits, float64raw, isStrictlySmaller, defaultFloatRecordConstraints, is32bits, } from '../__test-helpers__/FloatingPointHelpers'; import { floatToIndex, indexToFloat, MAX_VALUE_32 } from '../../../../src/arbitrary/_internals/helpers/FloatHelpers'; import { convertFromNextWithShrunkOnce, convertToNext } from '../../../../src/check/arbitrary/definition/Converters'; import { fakeNextArbitrary, fakeNextArbitraryStaticValue } from '../__test-helpers__/NextArbitraryHelpers'; import { fakeRandom } from '../__test-helpers__/RandomHelpers'; import { assertProduceCorrectValues, assertShrinkProducesStrictlySmallerValue, assertProduceSameValueGivenSameSeed, assertProduceValuesShrinkableWithoutContext, assertShrinkProducesSameValueWithoutInitialContext, } from '../__test-helpers__/NextArbitraryAssertions'; import * as IntegerMock from '../../../../src/arbitrary/integer'; function beforeEachHook() { jest.resetModules(); jest.restoreAllMocks(); } beforeEach(beforeEachHook); fc.configureGlobal({ ...fc.readConfigureGlobal(), beforeEach: beforeEachHook, }); function minMaxForConstraints(ct: FloatNextConstraints) { const noDefaultInfinity = ct.noDefaultInfinity; const { min = noDefaultInfinity ? -MAX_VALUE_32 : Number.NEGATIVE_INFINITY, max = noDefaultInfinity ? MAX_VALUE_32 : Number.POSITIVE_INFINITY, } = ct; return { min, max }; } describe('floatNext', () => { it('should accept any valid range of 32-bit floating point numbers (including infinity)', () => { fc.assert( fc.property(floatNextConstraints(), (ct) => { // Arrange spyInteger(); // Act const arb = floatNext(ct); // Assert expect(arb).toBeDefined(); }) ); }); it('should accept any constraits defining min (32-bit float not-NaN) equal to max', () => { fc.assert( fc.property( float32raw(), fc.record({ noDefaultInfinity: fc.boolean(), noNaN: fc.boolean() }, { withDeletedKeys: true }), (f, otherCt) => { // Arrange fc.pre(isNotNaN32bits(f)); spyInteger(); // Act const arb = floatNext({ ...otherCt, min: f, max: f }); // Assert expect(arb).toBeDefined(); } ) ); }); it('should reject non-32-bit or NaN floating point numbers if specified for min', () => { fc.assert( fc.property(float64raw(), (f64) => { // Arrange fc.pre(!isNotNaN32bits(f64)); const integer = spyInteger(); // Act / Assert expect(() => floatNext({ min: f64 })).toThrowError(); expect(integer).not.toHaveBeenCalled(); }) ); }); it('should reject non-32-bit or NaN floating point numbers if specified for max', () => { fc.assert( fc.property(float64raw(), (f64) => { // Arrange fc.pre(!isNotNaN32bits(f64)); const integer = spyInteger(); // Act / Assert expect(() => floatNext({ max: f64 })).toThrowError(); expect(integer).not.toHaveBeenCalled(); }) ); }); it('should reject if specified min is strictly greater than max', () => { fc.assert( fc.property(float32raw(), float32raw(), (fa32, fb32) => { // Arrange fc.pre(isNotNaN32bits(fa32)); fc.pre(isNotNaN32bits(fb32)); fc.pre(!Object.is(fa32, fb32)); // Object.is can distinguish -0 from 0, while !== cannot const integer = spyInteger(); const min = isStrictlySmaller(fa32, fb32) ? fb32 : fa32; const max = isStrictlySmaller(fa32, fb32) ? fa32 : fb32; // Act / Assert expect(() => floatNext({ min, max })).toThrowError(); expect(integer).not.toHaveBeenCalled(); }) ); }); it('should reject impossible noDefaultInfinity-based ranges', () => { // Arrange const integer = spyInteger(); // Act / Assert expect(() => floatNext({ min: Number.POSITIVE_INFINITY, noDefaultInfinity: true })).toThrowError(); expect(() => floatNext({ max: Number.NEGATIVE_INFINITY, noDefaultInfinity: true })).toThrowError(); expect(integer).not.toHaveBeenCalled(); }); it('should properly convert integer value for index between min and max into its associated float value', () => fc.assert( fc.property(fc.option(floatNextConstraints(), { nil: undefined }), fc.maxSafeNat(), (ct, mod) => { // Arrange const { instance: mrng } = fakeRandom(); const { min, max } = minMaxForConstraints(ct || {}); const minIndex = floatToIndex(min); const maxIndex = floatToIndex(max); const arbitraryGeneratedIndex = (mod % (maxIndex - minIndex + 1)) + minIndex; spyIntegerWithValue(() => arbitraryGeneratedIndex); // Act const arb = floatNext(ct); const { value_: f } = arb.generate(mrng); // Assert expect(f).toBe(indexToFloat(arbitraryGeneratedIndex)); }) )); describe('with NaN', () => { const withNaNRecordConstraints = { ...defaultFloatRecordConstraints, noNaN: fc.constant(false) }; it('should ask for a range with one extra value (far from zero)', () => { fc.assert( fc.property(floatNextConstraints(withNaNRecordConstraints), (ct) => { // Arrange const { max } = minMaxForConstraints(ct); const integer = spyInteger(); // Act floatNext({ ...ct, noNaN: true }); floatNext(ct); // Assert expect(integer).toHaveBeenCalledTimes(2); const integerConstraintsNoNaN = integer.mock.calls[0][0]; const integerConstraintsWithNaN = integer.mock.calls[1][0]; if (max > 0) { // max > 0 --> NaN will be added as the greatest value expect(integerConstraintsWithNaN.min).toBe(integerConstraintsNoNaN.min); expect(integerConstraintsWithNaN.max).toBe(integerConstraintsNoNaN.max! + 1); } else { // max <= 0 --> NaN will be added as the smallest value expect(integerConstraintsWithNaN.min).toBe(integerConstraintsNoNaN.min! - 1); expect(integerConstraintsWithNaN.max).toBe(integerConstraintsNoNaN.max); } }) ); }); it('should properly convert the extra value to NaN', () => fc.assert( fc.property(floatNextConstraints(withNaNRecordConstraints), (ct) => { // Arrange // Setup mocks for integer const { instance: mrng } = fakeRandom(); const arbitraryGenerated = { value: Number.NaN }; const integer = spyIntegerWithValue(() => arbitraryGenerated.value); // Call float next to find out the value required for NaN floatNext({ ...ct, noNaN: true }); const arb = floatNext(ct); // Extract NaN "index" const { min: minNonNaN } = integer.mock.calls[0][0]; const { min: minNaN, max: maxNaN } = integer.mock.calls[1][0]; const indexForNaN = minNonNaN !== minNaN ? minNaN : maxNaN; if (indexForNaN === undefined) throw new Error('No value available for NaN'); arbitraryGenerated.value = indexForNaN; // Act const { value_: f } = arb.generate(mrng); // Assert expect(f).toBe(Number.NaN); }) )); }); describe('without NaN', () => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { noNaN, ...noNaNRecordConstraints } = defaultFloatRecordConstraints; it('should ask integers between the indexes corresponding to min and max', () => { fc.assert( fc.property(floatNextConstraints(noNaNRecordConstraints), (ctDraft) => { // Arrange const ct = { ...ctDraft, noNaN: true }; const integer = spyInteger(); const { min, max } = minMaxForConstraints(ct); const minIndex = floatToIndex(min); const maxIndex = floatToIndex(max); // Act floatNext(ct); // Assert expect(integer).toHaveBeenCalledTimes(1); expect(integer).toHaveBeenCalledWith({ min: minIndex, max: maxIndex }); }) ); }); }); }); describe('floatNext (integration)', () => { type Extra = FloatNextConstraints | undefined; const extraParameters: fc.Arbitrary<Extra> = fc.option(floatNextConstraints(), { nil: undefined }); const isCorrect = (v: number, extra: Extra) => { expect(typeof v).toBe('number'); // should always produce numbers expect(is32bits(v)).toBe(true); // should always produce 32-bit floats if (extra === undefined) { return; // no other constraints } if (extra.noNaN) { expect(v).not.toBe(Number.NaN); // should not produce NaN if explicitely asked not too } if (extra.min !== undefined && !Number.isNaN(v)) { expect(v).toBeGreaterThanOrEqual(extra.min); // should always be greater than min when specified } if (extra.max !== undefined && !Number.isNaN(v)) { expect(v).toBeLessThanOrEqual(extra.max); // should always be smaller than max when specified } if (extra.noDefaultInfinity) { if (extra.min === undefined) { expect(v).not.toBe(Number.NEGATIVE_INFINITY); // should not produce -infinity when noInfinity and min unset } if (extra.max === undefined) { expect(v).not.toBe(Number.POSITIVE_INFINITY); // should not produce +infinity when noInfinity and max unset } } }; const isStrictlySmaller = (fa: number, fb: number) => Math.abs(fa) < Math.abs(fb) || // Case 1: abs(a) < abs(b) (Object.is(fa, +0) && Object.is(fb, -0)) || // Case 2: +0 < -0 --> we shrink from -0 to +0 (!Number.isNaN(fa) && Number.isNaN(fb)); // Case 3: notNaN < NaN, NaN is one of the extreme values const floatNextBuilder = (extra: Extra) => convertToNext(floatNext(extra)); it('should produce the same values given the same seed', () => { assertProduceSameValueGivenSameSeed(floatNextBuilder, { extraParameters }); }); it('should only produce correct values', () => { assertProduceCorrectValues(floatNextBuilder, isCorrect, { extraParameters }); }); it('should produce values seen as shrinkable without any context', () => { assertProduceValuesShrinkableWithoutContext(floatNextBuilder, { extraParameters }); }); it('should be able to shrink to the same values without initial context', () => { assertShrinkProducesSameValueWithoutInitialContext(floatNextBuilder, { extraParameters }); }); it('should preserve strictly smaller ordering in shrink', () => { assertShrinkProducesStrictlySmallerValue(floatNextBuilder, isStrictlySmaller, { extraParameters }); }); }); // Helpers function spyInteger() { const { instance, map } = fakeNextArbitrary<number>(); const { instance: mappedInstance } = fakeNextArbitrary(); const integer = jest.spyOn(IntegerMock, 'integer'); integer.mockImplementation(() => convertFromNextWithShrunkOnce(instance, undefined)); map.mockReturnValue(mappedInstance); return integer; } function spyIntegerWithValue(value: () => number) { const { instance } = fakeNextArbitraryStaticValue<number>(value); const integer = jest.spyOn(IntegerMock, 'integer'); integer.mockImplementation(() => convertFromNextWithShrunkOnce(instance, undefined)); return integer; }
the_stack
import { isInputObjectType, isInterfaceType, isEnumType, isObjectType, isScalarType, GraphQLSchema, GraphQLField, GraphQLType, GraphQLArgument, GraphQLInputField, } from 'graphql'; import { isString, isObject, isFloat, isNumber, } from '../../../../Common/utils/jsUtils'; import { getUnderlyingType } from '../../../../../shared/utils/graphqlSchemaUtils'; import { QualifiedTable } from '../../../../../metadata/types'; export type ArgValueKind = 'column' | 'static'; export type ArgValue = { kind: ArgValueKind; value: string; type: string; }; export const defaultArgValue: ArgValue = { kind: 'column', value: '', type: 'String', }; // Client Type export type RemoteFieldArgument = { name: string; depth: number; parentField: string; parentFieldDepth: number; isChecked: boolean; parent?: string; value: ArgValue; type: string; }; export interface TreeArgElement extends RemoteFieldArgument { isLeafArg: boolean; kind: 'argument'; } export type RemoteField = { name: string; depth: number; parent?: string; arguments: RemoteFieldArgument[]; }; export interface TreeFieldElement extends Omit<RemoteField, 'arguments'> { kind: 'field'; isChecked: boolean; enabled: boolean; } export type RJSchemaTreeElement = TreeArgElement | TreeFieldElement; export type RemoteRelationship = { name: string; remoteSchema: string; remoteFields: RemoteField[]; table: { name: string; schema: string; }; }; // Server Type type RemoteRelationshipFieldServer = { field?: Record<string, RemoteRelationshipFieldServer>; arguments: Record<string, any>; }; export type RemoteRelationshipServer = { remote_relationship_name: string; definition: { remote_field: Record<string, RemoteRelationshipFieldServer>; remote_schema: string; hasura_fields: string[]; }; table_name: string; table_schema: string; }; export const parseArgValue = (argValue: any): ArgValue | null => { if (isObject(argValue)) { return null; } if (isString(argValue)) { const isStatic = !argValue.startsWith('$'); return { value: isStatic ? argValue.toString() : argValue.substr(1), kind: isStatic ? 'static' : 'column', type: 'String', }; } if (argValue === true || argValue === false) { return { kind: 'static', value: argValue.toString(), type: 'Boolean', }; } return { kind: 'static', value: argValue.toString(), type: (isNumber(argValue) && (isFloat(argValue) ? 'Float' : 'Int')) || 'String', }; }; // Converters and parsers const serialiseArguments = ( args: Record<string, any>, depth: number, parentField: string, parentFieldDepth: number, parent?: string ): RemoteFieldArgument[] => { let allArgs: RemoteFieldArgument[] = []; Object.keys(args).forEach(argName => { const argValue = args[argName]; const argValueMetadata = parseArgValue(argValue); if (argValueMetadata) { allArgs.push({ name: argName, depth, parent, isChecked: false, parentField, parentFieldDepth, value: argValueMetadata, type: argValueMetadata.type, }); } else { allArgs = [ ...allArgs, { name: argName, depth, parent, isChecked: false, parentField, parentFieldDepth, value: defaultArgValue, type: 'String', }, ...serialiseArguments( argValue, depth + 1, parentField, parentFieldDepth, argName ), ]; } }); return allArgs; }; const serialiseRemoteField = ( name: string, depth: number, field: RemoteRelationshipFieldServer, callback: (f: RemoteField) => void, parent?: string ): void => { callback({ name, depth, parent, arguments: serialiseArguments(field.arguments, 0, name, depth, undefined), }); if (field.field) { const subFieldName = Object.keys(field.field)[0]; const subField = field.field[subFieldName]; serialiseRemoteField(subFieldName, depth + 1, subField, callback, name); } }; export const parseRemoteRelationship = ( relationship: RemoteRelationshipServer ): RemoteRelationship => { const remoteField = relationship.definition.remote_field; const allRemoteFields: RemoteField[] = []; Object.keys(remoteField).forEach(fieldName => { serialiseRemoteField( fieldName, 0, remoteField[fieldName], (field: RemoteField) => allRemoteFields.push(field), undefined ); }); return { name: relationship.remote_relationship_name, remoteSchema: relationship.definition.remote_schema, table: { name: relationship.table_name, schema: relationship.table_schema, }, remoteFields: allRemoteFields, }; }; const getTypedArgValueInput = (argValue: ArgValue, type: string) => { let error: string | null = null; let value: any; if (argValue.kind === 'column') { return { value: `$${argValue.value}`, error, }; } switch (type) { case 'Float': { const number = parseFloat(argValue.value); if (window.isNaN(number)) { error = 'invalid float value'; } value = number; break; } case 'Int': { const number = parseInt(argValue.value, 10); if (window.isNaN(number)) { error = 'invalid int value'; } value = number; break; } case 'ID': { const number = parseInt(argValue.value, 10); if (window.isNaN(number)) { error = 'invalid int value'; } value = number; break; } case 'Boolean': { error = argValue.value.toLowerCase() !== 'false' && argValue.value.toLowerCase() !== 'true' ? 'invalid boolean value' : null; if (!error) { value = argValue.value.toLowerCase() === 'true'; } break; } default: value = argValue.value; break; } return { error, value, }; }; export type RemoteRelationshipPayload = { name: string; remote_schema: string; remote_field: Record<string, RemoteRelationshipFieldServer>; hasura_fields: string[]; table: QualifiedTable; }; export const getRemoteRelPayload = ( relationship: RemoteRelationship ): RemoteRelationshipPayload => { const hasuraFields: string[] = []; const getRemoteFieldArguments = (field: RemoteField) => { const getArgumentObject = (depth: number, parent?: string) => { const depthArguments = field.arguments.filter( a => a.depth === depth && a.parent === parent ); const finalArgObj: any = depthArguments.reduce( (argObj: any, currentArg) => { const nestedArgObj = getArgumentObject(depth + 1, currentArg.name); if (!nestedArgObj) { const argValueTyped = getTypedArgValueInput( currentArg.value, currentArg.type ); if (argValueTyped.error) { throw Error(argValueTyped.error); } if (currentArg.value.kind === 'column') { hasuraFields.push(argValueTyped.value); } return { ...argObj, [currentArg.name]: argValueTyped.value, }; } return { ...argObj, [currentArg.name]: nestedArgObj, }; return { ...argObj, }; }, {} ); return Object.keys(finalArgObj).length ? finalArgObj : undefined; }; return getArgumentObject(0); }; const getRemoteFieldObject = ( depth: number ): Record<string, RemoteRelationshipFieldServer> | undefined => { const obj: Record<string, RemoteRelationshipFieldServer> = {}; const depthRemoteFields = relationship.remoteFields.filter( f => f.depth === depth ); depthRemoteFields.forEach(f => { obj[f.name] = { field: getRemoteFieldObject(depth + 1), arguments: getRemoteFieldArguments(f) || {}, }; }); return Object.keys(obj).length ? obj : undefined; }; return { name: relationship.name, remote_schema: relationship.remoteSchema, remote_field: getRemoteFieldObject(0) || {}, hasura_fields: hasuraFields .map(f => f.substr(1)) .filter((v, i, s) => s.indexOf(v) === i), table: relationship.table, }; }; const isFieldChecked = ( relationship: RemoteRelationship, fieldName: string, depth: number, parent?: string ) => { return relationship.remoteFields.some(f => { return f.name === fieldName && f.depth === depth && f.parent === parent; }); }; /* returns checked value if arg is checked * returns null if arg isn't involved in the relationship */ export const getCheckedArgValue = ( relationship: RemoteRelationship, argName: string, argType: GraphQLType, depth: number, parentField: string, parentFieldDepth: number, parent?: string ): ArgValue | null => { const parentRemoteField = relationship.remoteFields.find(f => { return f.name === parentField && f.depth === parentFieldDepth; }); if (parentRemoteField) { const checkedArg = parentRemoteField.arguments.find( arg => arg.name === argName && arg.depth === depth && arg.parent === parent ); if (checkedArg) { return { ...checkedArg.value, type: getUnderlyingType(argType).type.name, }; } } return null; }; const buildArgElement = ( relationship: RemoteRelationship, arg: GraphQLArgument | GraphQLInputField, depth: number, parentField: string, parentFieldDepth: number, callback: (fe: TreeArgElement) => void, parent?: string ) => { const { type: argType }: { type: GraphQLType } = getUnderlyingType(arg.type); const argValue = getCheckedArgValue( relationship, arg.name, argType, depth, parentField, parentFieldDepth, parent ); const isLeafArg = isScalarType(argType) || isEnumType(argType); callback({ name: arg.name, kind: 'argument', depth, type: (isLeafArg && (isEnumType(argType) ? 'String' : getUnderlyingType(argType).type.name)) || undefined, parent, parentField, parentFieldDepth, value: argValue || defaultArgValue, isChecked: !!argValue, isLeafArg, }); if (!!argValue && (isInputObjectType(argType) || isInterfaceType(argType))) { const argFields = argType.getFields(); Object.values(argFields).forEach(argField => { buildArgElement( relationship, argField, depth + 1, parentField, parentFieldDepth, callback, arg.name ); }); } }; const buildFieldElement = ( relationship: RemoteRelationship, field: GraphQLField<any, any, Record<string, any>>, depth: number, callback: (element: RJSchemaTreeElement) => void, parent?: string ) => { const { type: fieldType }: { type: GraphQLType } = getUnderlyingType( field.type ); const isChecked = isFieldChecked(relationship, field.name, depth, parent); callback({ name: field.name, kind: 'field', depth, parent, isChecked, enabled: (field.args && !!field.args.length) || isObjectType(fieldType), }); if (isChecked) { if (field.args) { field.args.forEach(arg => { buildArgElement(relationship, arg, 0, field.name, depth, callback); }); } if (isObjectType(fieldType) || isInterfaceType(fieldType)) { const subFields = fieldType.getFields(); Object.values(subFields).forEach(subField => { buildFieldElement( relationship, subField, depth + 1, callback, field.name ); }); } } }; export const buildSchemaTree = ( relationship: RemoteRelationship, remoteSchema?: GraphQLSchema ): RJSchemaTreeElement[] => { if (!remoteSchema) return []; const schemaTree: (TreeArgElement | TreeFieldElement)[] = []; const queryType = remoteSchema.getQueryType(); if (!queryType) return []; const fields = queryType.getFields(); Object.values(fields).forEach(field => { buildFieldElement( relationship, field, 0, (fieldElement: RJSchemaTreeElement) => schemaTree.push(fieldElement) ); }); return schemaTree; }; export const compareRemoteFields = ( rf1: RemoteField | TreeFieldElement, rf2: RemoteField | TreeFieldElement ) => rf1.name === rf2.name && rf1.depth === rf2.depth && rf1.parent === rf2.parent; export const compareRFArguments = ( a1: RemoteFieldArgument, a2: RemoteFieldArgument ) => a1.name === a2.name && a1.depth === a2.depth && a1.parent === a2.parent && a1.parentField === a2.parentField && a1.parentFieldDepth === a2.parentFieldDepth; export const findRemoteFieldArgument = ( args: RemoteFieldArgument[], arg: RemoteFieldArgument ) => { return args.find(a => compareRFArguments(a, arg)); }; export const findRemoteField = ( fields: RemoteField[], field: RemoteField | TreeFieldElement ) => { return fields.find( f => f.name === field.name && f.depth === field.depth && f.parent === field.parent ); }; export const findArgParentField = ( fields: RemoteField[], arg: RemoteFieldArgument ) => { return fields.find( f => f.name === arg.parentField && f.depth === arg.parentFieldDepth ); };
the_stack
/// <reference types="angular" /> declare namespace mgcrea.ngStrap { /////////////////////////////////////////////////////////////////////////// // Modal // see http://mgcrea.github.io/angular-strap/#/modals /////////////////////////////////////////////////////////////////////////// namespace modal { type IModalService = (config?: IModalOptions) => IModal; interface IModalProvider { defaults: IModalOptions; } interface IModal { $promise: ng.IPromise<void>; show(): void; hide(): void; toggle(): void; } interface IModalOptions { animation?: string; backdropAnimation?: string; placement?: string; title?: string; content?: string; html?: boolean; backdrop?: boolean | string; keyboard?: boolean; show?: boolean; container?: string | boolean; controller?: any; controllerAs?: string; resolve?: any; locals?: any; template?: string; templateUrl?: string; contentTemplate?: string; prefixEvent?: string; id?: string; scope?: ng.IScope; onShow?(modal: IModal): void; onBeforeShow?(modal: IModal): void; onHide?(modal: IModal): void; onBeforeHide?(modal: IModal): void; } interface IModalScope extends ng.IScope { $show(): void; $hide(): void; $toggle(): void; } } /////////////////////////////////////////////////////////////////////////// // Aside // see http://mgcrea.github.io/angular-strap/#/asides /////////////////////////////////////////////////////////////////////////// namespace aside { type IAsideService = (config?: IAsideOptions) => IAside; interface IAsideProvider { defaults: IAsideOptions; } interface IAside { $promise: ng.IPromise<void>; show(): void; hide(): void; toggle(): void; } interface IAsideOptions { animation?: string; placement?: string; title?: string; content?: string; html?: boolean; backdrop?: boolean | string; keyboard?: boolean; show?: boolean; container?: string | boolean; controller?: any; controllerAs?: string; template?: string; templateUrl?: string; contentTemplate?: string; scope?: ng.IScope; onShow?(aside: IAside): void; onBeforeShow?(aside: IAside): void; onHide?(aside: IAside): void; onBeforeHide?(aside: IAside): void; } interface IAsideScope extends ng.IScope { $show(): void; $hide(): void; $toggle(): void; } } /////////////////////////////////////////////////////////////////////////// // Alert // see http://mgcrea.github.io/angular-strap/#/alerts /////////////////////////////////////////////////////////////////////////// namespace alert { type IAlertService = (config?: IAlertOptions) => IAlert; interface IAlertProvider { defaults: IAlertOptions; } interface IAlert { $promise: ng.IPromise<void>; show(): void; hide(): void; toggle(): void; } interface IAlertOptions { animation?: string; placement?: string; title?: string; content?: string; type?: string; show?: boolean; container?: string | boolean; controller?: any; controllerAs?: string; template?: string; templateUrl?: string; duration?: number | boolean; dismissable?: boolean; onShow?(alert: IAlert): void; onBeforeShow?(alert: IAlert): void; onHide?(alert: IAlert): void; onBeforeHide?(alert: IAlert): void; } interface IAlertScope extends ng.IScope { $show(): void; $hide(): void; $toggle(): void; } } /////////////////////////////////////////////////////////////////////////// // Tooltip // see http://mgcrea.github.io/angular-strap/#/tooltips /////////////////////////////////////////////////////////////////////////// namespace tooltip { type ITooltipService = (element: ng.IAugmentedJQuery, config?: ITooltipOptions) => ITooltip; interface ITooltipProvider { defaults: ITooltipOptions; } interface ITooltip { $promise: ng.IPromise<void>; show(): void; hide(): void; toggle(): void; } interface ITooltipOptions { animation?: string; placement?: string; trigger?: string; title?: string; html?: boolean; delay?: number | { show: number; hide: number}; container?: string | boolean; target?: string | ng.IAugmentedJQuery | boolean; template?: string; templateUrl?: string; titleTemplate?: string; prefixEvent?: string; id?: string; onShow?(tooltip: ITooltip): void; onBeforeShow?(tooltip: ITooltip): void; onHide?(tooltip: ITooltip): void; onBeforeHide?(tooltip: ITooltip): void; viewport?: string | { selector: string; padding: string | number }; } interface ITooltipScope extends ng.IScope { $show(): void; $hide(): void; $toggle(): void; $setEnabled(isEnabled: boolean): void; } } /////////////////////////////////////////////////////////////////////////// // Popover // see http://mgcrea.github.io/angular-strap/#/popovers /////////////////////////////////////////////////////////////////////////// namespace popover { type IPopoverService = (element: ng.IAugmentedJQuery, config?: IPopoverOptions) => IPopover; interface IPopoverProvider { defaults: IPopoverOptions; } interface IPopover { $promise: ng.IPromise<void>; show(): void; hide(): void; toggle(): void; } interface IPopoverOptions { animation?: string; placement?: string; trigger?: string; title?: string; content?: string; html?: boolean; delay?: number | { show: number; hide: number }; container?: string | boolean; target?: string | ng.IAugmentedJQuery | boolean; template?: string; templateUrl?: string; contentTemplate?: string; autoClose?: boolean; id?: string; onShow?(popover: IPopover): void; onBeforeShow?(popover: IPopover): void; onHide?(popover: IPopover): void; onBeforeHide?(popover: IPopover): void; viewport?: string | { selector: string; padding: string | number }; } interface IPopoverScope extends ng.IScope { $show(): void; $hide(): void; $toggle(): void; } } /////////////////////////////////////////////////////////////////////////// // Typeahead // see http://mgcrea.github.io/angular-strap/#/typeaheads /////////////////////////////////////////////////////////////////////////// namespace typeahead { type ITypeaheadService = (element: ng.IAugmentedJQuery, controller: any, config?: ITypeaheadOptions) => ITypeahead; interface ITypeaheadProvider { defaults: ITypeaheadOptions; } interface ITypeahead { $promise: ng.IPromise<void>; show(): void; hide(): void; toggle(): void; } interface ITypeaheadOptions { animation?: string; placement?: string; trigger?: string; html?: boolean; delay?: number | { show: number; hide: number }; container?: string | boolean; template?: string; limit?: number; minLength?: number; autoSelect?: boolean; comparator?: string; id?: string; watchOptions?: boolean; trimValue?: boolean; onShow?(typeahead: ITypeahead): void; onBeforeShow?(typeahead: ITypeahead): void; onHide?(typeahead: ITypeahead): void; onBeforeHide?(typeahead: ITypeahead): void; onSelect?(typeahead: ITypeahead): void; } } /////////////////////////////////////////////////////////////////////////// // Datepicker // see http://mgcrea.github.io/angular-strap/#/datepickers /////////////////////////////////////////////////////////////////////////// namespace datepicker { type IDatepickerService = (element: ng.IAugmentedJQuery, controller: any, config?: IDatepickerOptions) => IDatepicker; interface IDatepickerProvider { defaults: IDatepickerOptions; } interface IDatepicker { update(date: Date): void; updateDisabledDates(dateRanges: IDatepickerDateRange[]): void; select(dateConstructorArg: string | number | number[], keep: boolean): void; setMode(mode: any): void; int(): void; destroy(): void; show(): void; hide(): void; } interface IDatepickerDateRange { start: Date; end: Date; } interface IDatepickerOptions { animation?: string; placement?: string; trigger?: string; html?: boolean; delay?: number | { show: number; hide: number }; container?: string | boolean; template?: string; onShow?(datepicker: IDatepicker): void; onBeforeShow?(datepicker: IDatepicker): void; onHide?(datepicker: IDatepicker): void; onBeforeHide?(datepicker: IDatepicker): void; dateFormat?: string; modelDateFormat?: string; dateType?: string; timezone?: string; autoclose?: boolean; useNative?: boolean; minDate?: Date; maxDate?: Date; startView?: number; minView?: number; startWeek?: number; startDate?: Date; iconLeft?: string; iconRight?: string; daysOfWeekDisabled?: string; disabledDates?: IDatepickerDateRange[]; } } /////////////////////////////////////////////////////////////////////////// // Timepicker // see http://mgcrea.github.io/angular-strap/#/timepickers /////////////////////////////////////////////////////////////////////////// namespace timepicker { type ITimepickerService = (element: ng.IAugmentedJQuery, controller: any, config?: ITimepickerOptions) => ITimepicker; interface ITimepickerProvider { defaults: ITimepickerOptions; } interface ITimepicker { } interface ITimepickerOptions { animation?: string; placement?: string; trigger?: string; html?: boolean; delay?: number | { show: number; hide: number; }; container?: string | boolean; template?: string; onShow?(timepicker: ITimepicker): void; onBeforeShow?(timepicker: ITimepicker): void; onHide?(timepicker: ITimepicker): void; onBeforeHide?(timepicker: ITimepicker): void; timeFormat?: string; modelTimeFormat?: string; timeType?: string; autoclose?: boolean; useNative?: boolean; minTime?: Date; // TODO maxTime?: Date; // TODO length?: number; hourStep?: number; minuteStep?: number; secondStep?: number; roundDisplay?: boolean; iconUp?: string; iconDown?: string; arrowBehaviour?: string; } } /////////////////////////////////////////////////////////////////////////// // Button // see http://mgcrea.github.io/angular-strap/#/buttons /////////////////////////////////////////////////////////////////////////// // No definitions for this module /////////////////////////////////////////////////////////////////////////// // Select // see http://mgcrea.github.io/angular-strap/#/selects /////////////////////////////////////////////////////////////////////////// namespace select { type ISelectService = (element: ng.IAugmentedJQuery, controller: any, config: ISelectOptions) => ISelect; interface ISelectProvider { defaults: ISelectOptions; } interface ISelect { update(matches: any): void; active(index: number): number; select(index: number): void; show(): void; hide(): void; } interface ISelectOptions { animation?: string; placement?: string; trigger?: string; html?: boolean; delay?: number | { show: number; hide: number; }; container?: string | boolean; template?: string; toggle?: boolean; onShow?(select: ISelect): void; onBeforeShow?(select: ISelect): void; onHide?(select: ISelect): void; onBeforeHide?(select: ISelect): void; multiple?: boolean; allNoneButtons?: boolean; allText?: string; noneText?: string; maxLength?: number; maxLengthHtml?: string; sort?: boolean; placeholder?: string; iconCheckmark?: string; id?: string; } } /////////////////////////////////////////////////////////////////////////// // Tabs // see http://mgcrea.github.io/angular-strap/#/tabs /////////////////////////////////////////////////////////////////////////// namespace tab { interface ITabProvider { defaults: ITabOptions; } interface ITabService { defaults: ITabOptions; controller: any; } interface ITabOptions { animation?: string; template?: string; navClass?: string; activeClass?: string; } } /////////////////////////////////////////////////////////////////////////// // Collapses // see http://mgcrea.github.io/angular-strap/#/collapses /////////////////////////////////////////////////////////////////////////// namespace collapse { interface ICollapseProvider { defaults: ICollapseOptions; } interface ICollapseOptions { animation?: string; activeClass?: string; disallowToggle?: boolean; startCollapsed?: boolean; allowMultiple?: boolean; } } /////////////////////////////////////////////////////////////////////////// // Dropdowsn // see http://mgcrea.github.io/angular-strap/#/dropdowns /////////////////////////////////////////////////////////////////////////// namespace dropdown { interface IDropdownProvider { defaults: IDropdownOptions; } type IDropdownService = (element: ng.IAugmentedJQuery, config: IDropdownOptions) => IDropdown; interface IDropdown { show(): void; hide(): void; destroy(): void; } interface IDropdownOptions { animation?: string; placement?: string; trigger?: string; html?: boolean; delay?: number | { show: number; hide: number; }; container?: string | boolean; template?: string; templateUrl?: string; onShow?(dropdown: IDropdown): void; onBeforeShow?(dropdown: IDropdown): void; onHide?(dropdown: IDropdown): void; onBeforeHide?(dropdown: IDropdown): void; } } /////////////////////////////////////////////////////////////////////////// // Navbar // see http://mgcrea.github.io/angular-strap/#/navbars /////////////////////////////////////////////////////////////////////////// namespace navbar { interface INavbarProvider { defaults: INavbarOptions; } interface INavbarOptions { activeClass?: string; routeAttr?: string; } interface INavbarService { defaults: INavbarOptions; } } /////////////////////////////////////////////////////////////////////////// // Scrollspy // see http://mgcrea.github.io/angular-strap/#/scrollspy /////////////////////////////////////////////////////////////////////////// namespace scrollspy { interface IScrollspyProvider { defaults: IScrollspyOptions; } type IScrollspyService = (element: ng.IAugmentedJQuery, options: IScrollspyOptions) => IScrollspy; interface IScrollspy { checkOffsets(): void; trackElement(target: any, source: any): void; untrackElement(target: any, source: any): void; activate(index: number): void; } interface IScrollspyOptions { target?: string; offset?: number; } } /////////////////////////////////////////////////////////////////////////// // Affix // see http://mgcrea.github.io/angular-strap/#/affix /////////////////////////////////////////////////////////////////////////// namespace affix { interface IAffixProvider { defaults: IAffixOptions; } type IAffixService = (element: ng.IAugmentedJQuery, options: IAffixOptions) => IAffix; interface IAffix { init(): void; destroy(): void; checkPositionWithEventLoop(): void; checkPosition(): void; } interface IAffixOptions { offsetTop?: number; offsetBottom?: number; offsetParent?: number; offsetUnpin?: number; } } }
the_stack
import {LOG4TS_PROVIDER_SERVICE} from "../main/impl/Log4TSProviderService"; import {Log4TSProvider} from "../main/api/Log4TSProvider"; import {$test, ArgumentFormatterType, DateFormatterType, LogChannel, LogLevel} from "typescript-logging"; describe("Test Log4TSProvider", () => { beforeEach(() => { /* * Clear any state, so we always start clean. */ LOG4TS_PROVIDER_SERVICE.clear(); }); test("Test create provider with minimum config set", () => { const provider = Log4TSProvider.createProvider("test", { groups: [{ expression: new RegExp("model.+"), }], }); expect(provider.name).toEqual("test"); expect(provider.groupConfigs.length).toEqual(1); const groupConfig = provider.groupConfigs[0]; expect(groupConfig.level).toEqual(LogLevel.Error); }); test("Test create provider with modified config", () => { const customChannel: LogChannel = { type: "LogChannel", write: () => null, }; const argumentFormatter: ArgumentFormatterType = () => ""; const dateFormatter: DateFormatterType = () => ""; const groupExpression = new RegExp("model.+"); const provider = Log4TSProvider.createProvider("test", { groups: [{expression: groupExpression}], level: LogLevel.Info, channel: customChannel, argumentFormatter, dateFormatter, }); expect(provider.name).toEqual("test"); const config = provider.config; expect(config.channel).toEqual(customChannel); expect(config.dateFormatter).toEqual(dateFormatter); expect(config.argumentFormatter).toEqual(argumentFormatter); expect(config.level).toEqual(LogLevel.Info); /* Group config must use the main config of the provider when none were provided for the group */ expect(provider.groupConfigs.length).toEqual(1); const groupConfig = provider.groupConfigs[0]; expect(groupConfig.channel).toEqual(customChannel); expect(groupConfig.expression).toEqual(groupExpression); expect(groupConfig.dateFormatter).toEqual(dateFormatter); expect(groupConfig.argumentFormatter).toEqual(argumentFormatter); expect(groupConfig.level).toEqual(LogLevel.Info); }); test("Test create provider and group custom config", () => { const argumentFormatter: ArgumentFormatterType = () => ""; const dateFormatter: DateFormatterType = () => ""; const groupExpression = new RegExp("model.+"); const provider = Log4TSProvider.createProvider("test", { groups: [{ expression: groupExpression, level: LogLevel.Debug, argumentFormatter, dateFormatter, }], }); /* The provider has defaults and must not match anything from above */ expect(provider.name).toEqual("test"); const config = provider.config; expect(config.dateFormatter).not.toEqual(dateFormatter); expect(config.argumentFormatter).not.toEqual(argumentFormatter); expect(config.level).toEqual(LogLevel.Error); /* Group config must use it's own settings as configured */ expect(provider.groupConfigs.length).toEqual(1); const groupConfigs = provider.groupConfigs; expect(groupConfigs.length).toEqual(1); const groupConfig = groupConfigs[0]; expect(groupConfig.expression).toEqual(groupExpression); expect(groupConfig.dateFormatter).toEqual(dateFormatter); expect(groupConfig.argumentFormatter).toEqual(argumentFormatter); expect(groupConfig.level).toEqual(LogLevel.Debug); }); test("Provider creates correct loggers", () => { const channel = new $test.ArrayRawLogChannel(); const groupExpressionModel = new RegExp("model.+"); const groupExpressionService = new RegExp("service.+"); const provider = Log4TSProvider.createProvider("test", { channel, groups: [ { expression: groupExpressionModel, level: LogLevel.Debug, }, { expression: groupExpressionService, }, ], level: LogLevel.Info, }); expect(provider.groupConfigs.length).toEqual(2); const groupConfigs = provider.groupConfigs; expect(groupConfigs.length).toEqual(2); expect(groupConfigs[0].expression).toEqual(groupExpressionModel); expect(groupConfigs[0].channel).toEqual(channel); expect(groupConfigs[1].expression).toEqual(groupExpressionService); expect(groupConfigs[1].channel).toEqual(channel); // Logger must match first group expression and level let logger = provider.getLogger("model.Hello"); expect(LogLevel.Debug).toEqual(logger.logLevel); expect(channel.size).toEqual(0); logger.debug("debug"); logger.info("info"); logger.trace("trace"); // Should not appear expect(channel.messages).toEqual(["debug", "info"]); channel.clear(); // Logger must match second group expression, level will be provider's one. logger = provider.getLogger("service.Awesome"); expect(LogLevel.Info).toEqual(logger.logLevel); logger.warn("warn"); logger.error("error"); logger.debug("debug"); logger.fatal(() => "fatal"); logger.info("info"); logger.trace(() => "trace"); expect(channel.messages).toEqual(["warn", "error", "fatal", "info"]); channel.clear(); // Logger does not match any group, and will fallback to default and use provider's defaults. logger = provider.getLogger("noMatchingGroup"); expect(LogLevel.Info).toEqual(logger.logLevel); logger.info("info"); logger.debug("debug"); expect(channel.messages).toEqual(["info"]); // Finally the loggers should remain the same when asked by same name. logger = provider.getLogger("model.Dance"); expect(logger === provider.getLogger("model.Dance")).toEqual(true); logger = provider.getLogger("notMatching"); expect(logger === provider.getLogger("notMatching")).toEqual(true); }); test("Test log level can be changed dynamically", () => { const channel = new $test.ArrayRawLogChannel(); /* Default logs to error */ const provider = Log4TSProvider.createProvider("test", { channel, groups: [{ expression: new RegExp("model.+"), identifier: "model", }, { expression: new RegExp("service.+"), }], }); expect(provider.groupConfigs[0].identifier).toEqual("model"); const logProduct = provider.getLogger("model.Product"); const logAccountService = provider.getLogger("service.AccountService"); logProduct.warn("warn"); logAccountService.warn("warn"); expect(channel.size).toEqual(0); /* Changes level to info for all groups */ provider.updateRuntimeSettings({level: LogLevel.Info}); logProduct.info("product"); logAccountService.info("accountService"); expect(channel.messages).toEqual(["product", "accountService"]); channel.clear(); const logCustomer = provider.getLogger("model.Customer"); const logCustomerService = provider.getLogger("service.CustomerService"); logCustomer.info("customer"); logCustomerService.info("customerService"); expect(channel.messages).toEqual(["customer", "customerService"]); channel.clear(); /* Change only 1 group */ provider.updateRuntimeSettingsGroup("model", {level: LogLevel.Error}); logProduct.warn("product"); logCustomer.warn("customer"); logAccountService.info("accountService"); logCustomerService.info("customerService"); expect(channel.messages).toEqual(["accountService", "customerService"]); channel.clear(); const logApple = provider.getLogger("model.amazing.Apple"); const logFruitService = provider.getLogger("service.amazing.FruitService"); logApple.warn("apple"); logApple.error("appleError"); logFruitService.debug("fruitDebug"); logFruitService.info("fruitInfo"); expect(channel.messages).toEqual(["appleError", "fruitInfo"]); }); test("Test channel can be changed dynamically", () => { const channel1 = new $test.ArrayRawLogChannel(); const channel2 = new $test.ArrayRawLogChannel(); /* Default logs to error */ const provider = Log4TSProvider.createProvider("test", { level: LogLevel.Info, channel: channel1, groups: [{ expression: new RegExp("model.+"), }, { expression: new RegExp("service.+"), identifier: "service" }], }); expect(provider.groupConfigs[0].identifier).toEqual("/model.+/"); // This is guaranteed to be set if no id was given originally. expect(provider.groupConfigs[1].identifier).toEqual("service"); const logProduct = provider.getLogger("model.Product"); const logService = provider.getLogger("service.ProductService"); logProduct.info("product"); logService.info("productService"); expect(channel1.messages).toEqual(["product", "productService"]); expect(channel2.messages).toEqual([]); channel1.clear(); channel2.clear(); /* Change channel for all */ provider.updateRuntimeSettings({channel: channel2}); logProduct.info("product"); logService.info("productService"); expect(channel2.messages).toEqual(["product", "productService"]); expect(channel1.messages).toEqual([]); channel1.clear(); channel2.clear(); const logFruit = provider.getLogger("model.Fruit"); const logFruitService = provider.getLogger("service.FruitService"); logFruit.info("fruit"); logFruitService.info("fruitService"); logProduct.info("product"); logService.info("productService"); expect(channel2.messages).toEqual(["fruit", "fruitService", "product", "productService"]); expect(channel1.messages).toEqual([]); channel1.clear(); channel2.clear(); }); /* Tests that must fail follow */ test("Test create provider config is missing group", () => { expect(() => Log4TSProvider.createProvider("test", {groups: []})) .toThrowError(new Error("Invalid configuration, 'groups' on configuration is empty, at least 1 group config must be specified.")); }); test("Test cannot create provider with same name twice", () => { Log4TSProvider.createProvider("test", { groups: [{ expression: new RegExp("model.+"), }], }); expect(() => Log4TSProvider.createProvider("test", { groups: [{ expression: new RegExp("model.+"), }], })).toThrowError(new Error("Log4TSProvider with name 'test' already exists, cannot create another.")); }); });
the_stack
import Transaction from "#SRC/js/structs/Transaction"; import Networking from "#SRC/js/constants/Networking"; import Batch from "#SRC/js/structs/Batch"; import { ADD_ITEM, SET, REMOVE_ITEM } from "#SRC/js/constants/TransactionTypes"; const { BRIDGE, HOST, CONTAINER } = Networking.type; import * as Container from "../Container"; describe("Container", () => { describe("#JSONReducer", () => { it("returns a null container as default object without docker object", () => { const batch = new Batch(); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: null, type: null, volumes: [], }); }); it("switches container name along with type", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); batch = batch.add( new Transaction(["container", "docker", "image"], "foo", SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { image: "foo", forcePullImage: null, privileged: null, }, portMappings: null, type: "DOCKER", volumes: [], }); }); it("creates new container info when there is nothing", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); batch = batch.add( new Transaction(["container", "docker", "image"], "foo", SET) ); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { image: "foo", forcePullImage: null, privileged: null, }, portMappings: null, type: "DOCKER", volumes: [], }); }); it("keeps top-level container info with type switch", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "docker", "image"], "foo", SET) ); batch = batch.add(new Transaction(["container", "type"], "MESOS", SET)); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { image: "foo", forcePullImage: null, privileged: null, }, portMappings: null, type: "MESOS", volumes: [], }); }); it("sets privileged correctly", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); batch = batch.add( new Transaction(["container", "docker", "privileged"], true, SET) ); batch = batch.add( new Transaction(["container", "docker", "image"], "foo", SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { image: "foo", privileged: true, forcePullImage: null, }, portMappings: null, type: "DOCKER", volumes: [], }); }); it("sets privileged correctly to false", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); batch = batch.add( new Transaction(["container", "docker", "image"], "foo", SET) ); batch = batch.add( new Transaction(["container", "docker", "privileged"], false, SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { image: "foo", privileged: false, forcePullImage: null, }, portMappings: null, type: "DOCKER", volumes: [], }); }); it("doesn't set privileged if path doesn't match type", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); batch = batch.add( new Transaction(["container", "docker", "image"], "foo", SET) ); batch = batch.add( new Transaction(["container", "foo", "privileged"], true, SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { image: "foo", forcePullImage: null, privileged: null, }, portMappings: null, type: "DOCKER", volumes: [], }); }); it("sets forcePullImage correctly", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); batch = batch.add( new Transaction(["container", "docker", "image"], "foo", SET) ); batch = batch.add( new Transaction(["container", "docker", "forcePullImage"], true, SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { image: "foo", forcePullImage: true, privileged: null, }, portMappings: null, type: "DOCKER", volumes: [], }); }); it("sets forcePullImage correctly to false", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); batch = batch.add( new Transaction(["container", "docker", "forcePullImage"], false, SET) ); batch = batch.add( new Transaction(["container", "docker", "image"], "foo", SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { image: "foo", forcePullImage: false, privileged: null, }, portMappings: null, type: "DOCKER", volumes: [], }); }); it("doesn't set forcePullImage if path doesn't match type", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "foo", "forcePullImage"], true, SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: null, type: null, volumes: [], }); }); it("does not remove forcePullImage when runtime is changed", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); batch = batch.add( new Transaction(["container", "docker", "forcePullImage"], true, SET) ); batch = batch.add(new Transaction(["container", "type"], "MESOS", SET)); batch = batch.add( new Transaction(["container", "docker", "image"], "foo", SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: true, image: "foo", privileged: null, }, portMappings: null, type: "MESOS", volumes: [], }); }); it("remembers forcePullImage from earlier setting", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); batch = batch.add( new Transaction(["container", "docker", "forcePullImage"], true, SET) ); batch = batch.add(new Transaction(["container", "type"], "MESOS", SET)); batch = batch.add( new Transaction(["container", "docker", "image"], "foo", SET) ); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: true, image: "foo", privileged: null, }, portMappings: null, type: "DOCKER", volumes: [], }); }); it("sets image correctly", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); batch = batch.add( new Transaction(["container", "docker", "image"], "foo", SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { image: "foo", forcePullImage: null, privileged: null, }, portMappings: null, type: "DOCKER", volumes: [], }); }); it("changes image value correctly", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "DOCKER", SET)); batch = batch.add( new Transaction(["container", "docker", "image"], "bar", SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { image: "bar", forcePullImage: null, privileged: null, }, portMappings: null, type: "DOCKER", volumes: [], }); }); it("doesn't set image if path doesn't match type", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "foo", "image"], "foo", SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: null, type: null, volumes: [], }); }); describe("PortMappings", () => { it("creates default portDefinition configurations", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("doesn't include hostPort or protocol when not enabled", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); // This is default // batch = batch.add( // new Transaction(['portDefinitions', 0, 'portMapping'], false) // ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "protocol", "udp"], true) ); batch = batch.add( new Transaction(["portDefinitions", 0, "hostPort"], 100) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: null, labels: null, name: null, protocol: null, servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("includes hostPort or protocol when not enabled for BRIDGE", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], BRIDGE, SET) ); // This is default // batch = batch.add( // new Transaction(['portDefinitions',0,'portMapping'], false) // ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "protocol", "tcp"], false) ); batch = batch.add( new Transaction(["portDefinitions", 0, "protocol", "udp"], true) ); batch = batch.add( new Transaction(["portDefinitions", 0, "automaticPort"], false) ); batch = batch.add( new Transaction(["portDefinitions", 0, "hostPort"], 100) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 100, labels: null, name: null, protocol: "udp", servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("creates default portDefinition configurations", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], BRIDGE, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("doesn't create portMappings by default", () => { let batch = new Batch(); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: null, type: null, volumes: [], }); }); it("doesn't create portMappings for HOST", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add(new Transaction(["networks", 0, "mode"], HOST, SET)); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: null, type: "DOCKER", volumes: [], }); }); it("creates two default portDefinition configurations", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 1, "portMapping"], true) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("sets the name value", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 0, "name"], "foo") ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: "foo", protocol: "tcp", servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("sets the port value", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 0, "automaticPort"], false) ); batch = batch.add( new Transaction(["portDefinitions", 0, "hostPort"], 100) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 100, labels: null, name: null, protocol: "tcp", servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("defaults port value to 0 if automaticPort", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); // This is default behavior // batch = batch.add( // new Transaction(['portDefinitions', 0, 'automaticPort'], true) // ); batch = batch.add( new Transaction(["portDefinitions", 0, "hostPort"], 100) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("sets the protocol value", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 0, "protocol", "tcp"], true) ); batch = batch.add( new Transaction(["portDefinitions", 0, "protocol", "udp"], true) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "udp,tcp", servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("adds the labels key if the portDefinition is load balanced", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 1, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 1, "loadBalanced"], true) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, { containerPort: 0, hostPort: 0, labels: { VIP_1: ":0" }, name: null, protocol: "tcp", servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("adds the index of the portDefinition to the VIP keys", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 1, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 0, "loadBalanced"], true) ); batch = batch.add( new Transaction(["portDefinitions", 1, "loadBalanced"], true) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 0, name: null, protocol: "tcp", labels: { VIP_0: ":0" }, servicePort: null, }, { containerPort: 0, hostPort: 0, name: null, protocol: "tcp", labels: { VIP_1: ":0" }, servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("adds the port to the VIP string", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 1, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 0, "automaticPort"], false) ); batch = batch.add( new Transaction(["portDefinitions", 0, "hostPort"], 300) ); batch = batch.add( new Transaction(["portDefinitions", 0, "containerPort"], 8080) ); batch = batch.add( new Transaction(["portDefinitions", 0, "loadBalanced"], true) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 8080, hostPort: 300, name: null, protocol: "tcp", labels: { VIP_0: ":8080" }, servicePort: null, }, { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("adds the app ID to the VIP string when it is defined", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 1, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 0, "automaticPort"], false) ); batch = batch.add( new Transaction(["portDefinitions", 1, "loadBalanced"], true) ); batch = batch.add(new Transaction(["id"], "foo")); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, { containerPort: 0, hostPort: 0, name: null, protocol: "tcp", labels: { VIP_1: "foo:0" }, servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("stores portDefinitions even if network is HOST when recorded", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "DOCKER", SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 1, "portMapping"], true) ); batch = batch.add( new Transaction(["portDefinitions", 0, "automaticPort"], false) ); batch = batch.add( new Transaction(["portDefinitions", 1, "loadBalanced"], true) ); batch = batch.add(new Transaction(["id"], "foo")); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ docker: { forcePullImage: null, image: "", privileged: null, }, portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, { containerPort: 0, hostPort: 0, name: null, protocol: "tcp", labels: { VIP_1: "foo:0" }, servicePort: null, }, ], type: "DOCKER", volumes: [], }); }); it("creates portMappings when container.type is MESOS", () => { let batch = new Batch(); batch = batch.add(new Transaction(["container", "type"], "MESOS", SET)); batch = batch.add( new Transaction(["networks", 0, "mode"], CONTAINER, SET) ); batch = batch.add(new Transaction(["portDefinitions"], null, ADD_ITEM)); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, ], type: "MESOS", volumes: [], }); }); describe("UCR - BRDIGE", () => { it("creates portMappings when container.type is MESOS", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "MESOS", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], BRIDGE, SET) ); batch = batch.add( new Transaction(["portDefinitions"], null, ADD_ITEM) ); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, ], type: "MESOS", volumes: [], }); }); it("includes hostPort or protocol when not enabled for BRIDGE", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "MESOS", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], BRIDGE, SET) ); // This is default // batch = batch.add( // new Transaction(['portDefinitions',0,'portMapping'], false) // ); batch = batch.add( new Transaction(["portDefinitions"], null, ADD_ITEM) ); batch = batch.add( new Transaction(["portDefinitions", 0, "protocol", "tcp"], false) ); batch = batch.add( new Transaction(["portDefinitions", 0, "protocol", "udp"], true) ); batch = batch.add( new Transaction(["portDefinitions", 0, "automaticPort"], false) ); batch = batch.add( new Transaction(["portDefinitions", 0, "hostPort"], 100) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: [ { containerPort: 0, hostPort: 100, labels: null, name: null, protocol: "udp", servicePort: null, }, ], type: "MESOS", volumes: [], }); }); it("creates default portDefinition configurations", () => { let batch = new Batch(); batch = batch.add( new Transaction(["container", "type"], "MESOS", SET) ); batch = batch.add( new Transaction(["networks", 0, "mode"], BRIDGE, SET) ); batch = batch.add( new Transaction(["portDefinitions"], null, ADD_ITEM) ); batch = batch.add( new Transaction(["portDefinitions", 0, "portMapping"], true) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: [ { containerPort: 0, hostPort: 0, labels: null, name: null, protocol: "tcp", servicePort: null, }, ], type: "MESOS", volumes: [], }); }); }); }); it("removes docker if no image is present", () => { let batch = Container.JSONParser({ container: { docker: { image: "nginx", pullConfig: { some: "value", }, }, }, }).reduce((batch, transaction) => batch.add(transaction), new Batch()); batch = batch.add( new Transaction(["container", "docker", "image"], "", SET) ); expect( batch.reduce(Container.JSONReducer.bind({}), { docker: { image: "alpine", forcePull: true, }, type: "DOCKER", }) ).toEqual({ type: "MESOS", portMappings: null, volumes: [], }); }); }); describe("#Unknown Values", () => { it("keep docker unknown values", () => { expect( Container.JSONParser({ container: { docker: { image: "nginx", pullConfig: { some: "value", }, }, }, }) .reduce((batch, transaction) => batch.add(transaction), new Batch()) .reduce(Container.JSONReducer.bind({}), {}) ).toEqual({ portMappings: null, docker: { image: "nginx", forcePullImage: null, privileged: null, pullConfig: { some: "value", }, }, type: "MESOS", volumes: [], }); }); it("keeps unknown container values", () => { let batch = new Batch(); batch = batch.add( new Transaction( ["container"], { type: "MESOS", linuxInfo: { ipcInfo: { mode: "PRIVATE", shmSize: 128 } }, }, SET ) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ type: "MESOS", linuxInfo: { ipcInfo: { mode: "PRIVATE", shmSize: 128 } }, }); }); }); describe("Volumes", () => { it("returns an empty array if no volumes are set", () => { const batch = new Batch(); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: null, type: null, volumes: [], }); }); it("returns a local volume", () => { let batch = new Batch(); batch = batch.add(new Transaction(["volumes"], null, ADD_ITEM)); batch = batch.add( new Transaction(["volumes", 0, "type"], "PERSISTENT", SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: null, type: "MESOS", volumes: [ { containerPath: null, persistent: { size: null, }, mode: "RW", }, ], }); }); it("returns an external volume", () => { let batch = new Batch(); batch = batch.add(new Transaction(["volumes"], null, ADD_ITEM)); batch = batch.add(new Transaction(["volumes", 0, "type"], "EXTERNAL")); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: null, type: "MESOS", volumes: [ { containerPath: null, external: { name: null, provider: "dvdi", options: { "dvdi/driver": "rexray", }, }, mode: "RW", }, ], }); }); it("returns a local and an external volume", () => { let batch = new Batch(); batch = batch.add(new Transaction(["volumes"], null, ADD_ITEM)); batch = batch.add( new Transaction(["volumes", 0, "type"], "PERSISTENT", SET) ); batch = batch.add(new Transaction(["volumes"], null, ADD_ITEM)); batch = batch.add( new Transaction(["volumes", 1, "type"], "EXTERNAL", SET) ); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: null, type: "MESOS", volumes: [ { containerPath: null, persistent: { size: null, }, mode: "RW", }, { containerPath: null, external: { name: null, provider: "dvdi", options: { "dvdi/driver": "rexray", }, }, mode: "RW", }, ], }); }); it("returns an empty array if all volumes have been removed", () => { let batch = new Batch(); batch = batch.add(new Transaction(["volumes"], null, ADD_ITEM)); batch = batch.add( new Transaction(["volumes", 0, "type"], "PERSISTENT", SET) ); batch = batch.add(new Transaction(["volumes"], null, ADD_ITEM)); batch = batch.add( new Transaction(["volumes", 1, "type"], "EXTERNAL", SET) ); batch = batch.add(new Transaction(["volumes"], 0, REMOVE_ITEM)); batch = batch.add(new Transaction(["volumes"], 0, REMOVE_ITEM)); expect(batch.reduce(Container.JSONReducer.bind({}), {})).toEqual({ portMappings: null, type: null, volumes: [], }); }); }); });
the_stack
import { ModelDoc } from '../component/components/doc'; import { ModelParagraph } from '../component/components/paragraph'; import { ModelText } from '../component/components/text'; import { ComponentService } from '../component/service'; import { ConfigServiceStub } from '../config/service.stub'; import { ReplaceChange } from '../model/change/replace'; import { IFragment } from '../model/fragment'; import { IModelNode } from '../model/node'; import { ModelService } from '../model/service'; import { RenderService } from '../render/service'; import { ServiceRegistry } from '../service/registry'; import { TextServiceStub } from '../text/service.stub'; import { generateId } from '../util/id'; import { LayoutService } from './service'; describe('LayoutService', () => { let configService: ConfigServiceStub; let componentService: ComponentService; let modelService: ModelService; let renderService: RenderService; let layoutService: LayoutService; beforeEach(() => { const serviceRegistry = new ServiceRegistry(); configService = new ConfigServiceStub(); serviceRegistry.registerService('config', configService); const textService = new TextServiceStub(); serviceRegistry.registerService('text', textService); componentService = new ComponentService(configService, serviceRegistry); const modelDoc = new ModelDoc('doc', 'doc', {}, [ new ModelParagraph('paragraph', 'paragraph1', {}, [new ModelText('text', 'text1', 'Hello world', {})]), new ModelParagraph('paragraph', 'paragraph2', {}, [ new ModelText('text', 'text2', 'Hello test', { weight: 700 }), ]), ]); modelService = new ModelService(modelDoc, componentService); renderService = new RenderService(componentService, modelService); layoutService = new LayoutService(renderService, textService); }); describe('when model did update', () => { describe('when no reflow', () => { beforeEach(() => { const change = new ReplaceChange( [0, 0, 0], [1, 0, 5], [ 'Hi', [], [ new ModelParagraph('paragraph', 'paragraph3', {}, [ new ModelText('text', 'text3', 'big', {}), ]), ], [], 'beautiful', ], ); modelService.applyChange(change); }); it('updates layout tree', () => { const doc = layoutService.getDoc(); const page = doc.firstChild!; const paragraph1 = page.firstChild!; const paragraph2 = paragraph1.nextSibling!; const paragraph3 = paragraph2.nextSibling!; const line1 = paragraph1.firstChild!; const line2 = paragraph2.firstChild!; const line3 = paragraph3.firstChild!; const text1 = line1.firstChild!; const lineBreak1 = text1.nextSibling!; const text2 = line2.firstChild!; const lineBreak2 = text2.nextSibling!; const text3 = line3.firstChild!; const lineBreak3 = text3.nextSibling!; const word1 = text1.firstChild!; const word2 = text2.firstChild!; const word3 = text3.firstChild!; const word4 = word3.nextSibling!; expect(lineBreak1).not.toBeNull(); expect(lineBreak2).not.toBeNull(); expect(lineBreak3).not.toBeNull(); expect(word1.text).toEqual('Hi'); expect(word2.text).toEqual('big'); expect(word3.text).toEqual('beautiful '); expect(word4.text).toEqual('test'); }); }); describe('when line reflow', () => { beforeEach(() => { // Page inner width is 700, each character width is 20, // we need at least 35 characters to trigger line reflow const change = new ReplaceChange([0, 0, 0], [0, 0, 6], ['Hello '.repeat(6)]); modelService.applyChange(change); }); it('updates layout tree', () => { const doc = layoutService.getDoc(); const page = doc.firstChild!; const paragraph1 = page.firstChild!; const paragraph2 = paragraph1.nextSibling!; const line1 = paragraph1.firstChild!; const line2 = line1.nextSibling!; const line3 = paragraph2.firstChild!; const text1 = line1.firstChild!; const text2 = line2.firstChild!; const text3 = line3.firstChild!; const lineBreak1 = text2.nextSibling!; const lineBreak2 = text3.nextSibling!; const word1 = text1.firstChild!; const word2 = word1.nextSibling!; const word3 = word2.nextSibling!; const word4 = word3.nextSibling!; const word5 = word4.nextSibling!; const word6 = text2.firstChild!; const word7 = word6.nextSibling!; const word8 = text3.firstChild!; const word9 = word8.nextSibling!; expect(lineBreak1).not.toBeNull(); expect(lineBreak2).not.toBeNull(); expect(word1.text).toEqual('Hello '); expect(word2.text).toEqual('Hello '); expect(word3.text).toEqual('Hello '); expect(word4.text).toEqual('Hello '); expect(word5.text).toEqual('Hello '); expect(word6.text).toEqual('Hello '); expect(word7.text).toEqual('world'); expect(word8.text).toEqual('Hello '); expect(word9.text).toEqual('test'); }); }); describe('when page reflow', () => { beforeEach(() => { // Page inner height is 900, each paragraph height is 181, // we need 4 more paragraphs to trigger page reflow const fragment: IFragment = ['Hello ', [], [], [], 'beautiful']; for (let n = 0; n < 4; n++) { (fragment[2] as IModelNode<any>[]).push( new ModelParagraph('paragraph', generateId(), {}, [new ModelText('text', 'text3', 'big', {})]), ); } const change = new ReplaceChange([0, 0, 0], [0, 0, 5], fragment); modelService.applyChange(change); }); it('updates layout tree', () => { const doc = layoutService.getDoc(); const page1 = doc.firstChild!; const page2 = page1.nextSibling!; const paragraph1 = page1.firstChild!; const paragraph2 = paragraph1.nextSibling!; const paragraph3 = paragraph2.nextSibling!; const paragraph4 = paragraph3.nextSibling!; const paragraph5 = page2.firstChild!; const paragraph6 = paragraph5.nextSibling!; const line1 = paragraph1.firstChild!; const line2 = paragraph2.firstChild!; const line3 = paragraph3.firstChild!; const line4 = paragraph4.firstChild!; const line5 = paragraph5.firstChild!; const line6 = paragraph6.firstChild!; const text1 = line1.firstChild!; const text2 = line2.firstChild!; const text3 = line3.firstChild!; const text4 = line4.firstChild!; const text5 = line5.firstChild!; const text6 = line6.firstChild!; const lineBreak1 = text1.nextSibling!; const lineBreak2 = text2.nextSibling!; const lineBreak3 = text3.nextSibling!; const lineBreak4 = text4.nextSibling!; const lineBreak5 = text5.nextSibling!; const lineBreak6 = text6.nextSibling!; const word1 = text1.firstChild!; const word2 = text2.firstChild!; const word3 = text3.firstChild!; const word4 = text4.firstChild!; const word5 = text5.firstChild!; const word6 = word5.nextSibling!; const word7 = text6.firstChild!; const word8 = word7.nextSibling!; expect(lineBreak1).not.toBeNull(); expect(lineBreak2).not.toBeNull(); expect(lineBreak3).not.toBeNull(); expect(lineBreak4).not.toBeNull(); expect(lineBreak5).not.toBeNull(); expect(lineBreak6).not.toBeNull(); expect(word1.text).toEqual('Hello '); expect(word2.text).toEqual('big'); expect(word3.text).toEqual('big'); expect(word4.text).toEqual('big'); expect(word5.text).toEqual('beautiful '); expect(word6.text).toEqual('world'); expect(word7.text).toEqual('Hello '); expect(word8.text).toEqual('test'); }); }); }); describe('getDoc', () => { it('returns doc', () => { const doc = layoutService.getDoc(); const page = doc.firstChild!; const paragraph1 = page.firstChild!; const paragraph2 = paragraph1.nextSibling!; const line1 = paragraph1.firstChild!; const line2 = paragraph2.firstChild!; const text1 = line1.firstChild!; const text2 = line2.firstChild!; const lineBreak1 = text1.nextSibling!; const lineBreak2 = text2.nextSibling!; const word1 = text1.firstChild!; const word2 = word1.nextSibling!; const word3 = text2.firstChild!; const word4 = word3.nextSibling!; expect(lineBreak1).not.toBeNull(); expect(lineBreak2).not.toBeNull(); expect(word1.text).toEqual('Hello '); expect(word2.text).toEqual('world'); expect(word3.text).toEqual('Hello '); expect(word4.text).toEqual('test'); }); }); });
the_stack
import React from 'react'; import createClass from 'create-react-class'; import _, { map } from 'lodash'; import { Meta, Story } from '@storybook/react'; import { Selection, SearchableMultiSelect } from './../../index'; import Resizer from '../Resizer/Resizer'; import { ISearchableMultiSelectProps } from './SearchableMultiSelect'; //👇 Provide Storybook with the component name, 'section', any subcomponents and a description export default { title: 'Controls/SearchableMultiSelect', component: SearchableMultiSelect, subcomponents: { 'SearchableMultiSelect.SelectionOption': SearchableMultiSelect.Option.Selection, 'SearchableMultiSelect.Option.Selected': SearchableMultiSelect.Option.Selected, 'SearchableMultiSelect.OptionGroup': SearchableMultiSelect.OptionGroup, 'SearchableMultiSelect.SearchFieldComponent': SearchableMultiSelect.SearchField, 'SearchableMultiSelect.Option': SearchableMultiSelect.Option, }, parameters: { docs: { description: { component: SearchableMultiSelect.peek.description, }, }, }, } as Meta; //👇 Destructure any child components that we will need const { Option } = SearchableMultiSelect; //👇 Add a key prop to each element of the array function addKeys(children: any) { return map(children, (child, index) => ({ ...child, key: index })); } /* Default */ export const Default: Story<ISearchableMultiSelectProps> = (args) => { return ( <Resizer> {(width) => { // const responsiveMode = width >= 400 ? 'large' : 'small'; return ( <SearchableMultiSelect {...args} // responsiveMode={responsiveMode} ></SearchableMultiSelect> ); }} </Resizer> ); }; Default.storyName = 'Default'; Default.args = { children: addKeys([ <Option isDisabled>Alabama</Option>, <Option>Alaska</Option>, <Option>Arizona</Option>, <Option>Arkansas</Option>, <Option>California</Option>, <Option>Colorado</Option>, <Option>Connecticut</Option>, <Option>Delaware</Option>, <Option>Florida</Option>, <Option>Georgia</Option>, <Option>Hawaii</Option>, <Option>Idaho</Option>, <Option>Illinois</Option>, <Option>Indiana</Option>, <Option>Iowa</Option>, <Option>Kansas</Option>, <Option>Kentucky</Option>, <Option>Louisiana</Option>, <Option>Maine</Option>, <Option>Maryland</Option>, <Option>Massachusetts</Option>, <Option>Michigan</Option>, <Option>Minnesota</Option>, <Option>Mississippi</Option>, <Option>Missouri</Option>, <Option>Montana Nebraska</Option>, <Option>Nevada</Option>, <Option>New Hampshire</Option>, <Option>New Jersey</Option>, <Option>New Mexico</Option>, <Option>New York</Option>, <Option>North Carolina</Option>, <Option>North Dakota</Option>, <Option>Ohio</Option>, <Option>Oklahoma</Option>, <Option>Oregon</Option>, <Option>Pennsylvania Rhode Island</Option>, <Option>South Carolina</Option>, <Option>South Dakota</Option>, <Option>Tennessee</Option>, <Option>Texas</Option>, <Option>Utah</Option>, <Option>Vermont</Option>, <Option>Virginia</Option>, <Option>Washington</Option>, <Option>West Virginia</Option>, <Option>Wisconsin</Option>, <Option>Wyoming</Option>, ]), }; /* Props */ export const Props: Story<ISearchableMultiSelectProps> = (args) => { const { Option } = SearchableMultiSelect; const Component = createClass({ getInitialState() { return { isRequired: false, }; }, handleChange(event: any) { this.setState({ isRequired: event.length > 0, }); }, render() { return ( <Resizer> {(width) => { const responsiveMode = width >= 768 ? 'large' : 'small'; return ( <section> <h5>Loading</h5> <SearchableMultiSelect {...args} responsiveMode={responsiveMode} isLoading={true} > <Option>Alabama</Option> </SearchableMultiSelect> <h5>Disabled</h5> <SearchableMultiSelect {...args} responsiveMode={responsiveMode} isDisabled={true} > <Option>Alabama</Option> </SearchableMultiSelect> <h5>Custom option selections</h5> <SearchableMultiSelect {...args} responsiveMode={responsiveMode} selectedIndices={[0, 1, 2, 3]} > <Option Selection={{ kind: 'warning' }}>Washington</Option> <Option Selection={{ kind: 'success' }}>Oregon</Option> <Option Selection={{ kind: 'danger' }}>California</Option> <Option Selection={{ kind: 'container' }}>Nevada</Option> </SearchableMultiSelect> <h5>No remove all option</h5> <SearchableMultiSelect {...args} responsiveMode={responsiveMode} hasRemoveAll={false} initialState={{ selectedIndices: [0, 1, 2], }} > <Option>Washington</Option> <Option>Oregon</Option> <Option>California</Option> </SearchableMultiSelect> </section> ); }} </Resizer> ); }, }); return <Component />; }; Props.storyName = 'Props'; /* Asynchronous */ export const Asynchronous: Story<ISearchableMultiSelectProps> = (args) => { const { Option } = SearchableMultiSelect; const allData: any = { 100: { name: 'Rita Daniel' }, 101: { name: 'Meghan Mcgowan' }, 102: { name: 'Latisha Kent' }, 103: { name: 'Jeannine Horton' }, 104: { name: 'Noreen Joyner' }, 105: { name: 'Angelique Head' }, 106: { name: 'Kim Salinas' }, 107: { name: 'Alexis Small' }, 108: { name: 'Fernandez Singleton' }, 109: { name: 'Jacqueline Alvarado' }, 110: { name: 'Cornelia Roman' }, 111: { name: 'John Gonzales' }, 112: { name: 'Mcleod Hodge' }, 113: { name: 'Fry Barrera' }, 114: { name: 'Jannie Compton' }, 115: { name: 'June Odom' }, 116: { name: 'Rose Foster' }, 117: { name: 'Kathryn Prince' }, 118: { name: 'Hebert Bowman' }, 119: { name: 'Shawn Burgess' }, }; const Component = createClass({ getInitialState() { return { selectedIds: [], // aka our full set of selections regardless of currently search visibleIds: [], // aka current search results isLoading: false, }; }, componentDidMount() { this.handleSearch(''); }, handleSearch(searchText: string) { this.setState({ isLoading: true }); // Fake an API call setTimeout(() => { const visibleIds = _.reduce( allData, (acc: any[], { name }: { name: string }, id: string) => { return _.includes(name.toLowerCase(), searchText.toLowerCase()) ? acc.concat(id) : acc; }, [] ); this.setState({ visibleIds, isLoading: false, }); }, 750); }, handleRemove({ props: { callbackId }, }: { props: { callbackId: string; }; }) { this.setState({ selectedIds: _.without(this.state.selectedIds, callbackId), }); }, handleSelect( index: number, { props: { callbackId }, }: { props: { callbackId: string; }; } ) { this.setState({ selectedIds: _.xor(this.state.selectedIds, [callbackId]), }); }, render() { const { isLoading, visibleIds, selectedIds } = this.state; // Calculate selected indices based on selected ids const selectedIndices = _.reduce( visibleIds, (acc: any[], id: string, index: number) => { return _.includes(selectedIds, id) ? acc.concat(index) : acc; }, [] ); return ( <section> <SearchableMultiSelect {...args} hasSelections={false} isLoading={isLoading} onSelect={this.handleSelect} onSearch={this.handleSearch} selectedIndices={selectedIndices} optionFilter={_.constant(true)} SearchField={{ placeholder: 'Type here to simulate an API backed search', }} > {_.map(visibleIds, (id) => ( <Option key={id} callbackId={id}> {allData[id].name} </Option> ))} </SearchableMultiSelect> {!_.isEmpty(selectedIds) ? ( <Selection isBold hasBackground Label='Selected' kind='container' isRemovable={false} > {_.map(selectedIds, (id) => ( <Selection key={id} Label={allData[id].name} callbackId={id} onRemove={this.handleRemove} /> ))} </Selection> ) : null} </section> ); }, }); return <Component />; }; Asynchronous.storyName = 'Asynchronous'; Asynchronous.args = { ...Default.args, }; /* Grouped Options */ export const GroupedOptions: Story<ISearchableMultiSelectProps> = (args) => { const { Option, OptionGroup } = SearchableMultiSelect; const Component = createClass({ render() { return ( <SearchableMultiSelect {...args} hasSelectAll initialState={{ selectedIndices: [0, 1, 2, 3, 11, 12, 48, 49], }} > <OptionGroup> Northeast <Option>Connecticut</Option> <Option>Delaware</Option> <Option>Maine</Option> <Option>Maryland</Option> <Option>Massachusetts</Option> <Option>New Hampshire</Option> <Option>New Jersey</Option> <Option>New York</Option> <Option>Pennsylvania</Option> <Option>Rhode Island</Option> <Option>Vermont</Option> </OptionGroup> <OptionGroup> Southeast <Option>Alabama</Option> <Option>Arkansas</Option> <Option>Florida</Option> <Option>Georgia</Option> <Option>Kentucky</Option> <Option>Louisiana</Option> <Option>Mississippi</Option> <Option>North Carolina</Option> <Option>South Carolina</Option> <Option>Tennessee</Option> <Option>Virginia</Option> <Option>West Virginia</Option> </OptionGroup> <OptionGroup> Midwest <Option>Illinois</Option> <Option>Indiana</Option> <Option>Iowa</Option> <Option>Kansas</Option> <Option>Michigan</Option> <Option>Minnesota</Option> <Option>Missouri</Option> <Option>Nebraska</Option> <Option>North Dakota</Option> <Option>Ohio</Option> <Option>South Dakota</Option> <Option>Wisconsin</Option> </OptionGroup> <OptionGroup> Southwest <Option>Arizona</Option> <Option>New Mexico</Option> <Option>Oklahoma</Option> <Option>Texas</Option> </OptionGroup> <OptionGroup> West <Option>California</Option> <Option>Colorado</Option> <Option>Idaho</Option> <Option>Montana</Option> <Option>Nevada</Option> <Option>Oregon</Option> <Option>Utah</Option> <Option>Washington</Option> <Option>Wyoming</Option> </OptionGroup> <Option>Alaska</Option> <Option>Hawaii</Option> </SearchableMultiSelect> ); }, }); return <Component />; }; GroupedOptions.storyName = 'GroupedOptions'; /* Custom Selection Label */ export const CustomSelectionLabel: Story<ISearchableMultiSelectProps> = ( args ) => { const { Option, SelectionLabel } = SearchableMultiSelect; const Component = createClass({ render() { return ( <SearchableMultiSelect {...args}> <SelectionLabel>Selected States</SelectionLabel> <Option>Alabama</Option> <Option>Alaska</Option> <Option>Arizona</Option> <Option>Arkansas</Option> <Option>California</Option> <Option>Colorado</Option> <Option>Connecticut</Option> <Option>Delaware</Option> <Option>Florida</Option> <Option>Georgia</Option> <Option>Hawaii</Option> <Option>Idaho</Option> <Option>Illinois</Option> <Option>Indiana</Option> <Option>Iowa</Option> <Option>Kansas</Option> <Option>Kentucky</Option> <Option>Louisiana</Option> <Option>Maine</Option> <Option>Maryland</Option> <Option>Massachusetts</Option> <Option>Michigan</Option> <Option>Minnesota</Option> <Option>Mississippi</Option> <Option>Missouri</Option> <Option>Montana Nebraska</Option> <Option>Nevada</Option> <Option>New Hampshire</Option> <Option>New Jersey</Option> <Option>New Mexico</Option> <Option>New York</Option> <Option>North Carolina</Option> <Option>North Dakota</Option> <Option>Ohio</Option> <Option>Oklahoma</Option> <Option>Oregon</Option> <Option>Pennsylvania Rhode Island</Option> <Option>South Carolina</Option> <Option>South Dakota</Option> <Option>Tennessee</Option> <Option>Texas</Option> <Option>Utah</Option> <Option>Vermont</Option> <Option>Virginia</Option> <Option>Washington</Option> <Option>West Virginia</Option> <Option>Wisconsin</Option> <Option>Wyoming</Option> </SearchableMultiSelect> ); }, }); return <Component />; }; CustomSelectionLabel.storyName = 'CustomSelectionLabel'; /* Select All */ export const SelectAll: Story<ISearchableMultiSelectProps> = (args) => { const { Option } = SearchableMultiSelect; const Component = createClass({ render() { return ( <section style={{ marginBottom: '300px' }}> <Resizer> {(width) => { const responsiveMode = width >= 768 ? 'large' : 'small'; return ( <SearchableMultiSelect {...args} hasSelectAll selectAllText='Custom Select All Text' responsiveMode={responsiveMode} > <Option>Alabama</Option> <Option>Alaska</Option> <Option>Arizona</Option> <Option>Arkansas</Option> <Option>California</Option> <Option>Colorado</Option> <Option>Connecticut</Option> <Option>Delaware</Option> <Option>Florida</Option> <Option>Georgia</Option> <Option>Hawaii</Option> <Option>Idaho</Option> <Option>Illinois</Option> <Option>Indiana</Option> <Option>Iowa</Option> <Option>Kansas</Option> <Option>Kentucky</Option> <Option>Louisiana</Option> <Option>Maine</Option> <Option>Maryland</Option> <Option>Massachusetts</Option> <Option>Michigan</Option> <Option>Minnesota</Option> <Option>Mississippi</Option> <Option>Missouri</Option> <Option>Montana Nebraska</Option> <Option>Nevada</Option> <Option>New Hampshire</Option> <Option>New Jersey</Option> <Option>New Mexico</Option> <Option>New York</Option> <Option>North Carolina</Option> <Option>North Dakota</Option> <Option>Ohio</Option> <Option>Oklahoma</Option> <Option>Oregon</Option> <Option>Pennsylvania Rhode Island</Option> <Option>South Carolina</Option> <Option>South Dakota</Option> <Option>Tennessee</Option> <Option>Texas</Option> <Option>Utah</Option> <Option>Vermont</Option> <Option>Virginia</Option> <Option>Washington</Option> <Option>West Virginia</Option> <Option>Wisconsin</Option> <Option>Wyoming</Option> </SearchableMultiSelect> ); }} </Resizer> </section> ); }, }); return <Component />; }; SelectAll.storyName = 'SelectAll'; /* Formatted Options */ export const FormattedOptions: Story<ISearchableMultiSelectProps> = (args) => { // eslint-disable-next-line react/prop-types interface Props extends React.HTMLProps<HTMLParagraphElement> { match?: any; } function P({ children, ...rest }: Props) { return <p {...rest}>{children}</p>; } const OptionCols: any = ({ col1, col2, textMatch, }: { col1: string; col2: string; textMatch: string; }) => ( <div style={{ display: 'flex' }}> <div style={{ width: 100 }}> <P match={textMatch}>{col1}</P> </div> <div> <P match={textMatch}>{col2}</P> </div> </div> ); const optionFilter = ( searchText: string, { filterText, }: { filterText: string; } ) => { if (filterText) { return new RegExp(_.escapeRegExp(searchText), 'i').test(filterText); } return true; }; class Component extends React.Component { render() { return ( <SearchableMultiSelect {...args} optionFilter={optionFilter}> <SearchableMultiSelect.OptionGroup Selected=''> <div style={{ marginLeft: 27 }}> <OptionCols col1='ID' col2='NAME' /> </div> <SearchableMultiSelect.Option filterText='Foo' Selected='Foo (1234)' > {({ searchText }: { searchText: string }) => ( <OptionCols col1='1234' col2='Foo' textMatch={searchText} /> )} </SearchableMultiSelect.Option> <SearchableMultiSelect.Option filterText='Bar' Selected='Bar (2345)' > {({ searchText }: { searchText: string }) => ( <OptionCols col1='2345' col2='Bar' textMatch={searchText} /> )} </SearchableMultiSelect.Option> <SearchableMultiSelect.Option filterText='Baz' Selected='Baz (3456)' > {({ searchText }: { searchText: string }) => ( <OptionCols col1='3456' col2='Baz' textMatch={searchText} /> )} </SearchableMultiSelect.Option> </SearchableMultiSelect.OptionGroup> </SearchableMultiSelect> ); } } return <Component />; }; FormattedOptions.storyName = 'FormattedOptions'; FormattedOptions.args = { ...Default.args, }; /* Invalid */ export const Invalid: Story<ISearchableMultiSelectProps> = (args) => { const { Option } = SearchableMultiSelect; const Component = createClass({ getInitialState() { return { selectedLength: 0, }; }, handleChange(option: string, event: any) { let count = this.state.selectedLength; if (typeof event.props.children === 'string') { count--; } else { event.props.children.props.isSelected ? count-- : count++; } this.setState({ selectedLength: count, }); }, handleRemoveAll(option: string, event: any) { this.setState({ selectedLength: 0, }); }, render() { return ( <Resizer> {(width) => { const responsiveMode = width >= 400 ? 'large' : 'small'; return ( <SearchableMultiSelect {...args} responsiveMode={responsiveMode} onRemoveAll={this.handleRemoveAll} onSelect={this.handleChange} Error={ this.state.selectedLength > 1 ? null : 'Please select at least two options' } > <Option>Alabama</Option> <Option>Alaska</Option> <Option>Arizona</Option> <Option>Arkansas</Option> <Option>California</Option> <Option>Colorado</Option> <Option>Connecticut</Option> <Option>Delaware</Option> <Option>Florida</Option> <Option>Georgia</Option> <Option>Hawaii</Option> <Option>Idaho</Option> <Option>Illinois</Option> <Option>Indiana</Option> <Option>Iowa</Option> <Option>Kansas</Option> <Option>Kentucky</Option> <Option>Louisiana</Option> <Option>Maine</Option> <Option>Maryland</Option> <Option>Massachusetts</Option> <Option>Michigan</Option> <Option>Minnesota</Option> <Option>Mississippi</Option> <Option>Missouri</Option> <Option>Montana Nebraska</Option> <Option>Nevada</Option> <Option>New Hampshire</Option> <Option>New Jersey</Option> <Option>New Mexico</Option> <Option>New York</Option> <Option>North Carolina</Option> <Option>North Dakota</Option> <Option>Ohio</Option> <Option>Oklahoma</Option> <Option>Oregon</Option> <Option>Pennsylvania Rhode Island</Option> <Option>South Carolina</Option> <Option>South Dakota</Option> <Option>Tennessee</Option> <Option>Texas</Option> <Option>Utah</Option> <Option>Vermont</Option> <Option>Virginia</Option> <Option>Washington</Option> <Option>West Virginia</Option> <Option>Wisconsin</Option> <Option>Wyoming</Option> </SearchableMultiSelect> ); }} </Resizer> ); }, }); return <Component />; }; Invalid.storyName = 'Invalid';
the_stack
import { Context } from './context/context' import { getAttribute, nodeIs } from './utils/node' import { toPixels } from './utils/misc' import { parseColor, parseFloats } from './utils/parsing' import FontFamily from 'font-family-papandreou' import { SvgNode } from './nodes/svgnode' import { combineFontStyleAndFontWeight, findFirstAvailableFontFamily, fontAliases } from './utils/fonts' import { parseFill } from './fill/parseFill' import { ColorFill } from './fill/ColorFill' import { GState } from 'jspdf' import { RGBColor } from './utils/rgbcolor' export function parseAttributes(context: Context, svgNode: SvgNode, node?: Element): void { const domNode = node || svgNode.element // update color first so currentColor becomes available for this node const color = getAttribute(domNode, context.styleSheets, 'color') if (color) { const fillColor = parseColor(color, context.attributeState.color) if (fillColor.ok) { context.attributeState.color = fillColor } else { // invalid color passed, reset to black context.attributeState.color = new RGBColor('rgb(0,0,0)') } } const visibility = getAttribute(domNode, context.styleSheets, 'visibility') if (visibility) { context.attributeState.visibility = visibility } // fill mode const fill = getAttribute(domNode, context.styleSheets, 'fill') if (fill) { context.attributeState.fill = parseFill(fill, context) } // opacity is realized via a pdf graphics state const fillOpacity = getAttribute(domNode, context.styleSheets, 'fill-opacity') if (fillOpacity) { context.attributeState.fillOpacity = parseFloat(fillOpacity) } const strokeOpacity = getAttribute(domNode, context.styleSheets, 'stroke-opacity') if (strokeOpacity) { context.attributeState.strokeOpacity = parseFloat(strokeOpacity) } const opacity = getAttribute(domNode, context.styleSheets, 'opacity') if (opacity) { context.attributeState.opacity = parseFloat(opacity) } // stroke mode const strokeWidth = getAttribute(domNode, context.styleSheets, 'stroke-width') if (strokeWidth !== void 0 && strokeWidth !== '') { context.attributeState.strokeWidth = Math.abs(parseFloat(strokeWidth)) } const stroke = getAttribute(domNode, context.styleSheets, 'stroke') if (stroke) { if (stroke === 'none') { context.attributeState.stroke = null } else { // gradients, patterns not supported for strokes ... const strokeRGB = parseColor(stroke, context.attributeState.color) if (strokeRGB.ok) { context.attributeState.stroke = new ColorFill(strokeRGB) } } } const lineCap = getAttribute(domNode, context.styleSheets, 'stroke-linecap') if (lineCap) { context.attributeState.strokeLinecap = lineCap } const lineJoin = getAttribute(domNode, context.styleSheets, 'stroke-linejoin') if (lineJoin) { context.attributeState.strokeLinejoin = lineJoin } const dashArray = getAttribute(domNode, context.styleSheets, 'stroke-dasharray') if (dashArray) { const dashOffset = parseInt( getAttribute(domNode, context.styleSheets, 'stroke-dashoffset') || '0' ) context.attributeState.strokeDasharray = parseFloats(dashArray) context.attributeState.strokeDashoffset = dashOffset } const miterLimit = getAttribute(domNode, context.styleSheets, 'stroke-miterlimit') if (miterLimit !== void 0 && miterLimit !== '') { context.attributeState.strokeMiterlimit = parseFloat(miterLimit) } const xmlSpace = domNode.getAttribute('xml:space') if (xmlSpace) { context.attributeState.xmlSpace = xmlSpace } const fontWeight = getAttribute(domNode, context.styleSheets, 'font-weight') if (fontWeight) { context.attributeState.fontWeight = fontWeight } const fontStyle = getAttribute(domNode, context.styleSheets, 'font-style') if (fontStyle) { context.attributeState.fontStyle = fontStyle } const fontFamily = getAttribute(domNode, context.styleSheets, 'font-family') if (fontFamily) { const fontFamilies = FontFamily.parse(fontFamily) context.attributeState.fontFamily = findFirstAvailableFontFamily( context.attributeState, fontFamilies, context ) } const fontSize = getAttribute(domNode, context.styleSheets, 'font-size') if (fontSize) { const pdfFontSize = context.pdf.getFontSize() context.attributeState.fontSize = toPixels(fontSize, pdfFontSize) } const alignmentBaseline = getAttribute(domNode, context.styleSheets, 'vertical-align') || getAttribute(domNode, context.styleSheets, 'alignment-baseline') if (alignmentBaseline) { const matchArr = alignmentBaseline.match( /(baseline|text-bottom|alphabetic|ideographic|middle|central|mathematical|text-top|bottom|center|top|hanging)/ ) if (matchArr) { context.attributeState.alignmentBaseline = matchArr[0] } } const textAnchor = getAttribute(domNode, context.styleSheets, 'text-anchor') if (textAnchor) { context.attributeState.textAnchor = textAnchor } } export function applyAttributes( childContext: Context, parentContext: Context, node: Element ): void { let fillOpacity = 1.0, strokeOpacity = 1.0 fillOpacity *= childContext.attributeState.fillOpacity fillOpacity *= childContext.attributeState.opacity if ( childContext.attributeState.fill instanceof ColorFill && typeof childContext.attributeState.fill.color.a !== 'undefined' ) { fillOpacity *= childContext.attributeState.fill.color.a } strokeOpacity *= childContext.attributeState.strokeOpacity strokeOpacity *= childContext.attributeState.opacity if ( childContext.attributeState.stroke instanceof ColorFill && typeof childContext.attributeState.stroke.color.a !== 'undefined' ) { strokeOpacity *= childContext.attributeState.stroke.color.a } let hasFillOpacity = fillOpacity < 1.0 let hasStrokeOpacity = strokeOpacity < 1.0 // This is a workaround for symbols that are used multiple times with different // fill/stroke attributes. All paths within symbols are both filled and stroked // and we set the fill/stroke to transparent if the use element has // fill/stroke="none". if (nodeIs(node, 'use')) { hasFillOpacity = true hasStrokeOpacity = true fillOpacity *= childContext.attributeState.fill ? 1 : 0 strokeOpacity *= childContext.attributeState.stroke ? 1 : 0 } else if (childContext.withinUse) { if (childContext.attributeState.fill !== parentContext.attributeState.fill) { hasFillOpacity = true fillOpacity *= childContext.attributeState.fill ? 1 : 0 } else if (hasFillOpacity && !childContext.attributeState.fill) { fillOpacity = 0 } if (childContext.attributeState.stroke !== parentContext.attributeState.stroke) { hasStrokeOpacity = true strokeOpacity *= childContext.attributeState.stroke ? 1 : 0 } else if (hasStrokeOpacity && !childContext.attributeState.stroke) { strokeOpacity = 0 } } if (hasFillOpacity || hasStrokeOpacity) { const gState: GState = {} hasFillOpacity && (gState['opacity'] = fillOpacity) hasStrokeOpacity && (gState['stroke-opacity'] = strokeOpacity) childContext.pdf.setGState(new GState(gState)) } if ( childContext.attributeState.fill && childContext.attributeState.fill !== parentContext.attributeState.fill && childContext.attributeState.fill instanceof ColorFill && childContext.attributeState.fill.color.ok && !nodeIs(node, 'text') ) { // text fill color will be applied through setTextColor() childContext.pdf.setFillColor( childContext.attributeState.fill.color.r, childContext.attributeState.fill.color.g, childContext.attributeState.fill.color.b ) } if (childContext.attributeState.strokeWidth !== parentContext.attributeState.strokeWidth) { childContext.pdf.setLineWidth(childContext.attributeState.strokeWidth) } if ( childContext.attributeState.stroke !== parentContext.attributeState.stroke && childContext.attributeState.stroke instanceof ColorFill ) { childContext.pdf.setDrawColor( childContext.attributeState.stroke.color.r, childContext.attributeState.stroke.color.g, childContext.attributeState.stroke.color.b ) } if (childContext.attributeState.strokeLinecap !== parentContext.attributeState.strokeLinecap) { childContext.pdf.setLineCap(childContext.attributeState.strokeLinecap) } if (childContext.attributeState.strokeLinejoin !== parentContext.attributeState.strokeLinejoin) { childContext.pdf.setLineJoin(childContext.attributeState.strokeLinejoin) } if ( (childContext.attributeState.strokeDasharray !== parentContext.attributeState.strokeDasharray || childContext.attributeState.strokeDashoffset !== parentContext.attributeState.strokeDashoffset) && childContext.attributeState.strokeDasharray ) { childContext.pdf.setLineDashPattern( childContext.attributeState.strokeDasharray, childContext.attributeState.strokeDashoffset ) } if ( childContext.attributeState.strokeMiterlimit !== parentContext.attributeState.strokeMiterlimit ) { childContext.pdf.setLineMiterLimit(childContext.attributeState.strokeMiterlimit) } let font: string | undefined if (childContext.attributeState.fontFamily !== parentContext.attributeState.fontFamily) { if (fontAliases.hasOwnProperty(childContext.attributeState.fontFamily)) { font = fontAliases[childContext.attributeState.fontFamily] } else { font = childContext.attributeState.fontFamily } } if ( childContext.attributeState.fill && childContext.attributeState.fill !== parentContext.attributeState.fill && childContext.attributeState.fill instanceof ColorFill && childContext.attributeState.fill.color.ok ) { const fillColor = childContext.attributeState.fill.color childContext.pdf.setTextColor(fillColor.r, fillColor.g, fillColor.b) } let fontStyle: string | undefined if ( childContext.attributeState.fontWeight !== parentContext.attributeState.fontWeight || childContext.attributeState.fontStyle !== parentContext.attributeState.fontStyle ) { fontStyle = combineFontStyleAndFontWeight( childContext.attributeState.fontStyle, childContext.attributeState.fontWeight ) } if (font !== undefined || fontStyle !== undefined) { if (font === undefined) { if (fontAliases.hasOwnProperty(childContext.attributeState.fontFamily)) { font = fontAliases[childContext.attributeState.fontFamily] } else { font = childContext.attributeState.fontFamily } } childContext.pdf.setFont(font, fontStyle) } if (childContext.attributeState.fontSize !== parentContext.attributeState.fontSize) { // correct for a jsPDF-instance measurement unit that differs from `pt` childContext.pdf.setFontSize( childContext.attributeState.fontSize * childContext.pdf.internal.scaleFactor ) } } export function applyContext(context: Context): void { const { attributeState, pdf } = context let fillOpacity = 1.0, strokeOpacity = 1.0 fillOpacity *= attributeState.fillOpacity fillOpacity *= attributeState.opacity if ( attributeState.fill instanceof ColorFill && typeof attributeState.fill.color.a !== 'undefined' ) { fillOpacity *= attributeState.fill.color.a } strokeOpacity *= attributeState.strokeOpacity strokeOpacity *= attributeState.opacity if ( attributeState.stroke instanceof ColorFill && typeof attributeState.stroke.color.a !== 'undefined' ) { strokeOpacity *= attributeState.stroke.color.a } const gState: GState = {} gState['opacity'] = fillOpacity gState['stroke-opacity'] = strokeOpacity pdf.setGState(new GState(gState)) if ( attributeState.fill && attributeState.fill instanceof ColorFill && attributeState.fill.color.ok ) { // text fill color will be applied through setTextColor() pdf.setFillColor( attributeState.fill.color.r, attributeState.fill.color.g, attributeState.fill.color.b ) } else { pdf.setFillColor(0, 0, 0) } pdf.setLineWidth(attributeState.strokeWidth) if (attributeState.stroke instanceof ColorFill) { pdf.setDrawColor( attributeState.stroke.color.r, attributeState.stroke.color.g, attributeState.stroke.color.b ) } else { pdf.setDrawColor(0, 0, 0) } pdf.setLineCap(attributeState.strokeLinecap) pdf.setLineJoin(attributeState.strokeLinejoin) if (attributeState.strokeDasharray) { pdf.setLineDashPattern(attributeState.strokeDasharray, attributeState.strokeDashoffset) } else { pdf.setLineDashPattern([], 0) } pdf.setLineMiterLimit(attributeState.strokeMiterlimit) let font: string | undefined if (fontAliases.hasOwnProperty(attributeState.fontFamily)) { font = fontAliases[attributeState.fontFamily] } else { font = attributeState.fontFamily } if ( attributeState.fill && attributeState.fill instanceof ColorFill && attributeState.fill.color.ok ) { const fillColor = attributeState.fill.color pdf.setTextColor(fillColor.r, fillColor.g, fillColor.b) } else { pdf.setTextColor(0, 0, 0) } let fontStyle: string | undefined = '' if (attributeState.fontWeight === 'bold') { fontStyle = 'bold' } if (attributeState.fontStyle === 'italic') { fontStyle += 'italic' } if (fontStyle === '') { fontStyle = 'normal' } if (font !== undefined || fontStyle !== undefined) { if (font === undefined) { if (fontAliases.hasOwnProperty(attributeState.fontFamily)) { font = fontAliases[attributeState.fontFamily] } else { font = attributeState.fontFamily } } pdf.setFont(font, fontStyle) } else { pdf.setFont('helvetica', fontStyle) } // correct for a jsPDF-instance measurement unit that differs from `pt` pdf.setFontSize(attributeState.fontSize * pdf.internal.scaleFactor) }
the_stack
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export const CloudError = CloudErrorMapper; export const BaseResource = BaseResourceMapper; export const Sku: msRest.CompositeMapper = { serializedName: "Sku", type: { name: "Composite", className: "Sku", modelProperties: { name: { required: true, serializedName: "name", type: { name: "String" } }, capacity: { serializedName: "capacity", type: { name: "Number" } } } } }; export const PrivateEndpoint: msRest.CompositeMapper = { serializedName: "PrivateEndpoint", type: { name: "Composite", className: "PrivateEndpoint", modelProperties: { id: { readOnly: true, serializedName: "id", type: { name: "String" } } } } }; export const PrivateLinkServiceConnectionState: msRest.CompositeMapper = { serializedName: "PrivateLinkServiceConnectionState", type: { name: "Composite", className: "PrivateLinkServiceConnectionState", modelProperties: { status: { serializedName: "status", type: { name: "String" } }, description: { serializedName: "description", type: { name: "String" } }, actionsRequired: { serializedName: "actionsRequired", type: { name: "String" } } } } }; export const Resource: msRest.CompositeMapper = { serializedName: "Resource", type: { name: "Composite", className: "Resource", modelProperties: { id: { readOnly: true, serializedName: "id", type: { name: "String" } }, name: { readOnly: true, serializedName: "name", type: { name: "String" } }, type: { readOnly: true, serializedName: "type", type: { name: "String" } } } } }; export const PrivateEndpointConnection: msRest.CompositeMapper = { serializedName: "PrivateEndpointConnection", type: { name: "Composite", className: "PrivateEndpointConnection", modelProperties: { ...Resource.type.modelProperties, privateEndpoint: { serializedName: "properties.privateEndpoint", type: { name: "Composite", className: "PrivateEndpoint" } }, privateLinkServiceConnectionState: { required: true, serializedName: "properties.privateLinkServiceConnectionState", type: { name: "Composite", className: "PrivateLinkServiceConnectionState" } }, provisioningState: { serializedName: "properties.provisioningState", type: { name: "String" } } } } }; export const TrackedResource: msRest.CompositeMapper = { serializedName: "TrackedResource", type: { name: "Composite", className: "TrackedResource", modelProperties: { ...Resource.type.modelProperties, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, location: { required: true, serializedName: "location", type: { name: "String" } } } } }; export const Cluster: msRest.CompositeMapper = { serializedName: "Cluster", type: { name: "Composite", className: "Cluster", modelProperties: { ...TrackedResource.type.modelProperties, sku: { required: true, serializedName: "sku", type: { name: "Composite", className: "Sku" } }, zones: { serializedName: "zones", type: { name: "Sequence", element: { type: { name: "String" } } } }, minimumTlsVersion: { serializedName: "properties.minimumTlsVersion", type: { name: "String" } }, hostName: { readOnly: true, serializedName: "properties.hostName", type: { name: "String" } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, resourceState: { readOnly: true, serializedName: "properties.resourceState", type: { name: "String" } }, redisVersion: { readOnly: true, serializedName: "properties.redisVersion", type: { name: "String" } }, privateEndpointConnections: { readOnly: true, serializedName: "properties.privateEndpointConnections", type: { name: "Sequence", element: { type: { name: "Composite", className: "PrivateEndpointConnection" } } } } } } }; export const ClusterUpdate: msRest.CompositeMapper = { serializedName: "ClusterUpdate", type: { name: "Composite", className: "ClusterUpdate", modelProperties: { sku: { serializedName: "sku", type: { name: "Composite", className: "Sku" } }, minimumTlsVersion: { serializedName: "properties.minimumTlsVersion", type: { name: "String" } }, hostName: { readOnly: true, serializedName: "properties.hostName", type: { name: "String" } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, resourceState: { readOnly: true, serializedName: "properties.resourceState", type: { name: "String" } }, redisVersion: { readOnly: true, serializedName: "properties.redisVersion", type: { name: "String" } }, privateEndpointConnections: { readOnly: true, serializedName: "properties.privateEndpointConnections", type: { name: "Sequence", element: { type: { name: "Composite", className: "PrivateEndpointConnection" } } } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; export const Persistence: msRest.CompositeMapper = { serializedName: "Persistence", type: { name: "Composite", className: "Persistence", modelProperties: { aofEnabled: { serializedName: "aofEnabled", type: { name: "Boolean" } }, rdbEnabled: { serializedName: "rdbEnabled", type: { name: "Boolean" } }, aofFrequency: { serializedName: "aofFrequency", type: { name: "String" } }, rdbFrequency: { serializedName: "rdbFrequency", type: { name: "String" } } } } }; export const Module: msRest.CompositeMapper = { serializedName: "Module", type: { name: "Composite", className: "Module", modelProperties: { name: { required: true, serializedName: "name", type: { name: "String" } }, args: { serializedName: "args", type: { name: "String" } }, version: { readOnly: true, serializedName: "version", type: { name: "String" } } } } }; export const ProxyResource: msRest.CompositeMapper = { serializedName: "ProxyResource", type: { name: "Composite", className: "ProxyResource", modelProperties: { ...Resource.type.modelProperties } } }; export const Database: msRest.CompositeMapper = { serializedName: "Database", type: { name: "Composite", className: "Database", modelProperties: { ...ProxyResource.type.modelProperties, clientProtocol: { serializedName: "properties.clientProtocol", type: { name: "String" } }, port: { serializedName: "properties.port", type: { name: "Number" } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, resourceState: { readOnly: true, serializedName: "properties.resourceState", type: { name: "String" } }, clusteringPolicy: { serializedName: "properties.clusteringPolicy", type: { name: "String" } }, evictionPolicy: { serializedName: "properties.evictionPolicy", type: { name: "String" } }, persistence: { serializedName: "properties.persistence", type: { name: "Composite", className: "Persistence" } }, modules: { serializedName: "properties.modules", type: { name: "Sequence", element: { type: { name: "Composite", className: "Module" } } } } } } }; export const DatabaseUpdate: msRest.CompositeMapper = { serializedName: "DatabaseUpdate", type: { name: "Composite", className: "DatabaseUpdate", modelProperties: { clientProtocol: { serializedName: "properties.clientProtocol", type: { name: "String" } }, port: { serializedName: "properties.port", type: { name: "Number" } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, resourceState: { readOnly: true, serializedName: "properties.resourceState", type: { name: "String" } }, clusteringPolicy: { serializedName: "properties.clusteringPolicy", type: { name: "String" } }, evictionPolicy: { serializedName: "properties.evictionPolicy", type: { name: "String" } }, persistence: { serializedName: "properties.persistence", type: { name: "Composite", className: "Persistence" } }, modules: { serializedName: "properties.modules", type: { name: "Sequence", element: { type: { name: "Composite", className: "Module" } } } } } } }; export const AccessKeys: msRest.CompositeMapper = { serializedName: "AccessKeys", type: { name: "Composite", className: "AccessKeys", modelProperties: { primaryKey: { readOnly: true, serializedName: "primaryKey", type: { name: "String" } }, secondaryKey: { readOnly: true, serializedName: "secondaryKey", type: { name: "String" } } } } }; export const RegenerateKeyParameters: msRest.CompositeMapper = { serializedName: "RegenerateKeyParameters", type: { name: "Composite", className: "RegenerateKeyParameters", modelProperties: { keyType: { required: true, serializedName: "keyType", type: { name: "Enum", allowedValues: [ "Primary", "Secondary" ] } } } } }; export const ImportClusterParameters: msRest.CompositeMapper = { serializedName: "ImportClusterParameters", type: { name: "Composite", className: "ImportClusterParameters", modelProperties: { sasUri: { required: true, serializedName: "sasUri", type: { name: "String" } } } } }; export const ExportClusterParameters: msRest.CompositeMapper = { serializedName: "ExportClusterParameters", type: { name: "Composite", className: "ExportClusterParameters", modelProperties: { sasUri: { required: true, serializedName: "sasUri", type: { name: "String" } } } } }; export const ErrorAdditionalInfo: msRest.CompositeMapper = { serializedName: "ErrorAdditionalInfo", type: { name: "Composite", className: "ErrorAdditionalInfo", modelProperties: { type: { readOnly: true, serializedName: "type", type: { name: "String" } }, info: { readOnly: true, serializedName: "info", type: { name: "Object" } } } } }; export const ErrorDetail: msRest.CompositeMapper = { serializedName: "ErrorDetail", type: { name: "Composite", className: "ErrorDetail", modelProperties: { code: { readOnly: true, serializedName: "code", type: { name: "String" } }, message: { readOnly: true, serializedName: "message", type: { name: "String" } }, target: { readOnly: true, serializedName: "target", type: { name: "String" } }, details: { readOnly: true, serializedName: "details", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorDetail" } } } }, additionalInfo: { readOnly: true, serializedName: "additionalInfo", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorAdditionalInfo" } } } } } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", className: "ErrorResponse", modelProperties: { error: { serializedName: "error", type: { name: "Composite", className: "ErrorDetail" } } } } }; export const OperationStatus: msRest.CompositeMapper = { serializedName: "OperationStatus", type: { name: "Composite", className: "OperationStatus", modelProperties: { id: { serializedName: "id", type: { name: "String" } }, name: { serializedName: "name", type: { name: "String" } }, startTime: { serializedName: "startTime", type: { name: "String" } }, endTime: { serializedName: "endTime", type: { name: "String" } }, status: { serializedName: "status", type: { name: "String" } }, error: { serializedName: "error", type: { name: "Composite", className: "ErrorResponse" } } } } }; export const AzureEntityResource: msRest.CompositeMapper = { serializedName: "AzureEntityResource", type: { name: "Composite", className: "AzureEntityResource", modelProperties: { ...Resource.type.modelProperties, etag: { readOnly: true, serializedName: "etag", type: { name: "String" } } } } }; export const PrivateLinkResource: msRest.CompositeMapper = { serializedName: "PrivateLinkResource", type: { name: "Composite", className: "PrivateLinkResource", modelProperties: { ...Resource.type.modelProperties, groupId: { readOnly: true, serializedName: "properties.groupId", type: { name: "String" } }, requiredMembers: { readOnly: true, serializedName: "properties.requiredMembers", type: { name: "Sequence", element: { type: { name: "String" } } } }, requiredZoneNames: { serializedName: "properties.requiredZoneNames", type: { name: "Sequence", element: { type: { name: "String" } } } } } } }; export const OperationDisplay: msRest.CompositeMapper = { serializedName: "Operation_display", type: { name: "Composite", className: "OperationDisplay", modelProperties: { provider: { readOnly: true, serializedName: "provider", type: { name: "String" } }, resource: { readOnly: true, serializedName: "resource", type: { name: "String" } }, operation: { readOnly: true, serializedName: "operation", type: { name: "String" } }, description: { readOnly: true, serializedName: "description", type: { name: "String" } } } } }; export const Operation: msRest.CompositeMapper = { serializedName: "Operation", type: { name: "Composite", className: "Operation", modelProperties: { name: { readOnly: true, serializedName: "name", type: { name: "String" } }, isDataAction: { readOnly: true, serializedName: "isDataAction", type: { name: "Boolean" } }, display: { serializedName: "display", type: { name: "Composite", className: "OperationDisplay" } }, origin: { readOnly: true, serializedName: "origin", type: { name: "String" } }, actionType: { readOnly: true, serializedName: "actionType", type: { name: "String" } } } } }; export const OperationListResult: msRest.CompositeMapper = { serializedName: "OperationListResult", type: { name: "Composite", className: "OperationListResult", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "Operation" } } } }, nextLink: { readOnly: true, serializedName: "nextLink", type: { name: "String" } } } } }; export const ClusterList: msRest.CompositeMapper = { serializedName: "ClusterList", type: { name: "Composite", className: "ClusterList", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "Cluster" } } } }, nextLink: { readOnly: true, serializedName: "nextLink", type: { name: "String" } } } } }; export const DatabaseList: msRest.CompositeMapper = { serializedName: "DatabaseList", type: { name: "Composite", className: "DatabaseList", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "Database" } } } }, nextLink: { readOnly: true, serializedName: "nextLink", type: { name: "String" } } } } }; export const PrivateEndpointConnectionListResult: msRest.CompositeMapper = { serializedName: "PrivateEndpointConnectionListResult", type: { name: "Composite", className: "PrivateEndpointConnectionListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "PrivateEndpointConnection" } } } } } } }; export const PrivateLinkResourceListResult: msRest.CompositeMapper = { serializedName: "PrivateLinkResourceListResult", type: { name: "Composite", className: "PrivateLinkResourceListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "PrivateLinkResource" } } } } } } };
the_stack
/// <reference path="TypeScriptReferences/jquery/jquery.d.ts" /> /// <reference path="TypeScriptReferences/phonegap/phonegap.d.ts" /> /// <reference path="TypeScriptReferences/leaflet/leaflet.d.ts" /> /// <reference path="TypeScriptReferences/history/history.d.ts" /> /// <reference path="TypeScriptReferences/collections/collections.d.ts" /> /*reference includes, required for compilation*/ /// <reference path="OCM_Base.ts" /> /// <reference path="OCM_AppBase.ts" /> /// <reference path="OCM_App_LocationEditor.ts" /> /// <reference path="OCM_App_Util.ts" /> /// <reference path="OCM_AppBootstrap.ts" /> /// <reference path="OCM_FileUpload.ts" /> /// <reference path="OCM_Data.ts" /> /// <reference path="OCM_CommonUI.ts" /> /// <reference path="OCM_Geolocation.ts" /> /// <reference path="OCM_MapInit.ts" /> /// <reference path="OCM_Mapping.ts" /> //typescript declarations declare var localisation_dictionary: any; declare var languageList: Array<any>; interface JQuery { fastClick: any; swipebox: any; closeSlide: any; } interface JQueryStatic { swipebox: any; } interface HTMLFormElement { files: any; } interface Object { observe: any; } var Historyjs: Historyjs = <any>History; var IScroll: any; //////////////////////////////////////////////////////////////// module OCM { export class App extends OCM.LocationEditor { private resultItemTemplate: any; private fileUploadManager: OCM.FileUpload; private _autocomplete: any; constructor() { super(); this.mappingManager.setParentAppContext(this); this.appConfig.maxResults = 1000; this.appConfig.baseURL = "https://openchargemap.org/app/"; this.appConfig.loginProviderRedirectBaseURL = "https://openchargemap.org/site/loginprovider/?_mode=silent&_forceLogin=true&_redirectURL="; this.appConfig.loginProviderRedirectURL = this.appConfig.loginProviderRedirectBaseURL + this.appConfig.baseURL; this.appConfig.newsHomeUrl = null; this.apiClient.clientName = "ocm.app.webapp"; this.appState.languageCode = "en"; this.appState.menuDisplayed = false; this.apiClient.generalErrorCallback = $.proxy(this.showConnectionError, this); this.apiClient.authorizationErrorCallback = $.proxy(this.showAuthorizationError, this); this.appState.isEmbeddedAppMode = false; //used when app is embedded in another site this.appConfig.launchMapOnStartup = true; this.appState.mapLaunched = false; this.appState.appMode = OCM.AppMode.STANDARD; //this.appState.appMode = AppMode.LOCALDEV; this.appConfig.enableLiveMapQuerying = true; this.appConfig.enablePOIListView = false; // this.mappingManager.setMapAPI(MappingAPI.GOOGLE_NATIVE); this.enableLogging = true; /* if (this.appState.appMode === OCM.AppMode.LOCALDEV) { this.appConfig.baseURL = "http://localhost:81/app"; this.appConfig.loginProviderRedirectBaseURL = "http://localhost:81/site/loginprovider/?_mode=silent&_forceLogin=true&_redirectURL="; this.apiClient.serviceBaseURL = "http://localhost:8080/v2"; this.apiClient.serviceBaseURL_Standard = "http://localhost:8080/v2"; //this.apiClient.serviceBaseURL = "http://localhost:81/api/v2"; //this.apiClient.serviceBaseURL_Standard = "http://localhost:81/api/v2"; this.appConfig.loginProviderRedirectURL = this.appConfig.loginProviderRedirectBaseURL + this.appConfig.baseURL; } if (this.appState.appMode === OCM.AppMode.SANDBOXED) { this.appConfig.baseURL = "http://localhost:81/app"; this.apiClient.serviceBaseURL = "http://sandbox.api.openchargemap.io/v2"; this.appConfig.loginProviderRedirectURL = this.appConfig.loginProviderRedirectBaseURL + this.appConfig.baseURL; }*/ if (this.getParameter("mode") === "embedded") { this.appState.isEmbeddedAppMode = true; } if (this.getParameter("languagecode") != "") { this.appState.languageCode = this.getParameter("languagecode"); } if (this.appState.isEmbeddedAppMode) { this.appConfig.launchMapOnStartup = true; } } initApp() { /* App startup workflow: - Begin Observing Model Changes - Setup page history tracking for back/forwards navigation - Setup UI actions (button/link actions) - Load stored settings - Check if user already signed in - Load cached results from last search (if any) - If no cached results, show startup page and wait for an initial search to complete - kick off lazy refresh of favourites - show map/search page */ var app = this; //Begin observing app model changes such as poiList and other state this.beginObservingAppModelChanges(); this.appState.appInitialised = true; //wire up state tracking this.initStateTracking(); //wire up button events this.setupUIActions(); this.initEditors(); //populate language options this.populateDropdown("option-language", languageList, this.appState.languageCode); //load options settings from storage/cookies this.loadSettings(); //when options change, store settings $('#search-distance').change(function () { app.storeSettings(); }); $('#search-distance-unit').change(function () { app.storeSettings(); }); $('#option-language').change(function () { app.switchLanguage($("#option-language").val()); }); $('#filter-operator, #filter-connectiontype, #filter-connectionlevel,#filter-usagetype,#filter-statustype, #filter-minpowerkw') .change(function () { app.validateMultiSelect($(this)); app.storeSettings(); }); var app = this; //check if user signed in etc this.postLoginInit(); //if cached results exist, render them var cachedResults = this.apiClient.getCachedDataObject("SearchResults"); var cachedResult_Location = this.apiClient.getCachedDataObject("SearchResults_Location"); var cachedResult_SearchPos = this.apiClient.getCachedDataObject("SearchResults_SearchPos"); if (cachedResults !== null) { if (cachedResult_Location !== null) { (<HTMLInputElement>document.getElementById("search-location")).value = cachedResult_Location; } if (cachedResult_SearchPos != null) { app.viewModel.searchPosition = cachedResult_SearchPos; } //use cached POI results, observer will then render the results app.viewModel.isCachedResults = true; app.viewModel.poiList = cachedResults; app.viewModel.searchPOIList = cachedResults; } else { //navigate to startup page while we wait for results app.navigateToStartup(); app.viewModel.poiList = []; app.viewModel.searchPOIList = []; //search nearby on startup app.performSearch(true, false); } //if ID of location passed in, show details view var idParam = app.getParameter("id"); if (idParam !== null && idParam !== "") { var poiId = parseInt(app.getParameter("id"), 10); setTimeout(function () { app.showDetailsViewById(poiId, true); }, 100); } //switch to preferred language this.switchLanguage($("#option-language").val()); //lazy update of favourite POI details (if any) setTimeout(() => { app.syncFavourites() }, 10000); //hide splashscreen if present if (app.appState.isRunningUnderCordova) { setTimeout(function () { if (navigator.splashscreen) navigator.splashscreen.hide(); }, 2000); } //app.mappingManager.initMap("map-view"); } beginObservingAppModelChanges() { var app = this; //observe viewModel changes Object.observe(this.viewModel, function (changes) { changes.forEach(function (change) { //app.log("changed: app.viewModel." + change.name); //if viewModel.poiList changes, update the rendered list and refresh map markers if (change.name == "poiList") { app.log("Handling POI List Change event."); if (app.appConfig.enablePOIListView) { app.renderPOIList(app.viewModel.poiList); } else { } //after initial load subsequent queries auto refresh the map markers if (app.mappingManager.isMapReady()) { app.log("Auto refreshing map view"); app.refreshMapView(); } else { app.log("Map not ready, skipping refresh."); } } }); }); // observe mapping model changes app.log("Observing mappingManager changes"); Object.observe(this.mappingManager, function (changes) { changes.forEach(function (change) { app.log("changed: app.mappingManager." + change.name); if (change.name == "mapAPIReady" && app.mappingManager.mapAPIReady) { app.log("Mapping Step 1:Map API Ready - Initialising Map.", OCM.LogLevel.VERBOSE); //if (!app.mappingManager.isMapReady()) { app.mappingManager.initMap("map-view"); // } } if (change.name == "mapReady" && app.mappingManager.isMapReady()) { app.log("Mapping Step 2:Map Initialised. Performing First Render:", OCM.LogLevel.VERBOSE); app.refreshMapView(); //show main page app.navigateToMap(); } }); }); // observe map option changes Object.observe(this.mappingManager.mapOptions, function (changes) { changes.forEach(function (change) { app.log("changed: app.mappingManager.mapOptions." + change.name); if (change.name == "mapCentre") { if (app.appConfig.enableLiveMapQuerying) { app.log("Live map querying enabled, performing a search from map centre.."); app.mappingManager.mapOptions.requestSearchUpdate = true; } if (app.mappingManager.mapOptions.requestSearchUpdate) { app.mappingManager.mapOptions.requestSearchUpdate = false; var pos = app.mappingManager.mapOptions.mapCentre; app.log("Starting new search from map position: " + pos.coords.latitude + "," + pos.coords.longitude); app.viewModel.searchPosition = pos; app.performSearch(false, false); } /*if (app.mappingManager.mapOptions.enableTrackingMapCentre) { var pos = app.mappingManager.mapOptions.mapCentre; app.log("Would start new search: " + pos.coords.latitude + "," + pos.coords.longitude); app.viewModel.searchPosition = pos; app.performSearch(false, false); //disable tracking map centre until search/rendering has completed app.mappingManager.mapOptions.enableTrackingMapCentre = false; }*/ } if (change.name == "enableSearchByWatchingLocation") { app.refreshLocationWatcherStatus(); } }); }); // observe geolocation model changes Object.observe(this.geolocationManager, function (changes) { changes.forEach(function (change) { app.log("changed: app.geolocationManager." + change.name + "::" + JSON.stringify(change.oldValue)); if (change.name == "clientGeolocationPos") { //geolocation position has changed, if watching location is enabled perform a new search if different from last time if (!app.appState.isSearchInProgress && app.mappingManager.mapOptions.enableSearchByWatchingLocation) { app.log("Position watcher update, searching POIs again.."); app.performSearch(true, false); } else { //app.log("search still in progress, not updating results"); } } }); }); } setupUIActions() { //TODO: split into module specific UI var app = this; if (this.appConfig.launchMapOnStartup) { //pages are hidden by default, start by show map screen (once map api ready) if (!app.mappingManager.mapReady) { app.log("Map not ready yet. Waiting for map ready via model observer."); setTimeout(function () { if (!app.mappingManager.mapReady) { //map still not ready //app.showMessage("Map could not load, please try again or check network connection."); app.navigateToHome(); app.toggleMapView(); //switch from default map to list view } }, 10000); //map api load timeout } } else { //pages are hidden by default, show home screen this.navigateToStartup(); } //add header classes to header elements $("[data-role='header']").addClass("ui-header"); //enable file upload this.fileUploadManager = new OCM.FileUpload(); //set default back ui buttons handler app.setElementAction("a[data-rel='back']", function () { Historyjs.back(); }); app.setElementAction("a[data-rel='menu']", function () { //show menu when menu icon activated app.toggleMenu(true); }); //toggle menu on native menu button if (app.appState.isRunningUnderCordova) { document.addEventListener("menubutton", function () { app.toggleMenu(null); }, false); } if (app.appState.isEmbeddedAppMode) { $("#option-expand").show(); app.setElementAction("#option-expand", function () { //open app in full window var newWindow = window.open(app.appConfig.baseURL, "_blank"); }); } app.setElementAction("#app-menu-container", function () { //hide menu if menu container tapped app.toggleMenu(false); //if map page is the most recent view, need to re-show (native) map which was hidden when menu was shown if (app.appState.isRunningUnderCordova) { if (app.appState._lastPageId == "map-page") { app.log("menu dismissed, showing map again"); app.mappingManager.showMap(); } else { app.log("menu dismissed resuming page:" + app.appState._lastPageId); } } }); //set home page ui link actions app.setElementAction("a[href='#map-page'],#search-map", function () { app.navigateToMap(); }); app.setElementAction("a[href='#news-page']", function () { app.navigateToNews(); }); app.setElementAction("a[href='#addlocation-page'],#search-addlocation", function () { app.navigateToAddLocation(); }); app.setElementAction("a[href='#favourites-page'],#search-favourites", function () { app.navigateToFavourites(); }); app.setElementAction("a[href='#settings-page'],#search-settings", function () { app.navigateToSettings(); }); app.setElementAction("a[href='#about-page']", function () { app.navigateToAbout(); }); app.setElementAction("a[href='#profile-page']", function () { app.navigateToProfile(); }); app.setElementAction("#signin-button", function (e) { app.log("Signing In"); if (e) e.preventDefault(); app.beginLogin(); }); app.setElementAction("#signout-button", function (e) { app.log("Signing Out"); if (e) e.preventDefault(); app.logout(false); }); //search page button actions app.setElementAction("#search-nearby", function () { app.performSearch(true, false); }); app.setElementAction("#search-button", function () { app.performSearch(false, true); }); app.setElementAction("#map-toggle-list", function () { app.toggleMapView(); }); app.setElementAction("#map-refresh", function () { //refresh search based on map centre if (app.mappingManager.mapOptions.mapCentre != null) { app.viewModel.searchPosition = app.mappingManager.mapOptions.mapCentre; app.performSearch(false, false); } }); //if map type selection changes, update map $("#pref-basemap-type").on("change", function () { if (app.mappingManager.mapReady) { app.mappingManager.setMapType($("#pref-basemap-type").val()); } app.storeSettings(); }); //if search behaviour option changed, update mapping manager mode $("#pref-search-behaviour").on("change", function () { var selectedVal = $("#pref-search-behaviour").val(); app.log("Changing search behaviour:" + selectedVal); if (selectedVal == "Auto") { app.mappingManager.mapOptions.enableSearchByWatchingLocation = true; } else { app.mappingManager.mapOptions.enableSearchByWatchingLocation = false; } app.storeSettings(); }); //details page ui actions app.setElementAction("#option-favourite", function () { app.toggleFavouritePOI(app.viewModel.selectedPOI, null); }); app.setElementAction("#option-edit, #details-edit", function () { app.navigateToEditLocation(); }); //comment/checkin ui actions app.setElementAction("#option-checkin, #btn-checkin", function () { app.navigateToAddComment(); }); app.setElementAction("#submitcomment-button", function () { app.performCommentSubmit(); }); //media item uploads app.setElementAction("#option-uploadphoto, #btn-uploadphoto", function () { app.navigateToAddMediaItem(); }); app.setElementAction("#submitmediaitem-button", function () { app.performMediaItemSubmit(); }); //HACK: adjust height of content based on browser window size $(window).resize(function () { app.adjustMainContentHeight(); }); } refreshLocationWatcherStatus() { var app = this; //start or stop watching user location for searches if (app.mappingManager.mapOptions.enableSearchByWatchingLocation) { app.log("Starting to watch user location"); app.geolocationManager.startWatchingUserLocation(); } else { app.log("Stop watching user location"); app.geolocationManager.stopWatchingUserLocation(); } } checkSelectedAPIMode() { if ($("#filter-apimode").val() == "standard") { this.apiClient.serviceBaseURL = this.apiClient.serviceBaseURL_Standard; } if ($("#filter-apimode").val() == "sandbox") { this.apiClient.serviceBaseURL = this.apiClient.serviceBaseURL_Sandbox; } } toggleMapView(forceHideList: boolean = false) { var app = this; if ($("#mapview-container").hasClass("hidden-xs") || forceHideList == true) { //set map to show on small display //hide list $("#listview-container").addClass("hidden-xs"); $("#listview-container").addClass("hidden-sm"); //show map $("#mapview-container").removeClass("hidden-xs"); $("#mapview-container").removeClass("hidden-sm"); $("#map-toggle-icon").removeClass("fa-map-marker"); $("#map-toggle-icon").addClass("fa-list"); //refresh/show map app.setMapFocus(true); //app.refreshMapView(); } else { //set list to show on small display //hide map $("#mapview-container").addClass("hidden-xs"); $("#mapview-container").addClass("hidden-sm"); //show list app.setMapFocus(false); $("#listview-container").removeClass("hidden-xs"); $("#listview-container").removeClass("hidden-sm"); $("#map-toggle-icon").removeClass("fa-list"); $("#map-toggle-icon").addClass("fa-map-marker"); } } postLoginInit() { var userInfo = this.getLoggedInUserInfo(); //if user logged in, enable features if (!this.isUserSignedIn()) { //user is not signed in //$("#login-summary").html("<input type=\"button\" id=\"login-button\" class='btn btn-primary' data-mini=\"true\" data-icon=\"arrow-r\" value=\"Sign In\" onclick='ocm_app.beginLogin();'/>"); $("#user-profile-info").html(""); $("#signin-button").show(); $("#menu-signin").show(); $("#menu-signout").hide(); } else { //user is signed in $("#user-profile-info").html("Signed in as: " + userInfo.Username); $("#signin-button").hide(); $("#menu-signin").hide(); $("#menu-signout").show(); } } beginLogin() { this.showProgressIndicator(); //reset previous authorization warnings this.apiClient.hasAuthorizationError = false; var app = this; if (this.appState.isRunningUnderCordova) { //do phonegapped login using InAppBrowser var ref: any = window.open(this.appConfig.loginProviderRedirectBaseURL + 'AppLogin?redirectWithToken=true', '_blank', 'location=yes'); //attempt attach event listeners try { ref.addEventListener('loaderror', function (event) { app.log('loaderror: ' + event.message, LogLevel.ERROR); }); ref.addEventListener('loadstart', function (event) { app.log('loadstart: ' + event.url); //attempt to fetch from url var url = event.url; var token = app.getParameterFromURL("OCMSessionToken", url); if (token.length > 0) { app.log('OCM: Got a token ' + event.url); var userInfo = { "Identifier": app.getParameterFromURL("Identifier", url), "Username": app.getParameterFromURL("Identifier", url), "SessionToken": app.getParameterFromURL("OCMSessionToken", url), "AccessToken": "", "Permissions": app.getParameterFromURL("Permissions", url) }; app.log('got login: ' + userInfo.Username); app.setLoggedInUserInfo(userInfo); app.postLoginInit(); //return to default app.navigateToMap(); app.hideProgressIndicator(); ref.close(); } else { app.log('OCM: Not got a token ' + event.url); } }); ref.addEventListener('exit', function (event) { app.log(event.type); }); } catch (err) { app.log("OCM: error adding inappbrowser events :" + err); } app.log("OCM: inappbrowser events added.."); } else { if (!app.appState.isEmbeddedAppMode) { //do normal web login app.log("OCM: not cordova, redirecting after login.."); window.location.href = this.appConfig.loginProviderRedirectURL; } else { //embedded app mode requires iframe for non-frameable authentication workflow var authWindow = window.open(this.appConfig.loginProviderRedirectBaseURL + 'AppLogin?redirectWithToken=true', "_blank", "width=320, height=400"); app.appState._appPollForLogin = setInterval(function () { app.log("Polling for login result.."); if (app.isUserSignedIn()) { var userInfo = app.getLoggedInUserInfo(); clearInterval(app.appState._appPollForLogin); app.log('Login Completed. ' + userInfo.Username); app.setLoggedInUserInfo(userInfo); app.postLoginInit(); //return to default app.navigateToHome(); app.hideProgressIndicator(); authWindow.close(); } }, 1000); } } } logout(navigateToHome: boolean) { var app = this; this.clearCookie("Identifier"); this.clearCookie("Username"); this.clearCookie("OCMSessionToken"); this.clearCookie("AccessPermissions"); if (navigateToHome == true) { app.postLoginInit(); //refresh signed in/out ui if (this.appState.isRunningUnderCordova) { app.navigateToMap(); } else { setTimeout(function () { window.location.href = app.appConfig.baseURL; }, 100); } } else { app.postLoginInit(); //refresh signed in/out ui } } validateMultiSelect($multiSelect: JQuery) { //for a given multi select element, ensure that (All) option isn't set at same time as another option var options = this.getMultiSelectionAsArray($multiSelect, ""); if (options.length > 1) { //multiple options selected, check (All) option not selected along with other options var allOptionIndex = options.indexOf(""); if (allOptionIndex >= 0) { //all option selected along with other options, remove it then reset the selected options of the multiselect list options = options.splice(allOptionIndex, 1); $multiSelect.val(options); this.log("(All) option removed from multi select - other options selected at same time", LogLevel.VERBOSE); } } } storeSettings() { if (this.appState.suppressSettingsSave == false) { //save option settings to cookies this.setCookie("optsearchdist", $('#search-distance').val()); this.setCookie("optsearchdistunit", $('#search-distance-unit').val()); this.setCookie("optlanguagecode", $('#option-language').val()); this.setCookie("filterapimode", $('#filter-apimode').val()); this.setCookie("optbasemaptype", $('#pref-basemap-type').val()); this.setCookie("optsearchbehaviour", $('#pref-search-behaviour').val()); this.setCookie("filterminpowerkw", $('#filter-minpowerkw').val()); this.setCookie("filteroperator", $('#filter-operator').val()); this.setCookie("filterconnectiontype", $('#filter-connectiontype').val()); this.setCookie("filterconnectionlevel", $('#filter-connectionlevel').val()); this.setCookie("filterusagetype", $('#filter-usagetype').val()); this.setCookie("filterstatustype", $('#filter-statustype').val()); } } loadSettings() { this.loadPref("optsearchdist", $("#search-distance"), false); this.loadPref("optsearchdistunit", $("#search-distance-unit"), false); this.loadPref("optlanguagecode", $("#option-language"), false); this.loadPref("filterapimode", $("#filter-apimode"), false); this.loadPref("optbasemaptype", $("#pref-basemap-type"), false); this.loadPref("optsearchbehaviour", $("#pref-search-behaviour"), false); this.loadPref("filterminpowerkw", $("#filter-minpowerkw"), true); this.loadPref("filteroperator", $("#filter-operator"), true); this.loadPref("filterconnectiontype", $("#filter-connectiontype"), true); this.loadPref("filterconnectionlevel", $("#filter-connectionlevel"), true); this.loadPref("filterusagetype", $("#filter-usagetype"), true); this.loadPref("filterstatustype", $("#filter-statustype"), true); } loadPref(settingName: string, $boundFormElement: JQuery, isMultiSelect: boolean) { if (this.getCookie(settingName) != null) { this.log("Loading pref " + settingName + " (" + isMultiSelect + "):" + this.getCookie(settingName)); if (isMultiSelect) { $boundFormElement.val(this.getCookie(settingName).toString().split(",")); } else { $boundFormElement.val(this.getCookie(settingName)); } } } performCommentSubmit() { var app = this; if (!app.appState.isSubmissionInProgress) { app.checkSelectedAPIMode(); if (app.appState.enableCommentSubmit === true) { app.appState.enableCommentSubmit = false; var refData = this.apiClient.referenceData; var item = this.apiClient.referenceData.UserComment; //collect form values item.ChargePointID = this.viewModel.selectedPOI.ID; item.CheckinStatusType = this.apiClient.getRefDataByID(refData.CheckinStatusTypes, $("#checkin-type").val()); item.CommentType = this.apiClient.getRefDataByID(refData.UserCommentTypes, $("#comment-type").val()); item.UserName = $("#comment-username").val(); item.Comment = $("#comment-text").val(); item.Rating = $("#comment-rating").val(); //show progress this.showProgressIndicator(); this.appState.isSubmissionInProgress = true; //submit this.apiClient.submitUserComment(item, this.getLoggedInUserInfo(), function (jqXHR, textStatus) { app.submissionCompleted(jqXHR, textStatus); //refresh POI details via API if (item.ChargePointID > 0) { app.showDetailsViewById(item.ChargePointID, true); app.navigateToLocationDetails(); } }, $.proxy(this.submissionFailed, this) ); } else { this.log("Comment submit not enabled"); } } } performMediaItemSubmit() { var app = this; if (!app.appState.isSubmissionInProgress) { this.checkSelectedAPIMode(); var $fileupload = $(':file'); var mediafile = (<HTMLFormElement>$fileupload[0]).files[0]; var name, size, type; if (mediafile) { name = mediafile.name; size = mediafile.size; type = mediafile.type; } var formData = new FormData(); formData.append("id", this.viewModel.selectedPOI.ID); formData.append("comment", $("#comment").val()); formData.append("mediafile", mediafile); /*var imageData = this.fileUploadManager.getImageData(); formData.append("mediafile", imageData); formData.append("contenttype", "Base64,[Image/PNG]"); */ //show progress this.showProgressIndicator(); this.appState.isSubmissionInProgress = true; //submit this.apiClient.submitMediaItem( formData, this.getLoggedInUserInfo(), function (jqXHR, textStatus) { app.submissionCompleted(jqXHR, textStatus); //refresh POI details via API if (app.viewModel.selectedPOI.ID > 0) { app.showDetailsViewById(app.viewModel.selectedPOI.ID, true); app.navigateToLocationDetails(); } }, function () { app.appState.isSubmissionInProgress = false; app.hideProgressIndicator(); app.showMessage("Sorry, your submission could not be processed. Please check your network connection or try again later."); }, $.proxy(this.mediaSubmissionProgress, this) ); } } mediaSubmissionProgress(progressEvent: any) { if (progressEvent.lengthComputable) { var percentComplete = Math.round((progressEvent.loaded / progressEvent.total) * 100); $("#file-upload-progress-bar").show(); //this.log("Media upload progress:" + percentComplete); document.getElementById("file-upload-progress").style.width = percentComplete + "%"; } } submissionCompleted(jqXHR, textStatus) { this.log("submission::" + textStatus, LogLevel.VERBOSE); this.hideProgressIndicator(); this.appState.isSubmissionInProgress = false; if (textStatus != "error") { this.showMessage("Thank you for your contribution, you may need to refresh your search for changes to appear. If approval is required your change may take 1 or more days to show up. (Status Code: " + textStatus + ")"); if (this.viewModel.selectedPOI != null) { //navigate to last viewed location this.showDetailsView(document.getElementById("content-placeholder"), this.viewModel.selectedPOI); this.showPage("locationdetails-page", "Location Details"); } else { //navigate back to search page this.navigateToMap(); } } else { this.showMessage("Sorry, there was a problem accepting your submission. Please try again later. (Status Code: " + textStatus + ")."); } } clearSearchRequest() { var app = this; //clear search timeout if (app.appState._appSearchTimer != null) { clearTimeout(app.appState._appSearchTimer); app.appState._appSearchTimer = null; app.hideProgressIndicator(); } app.appState._appSearchTimestamp = null; app.appState.isSearchInProgress = false; app.appState.isSearchRequested = false; } submissionFailed() { this.hideProgressIndicator(); this.appState.isSubmissionInProgress = false; this.showMessage("Sorry, there was an unexpected problem accepting your contribution. Please check your internet connection and try again later."); } performSearch(useClientLocation: boolean = false, useManualLocation: boolean = false) { var app = this; if (this.appState._appSearchTimer == null) { if (this.appState._appSearchTimestamp != null) { var timeSinceLastSearchMS = <any>new Date() - <any>this.appState._appSearchTimestamp; if (timeSinceLastSearchMS < this.appConfig.searchFrequencyMinMS) { this.log("Search too soon since last results. Skipping."); return; } } this.appState._appSearchTimestamp = new Date(); this.appState._appSearchTimer = setTimeout( function () { //app search has timed out if (app.appState._appSearchTimer != null) { clearTimeout(app.appState._appSearchTimer); app.appState._appSearchTimer = null; app.log("performSearch: previous search has timed out.") app.hideProgressIndicator(); app.showMessage("Search timed out. Please check your network connection."); app.logAnalyticsEvent("Search", "Timeout"); } }, this.appConfig.searchTimeoutMS ); //begin new search this.showProgressIndicator(); this.appState.isSearchRequested = true; //used to signal that geolocation updates etc should continue a search after they complete this.viewModel.isCachedResults = false; //detect if mapping/geolocation available if (useClientLocation == true) { //initiate client geolocation (if not already determined) if (this.geolocationManager.clientGeolocationPos == null) { this.geolocationManager.determineUserLocation($.proxy( this.determineUserLocationCompleted, this), $.proxy( this.determineUserLocationFailed, this)); return; } else { this.viewModel.searchPosition = this.geolocationManager.clientGeolocationPos; } } var distance = parseInt((<HTMLInputElement>document.getElementById("search-distance")).value); var distance_unit = (<HTMLInputElement>document.getElementById("search-distance-unit")).value; if (this.viewModel.searchPosition == null || useManualLocation == true) { // search position not set, attempt fetch from location input and return for now var locationText = (<HTMLInputElement>document.getElementById("search-location")).value; if (locationText === null || locationText == "") { app.logAnalyticsEvent("Search", "Geolocation"); //try to geolocate via browser location API this.geolocationManager.determineUserLocation($.proxy( this.determineUserLocationCompleted, this), $.proxy( this.determineUserLocationFailed, this)); return; } else { // try to gecode text location name, if new lookup not // attempted, continue to rendering app.logAnalyticsEvent("Search", "Geocode", locationText); var lookupAttempted = this.geolocationManager.determineGeocodedLocation(locationText, $.proxy(this.determineGeocodedLocationCompleted, this), $.proxy(this.determineGeocodedLocationFailed, this)); if (lookupAttempted == true) { return; } } } if (this.viewModel.searchPosition != null && this.viewModel.searchPosition.coords != null && !this.appState.isSearchInProgress) { this.appState.isSearchInProgress = true; var params = new OCM.POI_SearchParams(); params.latitude = this.viewModel.searchPosition.coords.latitude; params.longitude = this.viewModel.searchPosition.coords.longitude; params.distance = distance; params.distanceUnit = distance_unit; params.maxResults = this.appConfig.maxResults; params.includeComments = true; params.enableCaching = true; //map viewport search on bounding rectangle instead of map centre if (this.appConfig.enableLiveMapQuerying) { if (this.mappingManager.isMapReady()) { var bounds = this.mappingManager.getMapBounds(); if (bounds != null) { params.boundingbox = "(" + bounds[0].latitude + "," + bounds[0].longitude + "),(" + bounds[1].latitude + "," + bounds[1].longitude + ")"; } //close zooms are 1:1 level of detail, zoomed out samples less data var zoomLevel = this.mappingManager.getMapZoom(); if (zoomLevel > 10) { params.levelOfDetail = 1; } else if (zoomLevel > 6) { params.levelOfDetail = 3; } else if (zoomLevel > 4) { params.levelOfDetail = 5; } else if (zoomLevel > 3) { params.levelOfDetail = 10; } else { params.levelOfDetail = 20; } this.log("zoomLevel:" + zoomLevel + " :Level of detail:" + params.levelOfDetail); } } //apply filter settings from UI if ($("#filter-submissionstatus").val() != 200) params.submissionStatusTypeID = $("#filter-submissionstatus").val(); if ($("#filter-connectiontype").val() != "") params.connectionTypeID = $("#filter-connectiontype").val(); if ($("#filter-minpowerkw").val() != "") params.minPowerKW = $("#filter-minpowerkw").val(); if ($("#filter-operator").val() != "") params.operatorID = $("#filter-operator").val(); if ($("#filter-connectionlevel").val() != "") params.levelID = $("#filter-connectionlevel").val(); if ($("#filter-usagetype").val() != "") params.usageTypeID = $("#filter-usagetype").val(); if ($("#filter-statustype").val() != "") params.statusTypeID = $("#filter-statustype").val(); this.checkSelectedAPIMode(); this.log("Performing search.."); app.logAnalyticsEvent("Search", "Perform Search"); this.apiClient.fetchLocationDataListByParam(params, "ocm_app.handleSearchCompleted", "ocm_app.handleSearchError"); } } else { this.log("Search still in progress, ignoring search request.."); } } handleSearchError(result) { this.clearSearchRequest(); if (result.status == 200) { //all ok } else { this.showMessage("There was a problem performing your search. Please check your internet connection."); } } determineUserLocationCompleted(pos) { this.clearSearchRequest(); this.viewModel.searchPosition = pos; //this.geolocationManager.clientGeolocationPos = pos; this.performSearch(); } determineUserLocationFailed() { this.clearSearchRequest(); this.showMessage("Could not automatically determine your location. Search by location name instead."); } determineGeocodedLocationCompleted(pos: GeoPosition) { this.viewModel.searchPosition = pos; this.clearSearchRequest(); this.mappingManager.updateMapCentrePos(pos.coords.latitude, pos.coords.longitude, true); //this.performSearch(); } determineGeocodedLocationFailed() { this.clearSearchRequest(); this.logAnalyticsEvent("Search", "Geocoding Failed"); this.showMessage("The position of this address could not be determined. You may wish to try starting with a simpler address."); } handleSearchCompleted(poiList: Array<any>) { this.appState._appSearchTimestamp = new Date(); //indicate search has completed this.clearSearchRequest(); //hydrate compact POI list (expand navigation reference data) poiList = this.apiClient.hydrateCompactPOIList(poiList); //inform viewmodel of changes this.viewModel.resultsBatchID++; //indicates that results have changed and need reprocessed (maps etc) this.viewModel.poiList = poiList; this.viewModel.searchPOIList = poiList; if (poiList != null && poiList.length > 0) { this.logAnalyticsEvent("Search", "Completed", "Results", poiList.length); this.log("Caching search results.."); if (poiList.length <= 101) { this.apiClient.setCachedDataObject("SearchResults", poiList); } else { //only cache first 100 results, otherwise cache storage quota may be exceeded var cacheList = poiList.splice(0, 100); this.apiClient.setCachedDataObject("SearchResults", cacheList); } this.apiClient.setCachedDataObject("SearchResults_Location", (<HTMLInputElement>document.getElementById("search-location")).value); this.apiClient.setCachedDataObject("SearchResults_SearchPos", this.viewModel.searchPosition); } else { this.log("No search results, will not overwrite cached search results."); } } renderPOIList(locationList: Array<any>) { //this.viewModel.poiList = locationList; this.log("Rendering " + locationList.length + " search results.."); $("#search-no-data").hide(); this.hideProgressIndicator(); this.appState.isSearchInProgress = false; var appContext = this; //var $listContent = $('#results-list'); var $listContent = $('<ul id="results-list" class="results-list"></ul>'); if (this.resultItemTemplate == null) this.resultItemTemplate = $("#results-item-template").html(); $listContent.children().remove(); if (this.viewModel.poiList == null || this.viewModel.poiList.length == 0) { var $content = $("<li class=\"section-heading\"><p><span class=\"ui-li-count\">0 Results match your search</span></p></li>"); $listContent.append($content); } else { var distUnitPref = <HTMLInputElement>document.getElementById("search-distance-unit"); var distance_unit = "Miles"; if (distUnitPref != null) distance_unit = distUnitPref.value; var introText = "<h3 style='margin-top:0'>The following " + locationList.length + " locations match your search</h3>"; if (this.viewModel.isCachedResults) { introText = "<p class='alert alert-warning'>You are viewing old search results. Search again to see the latest information.</p>"; } var $resultCount = $(introText); $listContent.append($resultCount); var isAlternate = false; for (var i = 0; i < this.viewModel.poiList.length; i++) { var poi = this.viewModel.poiList[i]; var distance = poi.AddressInfo.Distance; if (distance == null) distance = 0; var addressHTML = OCM.Utils.formatPOIAddress(poi); var contactHTML = ""; contactHTML += OCM.Utils.formatPhone(poi.AddressInfo.ContactTelephone1, "Tel."); var itemTemplate = "<li class='result'>" + this.resultItemTemplate + "</li>"; var locTitle = poi.AddressInfo.Title; locTitle += "<div class='pull-right'>"; if (poi.UserComments && poi.UserComments != null) { locTitle += "<span class='badge'><i class=\"fa fa-comment-o\" ></i> " + poi.UserComments.length + "</span>"; } if (poi.MediaItems && poi.MediaItems != null) { locTitle += "<span class='badge'><i class=\"fa fa-camera\" ></i> " + poi.MediaItems.length + "</span>"; } locTitle += "</div>"; if (poi.AddressInfo.Town != null && poi.AddressInfo.Town != "") locTitle = poi.AddressInfo.Town + " - " + locTitle; itemTemplate = itemTemplate.replace("{locationtitle}", locTitle); itemTemplate = itemTemplate.replace("{location}", addressHTML); itemTemplate = itemTemplate.replace("{comments}", ""); var direction = ""; if (this.viewModel.searchPosition != null && this.viewModel.searchPosition.coords != null) direction = this.geolocationManager.getCardinalDirectionFromBearing(this.geolocationManager.getBearing(this.viewModel.searchPosition.coords.latitude, this.viewModel.searchPosition.coords.longitude, poi.AddressInfo.Latitude, poi.AddressInfo.Longitude)); itemTemplate = itemTemplate.replace("{distance}", distance.toFixed(1)); itemTemplate = itemTemplate.replace("{distanceunit}", distance_unit + (direction != "" ? " <span title='" + direction + "' class='direction-" + direction + "'>&nbsp;&nbsp;</span>" : "")); var statusInfo = ""; if (poi.UsageType != null) { statusInfo += "<strong>" + poi.UsageType.Title + "</strong><br/>"; } if (poi.StatusType != null) { statusInfo += poi.StatusType.Title; } var maxLevel = null; if (poi.Connections != null) { if (poi.Connections.length > 0) { for (var c = 0; c < poi.Connections.length; c++) { var con = poi.Connections[c]; if (con.Level != null) { if (maxLevel == null) { maxLevel = con.Level; } else { if (con.Level.ID > maxLevel.ID) maxLevel = con.Level; } } } } } if (maxLevel != null) { statusInfo += "<br/>" + maxLevel.Title + ""; } itemTemplate = itemTemplate.replace("{status}", statusInfo); var $item = $(itemTemplate); if (isAlternate) $item.addClass("alternate"); $item.on('click', <any>{ poi: poi }, function (e) { e.preventDefault(); e.stopPropagation(); //todo: rename as prepareDetailsView try { appContext.showDetailsView(this, e.data.poi); } catch (err) { } appContext.showPage("locationdetails-page", "Location Details"); }); $listContent.append($item); isAlternate = !isAlternate; } } //show hidden results ui $('#results-list').replaceWith($listContent); $("#results-list").css("display", "block"); } showDetailsViewById(id, forceRefresh) { var itemShown = false; //if id in current result list, show if (this.viewModel.poiList != null) { for (var i = 0; i < this.viewModel.poiList.length; i++) { if (this.viewModel.poiList[i].ID == id) { this.showDetailsView(document.getElementById("content-placeholder"), this.viewModel.poiList[i]); itemShown = true; } if (itemShown) break; } } if (!itemShown || forceRefresh == true) { //load poi details, then show this.log("Location not cached or forced refresh, fetching details:" + id); this.apiClient.fetchLocationById(id, "ocm_app.showDetailsFromList", null, true); } } showDetailsFromList(results) { var app = this; if (results.length > 0) { app.showDetailsView(document.getElementById("content-placeholder"), results[0]); } else { this.showMessage("The location you are attempting to view does not exist or has been removed."); } } showDetailsView(element, poi) { var mapSideViewMode = true; var templatePrefix = ""; this.viewModel.selectedPOI = poi; this.log("Showing OCM-" + poi.ID + ": " + poi.AddressInfo.Title); this.logAnalyticsEvent("POI", "View", "Ref", poi.ID); if (this.isFavouritePOI(poi, null)) { $("#option-favourite-icon").removeClass("fa-heart-o"); $("#option-favourite-icon").addClass("fa-heart"); } else { $("#option-favourite-icon").removeClass("fa-heart"); $("#option-favourite-icon").addClass("fa-heart-o"); } //TODO: bug/ref data load when editor opens clears settings var $element = $(element); var $poiTemplate; var $detailsView = null; if (mapSideViewMode == true) { $detailsView = $("#list-scroll-container"); } else { $detailsView = $("#locationdetails-view"); $detailsView.css("width", "90%"); $detailsView.css("display", "block"); } //populate details view var poiDetails = OCM.Utils.formatPOIDetails(poi, false); $("#details-locationtitle").html(poi.AddressInfo.Title); $("#details-address").html(poiDetails.address); $("#details-driving").html(poiDetails.drivingInfo); $("#details-contact").html(poiDetails.contactInfo); $("#details-additional").html(poiDetails.additionalInfo); $("#details-advanced").html(poiDetails.advancedInfo); var viewWidth = $(window).width(); this.mappingManager.showPOIOnStaticMap("details-map", poi, true, this.appState.isRunningUnderCordova, viewWidth, 200); var streetviewUrl = "https://maps.googleapis.com/maps/api/streetview?size=192x96&location=" + poi.AddressInfo.Latitude + "," + poi.AddressInfo.Longitude + "&fov=90&heading=0&pitch=0&sensor=false"; var streetViewLink = "https://maps.google.com/maps?q=&layer=c&cbll=" + poi.AddressInfo.Latitude + "," + poi.AddressInfo.Longitude + "&cbp=11,0,0,0,0"; $("#details-streetview").html("<a href='#' onclick=\"window.open('" + streetViewLink + "', '_system');\"><img src=\"" + streetviewUrl + "\" width=\"192\" height=\"96\" title=\"Approximate Streetview (if available): " + poi.AddressInfo.Title + "\" /></a>"); if (poi.UserComments != null) { var commentOutput = "<div class='comments'>"; for (var c = 0; c < poi.UserComments.length; c++) { var comment = poi.UserComments[c]; var commentDate = OCM.Utils.fixJSONDate(comment.DateCreated); var fragment = "<div class='card comment'>" + "<div class='row'>" + "<div class='col-sm-3'>" + (comment.User != null ? "<img class='user' src='https://www.gravatar.com/avatar/" + comment.User.EmailHash + "?d=mm' />" : "<img class='user' src='https://www.gravatar.com/avatar/00?f=y&d=mm'/>") + "<br/>" + ((comment.UserName != null && comment.UserName != "") ? comment.UserName : "(Anonymous)") + "</div>" + "<div class='col-sm-7'>" + "<h3>" + (comment.CommentType != null ? comment.CommentType.Title + " - " : "") + (comment.CheckinStatusType != null ? " " + comment.CheckinStatusType.Title : "") + "</h3>" + "<p>" + (comment.Comment != null ? comment.Comment : "(No Comment)") + "</p> " + "<small>" + commentDate.toLocaleDateString() + "<em>" + "</em></small></div>" + "<div class='col-sm-2'>" + (comment.Rating != null ? "" + comment.Rating + " out of 5" : " Not Rated") + "</div>" + "</div></div>"; commentOutput += fragment; } commentOutput += "</div>"; $("#details-usercomments").html(commentOutput); } else { $("#details-usercomments").html("<span class='prompt'>No comments/check-ins submitted yet. Help others by adding your comment.</span>"); } if (poi.MediaItems != null) { //gallery var mediaItemOutput = "<div class='comments'>"; for (var c = 0; c < poi.MediaItems.length; c++) { var mediaItem = poi.MediaItems[c]; if (mediaItem.IsEnabled == true) { var itemDate = OCM.Utils.fixJSONDate(mediaItem.DateCreated); var mediaItemThumbnail = mediaItem.ItemThumbnailURL; var mediumSizeThumbnail = mediaItemThumbnail.replace(".thmb.", ".medi."); mediaItemOutput += "<div class='card comment'><div class='row'>" + "<div class='col-xs-6'><a class='swipebox' href='" + mediumSizeThumbnail + "' target='_blank' title='" + ((mediaItem.Comment != null && mediaItem.Comment != "") ? mediaItem.Comment : poi.AddressInfo.Title) + "'><img class='img-responsive img-thumbnail' src='" + mediaItem.ItemThumbnailURL + "'/></a></div>" + "<div class='col-xs-6'><p>" + (mediaItem.Comment != null ? mediaItem.Comment : "(No Comment)") + "</p> " + "<small><cite>" + ((mediaItem.User != null) ? mediaItem.User.Username : "(Anonymous)") + " " + itemDate.toLocaleDateString() + "</cite></small>" + "</div>" + "</div></div>"; } } mediaItemOutput += "</div>"; $("#details-mediaitems").html(""); $("#details-mediaitems-gallery").html(mediaItemOutput); //activate swipebox gallery $('.swipebox').swipebox(); } else { $("#details-mediaitems").html("<span class='prompt'>No photos submitted yet. Can you add one?</span>"); $("#details-mediaitems-gallery").html(""); } if (mapSideViewMode) { $poiTemplate = $("#details-content").detach(); $poiTemplate.appendTo($detailsView); $("#results-list").hide(); $(".details-body").css("margin-top", "0"); $("#details-locationtitle").css("font-size", "1em"); $("#details-map").hide(); } else { } //once displayed, try fetching a more accurate distance estimate if (this.viewModel.searchPosition != null) { //TODO: observe property to update UI this.geolocationManager.getDrivingDistanceBetweenPoints(this.viewModel.searchPosition.coords.latitude, this.viewModel.searchPosition.coords.longitude, poi.AddressInfo.Latitude, poi.AddressInfo.Longitude, $("#search-distance-unit").val(), this.updatePOIDistanceDetails); } //apply translations (if required) if (this.appState.languageCode != null) { OCM.Utils.applyLocalisation(false); } } adjustMainContentHeight() { //HACK: adjust map/list content to main viewport var preferredContentHeight = $(window).height() - 90; if ($("#map-view").height() != preferredContentHeight) { this.log("adjusting content height:" + preferredContentHeight, LogLevel.VERBOSE); document.getElementById("map-view").style.height = preferredContentHeight + "px"; document.getElementById("listview-container").style.height = preferredContentHeight + "px"; document.getElementById("listview-container").style.maxHeight = preferredContentHeight + "px"; $(".fit-to-viewport").height(preferredContentHeight); this.mappingManager.updateMapSize(); } return preferredContentHeight; } refreshMapView() { if (!this.mappingManager.mapAPIReady) { this.log("app.refreshMapView: API Not Ready"); return; } //on showing map, adjust map container height to match page var mapHeight = this.adjustMainContentHeight(); this.mappingManager.refreshMapView(mapHeight, this.viewModel.poiList, this.viewModel.searchPosition); //set map type based on pref this.mappingManager.setMapType($("#pref-basemap-type").val()); this.appConfig.autoRefreshMapResults = true; } setMapFocus(hasFocus: boolean) { if (hasFocus) { //this.mappingManager.showMap(); this.mappingManager.focusMap(); } else { this.mappingManager.unfocusMap(); //this.mappingManager.hideMap(); } } updatePOIDistanceDetails(response, status) { if (response != null) { var result = response.rows[0].elements[0]; if (result.status == "OK") { var origin = response.originAddresses[0]; $("#addr_distance").after(" - driving distance: " + result.distance.text + " (" + result.duration.text + ") from " + origin); } } } isFavouritePOI(poi, itineraryName: string = null) { if (poi != null) { var favouriteLocations = this.apiClient.getCachedDataObject("favouritePOIList"); if (favouriteLocations != null) { for (var i = 0; i < favouriteLocations.length; i++) { if (favouriteLocations[i].poi.ID == poi.ID && (favouriteLocations[i].itineraryName == itineraryName || (itineraryName == null && favouriteLocations[i].itineraryName == null))) { return true; } } } } return false; } addFavouritePOI(poi, itineraryName: string = null) { if (poi != null) { if (!this.isFavouritePOI(poi, itineraryName)) { var favouriteLocations = this.apiClient.getCachedDataObject("favouritePOIList"); if (favouriteLocations == null) { favouriteLocations = new Array(); } if (itineraryName != null) { favouriteLocations.push({ "poi": poi, "itineraryName": itineraryName }); //add to specific itinerary } favouriteLocations.push({ "poi": poi, "itineraryName": null }); // add to 'all' list this.log("Added Favourite POI OCM-" + poi.ID + ": " + poi.AddressInfo.Title); this.apiClient.setCachedDataObject("favouritePOIList", favouriteLocations); } else { var favouriteLocations = this.apiClient.getCachedDataObject("favouritePOIList"); if (favouriteLocations != null) { for (var i = 0; i < favouriteLocations.length; i++) { if (favouriteLocations[i].poi.ID == poi.ID) { favouriteLocations[i] = poi; this.log("Updated Favourite POI OCM-" + poi.ID + ": " + poi.AddressInfo.Title); } } } } } } removeFavouritePOI(poi, itineraryName: string = null) { if (poi != null) { if (this.isFavouritePOI(poi, itineraryName)) { var favouriteLocations = this.apiClient.getCachedDataObject("favouritePOIList"); if (favouriteLocations == null) { favouriteLocations = new Array(); } var newFavList = new Array(); for (var i = 0; i < favouriteLocations.length; i++) { if (favouriteLocations[i].poi.ID == poi.ID && favouriteLocations[i].itineraryName == itineraryName) { //skip item } else { newFavList.push(favouriteLocations[i]); } } this.apiClient.setCachedDataObject("favouritePOIList", newFavList); this.log("Removed Favourite POI OCM-" + poi.ID + ": " + poi.AddressInfo.Title); } else { this.log("Cannot remove: Not a Favourite POI OCM-" + poi.ID + ": " + poi.AddressInfo.Title); } } } toggleFavouritePOI(poi, itineraryName: string = null) { if (poi != null) { var $favIcon = $("#option-favourite-icon"); if (this.isFavouritePOI(poi, itineraryName)) { this.removeFavouritePOI(poi, itineraryName); $favIcon.removeClass("fa-heart"); $favIcon.addClass("fa-heart-o"); this.logAnalyticsEvent("Favourite", "Remove", "Ref", poi.ID); } else { this.addFavouritePOI(poi, itineraryName); $favIcon.removeClass("fa-heart-o"); $favIcon.addClass("fa-heart"); this.logAnalyticsEvent("Favourite", "Add", "Ref", poi.ID); } } } getFavouritePOIList(itineraryName: string = null) { var favouriteLocations = this.apiClient.getCachedDataObject("favouritePOIList"); var poiList = new Array(); if (favouriteLocations != null) { for (var i = 0; i < favouriteLocations.length; i++) { if (favouriteLocations[i].itineraryName == itineraryName) { poiList.push(favouriteLocations[i].poi); } } } return poiList; } syncFavourites() { var app = this; //refresh info for all favourites var favourites = this.getFavouritePOIList(); if (favourites != null) { for (var i = 0; i < favourites.length; i++) { var poi = favourites[i]; this.log("Refreshing data for favourite POI: OCM-" + poi.ID); this.apiClient.fetchLocationById(poi.ID, "ocm_app.updateCachedFavourites", function (error) { if (error.status != 200) { app.log("Failed to refresh favourite POI." + JSON.stringify(error)); } }, true); } } } updateCachedFavourites(poiList) { if (poiList != null) { for (var i = 0; i < poiList.length; i++) { //add/update favourites POI details this.addFavouritePOI(poiList[i]); } } } switchLanguage(languageCode: string) { this.log("Switching UI language: " + languageCode); this.appState.languageCode = languageCode; localisation_dictionary = eval("localisation_dictionary_" + languageCode); //apply translations OCM.Utils.applyLocalisation(false); //store language preference this.storeSettings(); } hidePage(pageId: string) { $("#" + pageId).hide(); } showPage(pageId: string, pageTitle: string, skipState: boolean = false) { if (!pageTitle) pageTitle = pageId; this.log("app.showPage:" + pageId, LogLevel.VERBOSE); this.logAnalyticsView(pageId); //ensure startup page no longer shown if (pageId != "startup-page") document.getElementById("startup-page").style.display = 'none'; //hide last shown page if (this.appState._lastPageId && this.appState._lastPageId != null) { if (this.appState._lastPageId == "map-page" && pageId == "map-page") { this.appState._appQuitRequestCount++; if (this.appState._appQuitRequestCount >= 3) { //triple home page request, time to exit on android etc this.log("Multiple Home Requests, Time to Quit"); if (this.appState.isRunningUnderCordova) { if (confirm("Quit Open Charge Map?")) { (<any>navigator).app.exitApp(); } } } } else { //reset quit request counter this.appState._appQuitRequestCount = 0; } this.hidePage(this.appState._lastPageId); } //show new page document.getElementById(pageId).style.display = "block"; if (!this.appState.isEmbeddedAppMode) { //hack: reset scroll position for new page once page has had a chance to render setTimeout(function () { (<HTMLElement>document.documentElement).scrollIntoView(); }, 100); } /* if (pageId !== "map-page") { //native map needs to be hidden or offscreen this.setMapFocus(false); } else { this.setMapFocus(true); }*/ this.appState._lastPageId = pageId; if (skipState) { //skip storage of current state } else { Historyjs.pushState({ view: pageId, title: pageTitle }, pageTitle, "?view=" + pageId); } //hide menu when menu item activated this.toggleMenu(false); } initStateTracking() { var app = this; // Check Location if (document.location.protocol === 'file:') { //state not supported } // Establish Variables //this.Historyjs = History; // Note: We are using a capital H instead of a lower h var State = Historyjs.getState(); // Log Initial State State.data.view = "map-page"; Historyjs.log('initial:', State.data, State.title, State.url); // Bind to State Change Historyjs.Adapter.bind(window, 'statechange', function () { // Note: We are using statechange instead of popstate // Log the State var State = Historyjs.getState(); // Note: We are using History.getState() instead of event.state if (State.data.view) { if (app.appState._lastPageId && app.appState._lastPageId != null) { if (State.data.view == app.appState._lastPageId) return;//dont show same page twice } app.showPage(State.data.view, State.Title, true); } else { //on startup, load intro page/map app.navigateToHome(); app.log("pageid:" + app.appState._lastPageId); } //if swipebox is open, need to close it: if ($.swipebox && $.swipebox.isOpen) { $('html').removeClass('swipebox-html'); $('html').removeClass('swipebox-touch'); $("#swipebox-overlay").remove(); $(window).trigger('resize'); } }); } navigateToHome() { this.log("Navigate To: Start Page (Map)", LogLevel.VERBOSE); this.navigateToMap(); } navigateToMap(showLatestSearchResults: boolean = true) { this.log("Navigate To: Map Page", LogLevel.VERBOSE); this.showPage("map-page", "Map"); var app = this; //change title of map page to be Search $("#search-title-favourites").hide(); $("#search-title-main").show(); if (showLatestSearchResults) { app.viewModel.poiList = app.viewModel.searchPOIList; } this.setMapFocus(true); setTimeout(function () { app.refreshMapView(); }, 250); } navigateToFavourites() { this.log("Navigate To: Favourites", LogLevel.VERBOSE); var app = this; //get list of favourites as POI list and render in standard search page var favouritesList = app.getFavouritePOIList(); if (favouritesList === null || favouritesList.length === 0) { $("#favourites-list").html("<p>You have no favourite locations set. To add or remove a favourite, select the <i title=\"Toggle Favourite\" class=\"fa fa-heart-o\"></i> icon when viewing a location.</p>"); this.showPage("favourites-page", "Favourites"); } else { app.viewModel.poiList = favouritesList; //show favourites on search page app.navigateToMap(false); //change title of map page to be favourites $("#search-title-main").hide(); $("#search-title-favourites").show(); } } navigateToAddLocation() { this.log("Navigate To: Add Location", LogLevel.VERBOSE); var app = this; if (!app.isUserSignedIn()) { if (app.appConfig.allowAnonymousSubmissions) { app.showMessage("You are not signed in. You should sign in unless you wish to submit your edit anonymously."); } else { app.showMessage("You need to Sign In before you can add a location."); return; }; } app.isLocationEditMode = false; app.viewModel.selectedPOI = null; app.showLocationEditor(); this.showPage("editlocation-page", "Add Location"); } navigateToEditLocation() { this.log("Navigate To: Edit Location", LogLevel.VERBOSE); var app = this; if (!app.isUserSignedIn()) { if (app.appConfig.allowAnonymousSubmissions) { app.showMessage("You are not signed in. You should sign in unless you wish to submit your edit anonymously."); } else { app.showMessage("You need to Sign In before you can edit locations."); return; }; } //show editor app.showLocationEditor(); app.showPage("editlocation-page", "Edit Location", true); } navigateToLocationDetails() { this.log("Navigate To: Location Details", LogLevel.VERBOSE); //show location details for currently selected POI this.showPage("locationdetails-page", "Charging Location"); } navigateToProfile() { this.log("Navigate To: Profile", LogLevel.VERBOSE); this.showPage("profile-page", "Sign In"); } navigateToSettings() { this.log("Navigate To: Settings", LogLevel.VERBOSE); this.showPage("settings-page", "Settings"); } navigateToStartup() { this.log("Navigate To: Startup", LogLevel.VERBOSE); this.showPage("startup-page", "Open Charge Map", true); } navigateToAbout() { this.log("Navigate To: About", LogLevel.VERBOSE); try { var dataProviders = this.apiClient.referenceData.DataProviders; var summary = "<ul>"; for (var i = 0; i < dataProviders.length; i++) { if (dataProviders[i].IsApprovedImport == true || dataProviders[i].IsOpenDataLicensed == true) { summary += "<li>" + dataProviders[i].Title + (dataProviders[i].License != null ? ": <small class='subtle'>" + dataProviders[i].License : "") + "</small></li>"; } } summary += "</ul>"; $("#about-data").html(summary); } catch (exception) { ;; } this.showPage("about-page", "About"); } navigateToNews() { this.log("Navigate To: News", LogLevel.VERBOSE); this.showPage("news-page", "News"); (<HTMLIFrameElement>document.getElementById("news-frame")).src = this.appConfig.newsHomeUrl; } navigateToAddComment() { this.log("Navigate To: Add Comment", LogLevel.VERBOSE); var app = this; if (!app.isUserSignedIn()) { if (app.appConfig.allowAnonymousSubmissions) { app.showMessage("You are not signed in. You should sign in unless you wish to submit your edit anonymously."); } else { app.showMessage("You need to Sign In before adding a comment."); return; }; } //reset comment form on show (<HTMLFormElement>document.getElementById("comment-form")).reset(); app.appState.enableCommentSubmit = true; //show checkin/comment page this.showPage("submitcomment-page", "Add Comment", false); } navigateToAddMediaItem() { this.log("Navigate To: Add Media Item", LogLevel.VERBOSE); var app = this; if (!app.isUserSignedIn()) { app.showMessage("You need to Sign In before you can add photos."); } else { //show upload page this.showPage("submitmediaitem-page", "Add Media", false); } } showConnectionError() { $("#progress-indicator").hide(); $("#network-error").show(); } showAuthorizationError() { this.showMessage("Your session has expired, please sign in again."); } toggleMenu(showMenu: boolean) { if (showMenu != null) this.appState.menuDisplayed = !showMenu; if (this.appState.menuDisplayed) { //hide app menu this.setMapFocus(true); this.appState.menuDisplayed = false; $("#app-menu-container").hide(); } else { //show app menu this.appState.menuDisplayed = true; this.setMapFocus(false); $("#app-menu-container").show(); //TODO: handle back button from open menu //this.appState._lastPageId = "menu"; //Historyjs.pushState({ view: "menu", title: "Menu" }, "Menu", "?view=menu"); } } jumpToPageTop() { //jump to top of page this.log("Status tapped, scrolling to page top."); window.scrollTo(0, 0); } initPlacesAutocomplete() { // Create the search box and link it to the UI element. var input = <HTMLInputElement>document.getElementById('search-location'); this._autocomplete = new google.maps.places.Autocomplete(input); //this._autocomplete.setComponentRestrictions({ 'country': 'au' }); // When the user selects an address from the dropdown, populate the address // fields in the form. this._autocomplete.addListener('place_changed', $.proxy(this.searchFromSelectedPlace, this)); } searchFromSelectedPlace() { // Get the place details from the autocomplete object. var place = this._autocomplete.getPlace(); if (place != null) { this.determineGeocodedLocationCompleted(new GeoPosition(place.geometry.location.lat(), place.geometry.location.lng())); } } } }
the_stack
import { expect } from "chai"; import sinon from "sinon"; import { IModelConnection } from "@itwin/core-frontend"; import { KeySet } from "@itwin/presentation-common"; import { Presentation, SelectionManager } from "@itwin/presentation-frontend"; import { act, renderHook, RenderHookResult } from "@testing-library/react-hooks"; import { UnifiedSelectionContext, UnifiedSelectionContextProvider, UnifiedSelectionContextProviderProps, useUnifiedSelectionContext, } from "../../presentation-components/unified-selection/UnifiedSelectionContext"; describe("UnifiedSelectionContext", () => { const testIModel = {} as IModelConnection; function renderUnifiedSelectionContextHook( imodel = {} as IModelConnection, selectionLevel?: number, ): RenderHookResult<UnifiedSelectionContextProviderProps, UnifiedSelectionContext> { return renderHook( () => useUnifiedSelectionContext()!, { wrapper: UnifiedSelectionContextProvider, initialProps: { imodel, selectionLevel } as UnifiedSelectionContextProviderProps, }, ); } beforeEach(() => { const selectionManager = new SelectionManager({ scopes: undefined as any }); sinon.stub(Presentation, "selection").get(() => selectionManager); }); afterEach(() => { sinon.restore(); }); it("uses selection level 0 by default", () => { const { result } = renderUnifiedSelectionContextHook(); expect(result.current.selectionLevel).to.be.equal(0); }); it("updates context when receives different imodel connection", () => { const { rerender, result } = renderUnifiedSelectionContextHook(); const firstResult = result.current; const updatedImodel = {} as IModelConnection; rerender({ imodel: updatedImodel }); const secondResult = result.current; expect(firstResult).not.to.be.equal(secondResult); expect(firstResult.getSelection).not.to.be.equal(secondResult.getSelection); expect(firstResult.replaceSelection).not.to.be.equal(secondResult.replaceSelection); expect(firstResult.addToSelection).not.to.be.equal(secondResult.addToSelection); expect(firstResult.clearSelection).not.to.be.equal(secondResult.clearSelection); expect(firstResult.removeFromSelection).not.to.be.equal(secondResult.removeFromSelection); }); it("updates context when receives different selection level", () => { const { rerender, result } = renderUnifiedSelectionContextHook(); const firstResult = result.current; rerender({ imodel: result.current.imodel, selectionLevel: 1 }); const secondResult = result.current; expect(firstResult).not.to.be.equal(secondResult); expect(firstResult.getSelection).not.to.be.equal(secondResult.getSelection); expect(firstResult.replaceSelection).not.to.be.equal(secondResult.replaceSelection); expect(firstResult.addToSelection).not.to.be.equal(secondResult.addToSelection); expect(firstResult.clearSelection).not.to.be.equal(secondResult.clearSelection); expect(firstResult.removeFromSelection).not.to.be.equal(secondResult.removeFromSelection); }); it("updates context when current selection changes", () => { const { result } = renderUnifiedSelectionContextHook(testIModel); const firstResult = result.current; // eslint-disable-next-line @typescript-eslint/no-floating-promises act(() => { Presentation.selection.addToSelection("", testIModel, [{ className: "test", id: "1" }], 0); }); const secondResult = result.current; expect(firstResult).not.to.be.equal(secondResult); expect(firstResult.getSelection).not.to.be.equal(secondResult.getSelection); expect(firstResult.replaceSelection).to.be.equal(secondResult.replaceSelection); expect(firstResult.addToSelection).to.be.equal(secondResult.addToSelection); expect(firstResult.clearSelection).to.be.equal(secondResult.clearSelection); expect(firstResult.removeFromSelection).to.be.equal(secondResult.removeFromSelection); }); it("updates context when selection changes on one level above", () => { const { result } = renderUnifiedSelectionContextHook(testIModel, 1); const firstResult = result.current; // eslint-disable-next-line @typescript-eslint/no-floating-promises act(() => { Presentation.selection.addToSelection("", testIModel, [{ className: "test", id: "1" }], 0); }); const secondResult = result.current; expect(firstResult).not.to.be.equal(secondResult); expect(firstResult.getSelection).not.to.be.equal(secondResult.getSelection); expect(firstResult.replaceSelection).to.be.equal(secondResult.replaceSelection); expect(firstResult.addToSelection).to.be.equal(secondResult.addToSelection); expect(firstResult.clearSelection).to.be.equal(secondResult.clearSelection); expect(firstResult.removeFromSelection).to.be.equal(secondResult.removeFromSelection); }); it("does not update context when selection changes one level deeper", () => { const { result } = renderUnifiedSelectionContextHook(testIModel); const firstResult = result.current; // eslint-disable-next-line @typescript-eslint/no-floating-promises act(() => { Presentation.selection.addToSelection("", testIModel, [{ className: "test", id: "1" }], 1); }); const secondResult = result.current; expect(firstResult.getSelection).to.be.equal(secondResult.getSelection); }); describe("context", () => { const keys = new KeySet(); describe("getSelection", () => { let stubGetSelection: sinon.SinonStub<[IModelConnection, number?], Readonly<KeySet>>; beforeEach(() => { stubGetSelection = sinon.stub(Presentation.selection, "getSelection").returns(keys); }); it("gets current selection", () => { const { result } = renderUnifiedSelectionContextHook(testIModel); result.current.getSelection(10); expect(stubGetSelection).to.have.been.calledOnceWithExactly(testIModel, 10); }); it("makes KeySet reference be different from global KeySet", () => { const { result } = renderUnifiedSelectionContextHook(testIModel); const returnedKeySet = result.current.getSelection(); expect(returnedKeySet).not.to.be.equal(keys); }); it("returns same KeySet reference for same selection level", () => { const { result } = renderUnifiedSelectionContextHook(testIModel); const firstKeySet = result.current.getSelection(10); const secondKeySet = result.current.getSelection(10); expect(firstKeySet).to.be.equal(secondKeySet); }); it("returns different KeySet reference for different selection level", () => { const { result } = renderUnifiedSelectionContextHook(testIModel); const firstKeySet = result.current.getSelection(10); const secondKeySet = result.current.getSelection(9); expect(firstKeySet).not.to.be.equal(secondKeySet); }); it("returns different KeySet reference after selection changes", () => { const { result } = renderUnifiedSelectionContextHook(testIModel); const firstKeySet = result.current.getSelection(); // eslint-disable-next-line @typescript-eslint/no-floating-promises act(() => result.current.addToSelection([{ className: "test", id: "1" }])); const secondKeySet = result.current.getSelection(); expect(firstKeySet).not.to.be.equal(secondKeySet); }); it("returns a working KeySet", () => { stubGetSelection.restore(); const { result } = renderUnifiedSelectionContextHook(testIModel); const key = { className: "test", id: "1" }; // eslint-disable-next-line @typescript-eslint/no-floating-promises act(() => result.current.addToSelection([key])); const returnedKeySet = result.current.getSelection(); expect(returnedKeySet.has(key)).to.be.true; }); }); it("replaces current selection", () => { const { result } = renderUnifiedSelectionContextHook(testIModel); const stub = sinon.stub(Presentation.selection, "replaceSelection").returns(); result.current.replaceSelection(keys, 10); expect(stub).to.have.been.calledOnceWithExactly("UnifiedSelectionContext", testIModel, keys, 10); }); it("adds to current selection", () => { const { result } = renderUnifiedSelectionContextHook(testIModel); const stub = sinon.stub(Presentation.selection, "addToSelection").returns(); result.current.addToSelection(keys, 10); expect(stub).to.have.been.calledOnceWithExactly("UnifiedSelectionContext", testIModel, keys, 10); }); it("clears current selection", () => { const { result } = renderUnifiedSelectionContextHook(testIModel); const stub = sinon.stub(Presentation.selection, "clearSelection").returns(); result.current.clearSelection(10); expect(stub).to.have.been.calledOnceWithExactly("UnifiedSelectionContext", testIModel, 10); }); it("removes from current selection", () => { const { result } = renderUnifiedSelectionContextHook(testIModel); const stub = sinon.stub(Presentation.selection, "removeFromSelection").returns(); result.current.removeFromSelection(keys, 10); expect(stub).to.have.been.calledOnceWithExactly("UnifiedSelectionContext", testIModel, keys, 10); }); it("uses default selection level when one is not specified", () => { const { result } = renderUnifiedSelectionContextHook(testIModel, 4); const stubGetSelection = sinon.stub(Presentation.selection, "getSelection").returns(keys); result.current.getSelection(); expect(stubGetSelection).to.have.been.calledOnceWithExactly(testIModel, 4); const stubReplaceSelection = sinon.stub(Presentation.selection, "replaceSelection").returns(); result.current.replaceSelection(keys); expect(stubReplaceSelection).to.have.been.calledOnceWithExactly("UnifiedSelectionContext", testIModel, keys, 4); const stubAddToSelection = sinon.stub(Presentation.selection, "addToSelection").returns(); result.current.addToSelection(keys); expect(stubAddToSelection).to.have.been.calledOnceWithExactly("UnifiedSelectionContext", testIModel, keys, 4); const stubClearSelection = sinon.stub(Presentation.selection, "clearSelection").returns(); result.current.clearSelection(); expect(stubClearSelection).to.have.been.calledOnceWithExactly("UnifiedSelectionContext", testIModel, 4); const stubRemoveFromSelection = sinon.stub(Presentation.selection, "removeFromSelection").returns(); result.current.removeFromSelection(keys); expect(stubRemoveFromSelection).to.have.been.calledOnceWithExactly("UnifiedSelectionContext", testIModel, keys, 4); }); }); describe("useUnifiedSelectionContext", () => { it("returns `undefined` context when there is no unified selection context", () => { const { result } = renderHook(() => useUnifiedSelectionContext()); expect(result.current).to.be.undefined; }); }); });
the_stack
namespace colibri.core.io { interface IGetProjectFilesData { hash: string; maxNumberOfFiles: number; projectNumberOfFiles: number; rootFile: IFileData; error: string; } export async function apiRequest(method: string, body?: any) { try { const resp = await fetch("api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ method, body }) }); const json = await resp.json(); // This could happens in servers with session handling. // If the session expired, then the server send a redirect message. if (json.redirect) { document.location.href = json.redirect; } return json; } catch (e) { console.error(e); return new Promise((resolve, reject) => { resolve({ error: e.message }); }); } } export class FileStorage_HTTPServer implements IFileStorage { private _root: FilePath; private _changeListeners: ChangeListenerFunc[]; private _hash: string; constructor() { this._root = null; this._hash = ""; this._changeListeners = []; this.registerDocumentVisibilityListener(); } private registerDocumentVisibilityListener() { /* This flag is needed by Firefox. In Firefox the focus event is emitted when an object is drop into the window so we should filter that case. */ const flag = { drop: false }; window.addEventListener("drop", e => { flag.drop = true; }); window.addEventListener("focus", e => { if (flag.drop) { flag.drop = false; } else { this.updateWithServerChanges(); } }); } private async updateWithServerChanges() { const hashData = await apiRequest("GetProjectFilesHash", {}); if (hashData.error) { alert(hashData.error); return; } const hash = hashData.hash as string; if (hash === this._hash) { // nothing to do! console.log("Server files not changed (hash=" + hash + ")"); return; } this._hash = hash; const data = await apiRequest("GetProjectFiles", {}) as IGetProjectFilesData; if (data.error) { alert(data.error); return; } if (data.projectNumberOfFiles > data.maxNumberOfFiles) { alert(`Your project exceeded the maximum number of files allowed (${data.projectNumberOfFiles} > ${data.maxNumberOfFiles})`); return; } const change = new FileStorageChange(); const localFiles = this._root.flatTree([], true); const serverFiles = new FilePath(null, data.rootFile).flatTree([], true); const filesToContentTypePreload: FilePath[] = []; const localFilesMap = new Map<string, FilePath>(); for (const file of localFiles) { localFilesMap.set(file.getFullName(), file); } const serverFilesMap = new Map<string, FilePath>(); for (const file of serverFiles) { serverFilesMap.set(file.getFullName(), file); } // compute modified files { for (const file of localFiles) { const fileFullName = file.getFullName(); const serverFile = serverFilesMap.get(fileFullName); if (serverFile) { if (serverFile.getModTime() !== file.getModTime() || serverFile.getSize() !== file.getSize()) { console.log("Modified - " + fileFullName); file._setModTime(serverFile.getModTime()); file._setSize(serverFile.getSize()); change.recordModify(fileFullName); filesToContentTypePreload.push(file); } } } } // compute deleted files { const deletedFilesNamesSet = new Set<string>(); for (const file of localFiles) { const fileFullName = file.getFullName(); if (deletedFilesNamesSet.has(fileFullName)) { // when a parent folder was reported as deleted continue; } if (!serverFilesMap.has(fileFullName)) { console.log("Deleted " + fileFullName); file._remove(); change.recordDelete(fileFullName); if (file.isFolder()) { for (const child of file.getFiles()) { deletedFilesNamesSet.add(child.getFullName()); } } } } } // compute added files { const addedFilesNamesSet = new Set<string>(); for (const file of serverFiles) { const fileFullName = file.getFullName(); if (addedFilesNamesSet.has(fileFullName)) { // when a parent folder was reported as added continue; } if (!localFilesMap.has(fileFullName)) { console.log("Added " + fileFullName); const localParentFile = localFilesMap.get(file.getParent().getFullName()); localParentFile._add(file); file.visit(f => { localFilesMap.set(f.getFullName(), f); filesToContentTypePreload.push(f); }); change.recordAdd(fileFullName); if (file.isFolder()) { for (const child of file.getFiles()) { addedFilesNamesSet.add(child.getFullName()); } } } } } const reg = Platform.getWorkbench().getContentTypeRegistry(); for (const file of filesToContentTypePreload) { await reg.preload(file); } this.fireChange(change); } addChangeListener(listener: ChangeListenerFunc) { this._changeListeners.push(listener); } addFirstChangeListener(listener: ChangeListenerFunc) { this._changeListeners.unshift(listener); } removeChangeListener(listener: ChangeListenerFunc) { const i = this._changeListeners.indexOf(listener); this._changeListeners.splice(i, 1); } getRoot(): FilePath { return this._root; } async openProject(): Promise<FilePath> { this._root = null; this._hash = ""; await this.reload(); const root = this.getRoot(); const change = new FileStorageChange(); change.fullProjectLoaded(); this.fireChange(change); return root; } async createProject(templatePath: string, projectName: string): Promise<boolean> { const data = await apiRequest("CreateProject", { templatePath, projectName }); if (data.error) { alert("Cannot create the project."); return false; } return true; } async reload(): Promise<void> { const data = await apiRequest("GetProjectFiles", {}) as IGetProjectFilesData; let newRoot: FilePath; if (data.projectNumberOfFiles > data.maxNumberOfFiles) { newRoot = new FilePath(null, { name: "Unavailable", modTime: 0, size: 0, children: [], isFile: false }); alert(`Your project exceeded the maximum number of files allowed (${data.projectNumberOfFiles} > ${data.maxNumberOfFiles})`); } else { newRoot = new FilePath(null, data.rootFile); } this._hash = data.hash; this._root = newRoot; } private async fireChange(change: FileStorageChange) { for (const listener of this._changeListeners) { try { const result = listener(change); if (result instanceof Promise) { await result; } } catch (e) { console.error(e); } } } async createFile(folder: FilePath, fileName: string, content: string): Promise<FilePath> { const file = new FilePath(folder, { children: [], isFile: true, name: fileName, size: 0, modTime: 0 }); await this.setFileString_priv(file, content); folder._add(file); this._hash = ""; const change = new FileStorageChange(); change.recordAdd(file.getFullName()); await this.fireChange(change); return file; } async createFolder(container: FilePath, folderName: string): Promise<FilePath> { const newFolder = new FilePath(container, { children: [], isFile: false, name: folderName, size: 0, modTime: 0 }); const path = FilePath.join(container.getFullName(), folderName); const data = await apiRequest("CreateFolder", { path }); if (data.error) { alert(`Cannot create folder at '${path}'`); throw new Error(data.error); } newFolder["_modTime"] = data["modTime"]; container["_files"].push(newFolder); container._sort(); this._hash = ""; const change = new FileStorageChange(); change.recordAdd(newFolder.getFullName()); this.fireChange(change); return newFolder; } async getFileString(file: FilePath): Promise<string> { // const data = await apiRequest("GetFileString", { // path: file.getFullName() // }); // // if (data.error) { // alert(`Cannot get file content of '${file.getFullName()}'`); // return null; // } // // const content = data["content"]; // // return content; const resp = await fetch(file.getUrl(), { method: "GET" }); const content = await resp.text(); if (!resp.ok) { alert(`Cannot get the content of file '${file.getFullName()}'.`); return null; } return content; } async setFileString(file: FilePath, content: string): Promise<void> { await this.setFileString_priv(file, content); this._hash = ""; const change = new FileStorageChange(); change.recordModify(file.getFullName()); this.fireChange(change); } private async setFileString_priv(file: FilePath, content: string): Promise<void> { const data = await apiRequest("SetFileString", { path: file.getFullName(), content }); if (data.error) { alert(`Cannot set file content to '${file.getFullName()}'`); throw new Error(data.error); } const fileData = data as IFileData; file._setModTime(fileData.modTime); file._setSize(fileData.size); } async deleteFiles(files: FilePath[]) { const data = await apiRequest("DeleteFiles", { paths: files.map(file => file.getFullName()) }); if (data.error) { alert(`Cannot delete the files.`); throw new Error(data.error); } const deletedSet = new Set<FilePath>(); for (const file of files) { deletedSet.add(file); for (const file2 of file.flatTree([], true)) { deletedSet.add(file2); } } const change = new FileStorageChange(); for (const file of deletedSet) { file._remove(); change.recordDelete(file.getFullName()); } this._hash = ""; this.fireChange(change); } async renameFile(file: FilePath, newName: string) { const data = await apiRequest("RenameFile", { oldPath: file.getFullName(), newPath: FilePath.join(file.getParent().getFullName(), newName) }); if (data.error) { alert(`Cannot rename the file.`); throw new Error(data.error); } const fromPath = file.getFullName(); file._setName(newName); file.getParent()._sort(); this._hash = ""; const change = new FileStorageChange(); change.recordRename(fromPath, file.getFullName()); this.fireChange(change); } async copyFile(fromFile: FilePath, toFolder: FilePath) { const base = fromFile.getNameWithoutExtension(); let ext = fromFile.getExtension(); if (ext) { ext = "." + ext; } let suffix = ""; while (toFolder.getFile(base + suffix + ext)) { suffix += "_copy"; } const newName = base + suffix + ext; const data = await apiRequest("CopyFile", { fromPath: fromFile.getFullName(), toPath: FilePath.join(toFolder.getFullName(), newName) }); if (data.error) { alert(`Cannot copy the file ${fromFile.getFullName()}`); throw new Error(data.error); } const fileData = data.file as IFileData; const newFile = new FilePath(null, fileData); toFolder._add(newFile); this._hash = ""; const change = new FileStorageChange(); change.recordAdd(newFile.getFullName()); this.fireChange(change); return newFile; } async moveFiles(movingFiles: FilePath[], moveTo: FilePath): Promise<void> { const data = await apiRequest("MoveFiles", { movingPaths: movingFiles.map(file => file.getFullName()), movingToPath: moveTo.getFullName() }); const records = movingFiles.map(file => { return { from: file.getFullName(), to: FilePath.join(moveTo.getFullName(), file.getName()) }; }); if (data.error) { alert(`Cannot move the files.`); throw new Error(data.error); } for (const srcFile of movingFiles) { const i = srcFile.getParent().getFiles().indexOf(srcFile); srcFile.getParent().getFiles().splice(i, 1); moveTo._add(srcFile); } this._hash = ""; const change = new FileStorageChange(); for (const record of records) { change.recordRename(record.from, record.to); } this.fireChange(change); } async uploadFile(uploadFolder: FilePath, htmlFile: File): Promise<FilePath> { const formData = new FormData(); formData.append("uploadTo", uploadFolder.getFullName()); formData.append("file", htmlFile); const resp = await fetch("upload", { method: "POST", body: formData }); const data = await resp.json(); if (data.error) { alert(`Error sending file ${htmlFile.name}`); throw new Error(data.error); } const fileData = data.file as IFileData; let file = uploadFolder.getFile(htmlFile.name); const change = new FileStorageChange(); if (file) { file._setModTime(fileData.modTime); file._setSize(fileData.size); change.recordModify(file.getFullName()); } else { file = new FilePath(null, fileData); uploadFolder._add(file); change.recordAdd(file.getFullName()); } this._hash = ""; this.fireChange(change); return file; } async getImageSize(file: FilePath): Promise<ImageSize> { const key = "GetImageSize_" + file.getFullName() + "@" + file.getModTime(); const cache = localStorage.getItem(key); if (cache) { return JSON.parse(cache); } const data = await colibri.core.io.apiRequest("GetImageSize", { path: file.getFullName() }); if (data.error) { return null; } const size = { width: data.width, height: data.height }; window.localStorage.setItem(key, JSON.stringify(size)); return size; } } }
the_stack
import { OutcomesConfig, OutcomeAttribution, OutcomeAttributionType, SentUniqueOutcome } from '../../models/Outcomes'; import { NotificationClicked, NotificationReceived } from '../../models/Notification'; import Database from "../../services/Database"; import Log from "../../libraries/Log"; import { Utils } from "../../context/shared/utils/Utils"; import { logMethodCall, awaitOneSignalInitAndSupported } from '../../utils'; import OutcomeProps from '../../models/OutcomeProps'; const SEND_OUTCOME = "sendOutcome"; const SEND_UNIQUE_OUTCOME = "sendUniqueOutcome"; export default class OutcomesHelper { private outcomeName: string; private config: OutcomesConfig; private appId: string; private isUnique: boolean; /** * @param {string} appId * @param {OutcomesConfig} config - refers specifically to outcomes config * @param {boolean} isUnique * @param {string} outcomeName */ constructor(appId: string, config: OutcomesConfig, outcomeName: string, isUnique: boolean) { this.outcomeName = outcomeName; this.config = config; this.appId = appId; this.isUnique = isUnique; } /** * Returns `OutcomeAttribution` object which includes * 1) attribution type * 2) notification ids * * Note: this just looks at notifications that fall within the attribution window and * does not check if they have been previously attributed (used in both sendOutcome & sendUniqueOutcome) * @returns Promise */ async getAttribution(): Promise<OutcomeAttribution> { return await OutcomesHelper.getAttribution(this.config); } /** * Performs logging of method call and returns whether Outcomes are supported * @param {boolean} isUnique * @returns Promise */ async beforeOutcomeSend(): Promise<boolean>{ const outcomeMethodString = this.isUnique ? SEND_UNIQUE_OUTCOME : SEND_OUTCOME; logMethodCall(outcomeMethodString, this.outcomeName); if (!this.config) { Log.debug("Outcomes feature not supported by main application yet."); return false; } if (!this.outcomeName) { Log.error("Outcome name is required"); return false; } await awaitOneSignalInitAndSupported(); const isSubscribed = await OneSignal.privateIsPushNotificationsEnabled(); if (!isSubscribed) { Log.warn("Reporting outcomes is supported only for subscribed users."); return false; } return true; } /** * Returns array of notification ids outcome is currently attributed with * @param {string} outcomeName * @returns Promise */ async getAttributedNotifsByUniqueOutcomeName(): Promise<string[]> { const sentOutcomes = await Database.getAll<SentUniqueOutcome>("SentUniqueOutcome"); return sentOutcomes .filter(o => o.outcomeName === this.outcomeName) .reduce((acc: string[], curr: SentUniqueOutcome) => { const notificationIds = curr.notificationIds || []; return [...acc, ...notificationIds]; }, []); } /** * Returns array of new notifications that have never been attributed to the outcome * @param {string} outcomeName * @param {string[]} notificationIds */ async getNotifsToAttributeWithUniqueOutcome(notificationIds: string[]) { const previouslyAttributedArr: string[] = await this.getAttributedNotifsByUniqueOutcomeName(); return notificationIds.filter(id => (previouslyAttributedArr.indexOf(id) === -1)); } shouldSendUnique(outcomeAttribution: OutcomeAttribution, notifArr: string[]) { // we should only send if type is unattributed OR there are notifs to attribute if (outcomeAttribution.type === OutcomeAttributionType.Unattributed) { return true; } return notifArr.length > 0; } async saveSentUniqueOutcome(newNotificationIds: string[]): Promise<void>{ const outcomeName = this.outcomeName; const existingSentOutcome = await Database.get<SentUniqueOutcome>("SentUniqueOutcome", outcomeName); const currentSession = await Database.getCurrentSession(); const existingNotificationIds = !!existingSentOutcome ? existingSentOutcome.notificationIds : []; const notificationIds = [...existingNotificationIds, ...newNotificationIds]; const timestamp = currentSession ? currentSession.startTimestamp : null; await Database.put("SentUniqueOutcome", { outcomeName, notificationIds, sentDuringSession: timestamp }); } async wasSentDuringSession() { const sentOutcome = await Database.get<SentUniqueOutcome>("SentUniqueOutcome", this.outcomeName); if (!sentOutcome) { return false; } const session = await Database.getCurrentSession(); const sessionExistsAndWasPreviouslySent = session && sentOutcome.sentDuringSession === session.startTimestamp; const sessionWasClearedButWasPreviouslySent = !session && !!sentOutcome.sentDuringSession; return sessionExistsAndWasPreviouslySent || sessionWasClearedButWasPreviouslySent; } async send(outcomeProps: OutcomeProps): Promise<void>{ const { type, notificationIds, weight } = outcomeProps; switch (type) { case OutcomeAttributionType.Direct: if (this.isUnique) { await this.saveSentUniqueOutcome(notificationIds); } await OneSignal.context.updateManager.sendOutcomeDirect( this.appId, notificationIds, this.outcomeName, weight ); return; case OutcomeAttributionType.Indirect: if (this.isUnique) { await this.saveSentUniqueOutcome(notificationIds); } await OneSignal.context.updateManager.sendOutcomeInfluenced( this.appId, notificationIds, this.outcomeName, weight ); return; case OutcomeAttributionType.Unattributed: if (this.isUnique) { if (await this.wasSentDuringSession()) { Log.warn(`(Unattributed) unique outcome was already sent during this session`); return; } await this.saveSentUniqueOutcome([]); } await OneSignal.context.updateManager.sendOutcomeUnattributed( this.appId, this.outcomeName, weight); return; default: Log.warn("You are on a free plan. Please upgrade to use this functionality."); return; } } // statics /** * Static method: returns `OutcomeAttribution` object which includes * 1) attribution type * 2) notification ids * * Note: this just looks at notifications that fall within the attribution window and * does not check if they have been previously attributed (used in both sendOutcome & sendUniqueOutcome) * @param {OutcomesConfig} config * @returns Promise */ static async getAttribution(config: OutcomesConfig): Promise<OutcomeAttribution> { /** * Flow: * 1. check if the url was opened as a result of a notif; * 2. if so, send an api call reporting direct notification outcome * (currently takes into account the match strategy selected in the app's settings); * 3. else check all received notifs within timeframe from config; * 4. send an api call reporting an influenced outcome for each matching notification * respecting the limit from config too; * 5. if no influencing notification found, report unattributed outcome to the api. */ /* direct notifications */ if (config.direct && config.direct.enabled) { const clickedNotifications = await Database.getAll<NotificationClicked>("NotificationClicked"); if (clickedNotifications.length > 0) { return { type: OutcomeAttributionType.Direct, notificationIds: [clickedNotifications[0].notificationId] }; } } /* influencing notifications */ if (config.indirect && config.indirect.enabled) { const timeframeMs = config.indirect.influencedTimePeriodMin * 60 * 1000; const beginningOfTimeframe = new Date(new Date().getTime() - timeframeMs); const maxTimestamp = beginningOfTimeframe.getTime(); const allReceivedNotification = await Database.getAll<NotificationReceived>("NotificationReceived"); Log.debug(`\tFound total of ${allReceivedNotification.length} received notifications`); if (allReceivedNotification.length > 0) { const max: number = config.indirect.influencedNotificationsLimit; /** * To handle correctly the case when user got subscribed to a new app id * we check the appId on notifications to match the current app. */ const allReceivedNotificationSorted = Utils.sortArrayOfObjects( allReceivedNotification, (notif: NotificationReceived) => notif.timestamp, true, false ); const matchingNotificationIds = allReceivedNotificationSorted .filter(notif => notif.timestamp >= maxTimestamp) .slice(0, max) .map(notif => notif.notificationId); Log.debug(`\tTotal of ${matchingNotificationIds.length} received notifications are within reporting window.`); // Deleting all unmatched received notifications const notificationIdsToDelete = allReceivedNotificationSorted .filter(notif => matchingNotificationIds.indexOf(notif.notificationId) === -1) .map(notif => notif.notificationId); notificationIdsToDelete.forEach(id => Database.remove("NotificationReceived", id)); Log.debug(`\t${notificationIdsToDelete.length} received notifications will be deleted.`); if (matchingNotificationIds.length > 0) { return { type: OutcomeAttributionType.Indirect, notificationIds: matchingNotificationIds, }; } } } /* unattributed outcome report */ if (config.unattributed && config.unattributed.enabled) { return { type: OutcomeAttributionType.Unattributed, notificationIds: [] }; } return { type: OutcomeAttributionType.NotSupported, notificationIds: [], }; } }
the_stack
import Adapt, { BuildData, BuildHelpers, BuiltinProps, childrenIsEmpty, DeferredComponent, gql, ObserveForStatus, SFCBuildProps, waiting, WithChildren} from "@adpt/core"; import { minBy } from "lodash"; import { isArray } from "util"; import { mountedElement } from "../common"; import { ClusterInfo, computeNamespaceFromMetadata, LabelSelector, Metadata, PodTemplateSpec, ResourceBase, ResourcePropsWithConfig } from "./common"; import { K8sObserver } from "./k8s_observer"; import { deployIDToLabel, labelKey, registerResourceKind, resourceIdToName } from "./manifest_support"; import { Resource } from "./Resource"; import { isResourcePodTemplate } from "./utils"; /** @public */ export interface DeploymentUpdateStrategyRecreate { type: "Recreate"; } /** @public */ export interface RollingUpdateDeployment { /** * The maximum number of pods that can be scheduled above the desired number of pods. * * Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). * This can not be 0 if MaxUnavailable is 0. * Absolute number is calculated from percentage by rounding up. * Defaults to 25%. * * @example * When this is set to 30%, the new ReplicaSet can be scaled up immediately when the rolling update starts, * such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been * killed, new ReplicaSet can be scaled up further, ensuring that total number of pods running at any time * during the update is at most 130% of desired pods. */ maxSurge?: number | string; /** * The maximum number of pods that can be unavailable during the update. * * Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). * Absolute number is calculated from percentage by rounding down. * This can not be 0 if MaxSurge is 0. Defaults to 25%. * * @example * When this is set to 30%, the old ReplicaSet can be scaled down to 70% of desired pods * immediately when the rolling update starts. Once new pods are ready, old ReplicaSet * can be scaled down further, followed by scaling up the new ReplicaSet, ensuring that * the total number of pods available at all times during the update is at least 70% of * desired pods. */ maxUnavailable?: number | string; } /** Rolling update configuration for {@link k8s.DeploymentUpdateStrategy } */ interface DeploymentUpdateStrategyRollingUpdate { type: "RollingUpdate"; rollingUpdate?: RollingUpdateDeployment; } /** * Update Strategy for {@link k8s.Deployment} * * @public */ type DeploymentUpdateStrategy = DeploymentUpdateStrategyRollingUpdate | DeploymentUpdateStrategyRecreate; /** * Spec for {@link k8s.Deployment} for use in {@link k8s.Resource} * * @public */ export type DeploymentSpec = Exclude<DeploymentProps, ResourceBase> & { template: PodTemplateSpec }; /** * Props for {@link k8s.Deployment} * * @public */ export interface DeploymentProps extends WithChildren { /** Information about the k8s cluster (ip address, auth info, etc.) */ config: ClusterInfo; /** k8s metadata */ metadata: Metadata; /** * The minimum number of seconds for which a newly created pod should * be ready without any of its container crashing, for it to be considered * available. Defaults to 0 (pod will be considered available as soon as it is ready). */ minReadySeconds: number; /** Indicates that the deployment is paused */ paused: boolean; /** * The maximum time in seconds for a deployment to make progress before it is considered to be failed. * * The deployment controller will continue to process failed deployments and a condition with a * ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress * will not be estimated during the time a deployment is paused. Defaults to 600s. */ progressDeadlineSeconds: number; /** * Number of desired pods. * * Defaults to 1. 0 is not allowed. * * @defaultValue 1 */ replicas: number; /** * The number of old ReplicaSets to retain to allow rollback. * * This is a pointer to distinguish between explicit zero and not specified. Defaults to 10. * * @defaultValue 10 */ revisionHistoryLimit: number; /** * Label selector for pods. * * Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment. * It must match the pod template's labels. * * @remarks * * With Adapt, this is optional. If not specified, adapt will pick a selector that will work with the pods * it creates as part of this {@link k8s.Deployment} */ selector?: LabelSelector; /** * An deployment strategy to use to replace existing pods with new ones */ strategy: DeploymentUpdateStrategy; } function checkChildren(children: any) { if ((isArray(children) && children.length !== 1) || children == null) { throw new Error(`Deployment must only have a single Pod as a child, found ${children == null ? 0 : children.length}`); } const child = isArray(children) ? children[0] : children; if (!isResourcePodTemplate(child)) throw new Error(`Deployment child must be a Pod with the isTemplate prop set`); return child; } function makeDeploymentManifest(props: SFCBuildProps<DeploymentProps>, id: string, helpers: BuildHelpers) { const { metadata, minReadySeconds, paused, progressDeadlineSeconds, replicas, revisionHistoryLimit, selector: userSelector, strategy, children } = props; const child = checkChildren(children); const { deployID } = helpers; const labels = { [labelKey("deployment")]: resourceIdToName(props.key, id, deployID), [labelKey("deployID")]: deployIDToLabel(deployID), }; const podMetadataOrig = child.props.metadata || {}; const podMetadata = { ...podMetadataOrig, labels: { ...podMetadataOrig.labels, ...labels, }, annotations: { ...podMetadataOrig.annotations || {}, [labelKey("deployID")]: helpers.deployID, } }; const podSpec = child.props.spec; const selector = userSelector ? userSelector : { matchLabels: labels }; const spec = { minReadySeconds, paused, progressDeadlineSeconds, replicas, revisionHistoryLimit, selector, strategy, template: { metadata: podMetadata, spec: podSpec } }; return { metadata, spec }; } /** * Component for Kubernetes Deployment * * @public */ export class Deployment extends DeferredComponent<DeploymentProps> { static defaultProps = { metadata: {}, paused: false, replicas: 1, progressDeadlineSeconds: 600, minReadySeconds: 0, revisionHistoryLimit: 10, strategy: { type: "RollingUpdate", rollingUpdate: { maxSurge: "25%", maxUnavailable: "25%" }, } }; constructor(props: DeploymentProps) { super(props); if (!childrenIsEmpty(props.children)) checkChildren(props.children); } build(helpers: BuildHelpers) { const props = this.props as DeploymentProps & Required<BuiltinProps>; const { key, config } = props; if (childrenIsEmpty(props.children)) return null; const manifest = makeDeploymentManifest(props, mountedElement(props).id, helpers); return <Resource key={key} config={config} apiVersion="apps/v1" kind="Deployment" metadata={manifest.metadata} spec={manifest.spec} />; } deployedWhen = () => { if (childrenIsEmpty(this.props.children)) { return waiting("No pods specified, or waiting for Pod elements to not build to null"); } return true; } async status(_observe: ObserveForStatus, buildData: BuildData) { const succ = buildData.successor; if (!succ) return undefined; return succ.status(); } } function deployedWhen(statusObj: unknown) { const status: any = statusObj; if (!status || !status.status) return waiting(`Kubernetes cluster returned invalid status for Deployment`); const { availableReplicas, readyReplicas, replicas, updatedReplicas, conditions, } = status.status; const replicasDesired = status.spec.replicas; const ready = minBy([ { val: availableReplicas, field: "available" }, { val: readyReplicas, field: "ready" }, { val: updatedReplicas, field: "updated"}, { val: replicas, field: "current" }], (val) => val.val == null ? 0 : val.val)!; if (ready.val >= replicasDesired) return true; const conditionText = conditions && isArray(conditions) ? "\n" + conditions.map((c) => c.message).filter((c) => c.status !== "True").join("\n") : ""; return waiting( `Waiting for enough pods (${ready.val != null ? ready.val : 0} (${ready.field})/${replicasDesired} (desired)` + conditionText); } /** @internal */ export const deploymentResourceInfo = { kind: "Deployment", deployedWhen, statusQuery: async (props: ResourcePropsWithConfig, observe: ObserveForStatus, buildData: BuildData) => { const obs: any = await observe(K8sObserver, gql` query ($name: String!, $kubeconfig: JSON!, $namespace: String!) { withKubeconfig(kubeconfig: $kubeconfig) { readAppsV1NamespacedDeployment(name: $name, namespace: $namespace) @all(depth: 100) } }`, { name: resourceIdToName(props.key, buildData.id, buildData.deployID), kubeconfig: props.config.kubeconfig, namespace: computeNamespaceFromMetadata(props.metadata) } ); return obs.withKubeconfig.readAppsV1NamespacedDeployment; }, }; registerResourceKind(deploymentResourceInfo);
the_stack
import "es6-promise/auto"; import * as Calendar_Contracts from "./Contracts"; import * as Context from "VSS/Context"; import * as Controls from "VSS/Controls"; import * as Controls_Contributions from "VSS/Contributions/Controls"; import * as Controls_Notifications from "VSS/Controls/Notifications"; import * as Controls_Combos from "VSS/Controls/Combos"; import * as Controls_Dialog from "VSS/Controls/Dialogs"; import * as Controls_Validation from "VSS/Controls/Validation"; import * as Culture from "VSS/Utils/Culture"; import * as Utils_Date from "VSS/Utils/Date"; import * as Utils_String from "VSS/Utils/String"; import * as Utils_UI from "VSS/Utils/UI"; import * as WebApi_Contracts from "VSS/WebApi/Contracts"; import * as Work_Contracts from "TFS/Work/Contracts"; const domElem = Utils_UI.domElem; export interface IEventControlOptions { calendarEvent: Calendar_Contracts.CalendarEvent; title?: string; isEdit?: boolean; validStateChangedHandler: (valid: boolean) => any; membersPromise: PromiseLike<WebApi_Contracts.IdentityRef[]>; getIterations: () => PromiseLike<Work_Contracts.TeamSettingsIteration[]>; categoriesPromise: () => PromiseLike<Calendar_Contracts.IEventCategory[]>; } export interface IEventDialogOptions extends Controls_Dialog.IModalDialogOptions { source: Calendar_Contracts.IEventSource; calendarEvent: Calendar_Contracts.CalendarEvent; query: Calendar_Contracts.IEventQuery; membersPromise?: PromiseLike<WebApi_Contracts.IdentityRef[]>; isEdit?: boolean; } export class EditEventDialog extends Controls_Dialog.ModalDialogO<IEventDialogOptions> { private _$container: JQuery; private _calendarEvent: Calendar_Contracts.CalendarEvent; private _source: Calendar_Contracts.IEventSource; private _contributedControl: Calendar_Contracts.IDialogContent; private _content: Calendar_Contracts.IAddEventContent; private _$contributedContent: JQuery; private _eventValidationError: Controls_Notifications.MessageAreaControl; private _contributionsValid: boolean; private _$titleInput: JQuery; private _$startInput: JQuery; private _$endInput: JQuery; private _$textInputs: JQuery[]; private _$comboInputs: JQuery[]; public initializeOptions(options?: any) { super.initializeOptions( $.extend(options, { height: 345, coreCssClass: "add-event-dialog", }), ); } public initialize() { super.initialize(); this._calendarEvent = this._options.calendarEvent; this._source = this._options.source; this._contributionsValid = true; this._$textInputs = []; this._$comboInputs = []; // default content this._content = <Calendar_Contracts.IAddEventContent>{ title: true, start: true, end: true, }; this._createLayout(); } /** * Processes the data that the user has entered and either * shows an error message, or returns the edited note. */ public onOkClick(): any { this._buildCalendarEventFromFields().then(results => { if (this._contributedControl) { this._contributedControl.onOkClick().then(event => { this._calendarEvent = $.extend(this._calendarEvent, event); this.processResult(this._calendarEvent); }); } else { this.processResult(this._calendarEvent); } }); } private _createLayout() { this._$container = $(domElem("div")) .addClass("edit-event-container") .appendTo(this._element); this._$contributedContent = $(domElem("div")) .addClass("contributed-content-container") .appendTo(this._element); const membersPromise = this._options.membersPromise; let content; if (this._source.getEnhancer) { this._source.getEnhancer().then( enhancer => { const options = { calendarEvent: this._calendarEvent, isEdit: this._options.isEdit, categoriesPromise: this._source.getCategories.bind(this, this._options.query), validStateChangedHandler: (valid: boolean) => { this._contributionsValid = valid; // Erhm... e => { this._validate(true); }; }, membersPromise: this._options.membersPromise, getIterations: !!(<any>this._source).getIterations ? (<any>this._source).getIterations.bind(this._source) : null, }; Controls_Contributions.createContributedControl<Calendar_Contracts.IDialogContent>( this._$contributedContent, enhancer.addDialogId, $.extend(options, { bowtieVersion: 2 }), Context.getDefaultWebContext(), ).then( (control: Calendar_Contracts.IDialogContent) => { try { this._contributedControl = control; if (this._contributedControl.getContributedHeight) { this._contributedControl.getContributedHeight().then((height: number) => { this._$contributedContent.find(".external-content-host").css("height", height); }); } else { this._$contributedContent.find(".external-content-host").css("height", 0); } this._contributedControl.getTitle().then((title: string) => { this.setTitle(title); }); this._contributedControl.getFields().then((fields: Calendar_Contracts.IAddEventContent) => { this._content = fields; this._renderContent(); }); } catch (error) { this._renderContent(); } }, error => { this._renderContent(); }, ); }, error => { this._renderContent(); }, ); } else { this._renderContent(); } } private _renderContent() { this._eventValidationError = <Controls_Notifications.MessageAreaControl>Controls.BaseControl.createIn( Controls_Notifications.MessageAreaControl, this._$container, { closeable: false }, ); const $editControl = $(domElem("div", "event-edit-control")); const $fieldsContainer = $(domElem("table")).appendTo($editControl); // Build title input if (this._content.title) { this._$titleInput = $("<input type='text' class='requiredInfoLight' id='fieldTitle'/>") .val(this._calendarEvent.title) .bind("blur", e => { this._validate(true); }); } const startDateString = Utils_Date.localeFormat( Utils_Date.shiftToUTC(new Date(this._calendarEvent.startDate)), Culture.getDateTimeFormat().ShortDatePattern, true, ); let endDateString = startDateString; // Build start input if (this._content.start) { this._$startInput = $("<input type='text' id='fieldStartDate' />") .val(startDateString) .bind("blur", e => { this._validate(true); }); } // Build end input if (this._content.end) { if (this._calendarEvent.endDate) { endDateString = Utils_Date.localeFormat( Utils_Date.shiftToUTC(new Date(this._calendarEvent.endDate)), Culture.getDateTimeFormat().ShortDatePattern, true, ); } this._$endInput = $("<input type='text' id='fieldEndDate' />").bind("blur", e => { this._validate(true); }); this._$endInput.val(endDateString); } // Build text inputs if (this._content.textFields) { const textFields = this._content.textFields; for (const textField of textFields) { const textInput = $( Utils_String.format("<input type='text' class='requiredInfoLight' id='field{0}'/>", textField.label), ); if (textField.checkValid) { textInput.bind("blur", e => { this._validate(true); }); } if (textField.initialValue) { textInput.val(textField.initialValue); } if (textField.disabled) { textInput.prop("disabled", true); } this._$textInputs.push(textInput); } } // Build combo inputs if (this._content.comboFields) { const comboFields = this._content.comboFields; for (const comboField of comboFields) { const comboInput = $( Utils_String.format("<input type='text' class='requiredInfoLight' id='field{0}' />", comboField.label), ); if (comboField.initialValue) { comboInput.val(comboField.initialValue); } if (comboField.checkValid) { comboInput.bind("blur", e => { this._validate(true); }); } this._$comboInputs.push(comboInput); } } // Populate fields container with fields. The form fields array contain pairs of field label and field element itself. const fields = this._getFormFields(); for (let i = 0, l = fields.length; i < l; i += 1) { const labelName = fields[i][0]; const field = fields[i][1]; if (field) { if (i === 0) { field.attr("autofocus", true); } const $row = $(domElem("tr")); const fieldId = field.attr("id") || $("input", field).attr("id"); $(domElem("label")) .attr("for", fieldId) .text(labelName) .appendTo($(domElem("td", "label")).appendTo($row)); field.appendTo($(domElem("td")).appendTo($row)); $row.appendTo($fieldsContainer); } } this._$container.append($editControl).bind("keyup", event => { if (event.keyCode == Utils_UI.KeyCode.ENTER) { this.onOkClick(); } else if (event.keyCode == Utils_UI.KeyCode.ESCAPE) { this.onClose(); } }); if (this._content.comboFields) { this._buildComboControls(); } // Add date pickers combos to DOM <Controls_Combos.Combo>Controls.Enhancement.enhance(Controls_Combos.Combo, this._$startInput, { type: "date-time", }); <Controls_Combos.Combo>Controls.Enhancement.enhance(Controls_Combos.Combo, this._$endInput, { type: "date-time", }); this._setupValidators(); this._validate(); } private _setupValidators() { this._setupRequiredValidators(this._$titleInput, "Title cannot be empty"); this._setupDateValidators(this._$startInput, "Start date must be a valid date"); this._setupDateValidators( this._$endInput, "End date must be a valid date", "End date must be equal to or after start date", this._$startInput, DateComparisonOptions.GREATER_OR_EQUAL, ); // push text input fields for (let i = 0; i < this._$textInputs.length; i++) { const textField = this._content.textFields[i]; if (!textField.checkValid && textField.requiredField) { this._setupRequiredValidators(this._$textInputs[i], textField.validationErrorMessage); } } // push combo input fields for (let i = 0; i < this._$comboInputs.length; i++) { const comboField = this._content.comboFields[i]; if (!comboField.checkValid && comboField.requiredField) { this._setupRequiredValidators(this._$comboInputs[i], comboField.validationErrorMessage); } } } private _getFormFields(): any[] { const fields = []; // push basic fields fields.push(["Title", this._$titleInput]); fields.push(["Start Date", this._$startInput]); fields.push(["End Date", this._$endInput]); // push text input fields const textFields = this._content.textFields; const textInputs = this._$textInputs; for (let i = 0; i < textInputs.length; i++) { fields.push([textFields[i].label, textInputs[i]]); } // push combo input fields const comboFields = this._content.comboFields; const comboInputs = this._$comboInputs; for (let i = 0; i < comboInputs.length; i++) { fields.push([comboFields[i].label, comboInputs[i]]); } return fields; } private _buildComboControls() { const comboFields = this._content.comboFields; const comboInputs = this._$comboInputs; for (let i = 0; i < comboInputs.length; i++) { if (comboFields[i].disabled) { comboInputs[i].prop("disabled", true); } else { Controls.Enhancement.enhance(Controls_Combos.Combo, comboInputs[i], { source: comboFields[i].items, dropCount: 3, }); } } } private _buildCalendarEventFromFields(): PromiseLike<any> { if (this._$startInput) { this._calendarEvent.startDate = Utils_Date.shiftToLocal( Utils_Date.parseDateString(this._$startInput.val(), Culture.getDateTimeFormat().ShortDatePattern, true), ).toISOString(); } if (this._$endInput) { this._calendarEvent.endDate = Utils_Date.shiftToLocal( Utils_Date.parseDateString(this._$endInput.val(), Culture.getDateTimeFormat().ShortDatePattern, true), ).toISOString(); } if (this._$titleInput) { this._calendarEvent.title = $.trim(this._$titleInput.val()); } const promises: PromiseLike<any>[] = []; // create event data from text fields const textFields = this._content.textFields; const textInputs = this._$textInputs; for (let i = 0; i < textInputs.length; i++) { if (textFields[i].okCallback) { promises.push(textFields[i].okCallback(textInputs[i].val())); } else if (textFields[i].eventProperty) { this._calendarEvent[textFields[i].eventProperty] = $.trim(textInputs[i].val()); } } // create event data from combo fields const comboFields = this._content.comboFields; const comboInputs = this._$comboInputs; for (let i = 0; i < comboInputs.length; i++) { if (comboFields[i].okCallback) { promises.push(comboFields[i].okCallback(comboInputs[i].val())); } else if (comboFields[i].eventProperty) { this._calendarEvent[comboFields[i].eventProperty] = $.trim(comboInputs[i].val()); } } return Promise.all(promises); } private _validate(showError?: boolean) { if (!this._contributionsValid) { this._clearError(); this.updateOkButton(false); return; } const validationResult = []; const groupIsValid: boolean = Controls_Validation.validateGroup("default", validationResult); if (!groupIsValid) { if (showError) { this._setError(validationResult[0].getMessage()); } this.updateOkButton(false); return; } const errorPromises: PromiseLike<string>[] = []; // validate text input fields const textFields = this._content.textFields; const textInputs = this._$textInputs; for (let i = 0; i < textInputs.length; i++) { const textField = textFields[i]; if (textField.checkValid) { errorPromises.push( textField.checkValid($.trim(textInputs[i].val())).then((isValid: boolean) => { if (!isValid) { return textField.validationErrorMessage; } return "valid"; }), ); } } // validate combo input fields const comboFields = this._content.comboFields; const comboInputs = this._$comboInputs; for (let i = 0; i < comboInputs.length; i++) { const comboField = comboFields[i]; if (comboField.checkValid && !comboField.disabled) { errorPromises.push( comboField.checkValid($.trim(comboInputs[i].val())).then((isValid: boolean) => { if (!isValid) { return comboField.validationErrorMessage; } return "valid"; }), ); } } return Promise.all(errorPromises).then((results: string[]) => { const invalidMessages = results.filter(r => r !== "valid"); if (invalidMessages && invalidMessages.length > 0) { if (showError) { this._setError(invalidMessages[0]); } this.updateOkButton(false); return; } this._clearError(); this.updateOkButton(true); }); } private _setupDateValidators( $field: JQuery, validDateFormatMessage: string, relativeToErrorMessage?: string, $relativeToField?: JQuery, dateComparisonOptions?: DateComparisonOptions, ) { <Controls_Validation.DateValidator< Controls_Validation.DateValidatorOptions >>Controls.Enhancement.enhance(Controls_Validation.DateValidator, $field, { invalidCssClass: "date-invalid", group: "default", message: validDateFormatMessage, parseFormat: Culture.getDateTimeFormat().ShortDatePattern, }); this._setupRequiredValidators($field, validDateFormatMessage); if (relativeToErrorMessage) { <DateRelativeToValidator>Controls.Enhancement.enhance(DateRelativeToValidator, $field, { comparison: dateComparisonOptions, relativeToField: $relativeToField, group: "default", message: relativeToErrorMessage, parseFormat: Culture.getDateTimeFormat().ShortDatePattern, }); } } private _setupRequiredValidators($field: JQuery, requiredFieldMessage: string) { <Controls_Validation.RequiredValidator< Controls_Validation.BaseValidatorOptions >>Controls.Enhancement.enhance(Controls_Validation.RequiredValidator, $field, <Controls_Validation.BaseValidatorOptions>{ invalidCssClass: "field-invalid", group: "default", message: requiredFieldMessage, }); } private _setupCustomValidators($field: JQuery, validationFunction: (value: string) => boolean, invalidInputMessage: string) { <Controls_Validation.CustomValidator< Controls_Validation.CustomValidatorOptions >>Controls.Enhancement.enhance(Controls_Validation.CustomValidator, $field, <Controls_Validation.CustomValidatorOptions>{ invalidCssClass: "field-invalid", group: "default", message: invalidInputMessage, validate: validationFunction, }); } private _setError(errorMessage: string) { if (errorMessage && errorMessage.length !== 0 && errorMessage !== "invalid") { this._eventValidationError.setError($("<span />").html(errorMessage)); } else { this._clearError(); } } private _clearError() { this._eventValidationError.clear(); } } /** * A control which allows users to add / edit free-form events. * In addition to start/end dates, allows user to enter a title and select a category. */ export class EditFreeFormEventControl extends Controls.Control<IEventControlOptions> implements Calendar_Contracts.IDialogContent { private _calendarEvent: Calendar_Contracts.CalendarEvent; private _categories: Calendar_Contracts.IEventCategory[]; private _$descriptionInput: JQuery; private static height: number = 50; public initializeOptions(options?: any) { super.initializeOptions( $.extend(options, { coreCssClass: "edit-freeform-control", }), ); } public initialize() { super.initialize(); this._categories = []; this._element.addClass("bowtie-style"); this._calendarEvent = this._options.calendarEvent; this._createLayout(); } public onOkClick(): PromiseLike<any> { return Promise.resolve({ movable: true, description: this._$descriptionInput.val(), category: this._calendarEvent.category, }); } public getTitle(): PromiseLike<string> { return Promise.resolve(this._options.isEdit ? "Edit Event" : "Add Event"); } public getContributedHeight(): PromiseLike<number> { return Promise.resolve(EditFreeFormEventControl.height); } public getFields(): PromiseLike<Calendar_Contracts.IAddEventContent> { return this._options.categoriesPromise().then((categories: Calendar_Contracts.IEventCategory[]) => { let categoryTitles = undefined; if (categories) { this._categories = categories; categoryTitles = categories.map(cat => { return cat.title; }); } return <Calendar_Contracts.IAddEventContent>{ title: true, start: true, end: true, comboFields: [ <Calendar_Contracts.IAddEventComboField>{ label: "Category", initialValue: this._calendarEvent.category ? this._calendarEvent.category.title : "", items: categoryTitles || [], okCallback: this._categoryCallback.bind(this), }, ], }; }); } private _createLayout() { const $container = $(domElem("table")).appendTo(this._element); const descriptionString = this._calendarEvent.description || ""; this._$descriptionInput = $("<textarea rows='3' id='descriptionText' class=''requiredInfoLight' />").val( descriptionString, ); const $row = $(domElem("tr")); $(domElem("label")) .attr("for", this._$descriptionInput.attr("id")) .text("Description") .appendTo($(domElem("td", "label")).appendTo($row)); this._$descriptionInput.appendTo($(domElem("td")).appendTo($row)); $row.appendTo($container); } private _categoryCallback(value: string): PromiseLike<any> { let title = $.trim(value); if (!title || title.length === 0) { title = "Uncategorized"; } let category: Calendar_Contracts.IEventCategory = { title: title, id: Utils_String.format("freeForm.{0}", title), }; const categories = this._categories.filter(cat => cat.title === value); if (categories && categories.length > 0) { category = categories[0]; } this._calendarEvent.category = category; return Promise.resolve(null); } } /** * A control which allows users to add / edit days off events. * In addition to start/end dates, allows user to select a user (or the entire team). */ export class EditCapacityEventControl extends Controls.Control<IEventControlOptions> implements Calendar_Contracts.IDialogContent { private _calendarEvent: Calendar_Contracts.CalendarEvent; private _members: WebApi_Contracts.IdentityRef[]; private _iterations: Work_Contracts.TeamSettingsIteration[]; private static EVERYONE: string = "Everyone"; private static height: number = 50; public initializeOptions(options?: any) { super.initializeOptions( $.extend(options, { coreCssClass: "edit-capacity-control", }), ); } public initialize() { super.initialize(); this._element.addClass("bowtie-style"); this._calendarEvent = this._options.calendarEvent; this._members = []; this._iterations = []; this._createLayout(); } public onOkClick(): any { return Promise.resolve({ iterationId: this._calendarEvent.iterationId, member: this._calendarEvent.member, }); } public getTitle(): PromiseLike<string> { return Promise.resolve(this._options.isEdit ? "Edit Day off" : "Add Day off"); } public getFields(): PromiseLike<Calendar_Contracts.IAddEventContent> { return this._options.membersPromise.then((members: WebApi_Contracts.IdentityRef[]) => { this._members = members; const memberNames = []; memberNames.push(EditCapacityEventControl.EVERYONE); members.sort((a, b) => { return a.displayName.toLocaleLowerCase().localeCompare(b.displayName.toLocaleLowerCase()); }); members.forEach((member: WebApi_Contracts.IdentityRef, index: number, array: WebApi_Contracts.IdentityRef[]) => { memberNames.push(member.displayName); }); const initialMemberValue = this._calendarEvent.member.displayName || ""; let disabled = false; if (this._options.isEdit) { disabled = true; } return this._options.getIterations().then(iterations => { this._iterations = iterations; let initialIterationValue = iterations[0].name; let iteration; if (this._calendarEvent.iterationId) { iteration = iterations.filter(i => i.id === this._calendarEvent.iterationId)[0]; } else { iteration = this._getCurrentIteration(iterations, new Date(this._calendarEvent.startDate)); } if (iteration) { initialIterationValue = iteration.name; } return <Calendar_Contracts.IAddEventContent>{ start: true, end: true, comboFields: [ <Calendar_Contracts.IAddEventComboField>{ label: "Team Member", initialValue: initialMemberValue, items: memberNames, disabled: disabled, checkValid: this._checkMemberValid.bind(this), okCallback: this._memberCallback.bind(this), }, <Calendar_Contracts.IAddEventComboField>{ label: "Iteration", initialValue: initialIterationValue, items: iterations.map(iteration => { return iteration.name; }), checkValid: this._checkIterationValid.bind(this), okCallback: this._iterationCallback.bind(this), }, ], }; }); }); } private _createLayout() { //no op } private _getCurrentIteration( iterations: Work_Contracts.TeamSettingsIteration[], date: Date, ): Work_Contracts.TeamSettingsIteration { return iterations.filter( (iteration: Work_Contracts.TeamSettingsIteration, index: number, array: Work_Contracts.TeamSettingsIteration[]) => { if ( iteration.attributes.startDate !== null && iteration.attributes.finishDate !== null && date.valueOf() >= iteration.attributes.startDate.valueOf() && date.valueOf() <= iteration.attributes.finishDate.valueOf() ) { return true; } }, )[0]; } private _iterationCallback(value: string): PromiseLike<any> { const iteration = this._iterations.filter(i => i.name === $.trim(value))[0]; if (iteration) { this._calendarEvent.iterationId = iteration.id; } return Promise.resolve(null); } private _checkIterationValid(value: string): PromiseLike<boolean> { return Promise.resolve(this._iterations.filter(i => i.name === $.trim(value)).length > 0); } private _memberCallback(value: string): PromiseLike<any> { const member = this._members.filter(m => m.displayName === $.trim(value))[0]; if (member) { this._calendarEvent.member = member; } else { this._calendarEvent.member = <WebApi_Contracts.IdentityRef>{ displayName: EditCapacityEventControl.EVERYONE, }; } return Promise.resolve(null); } private _checkMemberValid(value: string): PromiseLike<boolean> { return Promise.resolve( this._members.filter(m => m.displayName === $.trim(value)).length > 0 || value === EditCapacityEventControl.EVERYONE, ); } } interface DateRelativeToValidatorOptions extends Controls_Validation.BaseValidatorOptions { relativeToField: any; comparison: DateComparisonOptions; message: string; group: string; parseFormat?: string; } const enum DateComparisonOptions { GREATER_OR_EQUAL, LESS_OR_EQUAL, } class DateRelativeToValidator extends Controls_Validation.BaseValidator<DateRelativeToValidatorOptions> { constructor(options?: DateRelativeToValidatorOptions) { super(options); } public initializeOptions(options?: DateRelativeToValidatorOptions) { super.initializeOptions(<DateRelativeToValidatorOptions>$.extend( { invalidCssClass: "date-relative-to-invalid", }, options, )); } public isValid(): boolean { let fieldText = $.trim(this.getValue()), relativeToFieldText = $.trim(this._options.relativeToField.val()), fieldDate, relativeToFieldDate, result = false; if (fieldText && relativeToFieldText) { fieldDate = Utils_Date.parseDateString(fieldText, this._options.parseFormat, true); relativeToFieldDate = Utils_Date.parseDateString(relativeToFieldText, this._options.parseFormat, true); } else { return true; } if ( fieldDate instanceof Date && !isNaN(fieldDate.getTime()) && relativeToFieldDate instanceof Date && !isNaN(relativeToFieldDate.getTime()) ) { if (this._options.comparison === DateComparisonOptions.GREATER_OR_EQUAL) { result = fieldDate >= relativeToFieldDate; } else { result = fieldDate <= relativeToFieldDate; } } else { result = true; } return result; } public getMessage() { return this._options.message; } }
the_stack
import * as arraybuffers from '../../arraybuffers/arraybuffers'; import * as socks_headers from '../../socks/headers'; import * as proxyintegrationtesttypes from './proxy-integration-test.types'; import ProxyIntegrationTester = proxyintegrationtesttypes.ProxyIntegrationTester; import ReceivedDataEvent = proxyintegrationtesttypes.ReceivedDataEvent; declare const freedom: freedom.FreedomInCoreEnv; // Integration test for the whole proxying system. // The real work is done in the Freedom module which performs each test. export function socksEchoTestDescription(useChurn:boolean) { var testStrings = [ 'foo', 'bar', 'longer string', '1', 'that seems like enough' ]; var testerFactoryManager :freedom.FreedomModuleFactoryManager<ProxyIntegrationTester>; var createTestModule = function(denyLocalhost?:boolean, sessionLimit?:number, ipv6Only?:boolean, reproxy?:boolean) : ProxyIntegrationTester { return testerFactoryManager(denyLocalhost, useChurn, sessionLimit, ipv6Only, reproxy); }; beforeEach((done) => { freedom('files/freedom-module.json', { debug: 'debug' }).then((freedomModuleFactoryManager: any) => { testerFactoryManager = freedomModuleFactoryManager; done(); }); }); afterEach(() => { expect(testerFactoryManager).not.toBeUndefined(); // Close all created interfaces to the freedom module. testerFactoryManager.close(); }); it('run a simple echo test', (done) => { var input = arraybuffers.stringToArrayBuffer('arbitrary test string'); var testModule = createTestModule(); testModule.startEchoServer().then((port:number) => { return testModule.connect(port); }).then((connectionId:string) => { return testModule.echo(connectionId, input); }).then((output:ArrayBuffer) => { expect(arraybuffers.byteEquality(input, output)).toBe(true); }).catch((e:any) => { expect(e).toBeUndefined(); }).then(done); }); it('detects a remote close', (done) => { var input = arraybuffers.stringToArrayBuffer('arbitrary test string'); var testModule = createTestModule(); var connId : string; testModule.startEchoServer().then((port:number) => { return testModule.connect(port); }).then((connectionId:string) => { connId = connectionId; return testModule.echo(connectionId, input); }).then((output:ArrayBuffer) => { expect(arraybuffers.byteEquality(input, output)).toBe(true); testModule.on('sockClosed', (cnnid:string) => { expect(cnnid).toBe(connId); done(); }); testModule.closeEchoConnections(); }); }); it('run multiple echo tests in a batch on one connection', (done) => { var testBuffers = testStrings.map(arraybuffers.stringToArrayBuffer); var testModule = createTestModule(); testModule.startEchoServer().then((port:number) => { return testModule.connect(port); }).then((connectionId:string) => { return testModule.echoMultiple(connectionId, testBuffers); }).then((outputs:ArrayBuffer[]) => { var concatenatedInputs = arraybuffers.concat(testBuffers); var concatenatedOutputs = arraybuffers.concat(outputs); var isEqual = arraybuffers.byteEquality(concatenatedInputs, concatenatedOutputs); expect(isEqual).toBe(true); }).catch((e:any) => { expect(e).toBeUndefined(); }).then(done); }); it('run multiple echo tests in series on one connection', (done) => { var testBuffers = testStrings.map(arraybuffers.stringToArrayBuffer); var testModule = createTestModule(); testModule.startEchoServer().then((port:number) => { return testModule.connect(port); }).then((connectionId:string) => { var i = 0; return new Promise<void>((F, R) => { var step = () => { if (i == testBuffers.length) { F(); return; } testModule.echo(connectionId, testBuffers[i]) .then((echo:ArrayBuffer) => { expect(arraybuffers.byteEquality(testBuffers[i], echo)).toBe(true); ++i; }).then(step); }; step(); }); }).catch((e:any) => { expect(e).toBeUndefined(); }).then(done); }); it('connect to the same server multiple times in parallel', (done) => { var testModule = createTestModule(); testModule.startEchoServer().then((port:number) : Promise<any> => { var promises = testStrings.map((s:string) : Promise<void> => { var buffer = arraybuffers.stringToArrayBuffer(s); return testModule.connect(port).then((connectionId:string) => { return testModule.echo(connectionId, buffer); }).then((response:ArrayBuffer) => { expect(arraybuffers.byteEquality(buffer, response)).toBe(true); }); }); return Promise.all(promises); }).catch((e:any) => { expect(e).toBeUndefined(); }).then(done); }); xit('connect to many different servers in parallel', (done) => { var testModule = createTestModule(); var promises = testStrings.map((s:string) : Promise<void> => { var buffer = arraybuffers.stringToArrayBuffer(s); // For each string, start a new echo server with that name, and // then echo that string from that server. return testModule.startEchoServer().then((port:number) => { return testModule.connect(port); }).then((connectionId:string) => { return testModule.echo(connectionId, buffer); }).then((response:ArrayBuffer) => { expect(arraybuffers.byteEquality(buffer, response)).toBe(true); }); }); Promise.all(promises).catch((e:any) => { expect(e).toBeUndefined(); }).then(done); }); it('run a localhost echo test while localhost is blocked.', (done) => { // Get a test module that doesn't allow localhost access. var testModule = createTestModule(true); testModule.startEchoServer().then((port:number) => { return testModule.connect(port); }).then((connectionId:string) => { // This code should not run, because testModule.connect() should // reject with a NOT_ALLOWED error. expect(connectionId).toBeUndefined(); }, (e:any) => { expect(e.reply).toEqual(socks_headers.Reply.NOT_ALLOWED); }).then(done); }); var runUproxyOrg404Test = (testModule:ProxyIntegrationTester, done:Function) => { var nonExistentPath = '/noSuchPath'; var input = arraybuffers.stringToArrayBuffer( 'GET ' + nonExistentPath + ' HTTP/1.0\r\n\r\n'); testModule.connect(80, 'uproxy.org').then((connectionId:string) => { var isDone = false; var outputString = ''; testModule.on('receivedData', (event:ReceivedDataEvent) => { if (isDone) { return; } expect(event.connectionId).toEqual(connectionId); outputString += arraybuffers.arrayBufferToString(event.response); if ((outputString.indexOf('HTTP/1.0 404 Not Found') != -1 && outputString.indexOf(nonExistentPath) != -1) || outputString.indexOf('HTTP/1.1 403 Forbidden') != -1) { isDone = true; done(); } }); return testModule.sendData(connectionId, input); }).catch((e:any) => { expect(e).toBeUndefined(); }); }; it('fetch from non-localhost address', (done) => { var testModule = createTestModule(); runUproxyOrg404Test(testModule, done); }); it('fetch from non-localhost address while localhost is blocked.', (done) => { var testModule = createTestModule(true); runUproxyOrg404Test(testModule, done); }); it('do a request that gets blocked, then another that succeeds.', (done) => { var nonExistentPath = '/noSuchPath'; var input = arraybuffers.stringToArrayBuffer( 'GET ' + nonExistentPath + ' HTTP/1.0\r\n\r\n'); // Get a test module that doesn't allow localhost access. var testModule = createTestModule(true); // Try to connect to localhost, and fail testModule.connect(1023).then((connectionId:string) => { // This code should not run, because testModule.connect() should // reject with a NOT_ALLOWED error. expect(connectionId).toBeUndefined(); }, (e:any) => { expect(e.reply).toEqual(socks_headers.Reply.NOT_ALLOWED); }).then(() => { runUproxyOrg404Test(testModule, done); }); }); it('run a localhost-resolving DNS name echo test while localhost is blocked.', (done) => { // Get a test module with one that doesn't allow localhost access. var testModule = createTestModule(true); testModule.startEchoServer().then((port:number) => { return testModule.connect(port, 'www.127.0.0.1.xip.io'); }).then((connectionId:string) => { // This code should not run, because testModule.connect() should // reject. expect(connectionId).toBeUndefined(); }, (e:any) => { // On many networks, www.127.0.0.1.xip.io is non-resolvable, because // corporate DNS can drop responses that resolve to local network // addresses. Accordingly, the error code may either indicate // HOST_UNREACHABLE (if resolution fails) or NOT_ALLOWED if name // resolution succeeds. However, to avoid portscanning leaks // (https://github.com/uProxy/uproxy/issues/809) NOT_ALLOWED will be reported // as FAILURE expect([socks_headers.Reply.HOST_UNREACHABLE, socks_headers.Reply.FAILURE]).toContain(e.reply); }).then(done); }); it('attempt to connect to a nonexistent echo daemon', (done) => { var testModule = createTestModule(); // 1023 is a reserved port. testModule.connect(1023).then((connectionId:string) => { // This code should not run, because there is no server on this port. expect(connectionId).toBeUndefined(); }).catch((e:any) => { expect(e.reply).toEqual(socks_headers.Reply.CONNECTION_REFUSED); }).then(done); }); it('attempt to connect to a nonexistent echo daemon while localhost is blocked', (done) => { var testModule = createTestModule(true); // 1023 is a reserved port. testModule.connect(1023).then((connectionId:string) => { // This code should not run, because localhost is blocked. expect(connectionId).toBeUndefined(); }).catch((e:any) => { expect(e.reply).toEqual(socks_headers.Reply.NOT_ALLOWED); }).then(done); }); it('attempt to connect to a nonexistent local echo daemon while localhost is blocked as 0.0.0.0', (done) => { var testModule = createTestModule(true); // 1023 is a reserved port. testModule.connect(1023, '0.0.0.0').then((connectionId:string) => { // This code should not run because the destination is invalid. expect(connectionId).toBeUndefined(); }).catch((e:any) => { // TODO: Make this just NOT_ALLOWED once this bug in ipadddr.js is fixed: // https://github.com/whitequark/ipaddr.js/issues/9 expect([socks_headers.Reply.NOT_ALLOWED, socks_headers.Reply.FAILURE]).toContain(e.reply); }).then(done); }); it('attempt to connect to a nonexistent local echo daemon while localhost is blocked as IPv6', (done) => { var testModule = createTestModule(true); // 1023 is a reserved port. testModule.connect(1023, '::1').then((connectionId:string) => { // This code should not run, because localhost is blocked. expect(connectionId).toBeUndefined(); }).catch((e:any) => { expect(e.reply).toEqual(socks_headers.Reply.NOT_ALLOWED); }).then(done); }); it('attempt to connect to a local network IP address while it is blocked', (done) => { var testModule = createTestModule(true); // 1023 is a reserved port. testModule.connect(1023, '10.5.5.5').then((connectionId:string) => { // This code should not run, because local network access is blocked. expect(connectionId).toBeUndefined(); }).catch((e:any) => { expect(e.reply).toEqual(socks_headers.Reply.NOT_ALLOWED); }).then(done); }); it('connection refused from DNS name', (done) => { var testModule = createTestModule(); // Many sites (such as uproxy.org) seem to simply ignore SYN packets on // unmonitored ports, but openbsd.org actually refuses the connection as // expected. testModule.connect(1023, 'openbsd.org').then((connectionId:string) => { // This code should not run, because there is no server on this port. expect(connectionId).toBeUndefined(); }).catch((e:any) => { expect(e.reply).toEqual(socks_headers.Reply.CONNECTION_REFUSED); }).then(done); }); it('connection refused from DNS name while localhost is blocked', (done) => { var testModule = createTestModule(true); // Many sites (such as uproxy.org) seem to simply ignore SYN packets on // unmonitored ports, but openbsd.org actually refuses the connection as // expected. testModule.connect(1023, 'openbsd.org').then((connectionId:string) => { // This code should not run, because there is no server on this port. expect(connectionId).toBeUndefined(); }).catch((e:any) => { // This should be CONNECTION_REFUSED, but since we can't be sure that the // domain isn't on the local network, and we're concerned about port // scanning, we return the generic FAILURE code instead. // See https://github.com/uProxy/uproxy/issues/809. expect(e.reply).toEqual(socks_headers.Reply.FAILURE); }).then(done); }); it('attempt to connect to a nonexistent DNS name', (done) => { var testModule = createTestModule(true); testModule.connect(80, 'www.nonexistentdomain.gov').then((connectionId:string) => { // This code should not run, because there is no such DNS name. expect(connectionId).toBeUndefined(); }).catch((e:any) => { expect(e.reply).toEqual(socks_headers.Reply.HOST_UNREACHABLE); }).then(done); }); it('Hit the session limit', (done) => { var limit = 4; var testModule = createTestModule(false, limit); var workingConnections : Promise<void>[] = []; testModule.startEchoServer().then((port:number) => { for (var i = 0; i < limit; ++i) { // Connections up to the limit are allowed. workingConnections.push(testModule.connect(port).catch((e) => { // These should not fail. expect(e).toBeUndefined(); })); } // This one is over the limit so it should fail to open. testModule.connect(port).catch((e) => { // Wait for the working connections to succeed. Promise.all(workingConnections).then(done); }); }); }); // TODO: Enable this test once https://code.google.com/p/webrtc/issues/detail?id=4823 // is fixed. xit('run a simple echo test but force IPv6 transport', (done) => { var input = arraybuffers.stringToArrayBuffer('arbitrary test string'); var testModule = createTestModule(undefined, undefined, true); testModule.startEchoServer().then((port:number) => { return testModule.connect(port); }).then((connectionId:string) => { return testModule.echo(connectionId, input); }).then((output:ArrayBuffer) => { expect(arraybuffers.byteEquality(input, output)).toBe(true); }).catch((e:any) => { expect(e).toBeUndefined(); }).then(done); }); it('run a simple echo test with reproxy', (done) => { var input = arraybuffers.stringToArrayBuffer('arbitrary test string'); var testModule = createTestModule(undefined, undefined, undefined, true); testModule.startEchoServer().then((port:number) => { return testModule.connect(port); }).then((connectionId:string) => { return testModule.echo(connectionId, input); }).then((output:ArrayBuffer) => { expect(arraybuffers.byteEquality(input, output)).toBe(true); return testModule.getReproxyBytesReceived(); }).then((bytes:number) => { expect(bytes).toEqual(input.byteLength); return testModule.getReproxyBytesSent(); }).then((bytes:number) => { expect(bytes).toEqual(input.byteLength); }).catch((e:any) => { expect(e).toBeUndefined(); }).then(done); }); xit('attempt to connect to a nonexistent DNS name with reproxy', (done) => { var testModule = createTestModule(true, undefined, undefined, true); testModule.connect(80, 'www.nonexistentdomain.gov').then((connectionId:string) => { // This code should not run, because there is no such DNS name. expect(connectionId).toBeUndefined(); }).catch((e:any) => { expect(e.reply).toEqual(socks_headers.Reply.HOST_UNREACHABLE); }).then(done); }); };
the_stack
import { useRef, useMemo, useState } from "react"; import { makeStyles, createStyles } from "@mui/styles"; import { useTheme } from "@mui/material/styles"; import Editor, { useMonaco } from "@monaco-editor/react"; import { useProjectContext } from "contexts/ProjectContext"; import { FieldType } from "constants/fields"; import { useEffect } from "react"; const useStyles = makeStyles((theme) => createStyles({ editorWrapper: { position: "relative", minWidth: 400, minHeight: 100, height: "calc(100% - 50px)", border: `1px solid ${theme.palette.divider}`, borderRadius: theme.shape.borderRadius, overflow: "hidden", }, saveButton: { marginTop: theme.spacing(1), }, editor: { // overwrite user-select: none that causes editor not focusable in Safari userSelect: "auto", }, }) ); export default function CodeEditor(props: any) { const { handleChange, extraLibs, height = 400, script, onValideStatusUpdate, diagnosticsOptions, onUnmount, onMount, } = props; const theme = useTheme(); const monacoInstance = useMonaco(); const [initialEditorValue] = useState(script ?? ""); const { tableState } = useProjectContext(); const classes = useStyles(); const editorRef = useRef<any>(); useEffect(() => { return () => { onUnmount?.(); }; }, []); function handleEditorDidMount(_, editor) { editorRef.current = editor; onMount?.(); } const themeTransformer = (theme: string) => { switch (theme) { case "dark": return "vs-dark"; default: return theme; } }; useMemo(async () => { if (!monacoInstance) { // useMonaco returns a monaco instance but initialisation is done asynchronously // dont execute the logic until the instance is initialised return; } const firestoreDefsFile = await fetch( `${process.env.PUBLIC_URL}/firestore.d.ts` ); const firebaseAuthDefsFile = await fetch( `${process.env.PUBLIC_URL}/auth.d.ts` ); const firebaseStorageDefsFile = await fetch( `${process.env.PUBLIC_URL}/storage.d.ts` ); const firestoreDefs = await firestoreDefsFile.text(); const firebaseStorageDefs = await firebaseStorageDefsFile.text(); const firebaseAuthDefs = (await firebaseAuthDefsFile.text()) ?.replace("export", "declare") ?.replace("admin.auth", "adminauth"); try { monacoInstance.languages.typescript.javascriptDefaults.addExtraLib( firestoreDefs ); monacoInstance.languages.typescript.javascriptDefaults.addExtraLib( firebaseAuthDefs ); monacoInstance.languages.typescript.javascriptDefaults.addExtraLib( firebaseStorageDefs ); monacoInstance.languages.typescript.javascriptDefaults.setDiagnosticsOptions( diagnosticsOptions ?? { noSemanticValidation: true, noSyntaxValidation: false, } ); // compiler options monacoInstance.languages.typescript.javascriptDefaults.setCompilerOptions( { target: monacoInstance.languages.typescript.ScriptTarget.ES2020, allowNonTsExtensions: true, } ); if (extraLibs) { monacoInstance.languages.typescript.javascriptDefaults.addExtraLib( extraLibs.join("\n"), "ts:filename/extraLibs.d.ts" ); } monacoInstance.languages.typescript.javascriptDefaults.addExtraLib( [ " /**", " * utility functions", " */", ` declare namespace utilFns { /** * Sends out an email through sendGrid */ function sendEmail(msg: { from: string; templateId: string; personalizations: { to: string; dynamic_template_data: any }[]; }): void {} /** * Gets the secret defined in Google Cloud Secret */ async function getSecret(name: string, v?: string): any {} /** * Async version of forEach */ async function asyncForEach(array: any[], callback: Function): void {} /** * Generate random ID from numbers and English characters including lowercase and uppercase */ function generateId(): string {} /** * Add an item to an array field */ function arrayUnion(val: string): void {} /** * Remove an item to an array field */ function arrayRemove(val: string): void {} /** * Increment a number field */ function increment(val: number): void {} function hasRequiredFields(requiredFields: string[], data: any): boolean {} function hasAnyRole( authorizedRoles: string[], context: functions.https.CallableContext ): boolean {} } `, ].join("\n"), "ts:filename/utils.d.ts" ); const rowDefinition = [ ...Object.keys(tableState?.columns!).map((columnKey: string) => { const column = tableState?.columns[columnKey]; switch (column.type) { case FieldType.shortText: case FieldType.longText: case FieldType.email: case FieldType.phone: case FieldType.code: return `${columnKey}:string`; case FieldType.singleSelect: const typeString = [ ...(column.config?.options?.map((opt) => `"${opt}"`) ?? []), ].join(" | "); return `${columnKey}:${typeString}`; case FieldType.multiSelect: return `${columnKey}:string[]`; case FieldType.checkbox: return `${columnKey}:boolean`; default: return `${columnKey}:any`; } }), ].join(";\n"); const availableFields = Object.keys(tableState?.columns!) .map((columnKey: string) => `"${columnKey}"`) .join("|\n"); const extensionsDefinition = ` // basic types that are used in all places type Row = {${rowDefinition}}; type Field = ${availableFields} | string | object; type Fields = Field[]; type Trigger = "create" | "update" | "delete"; type Triggers = Trigger[]; // function types that defines extension body and should run type Condition = boolean | ((data: ExtensionContext) => boolean | Promise<boolean>); // the argument that the extension body takes in type ExtensionContext = { row: Row; ref:FirebaseFirestore.DocumentReference; storage:firebasestorage.Storage; db:FirebaseFirestore.Firestore; auth:adminauth.BaseAuth; change: any; triggerType: Triggers; fieldTypes: any; extensionConfig: { label: string; type: string; triggers: Trigger[]; conditions: Condition; requiredFields: string[]; extensionBody: any; }; utilFns: any; } // extension body definition type slackEmailBody = { channels?: string[]; text?: string; emails: string[]; blocks?: object[]; attachments?: any; } type slackChannelBody = { channels: string[]; text?: string; emails?: string[]; blocks?: object[]; attachments?: any; } type DocSyncBody = (context: ExtensionContext) => Promise<{ fieldsToSync: Fields; row: Row; targetPath: string; }> type HistorySnapshotBody = (context: ExtensionContext) => Promise<{ trackedFields: Fields; }> type AlgoliaIndexBody = (context: ExtensionContext) => Promise<{ fieldsToSync: Fields; index: string; row: Row; objectID: string; }> type MeiliIndexBody = (context: ExtensionContext) => Promise<{ fieldsToSync: Fields; index: string; row: Row; objectID: string; }> type BigqueryIndexBody = (context: ExtensionContext) => Promise<{ fieldsToSync: Fields; index: string; row: Row; objectID: string; }> type SlackMessageBody = (context: ExtensionContext) => Promise<slackEmailBody | slackChannelBody>; type SendgridEmailBody = (context: ExtensionContext) => Promise<any>; type ApiCallBody = (context: ExtensionContext) => Promise<{ body: string; url: string; method: string; callback: any; }> type TwilioMessageBody = (context: ExtensionContext) => Promise<{ body: string; from: string; to: string; }> type TaskBody = (context: ExtensionContext) => Promise<any> `; monacoInstance.languages.typescript.javascriptDefaults.addExtraLib( [ " /**", " * extensions type configuration", " */", extensionsDefinition, ].join("\n"), "ts:filename/extensions.d.ts" ); monacoInstance.languages.typescript.javascriptDefaults.addExtraLib( [ " declare var require: any;", " declare var Buffer: any;", " const ref:FirebaseFirestore.DocumentReference", " const storage:firebasestorage.Storage", " const db:FirebaseFirestore.Firestore;", " const auth:adminauth.BaseAuth;", "declare class row {", " /**", " * Returns the row fields", " */", ...Object.keys(tableState?.columns!).map((columnKey: string) => { const column = tableState?.columns[columnKey]; switch (column.type) { case FieldType.shortText: case FieldType.longText: case FieldType.email: case FieldType.phone: case FieldType.code: return `static ${columnKey}:string`; case FieldType.singleSelect: const typeString = [ ...(column.config?.options?.map((opt) => `"${opt}"`) ?? []), // "string", ].join(" | "); return `static ${columnKey}:${typeString}`; case FieldType.multiSelect: return `static ${columnKey}:string[]`; case FieldType.checkbox: return `static ${columnKey}:boolean`; default: return `static ${columnKey}:any`; } }), "}", ].join("\n"), "ts:filename/rowFields.d.ts" ); } catch (error) { console.error( "An error occurred during initialization of Monaco: ", error ); } }, [tableState?.columns, monacoInstance]); function handleEditorValidation(markers) { if (onValideStatusUpdate) { onValideStatusUpdate({ isValid: markers.length <= 0, }); } } return ( <> <div className={classes.editorWrapper}> <Editor theme={themeTransformer(theme.palette.mode)} onMount={handleEditorDidMount} language="javascript" height={height} value={initialEditorValue} onChange={handleChange} onValidate={handleEditorValidation} options={{ // readOnly: disabled, fontFamily: theme.typography.fontFamilyMono, rulers: [80], minimap: { enabled: false }, // ...editorOptions, }} className={classes.editor} /> </div> </> ); }
the_stack
import {Component, ElementRef, Inject, OnInit, ViewChild} from '@angular/core'; import {JsonPipe} from "@angular/common"; import {TestCase} from "../../../models/test-case.model"; import {Page} from "../../../shared/models/page"; import {MobileRecordingComponent} from "./mobile-recording.component"; import {MirroringContainerComponent} from "./mirroring-container.component"; import {TestStep} from "../../../models/test-step.model"; import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from "@angular/material/dialog"; import {StepBulkUpdateFormComponent} from "../../../components/webcomponents/step-bulk-update-form.component"; import {TestStepType} from "../../../enums/test-step-type.enum"; import {AuthenticationGuard} from "../../../shared/guards/authentication.guard"; import {NotificationsService, NotificationType} from "angular2-notifications"; import {TranslateService} from '@ngx-translate/core'; import {ToastrService} from "ngx-toastr"; import {MirroringData} from "../../models/mirroring-data.model"; import {DevicesService} from "../../services/devices.service"; import {ElementService} from 'app/shared/services/element.service'; import {TestCaseService} from "../../../services/test-case.service"; import {TestStepService} from "../../../services/test-step.service"; import {ActivatedRoute, Params} from "@angular/router"; import {MobileRecorderEventService} from "../../../services/mobile-recorder-event.service"; import {TestStepMoreActionFormComponent} from "../../../components/webcomponents/test-step-more-action-form.component"; import {StepSummaryComponent} from "../../../components/webcomponents/step-summary.component"; import {WorkspaceVersionService} from "../../../shared/services/workspace-version.service"; import {ActionElementSuggestionComponent} from "../../../components/webcomponents/action-element-suggestion.component"; import {ActionTestDataFunctionSuggestionComponent} from "../../../components/webcomponents/action-test-data-function-suggestion.component"; import {ActionTestDataParameterSuggestionComponent} from "../../../components/webcomponents/action-test-data-parameter-suggestion.component"; import {ActionTestDataEnvironmentSuggestionComponent} from "../../../components/webcomponents/action-test-data-environment-suggestion.component"; import {ElementFormComponent} from "../../../components/webcomponents/element-form.component"; import {RecorderActionTemplateConstant} from "./recorder-action-template-constant"; import {MobileElement} from "../../models/mobile-element.model"; import {Position} from "../../models/position.model"; import {SendKeysRequest} from "../../models/send-keys-request.model"; import {WorkspaceType} from "../../../enums/workspace-type.enum"; import {Element} from "../../../models/element.model"; import {Observable} from "rxjs"; import {ElementLocatorType} from "../../../enums/element-locator-type.enum"; import {ElementCreateType} from "../../../enums/element-create-type.enum"; import {TestStepConditionType} from "../../../enums/test-step-condition-type.enum"; import {TestDataType} from "../../../enums/test-data-type.enum"; import {TestStepPriority} from "../../../enums/test-step-priority.enum"; import {ConfirmationModalComponent} from "../../../shared/components/webcomponents/confirmation-modal.component"; import {NaturalTextActionsService} from "../../../services/natural-text-actions.service"; import {NaturalTextActions} from "../../../models/natural-text-actions.model"; import {TestCaseActionStepsComponent} from "../../../components/webcomponents/test-case-action-steps.component"; import {WorkspaceVersion} from "../../../models/workspace-version.model"; import {DuplicateLocatorWarningComponent} from "../../../components/webcomponents/duplicate-locator-warning.component"; import {AddonActionService} from "../../../services/addon-action.service"; @Component({ selector: 'app-mobile-step-recorder', templateUrl: './mobile-step-recorder.component.html', providers: [JsonPipe] }) export class MobileStepRecorderComponent extends MobileRecordingComponent implements OnInit { public testCase: TestCase; public templates: Page<any>; public searchTerm: string; public version: WorkspaceVersion; public addonAction: Page<any>; public selectedTemplate: any; public canDrag: boolean = false; public isCheckHelpPreference: boolean; public inputValue: any; @ViewChild('customDialogContainerH50') customDialogContainerH50: ElementRef @ViewChild('customDialogContainerH100') customDialogContainerH100: ElementRef @ViewChild('mirroringContainerComponent') mirroringContainerComponent: MirroringContainerComponent; @ViewChild('stepList') stepList: TestCaseActionStepsComponent; // TODO // public isRibbonShowed: boolean = true; private locatorTypes = { accessibility_id: {variableName: "accessibilityId"}, id_value: {variableName: "id"}, xpath: {variableName: "xpath"}, class_name: {variableName: "type"}, name: {variableName: "name"} }; private selectedStepsList: TestStep[]=[]; private bulkStepUpdateDialogRef: MatDialogRef<StepBulkUpdateFormComponent>; public draggedSteps: TestStep[]; public currentStepType: string = TestStepType.ACTION_TEXT; public pauseRecord: boolean = false; private viewAfterLastAction: string = 'NATIVE_APP'; public actionStep: TestStep; public addActionStepAfterSwitch: boolean = false; public isElseIfStep: boolean = false; private isNeedToUpdateId: number; public editedStep: TestStep; public isReorder: boolean = false; constructor( public authGuard: AuthenticationGuard, public notificationsService: NotificationsService, public translate: TranslateService, public toastrService: ToastrService, @Inject(MAT_DIALOG_DATA) public data: MirroringData, public JsonPipe: JsonPipe, public localDeviceService: DevicesService, //public cloudDeviceService: CloudDevicesService, public elementService: ElementService, public dialogRef: MatDialogRef<MobileRecordingComponent>, public dialog: MatDialog, public testCaseService: TestCaseService, public testStepService: TestStepService, public naturalTextActionsService: NaturalTextActionsService, public addonActionService: AddonActionService, public applicationVersionService: WorkspaceVersionService, private route: ActivatedRoute, private mobileRecorderEventService: MobileRecorderEventService ) { super( authGuard, notificationsService, translate, toastrService, data, JsonPipe, localDeviceService, //cloudDeviceService, elementService, dialogRef, dialog) } get halfHeightDialogsOpen(): boolean { return Boolean( this?.dialog?.openDialogs?.find(dialog => { return dialog.componentInstance instanceof ActionElementSuggestionComponent|| dialog.componentInstance instanceof ActionTestDataFunctionSuggestionComponent || dialog.componentInstance instanceof ActionTestDataParameterSuggestionComponent || dialog.componentInstance instanceof ActionTestDataEnvironmentSuggestionComponent || dialog.componentInstance instanceof ElementFormComponent ; }) ); }; get fullHeightDialogsOpen(): boolean { return Boolean( this?.dialog?.openDialogs?.find(dialog => dialog.componentInstance instanceof TestStepMoreActionFormComponent || dialog.componentInstance instanceof StepSummaryComponent) ); } get canShowBulkActions() { return this.selectedStepsList && this.selectedStepsList.length>1; } ngOnInit(): void { super.ngOnInit(); this.route.params.subscribe((params: Params) => { this.fetchTestCase(this.route.snapshot.queryParamMap['params'].testCaseId); }); super.mobileRecorderComponentInstance = this; } ngOnChanges() { if (Boolean(this.data.testCaseId)) this.fetchTestCase(this.data.testCaseId); } selectedSteps(steps: TestStep[]) { this.selectedStepsList = steps; } onPositionChange(steps: TestStep[]) { this.draggedSteps = steps; } onStepType(type: string) { this.currentStepType = type; } private saveLaunchStep() { let templateId = RecorderActionTemplateConstant.launch_app[this.platform]; this.saveElementAndCreateStep(templateId); } public saveTapStep(mobileElement: MobileElement) { let templateId = RecorderActionTemplateConstant.tap[this.platform]; let elementName = mobileElement.text && mobileElement.text.length < 250 ? mobileElement.text : mobileElement.type; this.saveElementAndCreateStep(templateId, elementName, undefined, mobileElement); } public saveDeviceTapStep(tapPoint: Position) { tapPoint.y = (Number(tapPoint.y) / this.mirroringContainerComponent.screenOriginalHeight) * 100; tapPoint.x = (Number(tapPoint.x) / this.mirroringContainerComponent.screenOriginalWidth) * 100; let templateId = RecorderActionTemplateConstant.tapByRelativeCoordinates[this.platform]; this.saveElementAndCreateStep(templateId, null, tapPoint.x + "," + tapPoint.y); } public saveNavigateBackStep() { let templateId = RecorderActionTemplateConstant.navigateBack[this.platform]; this.saveElementAndCreateStep(templateId); } public saveChangeOrientationStep(isLandscape) { let templateId = isLandscape ? RecorderActionTemplateConstant.setOrientationAsLandscape[this.platform] : RecorderActionTemplateConstant.setOrientationAsPortrait[this.platform]; this.saveElementAndCreateStep(templateId); } public saveEnterStep(sendKeysRequest: SendKeysRequest) { let mobileElement = sendKeysRequest.mobileElement; let templateId = RecorderActionTemplateConstant.enter[this.platform]; let elementName = mobileElement.text && mobileElement.text.length < 250 ? mobileElement.text : mobileElement.type; this.saveElementAndCreateStep(templateId, elementName, sendKeysRequest.keys, sendKeysRequest.mobileElement); } public saveClearStep(mobileElement: MobileElement) { let templateId = RecorderActionTemplateConstant.clear[this.platform]; let elementName = mobileElement.text && mobileElement.text.length < 250 ? mobileElement.text : mobileElement.type; this.saveElementAndCreateStep(templateId, elementName, undefined, mobileElement); } private fetchTestCase(testCaseId: number) { this.testCaseService.show(testCaseId).subscribe(testCase => { this.testCase = testCase this.applicationVersionService.show(this.testCase.workspaceVersionId).subscribe(res => { this.version = res; this.fetchActionTemplates(); this.fetchAddonActionTemplates(); }) }) } private fetchActionTemplates() { let workspaceType: WorkspaceType = this.version.workspace.workspaceType; this.naturalTextActionsService.findAll("workspaceType:" + workspaceType).subscribe(actions => { this.templates = actions; }); } fetchAddonActionTemplates() { let workspaceType: WorkspaceType = this.version.workspace.workspaceType; this.addonActionService.findAll("workspaceType:" +workspaceType+",status:INSTALLED").subscribe(actions => { this.addonAction = actions; this.addLaunchStep(); }) } private saveElementAndCreateStep(templateId: number, elementName?: String, testData?: String, mobileElement?: MobileElement, fromTestData?: String, toTestData?: String) { if(this.canDrag|| this.pauseRecord) return; this.checkViewAndAddActionStep(templateId, elementName, testData, mobileElement, fromTestData, toTestData); } private saveElement(elementName, mobileElement?: MobileElement): Observable<Element[]> { let element = new Element(); element.name = elementName.replace(/[{}().+*?^$%`'/\\|]/g,'_'); element.locatorType = (mobileElement.accessibilityId) ? ElementLocatorType.accessibility_id : (mobileElement.id ? ElementLocatorType.id_value : ElementLocatorType.xpath); element.locatorValue = mobileElement[this.locatorTypes[element.locatorType].variableName]; element.createdType = ElementCreateType.MOBILE_INSPECTOR; let elements: Element[] = [element]; elements.forEach(element => element.workspaceVersionId = this.testCase.workspaceVersionId); return this.elementService.bulkCreate(elements) } private createStepAfterRefresh(currentStep: TestStep) { setTimeout(() => { if (this.stepList.isStepFetchComplete) { if(this.isNeedToUpdateId > 0) { this.stepList.testSteps.content[this.isNeedToUpdateId].isNeedToUpdate = true; this.isNeedToUpdateId = 0; } this.selectedIndex = this.fullScreenMode? 0:1; this.mobileRecorderEventService.emitStepRecord(currentStep); this.stepList.isStepFetchCompletedTmp = false; } else { this.createStepAfterRefresh(currentStep); } }, 500); } private addLaunchStep() { setTimeout(() => { if (this.stepList.isStepFetchComplete) { if(this.stepList?.testSteps?.content?.length == 0 ){ this.saveLaunchStep(); this.stepList.isStepFetchCompletedTmp = false; } } else { this.addLaunchStep(); } }, 500); } public createStep(currentStep: TestStep, isSwitchStep?:boolean) { this.dialog.openDialogs?.find( dialog => dialog.componentInstance instanceof TestStepMoreActionFormComponent)?.close(); currentStep.action = currentStep.template.actionText(currentStep?.element?.toString(), currentStep?.testDataVal?.toString()) if (this.stepList.isAnyStepEditing) { if (this.stepList.editedStep.isConditionalType||this.isElseIfStep) { currentStep.parentId = this.stepList.editedStep.id; if(this.isElseIfStep){ currentStep.parentId = this.stepList.editedStep.id; currentStep.conditionType = TestStepConditionType.CONDITION_ELSE_IF; if(!this.stepList.editedStep.isConditionalType){ currentStep.parentId = this.findConditionalParent(this.stepList.editedStep).id; currentStep.siblingStep = this.stepList.testSteps.content.slice().reverse().find(step => (step.isConditionalElse || step.isConditionalElseIf) && step.parentId == this.findConditionalParent(this.stepList.editedStep).id); if(Boolean(currentStep.siblingStep)){ currentStep.position = currentStep.siblingStep.position + 1; this.isNeedToUpdateId = this.stepList.testSteps.content.indexOf(this.stepList.testSteps.content.find(step => step.id == currentStep.siblingStep.id)); } else { this.isNeedToUpdateId = -1; } } else { currentStep.parentId = this.editedStep.id; } this.editedStep = null; } else { currentStep.conditionType = null; } if(this.stepList.editedStep.isForLoop && this.stepList.editedStep.siblingStep?.isConditionalType){ currentStep.conditionType = this.stepList.editedStep.siblingStep.conditionType; //currentStep.dataMap = new StepDetailsDataMap().deserialize({...{...currentStep.dataMap},...{...this.stepList.editedStep.siblingStep.dataMap}}); } if (this.stepList.editedStep.isConditionalWhileLoop && this.stepList.editedStep.siblingStep?.isConditionalType){ currentStep.conditionType = this.stepList.editedStep.siblingStep.conditionType; } } else if (this.stepList.editedStep.isWhileLoop){ currentStep.parentId = this.stepList.editedStep.id; currentStep.conditionType = TestStepConditionType.LOOP_WHILE } else currentStep.parentId = this.stepList.editedStep.parentId; if(this.addActionStepAfterSwitch && !Boolean(isSwitchStep)) { this.actionStep = currentStep; return; } this.stepList.fetchSteps(); this.createStepAfterRefresh(currentStep); } else{ if(this.addActionStepAfterSwitch && !Boolean(isSwitchStep)) { this.actionStep = currentStep; return; } this.mobileRecorderEventService.emitStepRecord(currentStep); this.selectedIndex = this.fullScreenMode? 0:1; } } updateRecordedElement() { if(this.canDrag) return; let elementFormComponent:ElementFormComponent= this.dialog.openDialogs?.find(dialog => dialog.componentInstance instanceof ElementFormComponent)?.componentInstance; if(!Boolean(elementFormComponent)) return; let inspectedElement = this.mirroringContainerComponent.inspectedElement.mobileElement; let locatorType = (inspectedElement.accessibilityId) ? ElementLocatorType.accessibility_id : (inspectedElement.id ? ElementLocatorType.id_value : ElementLocatorType.xpath); let definition = inspectedElement[this.locatorTypes[locatorType].variableName]; elementFormComponent.element.locatorType = locatorType; elementFormComponent.element.locatorValue = definition; } openBulkUpdate() { this.bulkStepUpdateDialogRef = this.dialog.open(StepBulkUpdateFormComponent, { width: '450px', panelClass: ['mat-dialog', 'rds-none'], data: { steps: this.selectedStepsList } }) this.bulkStepUpdateDialogRef.afterClosed().subscribe((result) => { if (result) { this.selectedStepsList = []; this.testCase = undefined; this.fetchTestCase(this.route.snapshot.queryParamMap['params'].testCaseId); } }) } bulkDeleteConfirm() { const dialogRef = this.dialog.open(ConfirmationModalComponent, { width: '450px', data: { description: this.translate.instant("message.common.confirmation.message", {FieldName: 'Test Steps'}) }, panelClass: ['matDialog', 'delete-confirm'] }); dialogRef.afterClosed().subscribe(result => {if (result) this.bulkDestroy();}); } private bulkDestroy() { this.testStepService.bulkDestroy(this.selectedStepsList).subscribe({ next: () => { this.fetchTestCase(this.route.snapshot.queryParamMap['params'].testCaseId); this.showNotification(NotificationType.Success, this.translate.instant("message.common.deleted.success", {FieldName: 'Test Steps'})); this.selectedStepsList = []; }, error: (error) => { if (error.status == "400") { this.showNotification(NotificationType.Error, error.error); } else { this.showNotification(NotificationType.Error, this.translate.instant("message.common.deleted.failure", {FieldName: 'Test Steps'})); } } }) } cancelDragging() { this.selectedStepsList =[] this.draggedSteps = []; this.canDrag = false; this.fetchTestCase(this.route.parent.snapshot.params.testCaseId); } updateSorting() { this.testStepService.bulkUpdate(this.draggedSteps).subscribe(() => { this.showNotification(NotificationType.Success, this.translate.instant('testcase.details.steps.re-order.success')); this.cancelDragging(); }, error => this.showAPIError(error, this.translate.instant('testcase.details.steps.re-order.failure')) ); } private populateAttributesFromDetails(template: NaturalTextActions): TestStep { let currentStep = new TestStep(); currentStep.template = template; currentStep.naturalTextActionId = currentStep.template.id; //currentStep.dataMap = new StepDetailsDataMap(); currentStep.type = TestStepType.ACTION_TEXT; let commonData = this.stepList.stepForm if(commonData.get('waitTime')){ currentStep.waitTime = commonData.get('waitTime').value; currentStep.priority = commonData.get('priority').value; currentStep.preRequisiteStepId = commonData.get('preRequisiteStepId').value; currentStep.conditionType = commonData.get('conditionType').value; currentStep.disabled = commonData.get('disabled').value; currentStep.conditionIf = commonData.get('conditionIf')?.value; } else { currentStep.waitTime = 30; currentStep.priority = TestStepPriority.MAJOR; currentStep.disabled = false; } return currentStep; } private checkViewAndAddActionStep(templateId: number, elementName?: String, testData?: String, mobileElement?: MobileElement, fromTestData?: String, toTestData?: String) { if(this.viewAfterLastAction != this.getMirroringContainerComponent().viewType){ const switchViewTemplateId = this.getMirroringContainerComponent().viewType == 'NATIVE_APP'? RecorderActionTemplateConstant.switchToNativeAppContext[this.platform] : RecorderActionTemplateConstant.switchToWebviewContext[this.platform]; this.naturalTextActionsService.findAll("id:" + switchViewTemplateId ).subscribe(templates => { this.createSwitchStepAndActionActionStep(this.populateAttributesFromDetails(templates.content[0]), templateId, elementName, testData, mobileElement, fromTestData, toTestData); }); } else { this.addActionStepAfterSwitch = false; this.addActionStep(templateId, elementName, testData, mobileElement, fromTestData, toTestData) } } private addActionStep(templateId: number, elementName?: String, testData?: String, mobileElement?: MobileElement, fromTestData?: String, toTestData?: String){ this.naturalTextActionsService.findAll("id:" + templateId).subscribe(templates => { let currentStep: TestStep = this.populateAttributesFromDetails(templates.content[0]); if (Boolean(testData)) { currentStep.testDataVal = testData; currentStep.testDataType = TestDataType.raw; } if (Boolean(elementName)) { let locatorType = (mobileElement.accessibilityId) ? ElementLocatorType.accessibility_id : (mobileElement.id ? ElementLocatorType.id_value : ElementLocatorType.xpath); let element = new Element(); element.locatorValue = mobileElement[this.locatorTypes[locatorType].variableName]; let query = 'workspaceVersionId:' + this.version.id + ',locatorType:' + locatorType + ',locatorValue:' + element.locatorValueWithSpecialCharacters; query = this.byPassSpecialCharacters(query); this.elementService.findAll(query).subscribe(res => { if(res?.content?.length){ this.openDuplicateLocatorWarning(res.content, elementName, mobileElement, currentStep); } else { this.saveElement(elementName, mobileElement).subscribe(elements => { currentStep.element = elements[0].name; this.createStep(currentStep); }) } }); } else { this.createStep(currentStep); } }) } private openDuplicateLocatorWarning(res: Element[],uiIdentifierName: String , mobileElement:MobileElement, currentStep: TestStep) { let description = this.translate.instant('element.inspector.create_confirmation.description', {elementType: this.locatorTypes[res[0].locatorType].variableName, definition: res[0].locatorValue}); const dialogRef = this.dialog.open(DuplicateLocatorWarningComponent, { width: '568px', height: 'auto', data: { description: description, elements: res, isRecorder: true, }, panelClass: ['mat-dialog', 'rds-none'] }); dialogRef.afterClosed() .subscribe(result => { if (result) { this.saveElement(uiIdentifierName, mobileElement).subscribe(elements => { currentStep.element = elements[0].name; this.createStep(currentStep); }) } else if(result!=undefined) { currentStep.element = res[0].name; this.createStep(currentStep); } }); } private createSwitchStepAndActionActionStep(SwitchStep: TestStep, templateId: number, elementName?: String, testData?: String, mobileElement?: MobileElement, fromTestData?: String, toTestData?: String) { this.viewAfterLastAction = this.getMirroringContainerComponent().viewType; this.populateActionStep(templateId, elementName, testData, mobileElement, fromTestData, toTestData); this.createStep(SwitchStep, true); } private populateActionStep(templateId: number, elementName: String, testData: String, mobileElement: MobileElement, fromTestData?: String, toTestData?: String) { this.addActionStepAfterSwitch = true; this.addActionStep(templateId, elementName, testData, mobileElement, fromTestData, toTestData); } public findConditionalParent(parentStep: TestStep) { return parentStep.isConditionalType ? parentStep : this.findConditionalParent(parentStep.parentStep); } public findConditionalIfParent(parentStep: TestStep) { return parentStep.isConditionalIf ? parentStep : this.findConditionalParent(parentStep.parentStep); } }
the_stack
namespace models { /** Upper bound on the amount of suggestions to generate. */ const MAX_SUGGESTIONS = 12; /** * Additional arguments to pass into the model, in addition to the model * parameters themselves. */ interface TrieModelOptions { /** * How to break words in a phrase. */ wordBreaker?: WordBreakingFunction; /** * This should simplify a search term into a key. */ searchTermToKey?: (searchTerm: string) => string; /** * Indicates that the model's written form has 'casing' behavior. */ languageUsesCasing?: boolean; /** * Specifies a function used to apply the language's casing rules to a word. */ applyCasing?: CasingFunction; /** * Any punctuation to expose to the user. */ punctuation?: LexicalModelPunctuation; } /** * Used to determine the probability of an entry from the trie. */ type TextWithProbability = { text: string; // TODO: use negative-log scaling instead? p: number; // real-number weight, from 0 to 1 } /** * @class TrieModel * * Defines a trie-backed word list model, or the unigram model. * Unigram models throw away all preceding words, and search * for the next word exclusively. As such, they can perform simple * prefix searches within words, however they are not very good * at predicting the next word. */ export class TrieModel implements LexicalModel { configuration: Configuration; private _trie: Trie; readonly breakWords: WordBreakingFunction; readonly punctuation?: LexicalModelPunctuation; readonly languageUsesCasing?: boolean; readonly applyCasing?: CasingFunction; constructor(trieData: object, options: TrieModelOptions = {}) { this.languageUsesCasing = options.languageUsesCasing; this.applyCasing = options.applyCasing; this._trie = new Trie( trieData['root'], trieData['totalWeight'], options.searchTermToKey as Wordform2Key || defaultSearchTermToKey ); this.breakWords = options.wordBreaker || getDefaultWordBreaker(); this.punctuation = options.punctuation; } configure(capabilities: Capabilities): Configuration { return this.configuration = { leftContextCodePoints: capabilities.maxLeftContextCodePoints, rightContextCodePoints: capabilities.maxRightContextCodePoints }; } toKey(text: USVString): USVString { return this._trie.toKey(text); } predict(transform: Transform, context: Context): Distribution<Suggestion> { // Special-case the empty buffer/transform: return the top suggestions. if (!transform.insert && !context.left && !context.right && context.startOfBuffer && context.endOfBuffer) { return makeDistribution(this._trie.firstN(MAX_SUGGESTIONS).map(({text, p}) => ({ transform: { insert: text, deleteLeft: 0 }, displayAs: text, p: p }))); } // Compute the results of the keystroke: let newContext = models.applyTransform(transform, context); // Computes the different in word length after applying the transform above. let leftDelOffset = transform.deleteLeft - transform.insert.kmwLength(); // All text to the left of the cursor INCLUDING anything that has // just been typed. let prefix = models.getLastPreCaretToken(this.breakWords, newContext); // Return suggestions from the trie. return makeDistribution(this._trie.lookup(prefix).map(({text, p}) => models.transformToSuggestion({ insert: text, // Delete whatever the prefix that the user wrote. deleteLeft: leftDelOffset + prefix.kmwLength() // Note: a separate capitalization/orthography engine can take this // result and transform it as needed. }, p ))); /* Helper */ function makeDistribution(suggestions: WithOutcome<Suggestion>[]): Distribution<Suggestion> { let distribution: Distribution<Suggestion> = []; for(let s of suggestions) { distribution.push({sample: s, p: s.p}); } return distribution; } } get wordbreaker(): WordBreakingFunction { return this.breakWords; } public traverseFromRoot(): LexiconTraversal { return new TrieModel.Traversal(this._trie['root'], ''); } private static Traversal = class implements LexiconTraversal { /** * The lexical prefix corresponding to the current traversal state. */ prefix: String; /** * The current traversal node. Serves as the 'root' of its own sub-Trie, * and we cannot navigate back to its parent. */ root: Node; constructor(root: Node, prefix: string) { this.root = root; this.prefix = prefix; } *children(): Generator<{char: string, traversal: () => LexiconTraversal}> { let root = this.root; if(root.type == 'internal') { for(let entry of root.values) { let entryNode = root.children[entry]; // UTF-16 astral plane check. if(models.isHighSurrogate(entry)) { // First code unit of a UTF-16 code point. // For now, we'll just assume the second always completes such a char. // // Note: Things get nasty here if this is only sometimes true; in the future, // we should compile-time enforce that this assumption is always true if possible. if(entryNode.type == 'internal') { let internalNode = entryNode; for(let lowSurrogate of internalNode.values) { let prefix = this.prefix + entry + lowSurrogate; yield { char: entry + lowSurrogate, traversal: function() { return new TrieModel.Traversal(internalNode.children[lowSurrogate], prefix) } } } } else { // Determine how much of the 'leaf' entry has no Trie nodes, emulate them. let fullText = entryNode.entries[0].key; entry = entry + fullText[this.prefix.length + 1]; // The other half of the non-BMP char. let prefix = this.prefix + entry; yield { char: entry, traversal: function () {return new TrieModel.Traversal(entryNode, prefix)} } } } else if(models.isSentinel(entry)) { continue; } else if(!entry) { // Prevent any accidental 'null' or 'undefined' entries from having an effect. continue; } else { let prefix = this.prefix + entry; yield { char: entry, traversal: function() { return new TrieModel.Traversal(entryNode, prefix)} } } } return; } else { // type == 'leaf' let prefix = this.prefix; let children = root.entries.filter(function(entry) { return entry.key != prefix && prefix.length < entry.key.length; }) for(let {key} of children) { let nodeKey = key[prefix.length]; if(models.isHighSurrogate(nodeKey)) { // Merge the other half of an SMP char in! nodeKey = nodeKey + key[prefix.length+1]; } yield { char: nodeKey, traversal: function() { return new TrieModel.Traversal(root, prefix + nodeKey)} } }; return; } } get entries(): string[] { if(this.root.type == 'leaf') { let prefix = this.prefix; let matches = this.root.entries.filter(function(entry) { return entry.key == prefix; }); return matches.map(function(value) { return value.content }); } else { let matchingLeaf = this.root.children[models.SENTINEL_CODE_UNIT]; if(matchingLeaf && matchingLeaf.type == 'leaf') { return matchingLeaf.entries.map(function(value) { return value.content }); } else { return []; } } } } }; ///////////////////////////////////////////////////////////////////////////////// // What remains in this file is the trie implementation proper. Note: to // // reduce bundle size, any functions/methods related to creating the trie have // // been removed. // ///////////////////////////////////////////////////////////////////////////////// /** * An **opaque** type for a string that is exclusively used as a search key in * the trie. There should be a function that converts arbitrary strings * (queries) and converts them into a standard search key for a given language * model. * * Fun fact: This opaque type has ALREADY saved my bacon and found a bug! */ type SearchKey = string & { _: 'SearchKey'}; /** * The priority queue will always pop the most weighted item. There can only * be two kinds of items right now: nodes, and entries; both having a weight * attribute. */ type Weighted = Node | Entry; /** * A function that converts a string (word form or query) into a search key * (secretly, this is also a string). */ interface Wordform2Key { (wordform: string): SearchKey; } // The following trie implementation has been (heavily) derived from trie-ing // by Conrad Irwin. // trie-ing is copyright (C) 2015–2017 Conrad Irwin. // Distributed under the terms of the MIT license: // https://github.com/ConradIrwin/trie-ing/blob/df55d7af7068d357829db9e0a7faa8a38add1d1d/LICENSE type Node = InternalNode | Leaf; /** * An internal node in the trie. Internal nodes NEVER contain entries; if an * internal node should contain an entry, then it has a dummy leaf node (see * below), that can be accessed by node.children["\uFDD0"]. */ interface InternalNode { type: 'internal'; weight: number; /** Maintains the keys of children in descending order of weight. */ values: string[]; // TODO: As an optimization, "values" can be a single string! /** * Maps a single UTF-16 code unit to a child node in the trie. This child * node may be a leaf or an internal node. The keys of this object are kept * in sorted order in the .values array. */ children: { [codeunit: string]: Node }; } /** Only leaf nodes actually contain entries (i.e., the words proper). */ interface Leaf { type: 'leaf'; weight: number; entries: Entry[]; } /** * An entry in the prefix trie (stored in leaf nodes exclusively!) */ interface Entry { /** The actual word form, stored in the trie. */ content: string; /** A search key that usually simplifies the word form, for ease of search. */ key: SearchKey; weight: number; } /** * Wrapper class for the trie and its nodes. */ class Trie { private root: Node; /** The total weight of the entire trie. */ private totalWeight: number; /** * Converts arbitrary strings to a search key. The trie is built up of * search keys; not each entry's word form! */ toKey: Wordform2Key; constructor(root: Node, totalWeight: number, wordform2key: Wordform2Key) { this.root = root; this.toKey = wordform2key; this.totalWeight = totalWeight; } /** * Lookups an arbitrary prefix (a query) in the trie. Returns the top 3 * results in sorted order. * * @param prefix */ lookup(prefix: string): TextWithProbability[] { let searchKey = this.toKey(prefix); let lowestCommonNode = findPrefix(this.root, searchKey); if (lowestCommonNode === null) { return []; } return getSortedResults(lowestCommonNode, searchKey, this.totalWeight); } /** * Returns the top N suggestions from the trie. * @param n How many suggestions, maximum, to return. */ firstN(n: number): TextWithProbability[] { return getSortedResults(this.root, '' as SearchKey, this.totalWeight, n); } } /** * Finds the deepest descendent in the trie with the given prefix key. * * This means that a search in the trie for a given prefix has a best-case * complexity of O(m) where m is the length of the prefix. * * @param key The prefix to search for. * @param index The index in the prefix. Initially 0. */ function findPrefix(node: Node, key: SearchKey, index: number = 0): Node | null { // An important note - the Trie itself is built on a per-JS-character basis, // not on a UTF-8 character-code basis. if (node.type === 'leaf' || index === key.length) { return node; } // So, for SMP models, we need to match each char of the supplementary pair // in sequence. Each has its own node in the Trie. let char = key[index]; if (node.children[char]) { return findPrefix(node.children[char], key, index + 1); } return null; } /** * Returns all entries matching the given prefix, in descending order of * weight. * * @param prefix the prefix to match. * @param results the current results * @param queue */ function getSortedResults(node: Node, prefix: SearchKey, N: number, limit = MAX_SUGGESTIONS): TextWithProbability[] { let queue = new PriorityQueue(function(a: Weighted, b: Weighted) { // In case of Trie compilation issues that emit `null` or `undefined` return (b ? b.weight : 0) - (a ? a.weight : 0); }); let results: TextWithProbability[] = []; if (node.type === 'leaf') { // Assuming the values are sorted, we can just add all of the values in the // leaf, until we reach the limit. for (let item of node.entries) { if (item.key.startsWith(prefix)) { let { content, weight } = item; results.push({ text: content, p: weight / N }); if (results.length >= limit) { return results; } } } } else { queue.enqueue(node); let next: Weighted; while (next = queue.dequeue()) { if (isNode(next)) { // When a node is next up in the queue, that means that next least // likely suggestion is among its decsendants. // So we search all of its descendants! if (next.type === 'leaf') { queue.enqueueAll(next.entries); } else { // XXX: alias `next` so that TypeScript can be SURE that internal is // in fact an internal node. Because of the callback binding to the // original definition of node (i.e., a Node | Entry), this will not // type-check otherwise. let internal = next; queue.enqueueAll(next.values.map(char => { return internal.children[char]; })); } } else { // When an entry is up next in the queue, we just add its contents to // the results! results.push({ text: next.content, p: next.weight / N }); if (results.length >= limit) { return results; } } } } return results; } /** TypeScript type guard that returns whether the thing is a Node. */ function isNode(x: Entry | Node): x is Node { return 'type' in x; } /** * Converts wordforms into an indexable form. It does this by * normalizing into NFD, removing diacritics, and then converting * the result to lowercase. * * This is a very naïve implementation, that I only think will work on * some languages that use the Latin script. As of 2020-04-08, only * 4 out of 11 (36%) of published language models use the Latin script, * so this might not actually be a great default. * * This uses String.prototype.normalize() to convert normalize into NFD. * NFD is an easy way to separate a Latin character from its diacritics; * Even then, some Latin-based orthographies use code points that, * under NFD normalization, do NOT decompose into an ASCII letter and a * combining diacritical mark (e.g., SENĆOŦEN). * * Use this only in early iterations of the model. For a production lexical * model, you SHOULD write/generate your own key function, tailored to your * language. */ function defaultSearchTermToKey(wordform: string): SearchKey { /** * N.B.: this is (slightly) DIFFERENT than the version in * keymanapp/lexical-model-compiler/build-trie * as this is for compatibility for models built * BEFORE the searchTermToKey function was bundled with * all models. * * This compatibility version lowercases AFTER removing diacritics; * the new version (bundled in future models) lowercases, * NFD normalizes, THEN removes diacritics. */ return wordform .normalize('NFD') // Remove all combining diacritics (if input is in NFD) // common to Latin-orthographies. .replace(/[\u0300-\u036f]/g, '') .toLowerCase() as SearchKey; } function getDefaultWordBreaker() { let namespace: {}; // @ts-ignore if (typeof wordBreakers !== 'undefined') { // @ts-ignore namespace = wordBreakers; } else { namespace = require('@keymanapp/models-wordBreakers').wordBreakers; } return namespace['default']; } }
the_stack
import { ArrayExpression, BinaryExpression, CallExpression, ConditionalExpression, Expression, LogicalExpression, MemberExpression, NewExpression, ObjectExpression, SpreadElement, ThisExpression, UnaryExpression } from 'estree'; export function execArrayExpression(exp: ArrayExpression, context: Object) { let arr: any[] = []; exp.elements.forEach(element => { if (element.type === 'SpreadElement') { execSpreadElement(element, arr, context); } else { let value = execExpression(element, context); if (context && value in context) { value = context[value]; } arr.push(value); } }); return arr; } export function execBinaryExpression(exp: BinaryExpression, context: Object): string | boolean | number | null { let left: any = execExpression(exp.left, context); let right: any = execExpression(exp.right, context); let operator = exp.operator; if (context) { if (context.hasOwnProperty(left) && exp.left.type === 'Identifier') { left = context[left]; } if (context.hasOwnProperty(right) && exp.right.type === 'Identifier') { right = context[right]; } } switch (operator) { case '+': return left + right; case '-': return left - right; case '*': return left * right; case '**': return left ** right; case '/': return left / right; case '^': return left ^ right; case '&': return left & right; case 'in': return left in right; case 'instanceof': return left instanceof right; case '%': return left % right; case '>>': return left >> right; case '>>>': return left >>> right; case '<<': return left << right; case '>': return left > right; case '>=': return left >= right; case '<': return left < right; case '<=': return left <= right; case '|': return left | right; case '==': /* tslint:disable */ return left == right; /* tslint:enable */ case '===': return left === right; case '!=': /* tslint:disable */ return left != right; /* tslint:enable */ case '!==': return left !== right; default: return null; } } export function execCallExpression(exp: CallExpression, context: Object) { let callee = exp.callee; if (callee.type === 'Super') { throw new TypeError('super function in expression string is not supported'); } let interpret = execExpression(callee, context); let args = exp.arguments; let retArgs: any[] = []; args.forEach(arg => { if (arg.type === 'SpreadElement') { execSpreadElement(arg, retArgs, context); } else { let value = execExpression(arg, context); if (arg.type !== 'Literal') { if (context && value in context) { value = context[value]; } } retArgs.push(value); } }); let f; if (typeof interpret === 'string') { if (context && !(interpret in context)) { throw new TypeError('ReferenceError: ' + interpret + ' is not defined'); } f = context[interpret]; if (typeof f !== 'function') { throw new TypeError('TypeError: ' + f + ' is not a functions'); } } else if (interpret.type && interpret.type === '__RCRE_RUNTIME_FUNCTION__') { let object = interpret.object; let property = interpret.property; if (property === 'call') { return object.call(retArgs[0], ...retArgs.slice(1)); } if (property === 'apply') { return object.apply(retArgs[0], retArgs.slice(1)); } return object[property](...retArgs); } else if (typeof callee !== 'function') { throw new TypeError('callee is not a function'); } return f.apply(context, retArgs); } export function execConditionExpression(exp: ConditionalExpression, context: Object) { let test = execExpression(exp.test, context); if (test) { return execExpression(exp.consequent, context); } else { return execExpression(exp.alternate, context); } } export function execLogicalExpression(exp: LogicalExpression, context: Object) { let operator = exp.operator; let left = execExpression(exp.left, context); switch (operator) { case '||': if (!!left) { return left; } else { return execExpression(exp.right, context); } case '&&': if (!left) { return false; } else { let right = execExpression(exp.right, context); return !!right ? right : false; } default: break; } } export function execNewExpression(exp: NewExpression, context: Object) { let callee = exp.callee; if (callee.type !== 'Identifier') { throw new TypeError('declaring function in expression string is not supported'); } callee = execExpression(callee, context); let args = exp.arguments; let retArgs: any[] = []; args.forEach(arg => { if (arg.type === 'SpreadElement') { execSpreadElement(arg, retArgs, context); } else { let value = execExpression(arg, context); if (context && value in context) { value = context[value]; } retArgs.push(value); } }); if (typeof callee !== 'string') { throw new TypeError('invalid callee function of filters'); } if (context && !(callee in context)) { throw new TypeError('ReferenceError: ' + callee + ' is not defined'); } let f = context[callee]; if (typeof f !== 'function') { throw new TypeError('TypeError: ' + callee + ' is not a function'); } // @ts-ignore return new f(...retArgs); } export function execMemberExpression(exp: MemberExpression, context: Object) : string | boolean | number | Object | null { if (exp.object.type === 'Super') { throw new TypeError('Super node is not supported'); } let object = execExpression(exp.object, context); let property = execExpression(exp.property, context); if (object === false || object === undefined || object === null) { throw new TypeError('Uncaught TypeError: Cannot read property ' + property + ' of null'); } if (context) { if (object in context && (typeof object === 'string' || typeof object === 'number')) { object = context[object]; } } if ((typeof property === 'string' || typeof property === 'number') && (object !== null && object !== undefined)) { const funcFlag = '__RCRE_RUNTIME_FUNCTION__'; if (object.type === funcFlag) { let target = object.object; let prop = object.property; return { type: funcFlag, object: target[prop], property: property }; } // 返回值为函数不做处理 if (typeof object![property] === 'function') { return { type: funcFlag, object: object, property: property }; } return object![property]; } return null; } export function execObjectExpression(exp: ObjectExpression, context: Object) { let properties = exp.properties; let newObject = {}; for (let prop of properties) { if (prop.value.type === 'ObjectPattern' || prop.value.type === 'ArrayPattern' || prop.value.type === 'RestElement' || prop.value.type === 'AssignmentPattern') { throw new Error('ES6 Pattern syntax is not supported'); } let key = execExpression(prop.key, context); let value = execExpression(prop.value, context); if (context && key in context) { key = context[key]; } if (context && value in context) { value = context[value]; } if (key === null || key === undefined || typeof key === 'boolean' || key instanceof RegExp) { continue; } newObject[key] = value; } return newObject; } export function execThisExpression(exp: ThisExpression, context: Object) { return context; } export function execUnaryExpression(exp: UnaryExpression, context: Object) { let operator = exp.operator; let argument = exp.argument; let ret = execExpression(argument, context); if (context && ret in context) { ret = context[ret]; } switch (operator) { case '-': return -ret; case '+': return +ret; case '!': return !ret; case '~': return ~ret; case 'typeof': return typeof ret; default: throw new TypeError('UnaryExpression: ' + operator + ' operator is not supported'); } } export function execSpreadElement(element: SpreadElement, arr: any[], context: Object) { let args = element.argument; let spread = execExpression(args, context); if (!spread[Symbol.iterator]) { throw new TypeError(spread + '[Symbol.iterator is not a function]'); } let iterator = spread[Symbol.iterator](); let next = iterator.next(); while (!next.done) { arr.push(next.value); next = iterator.next(); } } export function execExpression(exp: Expression, context: Object): any { switch (exp.type) { case 'BinaryExpression': return execBinaryExpression(exp, context); case 'MemberExpression': return execMemberExpression(exp, context); case 'Literal': return exp.value; case 'Identifier': return exp.name; case 'ConditionalExpression': return execConditionExpression(exp, context); case 'ObjectExpression': return execObjectExpression(exp, context); case 'ThisExpression': return execThisExpression(exp, context); case 'ArrayExpression': return execArrayExpression(exp, context); case 'UnaryExpression': return execUnaryExpression(exp, context); // case 'UpdateExpression': // return execUpdateExpression(exp, context); case 'LogicalExpression': return execLogicalExpression(exp, context); case 'CallExpression': return execCallExpression(exp, context); case 'NewExpression': return execNewExpression(exp, context); case 'AssignmentExpression': case 'TemplateLiteral': case 'ClassExpression': case 'MetaProperty': case 'TaggedTemplateExpression': case 'AwaitExpression': case 'FunctionExpression': case 'ArrowFunctionExpression': case 'YieldExpression': case 'SequenceExpression': default: throw new TypeError(exp.type + ' is not supported'); } }
the_stack
import * as path from 'path'; import {Subject} from 'rxjs'; import {Promise} from 'bluebird'; import {Map as ImmutableMap} from 'immutable'; import * as browserResolve from 'browser-resolve'; import * as browserifyBuiltins from 'browserify/lib/builtins'; import * as babylon from 'babylon'; import * as postcss from 'postcss'; import * as parse5 from 'parse5'; import * as chalk from 'chalk'; import babelGenerator from 'babel-generator'; import * as babelCodeFrame from 'babel-code-frame'; import {ErrorObject} from '../common'; import {FileSystemCache, FileSystemTrap} from '../file_system'; import {CyclicDependencyGraph, Graph} from '../cyclic_dependency_graph'; import {babylonAstDependencies} from './babylon_ast_dependencies'; import {postcssAstDependencies} from './postcss_ast_dependencies'; import {parse5AstDependencies, rewriteParse5AstDependencies} from './parse5_ast_dependencies'; import {GraphOutput} from "../cyclic_dependency_graph/graph"; export class File { fileName: string; baseDirectory: string; ext: string; baseName: string; trap: FileSystemTrap; content: string | Buffer; hash: string; constructor(fileName: string) { this.fileName = fileName; this.baseDirectory = path.dirname(fileName); this.ext = path.extname(fileName); this.baseName = path.basename(fileName, this.ext); } } export class FileScan { file: File; identifiers: string[]; ast: any; constructor(file) { this.file = file; } } export class FileDependencies { scan: FileScan; resolved: string[]; resolvedByIdentifier: any; constructor(scan) { this.scan = scan; } } export class FileBuild { file: File; scan: FileScan; content: string | Buffer; url: string; sourceMap?: any; constructor(file, scan) { this.file = file; this.scan = scan; } } export interface buildOutput { graph: Graph, files: ImmutableMap<string, File> scans: ImmutableMap<string, FileScan> built: ImmutableMap<string, FileBuild> } export class Compiler { fileSystemCache = new FileSystemCache(); graph: CyclicDependencyGraph; files = ImmutableMap<string, File>(); scans = ImmutableMap<string, FileScan>(); built = ImmutableMap<string, FileBuild>(); dependencies = ImmutableMap<string, FileDependencies>(); start: Subject<string>; error = new Subject<ErrorObject>(); complete = new Subject<buildOutput>(); graphState: Graph; rootDirectory: string; constructor() { this.graph = new CyclicDependencyGraph((fileName: string) => this.handleGraphRequest(fileName)); this.start = this.graph.start; this.graph.error.subscribe((errorObject: ErrorObject) => this.handleErrorObject(errorObject)); this.graph.complete.subscribe((graphOutput: GraphOutput) => this.handleGraphOutput(graphOutput)); this.rootDirectory = process.cwd(); } startCompilation() { this.graph.traceFromEntryPoints(); } addEntryPoint(file: string) { this.graph.addEntryPoint(file); } getFileSourceUrl(file: File): string { const fileName = file.fileName; if (fileName.startsWith(this.rootDirectory)) { return fileName.slice(this.rootDirectory.length); } else { return fileName; } } getFileOutputUrl(file: File): Promise<string> { const baseDirectory = file.baseDirectory; let fileSystemPath; if (baseDirectory.startsWith(this.rootDirectory)) { fileSystemPath = baseDirectory.slice(this.rootDirectory.length); } else { fileSystemPath = baseDirectory; } const rootUrl = fileSystemPath.split(path.sep).join('/'); let url = rootUrl + '/' + file.baseName + '-' + file.hash + file.ext; if (url[0] !== '/') { url = '/' + url; } return Promise.resolve(url); } scanFile(file: File): Promise<FileScan> { switch(file.ext) { case '.js': return this.scanJsFile(file); case '.css': return this.scanCssFile(file); case '.html': return this.scanHtmlFile(file); } return this.scanUnknownFile(file); } scanHtmlFile(file: File): Promise<FileScan> { const {fileName, trap} = file; return Promise.all([ trap.readText(fileName), trap.readTextHash(fileName) ]) .then(([text, textHash]) => { file.content = text; file.hash = textHash; const ast = parse5.parse(text); const outcome = parse5AstDependencies(ast); const scan = new FileScan(file); scan.ast = ast; scan.identifiers = outcome.identifiers; return scan; }); } scanJsFile(file: File): Promise<FileScan> { const {fileName, trap} = file; return Promise.all([ trap.readText(fileName), trap.readTextHash(fileName) ]) .then(([text, textHash]) => { file.content = text; file.hash = textHash; const sourceType = fileName.indexOf('node_modules') !== -1 ? 'script' : 'module'; const ast = babylon.parse(text, { sourceType }); const outcome = babylonAstDependencies(ast); const scan = new FileScan(file); scan.ast = ast; scan.identifiers = outcome.identifiers; return scan; }); } scanCssFile(file): Promise<FileScan> { const {fileName, trap} = file; return Promise.all([ trap.readText(fileName), trap.readTextHash(fileName) ]) .then(([text, textHash]) => { file.content = text; file.hash = textHash; const ast = postcss.parse(text); const outcome = postcssAstDependencies(ast); // As we serve the files with different names, we need to remove // the `@import ...` rules ast.walkAtRules('import', rule => rule.remove()); const scan = new FileScan(file); scan.ast = ast; scan.identifiers = outcome.identifiers; return scan; }); } scanUnknownFile(file): Promise<FileScan> { const {fileName, trap} = file; return Promise.all([ trap.readText(fileName), trap.readModifiedTime(fileName) ]) .then(([buffer, modifiedTime]) => { file.content = buffer; file.hash = modifiedTime; const scan = new FileScan(file); scan.identifiers = []; return scan; }); } resolveIdentifier(identifier: string, file: File): Promise<string> { const {fileName, baseDirectory, trap} = file; return new Promise((res, rej) => { browserResolve( identifier, { filename: fileName, basedir: baseDirectory, modules: browserifyBuiltins, readFile: (path, cb) => trap.readTextCallBack(path, cb), isFile: (path, cb) => trap.isFileCallBack(path, cb) }, (err, fileName) => { if (err) return rej(err); res(fileName); } ); }); } build(file: File): Promise<FileBuild> { switch(file.ext) { case '.js': return this.buildJsFile(file); case '.css': return this.buildCssFile(file); case '.html': return this.buildHtmlFile(file); } return this.buildUnknownFile(file); } buildJsFile(file: File): Promise<FileBuild> { const sourceUrl = this.getFileSourceUrl(file); return this.getFileOutputUrl(file) .then(outputUrl => { const scan = this.scans.get(file.fileName); const babelFile = babelGenerator( scan.ast, { sourceMaps: true, sourceFileName: sourceUrl, sourceMapTarget: outputUrl }, file.content as string ); const build = new FileBuild(file, scan); build.url = outputUrl; build.content = babelFile.code; build.sourceMap = babelFile.map; return Promise.resolve(build); }); } buildCssFile(file: File): Promise<FileBuild> { const sourceUrl = this.getFileSourceUrl(file); return this.getFileOutputUrl(file) .then((outputUrl) => { const scan = this.scans.get(file.fileName); return Promise.resolve( postcss().process( scan.ast, { from: sourceUrl, to: outputUrl, // Generate a source map, but keep it separate from the code map: { inline: false, annotation: false } } ) ) .then(output => { const build = new FileBuild(file, scan); build.url = outputUrl; build.content = output.css; build.sourceMap = output.map; return Promise.resolve(build); }); }); } buildHtmlFile(file: File): Promise<FileBuild> { const scan = this.scans.get(file.fileName); const dependencies = this.dependencies.get(file.fileName); const outputUrls = []; for (const identifier of Object.keys(dependencies.resolvedByIdentifier)) { const depFileName = dependencies.resolvedByIdentifier[identifier]; const depFile = this.files.get(depFileName); outputUrls.push( this.getFileOutputUrl(depFile) .then(outputUrl => [identifier, outputUrl]) ); } return Promise.all(outputUrls) .then(data => { const identifiers = {}; for (const [identifier, outputUrl] of data) { identifiers[identifier] = outputUrl; } rewriteParse5AstDependencies(scan.ast, identifiers); return this.getFileOutputUrl(file) .then(outputUrl => { const build = new FileBuild(file, scan); build.url = outputUrl; build.content = parse5.serialize(scan.ast); return Promise.resolve(build); }); }); } buildUnknownFile(file: File): Promise<FileBuild> { const scan = this.scans.get(file.fileName); const build = new FileBuild(file, scan); return this.getFileOutputUrl(file) .then(outputUrl => { build.url = outputUrl; build.content = file.content; return Promise.resolve(build); }); } handleGraphRequest(fileName: string): Promise<string[]> { let file = this.files.get(fileName); if (!file) { file = this.createFile(fileName); this.files = this.files.set(fileName, file); } return this.scanFile(file) .then(scan => { this.scans = this.scans.set(fileName, scan); if (!this.isFileValid(file)) { return []; } return Promise.all( scan.identifiers.map(identifier => { return this.resolveIdentifier(identifier, file); }) ) .then(resolvedDependencies => { if (!this.isFileValid(file)) { return []; } const dependencies = new FileDependencies(scan); dependencies.resolved = resolvedDependencies; dependencies.resolvedByIdentifier = {}; for (let i=0; i<resolvedDependencies.length; i++) { const identifier = scan.identifiers[i]; dependencies.resolvedByIdentifier[identifier] = resolvedDependencies[i]; } this.dependencies = this.dependencies.set(fileName, dependencies); return resolvedDependencies; }); }); } isFileValid(file) { return this.files.get(file.fileName) === file; } handleErrorObject(errorObject: ErrorObject) { const {error, fileName} = errorObject; let text = Promise.resolve(null); if (error.loc && !error.codeFrame) { text = this.fileSystemCache.readText(fileName) .catch(_ => null); // Ignore any errors } text .then((text) => { const lines = []; // If the error occurred in a particular file's processing, we contextualize the error if (fileName) { lines.push(chalk.red(fileName) + '\n'); } // If the stack trace already contains the message, we improve the readability by omitting the message if (!error.stack.includes(error.message)) { lines.push(error.message); } // Improve the reporting on parse errors by generating a code frame if (text) { error.codeFrame = babelCodeFrame(text, error.loc.line, error.loc.column); } if ( error.codeFrame && // If another tool has already added the code frame to the error, we should avoid duplicating it !(error.message.includes(error.codeFrame) || error.stack.includes(error.codeFrame)) ) { lines.push(error.codeFrame); } lines.push(error.stack); errorObject.description = lines.join('\n'); this.error.next(errorObject); }) // Sanity check to ensure that errors are not swallowed .catch(err => console.error(err)); } handleGraphOutput(graphOutput: GraphOutput) { this.graphState = graphOutput.graph; for (const fileName of graphOutput.pruned) { this.purgeDataForFile(fileName); } this.buildFiles(); } buildFiles() { const fileBuilds = []; this.graphState.keySeq().forEach(fileName => { const file = this.files.get(fileName); fileBuilds.push(this.build(file)); }); Promise.all(fileBuilds) .then((builtFiles: FileBuild[]) => { this.built = ImmutableMap<string, FileBuild>().withMutations(map => { for (const builtFile of builtFiles) { map.set(builtFile.file.fileName, builtFile); } }); this.complete.next({ graph: this.graphState, files: this.files, scans: this.scans, built: this.built }); }); } purgeDataForFile(fileName: string) { this.files.delete(fileName); this.scans.delete(fileName); this.dependencies.delete(fileName); } createFile(fileName: string) { const file = new File(fileName); file.trap = this.fileSystemCache.createTrap(); return file; } }
the_stack
import IPackageRegistryEntry from '../../src/interfaces/IPackageRegistryEntry'; import Utils from '../../src/Utils'; chai.should(); describe('V2 Deploy Page', () => { const packageOne: IPackageRegistryEntry = { name: 'mycontract', version: '0.0.1', path: '/package/one', sizeKB: 9000 }; const packageTwo: IPackageRegistryEntry = { name: 'othercontract', version: '0.0.2', path: '/package/two', sizeKB: 12000 }; const deployData: { channelName: string, hasV1Capabilities: boolean, environmentName: string, packageEntries: IPackageRegistryEntry[], workspaceNames: string[], selectedPackage: IPackageRegistryEntry | undefined, committedDefinitions: string[], environmentPeers: string[], discoveredPeers: string[], orgMap: any, orgApprovals: any } = { channelName: 'mychannel', hasV1Capabilities: false, environmentName: 'myEnvironment', packageEntries: [packageOne, packageTwo], workspaceNames: ['workspaceOne'], selectedPackage: undefined, committedDefinitions: [], environmentPeers: ['Org1Peer1'], discoveredPeers: ['Org2Peer1'], orgMap: { Org1MSP: ['Org1Peer1'], Org2MSP: ['Org2Peer1'] }, orgApprovals: { Org1MSP: false, Org2MSP: false } }; const mockMessage: { path: string, deployData: any } = { path: 'deploy', deployData }; beforeEach(() => { Utils.postToVSCode = () => { return; }; cy.visit('build/index.html').then((window: Window) => { window.postMessage(mockMessage, '*'); cy.get('.vscode-dark').invoke('attr', 'class', 'vscode-light'); // Use the light theme as components render properly. }); }); it('should open the deploy page and show the correct channel name and environment name', () => { const subheadingContainer: Cypress.Chainable<JQuery<HTMLElement>> = cy.get('.heading-combo-container'); subheadingContainer.contains(deployData.channelName); subheadingContainer.contains(deployData.environmentName); }); it(`shouldn't be able to click Next`, () => { const nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('be.disabled'); }); it(`should be able to select a package and click Next to step two`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option const nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); }); it(`should be able to go back from step two`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option const nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); const backButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Back'); backButton.should('not.be.disabled'); backButton.click(); }); it(`should be able to go from step two to step three`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); nextButton = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); }); it(`should be able to go back from step three to step two`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); nextButton = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); const backButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Back'); backButton.should('not.be.disabled'); backButton.click(); }); it(`should keep the changed definition name and version in step two when going back`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); let nameInput: Cypress.Chainable<JQuery<HTMLInputElement>> = cy.get('#nameInput'); nameInput.click(); nameInput.clear(); // Delete all nextButton = cy.get('button').contains('Next'); nextButton.should('be.disabled'); nameInput = cy.get('#nameInput'); nameInput.type('newDefinition'); let versionInput: Cypress.Chainable<JQuery<HTMLInputElement>> = cy.get('#versionInput'); versionInput.click(); versionInput.clear(); // Delete all nextButton = cy.get('button').contains('Next'); nextButton.should('be.disabled'); versionInput = cy.get('#versionInput'); versionInput.type('0.0.2'); const backButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Back'); backButton.should('not.be.disabled'); backButton.click(); nextButton = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); nameInput = cy.get('#nameInput'); nameInput.should('contain.value', 'newDefinition'); versionInput = cy.get('#versionInput'); versionInput.should('contain.value', '0.0.2'); }); it('should use default definition name and version if package is changed', () => { const _packageOne: string = `${packageOne.name}@${packageOne.version} (packaged)`; const _packageTwo: string = `${packageTwo.name}@${packageTwo.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_packageOne).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); let nameInput: Cypress.Chainable<JQuery<HTMLInputElement>> = cy.get('#nameInput'); nameInput.click(); nameInput.clear(); // Delete all nextButton = cy.get('button').contains('Next'); nextButton.should('be.disabled'); nameInput = cy.get('#nameInput'); nameInput.type('newDefinition'); let versionInput: Cypress.Chainable<JQuery<HTMLInputElement>> = cy.get('#versionInput'); versionInput.click(); nameInput.clear(); // Delete all nextButton = cy.get('button').contains('Next'); nextButton.should('be.disabled'); nameInput = cy.get('#versionInput'); nameInput.type('0.0.2'); const backButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Back'); backButton.should('not.be.disabled'); backButton.click(); cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_packageTwo).click(); // Click on option nextButton = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); nameInput = cy.get('#nameInput'); nameInput.should('contain.value', packageTwo.name); versionInput = cy.get('#versionInput'); versionInput.should('contain.value', packageTwo.version); }); it(`should be able to toggle 'Perform Commit'`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); nextButton = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); const advancedSection: Cypress.Chainable<JQuery<HTMLElement>> = cy.get('#advancedAccordion'); advancedSection.click(); const commitToggle: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('#commitToggle'); commitToggle.should('be.checked'); commitToggle.uncheck({ force: true }); commitToggle.should('not.be.checked'); commitToggle.check({ force: true }); commitToggle.should('be.checked'); }); it('should be able to select a workspace', () => { const _package: string = `workspaceOne (open project)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('be.disabled'); const packageButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Package'); packageButton.should('not.be.disabled'); cy.stub(packageButton, 'click'); packageButton.click(); const packageThree: IPackageRegistryEntry = { name: 'newPackage', version: '0.0.1', sizeKB: 40000, path: '/some/path' }; const newData: { channelName: string, environmentName: string, packageEntries: IPackageRegistryEntry[], workspaceNames: string[], selectedPackage: IPackageRegistryEntry | undefined } = { channelName: 'mychannel', environmentName: 'myEnvironment', packageEntries: [packageOne, packageTwo, packageThree], workspaceNames: ['workspaceOne'], selectedPackage: packageThree }; const newMessage: { path: string, deployData: any } = { path: 'deploy', deployData: newData }; cy.visit('build/index.html').then((window: Window) => { window.postMessage(newMessage, '*'); cy.get('.vscode-dark').invoke('attr', 'class', 'vscode-light'); // Use the light theme as components render properly. // Simulate componentWillReceiveProps selected new package cy.get('#package-select').click(); cy.get('#package-select').contains(_package).click(); // Click on option cy.get('#package-select').click(); cy.get('#package-select').contains('newPackage@0.0.1 (packaged)').click(); // Click on option }); nextButton = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); }); it(`should keep the changed endorsement policy in step two when going back`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); let endorsementInput: Cypress.Chainable<JQuery<HTMLInputElement>> = cy.get('#endorsementInput'); endorsementInput.should('contain.value', ''); endorsementInput.click(); endorsementInput.type('OR("Org1MSP.member","Org2MSP.member")'); const backButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Back'); backButton.should('not.be.disabled'); backButton.click(); nextButton = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); endorsementInput = cy.get('#endorsementInput'); endorsementInput.should('contain.value', 'OR("Org1MSP.member","Org2MSP.member")'); }); it('should be able to select peers', () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); nextButton.click(); let customizeCommitSection: Cypress.Chainable<JQuery<HTMLElement>> = cy.get('#advancedAccordion'); customizeCommitSection.click(); let selectPeersButton: Cypress.Chainable<JQuery<HTMLElement>> = cy.get('#peer-select'); selectPeersButton.click(); let peerTwo: Cypress.Chainable<JQuery<HTMLElement>> = cy.get('span').contains('Org2Peer1'); peerTwo.click(); const backButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Back'); backButton.should('not.be.disabled'); backButton.click(); nextButton = cy.get('button').contains('Next'); nextButton.click(); customizeCommitSection = cy.get('#advancedAccordion'); customizeCommitSection.click(); selectPeersButton = cy.get('#peer-select'); selectPeersButton.click(); peerTwo = cy.get('span').contains('Org2Peer1'); peerTwo.should('have.attr', 'data-contained-checkbox-state', 'false'); cy.get('tr[id="Org1MSP-row"]').should((row: JQuery<HTMLElement>) => { const cells: JQuery<HTMLElement> = row.find('td'); expect(cells.eq(0)).to.contain('Org1MSP'); expect(cells.eq(1)).to.contain('Pending (part of this deploy)'); }); cy.get('tr[id="Org2MSP-row"]').should((row: JQuery<HTMLElement>) => { const cells: JQuery<HTMLElement> = row.find('td'); expect(cells.eq(0)).to.contain('Org2MSP'); expect(cells.eq(1)).to.contain('Not approved'); }); }); }); describe('V1 Deploy Page', () => { const packageOne: IPackageRegistryEntry = { name: 'mycontract', version: '0.0.1', path: '/package/one', sizeKB: 9000 }; const packageTwo: IPackageRegistryEntry = { name: 'othercontract', version: '0.0.2', path: '/package/two', sizeKB: 12000 }; const deployData: { channelName: string, hasV1Capabilities: boolean, environmentName: string, packageEntries: IPackageRegistryEntry[], workspaceNames: string[], selectedPackage: IPackageRegistryEntry | undefined, committedDefinitions: string[], environmentPeers: string[], discoveredPeers: string[], orgMap: any, orgApprovals: any } = { channelName: 'mychannel', hasV1Capabilities: true, environmentName: 'myEnvironment', packageEntries: [packageOne, packageTwo], workspaceNames: ['workspaceOne'], selectedPackage: undefined, committedDefinitions: [], environmentPeers: ['Org1Peer1'], discoveredPeers: ['Org2Peer1'], orgMap: { Org1MSP: ['Org1Peer1'], Org2MSP: ['Org2Peer1'] }, orgApprovals: { Org1MSP: false, Org2MSP: false } }; const v1Message: { path: string, deployData: any } = { path: 'deploy', deployData }; beforeEach(() => { Utils.postToVSCode = () => { return; }; cy.visit('build/index.html').then((window: Window) => { window.postMessage(v1Message, '*'); cy.get('.vscode-dark').invoke('attr', 'class', 'vscode-light'); // Use the light theme as components render properly. }); }); it('should open the deploy page and show the correct channel name and environment name', () => { const subheadingContainer: Cypress.Chainable<JQuery<HTMLElement>> = cy.get('.heading-combo-container'); subheadingContainer.contains(deployData.channelName); subheadingContainer.contains(deployData.environmentName); }); it(`shouldn't be able to click Next`, () => { const nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('be.disabled'); }); it(`should be able to select a package and click Next to step two`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option const nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); }); it(`should be able to go back from step two`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option const nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); const backButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Back'); backButton.should('not.be.disabled'); backButton.click(); }); it(`should be able to go from step two to step three`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); nextButton = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); }); it(`should be able to go back from step three to step two`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); nextButton = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); const backButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Back'); backButton.should('not.be.disabled'); backButton.click(); }); it('should be able to select a workspace', () => { const _package: string = `workspaceOne (open project)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('be.disabled'); const packageButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Package'); packageButton.should('not.be.disabled'); cy.stub(packageButton, 'click'); packageButton.click(); const packageThree: IPackageRegistryEntry = { name: 'newPackage', version: '0.0.1', sizeKB: 40000, path: '/some/path' }; const newData: { channelName: string, environmentName: string, packageEntries: IPackageRegistryEntry[], workspaceNames: string[], selectedPackage: IPackageRegistryEntry | undefined } = { channelName: 'mychannel', environmentName: 'myEnvironment', packageEntries: [packageOne, packageTwo, packageThree], workspaceNames: ['workspaceOne'], selectedPackage: packageThree }; const newMessage: { path: string, deployData: any } = { path: 'deploy', deployData: newData }; cy.visit('build/index.html').then((window: Window) => { window.postMessage(newMessage, '*'); cy.get('.vscode-dark').invoke('attr', 'class', 'vscode-light'); // Use the light theme as components render properly. // Simulate componentWillReceiveProps selected new package cy.get('#package-select').click(); cy.get('#package-select').contains(_package).click(); // Click on option cy.get('#package-select').click(); cy.get('#package-select').contains('newPackage@0.0.1 (packaged)').click(); // Click on option }); nextButton = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); }); it(`should keep the changed endorsement policy in step two when going back`, () => { const _package: string = `${packageOne.name}@${packageOne.version} (packaged)`; cy.get('#package-select').click(); // Expand dropdown cy.get('#package-select').contains(_package).click(); // Click on option let nextButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); let endorsementInput: Cypress.Chainable<JQuery<HTMLInputElement>> = cy.get('#endorsementInput'); endorsementInput.should('contain.value', ''); endorsementInput.click(); endorsementInput.type('OR("Org1MSP.member","Org2MSP.member")'); const backButton: Cypress.Chainable<JQuery<HTMLButtonElement>> = cy.get('button').contains('Back'); backButton.should('not.be.disabled'); backButton.click(); nextButton = cy.get('button').contains('Next'); nextButton.should('not.be.disabled'); nextButton.click(); endorsementInput = cy.get('#endorsementInput'); endorsementInput.should('contain.value', 'OR("Org1MSP.member","Org2MSP.member")'); }); });
the_stack
// libraries import React, {Component, createRef} from 'react'; import MapboxGLMap from 'react-map-gl'; import DeckGL from '@deck.gl/react'; import {createSelector} from 'reselect'; import WebMercatorViewport from 'viewport-mercator-project'; import {errorNotification} from 'utils/notifications-utils'; import * as VisStateActions from 'actions/vis-state-actions'; import * as MapStateActions from 'actions/map-state-actions'; import * as UIStateActions from 'actions/ui-state-actions'; // components import MapPopoverFactory from 'components/map/map-popover'; import MapControlFactory from 'components/map/map-control'; import {StyledMapContainer, StyledAttrbution} from 'components/common/styled-components'; import EditorFactory from './editor/editor'; // utils import {generateMapboxLayers, updateMapboxLayers} from 'layers/mapbox-utils'; import {setLayerBlending} from 'utils/gl-utils'; import {transformRequest} from 'utils/map-style-utils/mapbox-utils'; import { getLayerHoverProp, renderDeckGlLayer, prepareLayersToRender, prepareLayersForDeck, LayerHoverProp } from 'utils/layer-utils'; // default-settings import ThreeDBuildingLayer from 'deckgl-layers/3d-building-layer/3d-building-layer'; import { FILTER_TYPES, GEOCODER_LAYER_ID, THROTTLE_NOTIFICATION_TIME } from 'constants/default-settings'; import ErrorBoundary from 'components/common/error-boundary'; import {observeDimensions, unobserveDimensions} from '../utils/observe-dimensions'; import {LOCALE_CODES} from 'localization/locales'; import { Datasets, Filter, InteractionConfig, MapControls, MapState, MapStyle, Viewport } from 'reducers'; import {Layer} from 'layers'; import {SplitMapLayers} from 'reducers/vis-state-updaters'; import {LayerBaseConfig, VisualChannelDomain} from 'layers/base-layer'; /** @type {{[key: string]: React.CSSProperties}} */ const MAP_STYLE: {[key: string]: React.CSSProperties} = { container: { display: 'inline-block', position: 'relative', width: '100%', height: '100%' }, top: { position: 'absolute', top: '0px', pointerEvents: 'none', width: '100%', height: '100%' } }; const MAPBOXGL_STYLE_UPDATE = 'style.load'; const MAPBOXGL_RENDER = 'render'; const TRANSITION_DURATION = 0; const nop = () => {}; export const Attribution = () => ( <StyledAttrbution> <div className="attrition-logo"> Basemap by: <a className="mapboxgl-ctrl-logo" target="_blank" rel="noopener noreferrer" href="https://www.mapbox.com/" aria-label="Mapbox logo" /> </div> <div className="attrition-link"> <a href="https://kepler.gl/policy/" target="_blank" rel="noopener noreferrer"> © kepler.gl |{' '} </a> <a href="https://www.mapbox.com/about/maps/" target="_blank" rel="noopener noreferrer"> © Mapbox |{' '} </a> <a href="http://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer"> © OpenStreetMap |{' '} </a> <a href="https://www.mapbox.com/map-feedback/" target="_blank" rel="noopener noreferrer"> <strong>Improve this map</strong> </a> </div> </StyledAttrbution> ); MapContainerFactory.deps = [MapPopoverFactory, MapControlFactory, EditorFactory]; type MapboxStyle = string | object | undefined; interface MapContainerProps { datasets: Datasets; interactionConfig: InteractionConfig; layerBlending: string; layerOrder: number[]; layerData: any[]; layers: Layer[]; filters: Filter[]; mapState: MapState; mapControls: MapControls; mapStyle: {bottomMapStyle?: MapboxStyle; topMapStyle?: MapboxStyle} & MapStyle; mousePos: any; mapboxApiAccessToken: string; mapboxApiUrl: string; visStateActions: typeof VisStateActions; mapStateActions: typeof MapStateActions; uiStateActions: typeof UIStateActions; // optional primary?: boolean; // primary one will be reporting its size to appState readOnly?: boolean; isExport?: boolean; clicked?: any; hoverInfo?: any; mapLayers?: SplitMapLayers | null; onMapToggleLayer?: Function; onMapStyleLoaded?: Function; onMapRender?: Function; getMapboxRef?: (mapbox?: MapboxGLMap | null, index?: number) => void; index?: number; locale?: any; editor?: any; MapComponent?: typeof MapboxGLMap; deckGlProps?: any; onDeckInitialized?: (a: any, b: any) => void; onViewStateChange?: (viewport: Viewport) => void; } export default function MapContainerFactory( MapPopover, MapControl, Editor ): React.ComponentType<MapContainerProps> { class MapContainer extends Component<MapContainerProps> { static propTypes = { // required }; static defaultProps = { MapComponent: MapboxGLMap, deckGlProps: {}, index: 0, primary: true }; previousLayers = { // [layers.id]: mapboxLayerConfig }; displayName = 'MapContainer'; _deck: any = null; _map: mapboxgl.Map | null = null; _ref = createRef<HTMLDivElement>(); _deckGLErrorsElapsed: {[id: string]: number} = {}; constructor(props) { super(props); } componentDidMount() { if (!this._ref.current) { return; } observeDimensions(this._ref.current, this._handleResize); } componentWillUnmount() { // unbind mapboxgl event listener if (this._map) { this._map?.off(MAPBOXGL_STYLE_UPDATE, nop); this._map?.off(MAPBOXGL_RENDER, nop); } if (!this._ref.current) { return; } unobserveDimensions(this._ref.current); } _handleResize = dimensions => { const {primary} = this.props; if (primary) { const {mapStateActions} = this.props; if (dimensions && dimensions.width > 0 && dimensions.height > 0) { mapStateActions.updateMap(dimensions); } } }; layersSelector = props => props.layers; layerDataSelector = props => props.layerData; mapLayersSelector = props => props.mapLayers; layerOrderSelector = props => props.layerOrder; layersToRenderSelector = createSelector( this.layersSelector, this.layerDataSelector, this.mapLayersSelector, prepareLayersToRender ); layersForDeckSelector = createSelector( this.layersSelector, this.layerDataSelector, prepareLayersForDeck ); filtersSelector = props => props.filters; polygonFilters = createSelector(this.filtersSelector, filters => filters.filter(f => f.type === FILTER_TYPES.polygon) ); mapboxLayersSelector = createSelector( this.layersSelector, this.layerDataSelector, this.layerOrderSelector, this.layersToRenderSelector, generateMapboxLayers ); /* component private functions */ _onCloseMapPopover = () => { this.props.visStateActions.onLayerClick(null); }; _onLayerSetDomain = (idx: number, colorDomain: VisualChannelDomain) => { this.props.visStateActions.layerConfigChange(this.props.layers[idx], { colorDomain } as Partial<LayerBaseConfig>); }; _handleMapToggleLayer = layerId => { const {index: mapIndex = 0, visStateActions} = this.props; visStateActions.toggleLayerForMap(mapIndex, layerId); }; _onMapboxStyleUpdate = () => { // force refresh mapboxgl layers this.previousLayers = {}; this._updateMapboxLayers(); if (typeof this.props.onMapStyleLoaded === 'function') { this.props.onMapStyleLoaded(this._map); } }; _setMapboxMap: React.LegacyRef<MapboxGLMap> = mapbox => { if (!this._map && mapbox) { this._map = mapbox.getMap(); // i noticed in certain context we don't access the actual map element if (!this._map) { return; } // bind mapboxgl event listener this._map.on(MAPBOXGL_STYLE_UPDATE, this._onMapboxStyleUpdate); this._map.on(MAPBOXGL_RENDER, () => { if (typeof this.props.onMapRender === 'function') { this.props.onMapRender(this._map); } }); } if (this.props.getMapboxRef) { // The parent component can gain access to our MapboxGlMap by // providing this callback. Note that 'mapbox' will be null when the // ref is unset (e.g. when a split map is closed). this.props.getMapboxRef(mapbox, this.props.index); } }; _onDeckInitialized(gl) { if (this.props.onDeckInitialized) { this.props.onDeckInitialized(this._deck, gl); } } _onBeforeRender = ({gl}) => { setLayerBlending(gl, this.props.layerBlending); }; _onDeckError = (error, layer) => { const errorMessage = `An error in deck.gl: ${error.message} in ${layer.id}`; const notificationId = `${layer.id}-${error.message}`; // Throttle error notifications, as React doesn't like too many state changes from here. const lastShown = this._deckGLErrorsElapsed[notificationId]; if (!lastShown || lastShown < Date.now() - THROTTLE_NOTIFICATION_TIME) { this._deckGLErrorsElapsed[notificationId] = Date.now(); // Create new error notification or update existing one with same id. // Update is required to preserve the order of notifications as they probably are going to "jump" based on order of errors. const {uiStateActions} = this.props; uiStateActions.addNotification( errorNotification({ message: errorMessage, id: notificationId }) ); } }; /* component render functions */ /* eslint-disable complexity */ _renderMapPopover(layersToRender) { // TODO: move this into reducer so it can be tested const { mapState, hoverInfo, clicked, datasets, interactionConfig, layers, mousePos: {mousePosition, coordinate, pinned} } = this.props; if (!mousePosition || !interactionConfig.tooltip) { return null; } const layerHoverProp = getLayerHoverProp({ interactionConfig, hoverInfo, layers, layersToRender, datasets }); const compareMode = interactionConfig.tooltip.config ? interactionConfig.tooltip.config.compareMode : false; let pinnedPosition = {}; let layerPinnedProp: LayerHoverProp | null = null; if (pinned || clicked) { // project lnglat to screen so that tooltip follows the object on zoom const viewport = new WebMercatorViewport(mapState); const lngLat = clicked ? clicked.lngLat : pinned.coordinate; pinnedPosition = this._getHoverXY(viewport, lngLat); layerPinnedProp = getLayerHoverProp({ interactionConfig, hoverInfo: clicked, layers, layersToRender, datasets }); if (layerHoverProp && layerPinnedProp) { layerHoverProp.primaryData = layerPinnedProp.data; layerHoverProp.compareType = interactionConfig.tooltip.config.compareType; } } const commonProp = { onClose: this._onCloseMapPopover, zoom: mapState.zoom, container: this._deck ? this._deck.canvas : undefined }; return ( <ErrorBoundary> {layerPinnedProp && ( <MapPopover {...pinnedPosition} {...commonProp} layerHoverProp={layerPinnedProp} coordinate={interactionConfig.coordinate.enabled && (pinned || {}).coordinate} frozen={true} isBase={compareMode} /> )} {layerHoverProp && (!layerPinnedProp || compareMode) && ( <MapPopover x={mousePosition[0]} y={mousePosition[1]} {...commonProp} layerHoverProp={layerHoverProp} frozen={false} coordinate={interactionConfig.coordinate.enabled && coordinate} /> )} </ErrorBoundary> ); } /* eslint-enable complexity */ _getHoverXY(viewport, lngLat) { const screenCoord = !viewport || !lngLat ? null : viewport.project(lngLat); return screenCoord && {x: screenCoord[0], y: screenCoord[1]}; } _renderDeckOverlay(layersForDeck) { const { mapState, mapStyle, layerData, layerOrder, layers, visStateActions, mapboxApiAccessToken, mapboxApiUrl } = this.props; // initialise layers from props if exists let deckGlLayers = this.props.deckGlProps?.layers || []; // wait until data is ready before render data layers if (layerData && layerData.length) { // last layer render first const dataLayers = layerOrder .slice() .reverse() .filter(idx => layersForDeck[layers[idx].id]) .reduce((overlays, idx) => { const layerCallbacks = { onSetLayerDomain: val => this._onLayerSetDomain(idx, val) }; const layerOverlay = renderDeckGlLayer(this.props, layerCallbacks, idx); return overlays.concat(layerOverlay || []); }, []); deckGlLayers = deckGlLayers.concat(dataLayers); } if (mapStyle.visibleLayerGroups['3d building']) { deckGlLayers.push( new ThreeDBuildingLayer({ id: '_keplergl_3d-building', mapboxApiAccessToken, mapboxApiUrl, threeDBuildingColor: mapStyle.threeDBuildingColor, updateTriggers: { getFillColor: mapStyle.threeDBuildingColor } }) ); } return ( <DeckGL {...this.props.deckGlProps} viewState={mapState} id="default-deckgl-overlay" layers={deckGlLayers} onBeforeRender={this._onBeforeRender} onHover={visStateActions.onLayerHover} onClick={visStateActions.onLayerClick} onError={this._onDeckError} ref={comp => { if (comp && comp.deck && !this._deck) { this._deck = comp.deck; } }} onWebGLInitialized={gl => this._onDeckInitialized(gl)} /> ); } _updateMapboxLayers() { const mapboxLayers = this.mapboxLayersSelector(this.props); if (!Object.keys(mapboxLayers).length && !Object.keys(this.previousLayers).length) { return; } updateMapboxLayers(this._map, mapboxLayers, this.previousLayers); this.previousLayers = mapboxLayers; } _renderMapboxOverlays() { if (this._map && this._map.isStyleLoaded()) { this._updateMapboxLayers(); } } _onViewportChange = viewState => { const {width, height, ...restViewState} = viewState; const {primary} = this.props; // react-map-gl sends 0,0 dimensions during initialization // after we have received proper dimensions from observeDimensions const next = { ...(width > 0 && height > 0 ? viewState : restViewState), // enabling transition in two maps may lead to endless update loops transitionDuration: primary ? TRANSITION_DURATION : 0 }; if (typeof this.props.onViewStateChange === 'function') { this.props.onViewStateChange(next); } this.props.mapStateActions.updateMap(next); }; _toggleMapControl = panelId => { const {index, uiStateActions} = this.props; uiStateActions.toggleMapControl(panelId, Number(index)); }; /* eslint-disable complexity */ _renderMap() { const { mapState, mapStyle, mapStateActions, layers, MapComponent = MapboxGLMap, datasets, mapboxApiAccessToken, mapboxApiUrl, mapControls, isExport, locale, uiStateActions, visStateActions, interactionConfig, editor, index, primary } = this.props; const layersToRender = this.layersToRenderSelector(this.props); const layersForDeck = this.layersForDeckSelector(this.props); const mapProps = { ...mapState, width: '100%', height: '100%', preserveDrawingBuffer: true, mapboxApiAccessToken, mapboxApiUrl, onViewportChange: this._onViewportChange, transformRequest }; const isEdit = (mapControls.mapDraw || {}).active; const hasGeocoderLayer = layers.find(l => l.id === GEOCODER_LAYER_ID); const isSplit = Boolean(mapState.isSplit); return ( <> <MapControl datasets={datasets} availableLocales={Object.keys(LOCALE_CODES)} dragRotate={mapState.dragRotate} isSplit={isSplit} primary={primary} isExport={isExport} layers={layers} layersToRender={layersToRender} mapIndex={index} mapControls={mapControls} readOnly={this.props.readOnly} scale={mapState.scale || 1} top={interactionConfig.geocoder && interactionConfig.geocoder.enabled ? 52 : 0} editor={editor} locale={locale} onTogglePerspective={mapStateActions.togglePerspective} onToggleSplitMap={mapStateActions.toggleSplitMap} onMapToggleLayer={this._handleMapToggleLayer} onToggleMapControl={this._toggleMapControl} onSetEditorMode={visStateActions.setEditorMode} onSetLocale={uiStateActions.setLocale} onToggleEditorVisibility={visStateActions.toggleEditorVisibility} mapHeight={mapState.height} /> <MapComponent {...mapProps} key="bottom" ref={this._setMapboxMap} mapStyle={mapStyle.bottomMapStyle} getCursor={this.props.hoverInfo ? () => 'pointer' : undefined} onMouseMove={this.props.visStateActions.onMouseMove} > {this._renderDeckOverlay(layersForDeck)} {this._renderMapboxOverlays()} <Editor index={index} datasets={datasets} editor={editor} filters={this.polygonFilters(this.props)} isEnabled={isEdit} layers={layers} layersToRender={layersToRender} onDeleteFeature={visStateActions.deleteFeature} onSelect={visStateActions.setSelectedFeature} onUpdate={visStateActions.setFeatures} onTogglePolygonFilter={visStateActions.setPolygonFilterLayer} style={{ pointerEvents: isEdit ? 'all' : 'none', position: 'absolute', display: editor.visible ? 'block' : 'none' }} /> </MapComponent> {mapStyle.topMapStyle || hasGeocoderLayer ? ( <div style={MAP_STYLE.top}> <MapComponent {...mapProps} key="top" mapStyle={mapStyle.topMapStyle}> {this._renderDeckOverlay({[GEOCODER_LAYER_ID]: true})} </MapComponent> </div> ) : null} {this._renderMapPopover(layersToRender)} {!isSplit || index === 1 ? <Attribution /> : null} </> ); } render() { const {mapStyle} = this.props; return ( <StyledMapContainer ref={this._ref} style={MAP_STYLE.container}> {mapStyle.bottomMapStyle && this._renderMap()} </StyledMapContainer> ); } } return MapContainer; }
the_stack
import { licenseStatusEntityReducer, LicenseStatusEntityInitialState, LicenseStatusEntityState } from './license.reducer'; import { GetLicenseStatus, GetLicenseStatusSuccessExpiringSoon, GetLicenseStatusSuccess, GetLicenseStatusFailure, ApplyLicense, ApplyLicenseSuccess, ApplyLicenseFailure, RequestLicense, RequestLicenseSuccess, RequestLicenseFailure, TriggerWelcome } from './license.actions'; import { EntityStatus } from '../entities'; import { LicenseStatus, ApplyLicensePayload, RequestLicensePayload, ApplyLicenseResponse, RequestLicenseResponse } from './license.model'; import { HttpErrorResponse } from '@angular/common/http'; describe('licenseStatusEntityReducer', () => { const initialState: LicenseStatusEntityState = LicenseStatusEntityInitialState; // note: the error code doesn't matter, but it has to be passed to the // constructor const httpErrorResponse = new HttpErrorResponse({status: 400}); const licenseStatus: LicenseStatus = { license_id: 'a953c5bb-82a5-41be-b7dd-a5de1ea53ada', configured_at: '2018-04-26T21:14:34.000Z', licensed_period: { start: '2018-02-14T00:00:00.000Z', end: '2020-02-14T23:59:59.000Z' }, customer_name: 'Chef Dev' }; describe('LicenseStatus action types', () => { describe('GET', () => { const action = new GetLicenseStatus(); it('sets status to loading', () => { const { fetch: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.status).toEqual(EntityStatus.loading); }); it('leaves expiry_message intact', () => { const previousState = { ...initialState, fetch: { ...initialState.fetch, expiryMessage: 'something something expiry' } }; const { fetch: newState } = licenseStatusEntityReducer(previousState, action); expect(newState.expiryMessage).toEqual('something something expiry'); }); it('leaves errorResp intact', () => { const previousState = { ...initialState, fetch: { ...initialState.fetch, errorResp: httpErrorResponse } }; const { fetch: newState } = licenseStatusEntityReducer(previousState, action); expect(newState.errorResp).toEqual(httpErrorResponse); }); }); describe('GET_SUCCESS_EXPIRING_SOON', () => { const payload = { license: licenseStatus, expiry_message: '4 days remaining' }; const action = new GetLicenseStatusSuccessExpiringSoon(payload); it('sets status to loadingSuccess', () => { const { fetch: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.status).toEqual(EntityStatus.loadingSuccess); }); it('resets errorResp', () => { const previousState = { ...initialState, fetch: { ...initialState.fetch, errorResp: httpErrorResponse } }; const { fetch: newState } = licenseStatusEntityReducer(previousState, action); expect(newState.errorResp).toBeNull(); }); it('carries over expiry_message', () => { const { fetch: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.expiryMessage).toEqual('4 days remaining'); }); it('carries over the license status', () => { const { fetch: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.license).toEqual(licenseStatus); }); }); describe('GET_SUCCESS', () => { const payload = licenseStatus; const action = new GetLicenseStatusSuccess(payload); it('sets status to loadingSuccess', () => { const { fetch: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.status).toEqual(EntityStatus.loadingSuccess); }); it('resets errorResp', () => { const previousState = { ...initialState, fetch: { ...initialState.fetch, errorResp: httpErrorResponse } }; const { fetch: newState } = licenseStatusEntityReducer(previousState, action); expect(newState.errorResp).toBeNull(); }); it('resets expiry_message', () => { const previousState = { ...initialState, fetch: { ...initialState.fetch, expiryMessage: 'something something expiry' } }; const { fetch: newState } = licenseStatusEntityReducer(previousState, action); expect(newState.expiryMessage).toEqual(''); }); it('carries over the license status', () => { const { fetch: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.license).toEqual(licenseStatus); }); }); describe('GET_FAILURE', () => { const payload = httpErrorResponse; const action = new GetLicenseStatusFailure(payload); it('sets status to loadingFailure', () => { const { fetch: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.status).toEqual(EntityStatus.loadingFailure); }); it('carries over errorResp', () => { const { fetch: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.errorResp).toEqual(payload); }); it('leaves expiry_message intact', () => { const previousState = { ...initialState, fetch: { ...initialState.fetch, expiryMessage: 'something something expiry' } }; const { fetch: newState } = licenseStatusEntityReducer(previousState, action); expect(newState.expiryMessage).toEqual('something something expiry'); }); }); describe('APPLY', () => { const payload: ApplyLicensePayload = { license: 'any' }; const action = new ApplyLicense(payload); it('sets status to loading', () => { const { apply: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.status).toEqual(EntityStatus.loading); }); it('leaves errorResp intact', () => { const previousState = { ...initialState, apply: { ...initialState.fetch, errorResp: httpErrorResponse } }; const { apply: newState } = licenseStatusEntityReducer(previousState, action); expect(newState.errorResp).toEqual(httpErrorResponse); }); }); describe('APPLY_SUCCESS', () => { const payload: ApplyLicenseResponse = { status: licenseStatus }; const action = new ApplyLicenseSuccess(payload); it('sets status to loadingSuccess', () => { const { apply: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.status).toEqual(EntityStatus.loadingSuccess); }); // FIXME? Does it not matter, since this is a one-shot action? it('leaves errorResp intact', () => { const previousState = { ...initialState, apply: { ...initialState.fetch, errorResp: httpErrorResponse } }; const { apply: newState } = licenseStatusEntityReducer(previousState, action); expect(newState.errorResp).toEqual(httpErrorResponse); }); }); describe('APPLY_FAILURE', () => { const payload = httpErrorResponse; const action = new ApplyLicenseFailure(payload); it('sets status to loadingFailure', () => { const { apply: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.status).toEqual(EntityStatus.loadingFailure); }); it('sets errorResp', () => { const { apply: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.errorResp).toEqual(payload); }); }); describe('REQUEST', () => { const payload: RequestLicensePayload = { first_name: 'alice', last_name: 'schmidt', email: 'alice@schmidt.com', gdpr_agree: true }; const action = new RequestLicense(payload); it('sets status to loading', () => { const { request: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.status).toEqual(EntityStatus.loading); }); it('leaves errorResp intact', () => { const previousState = { ...initialState, request: { ...initialState.fetch, errorResp: httpErrorResponse } }; const { request: newState } = licenseStatusEntityReducer(previousState, action); expect(newState.errorResp).toEqual(httpErrorResponse); }); }); describe('REQUEST_SUCCESS', () => { const payload: RequestLicenseResponse = { status: licenseStatus, license: 'any' }; const action = new RequestLicenseSuccess(payload); it('sets status to loadingSuccess', () => { const { request: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.status).toEqual(EntityStatus.loadingSuccess); }); it('leaves errorResp intact', () => { const previousState = { ...initialState, request: { ...initialState.fetch, errorResp: httpErrorResponse } }; const { request: newState } = licenseStatusEntityReducer(previousState, action); expect(newState.errorResp).toEqual(httpErrorResponse); }); }); describe('REQUEST_FAILURE', () => { const payload = httpErrorResponse; const action = new RequestLicenseFailure(payload); it('sets status to loadingFailure', () => { const { request: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.status).toEqual(EntityStatus.loadingFailure); }); it('sets errorResp', () => { const { request: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.errorResp).toEqual(payload); }); }); describe('TRIGGER_WELCOME', () => { const action = new TriggerWelcome(); it('sets status to loadingSuccess', () => { const { triggerWelcome: newState } = licenseStatusEntityReducer(initialState, action); expect(newState.status).toEqual(EntityStatus.loadingSuccess); }); }); }); });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/serviceMappers"; import * as Parameters from "../models/parameters"; import { DataBoxManagementClientContext } from "../dataBoxManagementClientContext"; /** Class representing a Service. */ export class Service { private readonly client: DataBoxManagementClientContext; /** * Create a Service. * @param {DataBoxManagementClientContext} client Reference to the service client. */ constructor(client: DataBoxManagementClientContext) { this.client = client; } /** * This method provides the list of available skus for the given subscription and location. * @param location The location of the resource * @param availableSkuRequest Filters for showing the available skus. * @param [options] The optional parameters * @returns Promise<Models.ServiceListAvailableSkusResponse> */ listAvailableSkus(location: string, availableSkuRequest: Models.AvailableSkuRequest, options?: msRest.RequestOptionsBase): Promise<Models.ServiceListAvailableSkusResponse>; /** * @param location The location of the resource * @param availableSkuRequest Filters for showing the available skus. * @param callback The callback */ listAvailableSkus(location: string, availableSkuRequest: Models.AvailableSkuRequest, callback: msRest.ServiceCallback<Models.AvailableSkusResult>): void; /** * @param location The location of the resource * @param availableSkuRequest Filters for showing the available skus. * @param options The optional parameters * @param callback The callback */ listAvailableSkus(location: string, availableSkuRequest: Models.AvailableSkuRequest, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AvailableSkusResult>): void; listAvailableSkus(location: string, availableSkuRequest: Models.AvailableSkuRequest, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AvailableSkusResult>, callback?: msRest.ServiceCallback<Models.AvailableSkusResult>): Promise<Models.ServiceListAvailableSkusResponse> { return this.client.sendOperationRequest( { location, availableSkuRequest, options }, listAvailableSkusOperationSpec, callback) as Promise<Models.ServiceListAvailableSkusResponse>; } /** * This method provides the list of available skus for the given subscription, resource group and * location. * @param resourceGroupName The Resource Group Name * @param location The location of the resource * @param availableSkuRequest Filters for showing the available skus. * @param [options] The optional parameters * @returns Promise<Models.ServiceListAvailableSkusByResourceGroupResponse> */ listAvailableSkusByResourceGroup(resourceGroupName: string, location: string, availableSkuRequest: Models.AvailableSkuRequest, options?: msRest.RequestOptionsBase): Promise<Models.ServiceListAvailableSkusByResourceGroupResponse>; /** * @param resourceGroupName The Resource Group Name * @param location The location of the resource * @param availableSkuRequest Filters for showing the available skus. * @param callback The callback */ listAvailableSkusByResourceGroup(resourceGroupName: string, location: string, availableSkuRequest: Models.AvailableSkuRequest, callback: msRest.ServiceCallback<Models.AvailableSkusResult>): void; /** * @param resourceGroupName The Resource Group Name * @param location The location of the resource * @param availableSkuRequest Filters for showing the available skus. * @param options The optional parameters * @param callback The callback */ listAvailableSkusByResourceGroup(resourceGroupName: string, location: string, availableSkuRequest: Models.AvailableSkuRequest, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AvailableSkusResult>): void; listAvailableSkusByResourceGroup(resourceGroupName: string, location: string, availableSkuRequest: Models.AvailableSkuRequest, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AvailableSkusResult>, callback?: msRest.ServiceCallback<Models.AvailableSkusResult>): Promise<Models.ServiceListAvailableSkusByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, location, availableSkuRequest, options }, listAvailableSkusByResourceGroupOperationSpec, callback) as Promise<Models.ServiceListAvailableSkusByResourceGroupResponse>; } /** * [DEPRECATED NOTICE: This operation will soon be removed] This method validates the customer * shipping address and provide alternate addresses if any. * @param location The location of the resource * @param validateAddress Shipping address of the customer. * @param [options] The optional parameters * @deprecated This operation is deprecated. Please do not use it any longer. * @returns Promise<Models.ServiceValidateAddressMethodResponse> */ validateAddressMethod(location: string, validateAddress: Models.ValidateAddress, options?: msRest.RequestOptionsBase): Promise<Models.ServiceValidateAddressMethodResponse>; /** * @param location The location of the resource * @param validateAddress Shipping address of the customer. * @param callback The callback * @deprecated This operation is deprecated. Please do not use it any longer. */ validateAddressMethod(location: string, validateAddress: Models.ValidateAddress, callback: msRest.ServiceCallback<Models.AddressValidationOutput>): void; /** * @param location The location of the resource * @param validateAddress Shipping address of the customer. * @param options The optional parameters * @param callback The callback * @deprecated This operation is deprecated. Please do not use it any longer. */ validateAddressMethod(location: string, validateAddress: Models.ValidateAddress, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AddressValidationOutput>): void; validateAddressMethod(location: string, validateAddress: Models.ValidateAddress, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AddressValidationOutput>, callback?: msRest.ServiceCallback<Models.AddressValidationOutput>): Promise<Models.ServiceValidateAddressMethodResponse> { return this.client.sendOperationRequest( { location, validateAddress, options }, validateAddressMethodOperationSpec, callback) as Promise<Models.ServiceValidateAddressMethodResponse>; } /** * This method does all necessary pre-job creation validation under resource group. * @param resourceGroupName The Resource Group Name * @param location The location of the resource * @param validationRequest Inputs of the customer. * @param [options] The optional parameters * @returns Promise<Models.ServiceValidateInputsByResourceGroupResponse> */ validateInputsByResourceGroup(resourceGroupName: string, location: string, validationRequest: Models.ValidationRequestUnion, options?: msRest.RequestOptionsBase): Promise<Models.ServiceValidateInputsByResourceGroupResponse>; /** * @param resourceGroupName The Resource Group Name * @param location The location of the resource * @param validationRequest Inputs of the customer. * @param callback The callback */ validateInputsByResourceGroup(resourceGroupName: string, location: string, validationRequest: Models.ValidationRequestUnion, callback: msRest.ServiceCallback<Models.ValidationResponse>): void; /** * @param resourceGroupName The Resource Group Name * @param location The location of the resource * @param validationRequest Inputs of the customer. * @param options The optional parameters * @param callback The callback */ validateInputsByResourceGroup(resourceGroupName: string, location: string, validationRequest: Models.ValidationRequestUnion, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ValidationResponse>): void; validateInputsByResourceGroup(resourceGroupName: string, location: string, validationRequest: Models.ValidationRequestUnion, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ValidationResponse>, callback?: msRest.ServiceCallback<Models.ValidationResponse>): Promise<Models.ServiceValidateInputsByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, location, validationRequest, options }, validateInputsByResourceGroupOperationSpec, callback) as Promise<Models.ServiceValidateInputsByResourceGroupResponse>; } /** * This method does all necessary pre-job creation validation under subscription. * @param location The location of the resource * @param validationRequest Inputs of the customer. * @param [options] The optional parameters * @returns Promise<Models.ServiceValidateInputsResponse> */ validateInputs(location: string, validationRequest: Models.ValidationRequestUnion, options?: msRest.RequestOptionsBase): Promise<Models.ServiceValidateInputsResponse>; /** * @param location The location of the resource * @param validationRequest Inputs of the customer. * @param callback The callback */ validateInputs(location: string, validationRequest: Models.ValidationRequestUnion, callback: msRest.ServiceCallback<Models.ValidationResponse>): void; /** * @param location The location of the resource * @param validationRequest Inputs of the customer. * @param options The optional parameters * @param callback The callback */ validateInputs(location: string, validationRequest: Models.ValidationRequestUnion, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ValidationResponse>): void; validateInputs(location: string, validationRequest: Models.ValidationRequestUnion, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ValidationResponse>, callback?: msRest.ServiceCallback<Models.ValidationResponse>): Promise<Models.ServiceValidateInputsResponse> { return this.client.sendOperationRequest( { location, validationRequest, options }, validateInputsOperationSpec, callback) as Promise<Models.ServiceValidateInputsResponse>; } /** * This API provides configuration details specific to given region/location. * @param location The location of the resource * @param [options] The optional parameters * @returns Promise<Models.ServiceRegionConfigurationResponse> */ regionConfiguration(location: string, options?: Models.ServiceRegionConfigurationOptionalParams): Promise<Models.ServiceRegionConfigurationResponse>; /** * @param location The location of the resource * @param callback The callback */ regionConfiguration(location: string, callback: msRest.ServiceCallback<Models.RegionConfigurationResponse>): void; /** * @param location The location of the resource * @param options The optional parameters * @param callback The callback */ regionConfiguration(location: string, options: Models.ServiceRegionConfigurationOptionalParams, callback: msRest.ServiceCallback<Models.RegionConfigurationResponse>): void; regionConfiguration(location: string, options?: Models.ServiceRegionConfigurationOptionalParams | msRest.ServiceCallback<Models.RegionConfigurationResponse>, callback?: msRest.ServiceCallback<Models.RegionConfigurationResponse>): Promise<Models.ServiceRegionConfigurationResponse> { return this.client.sendOperationRequest( { location, options }, regionConfigurationOperationSpec, callback) as Promise<Models.ServiceRegionConfigurationResponse>; } /** * This method provides the list of available skus for the given subscription and location. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ServiceListAvailableSkusNextResponse> */ listAvailableSkusNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ServiceListAvailableSkusNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listAvailableSkusNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.AvailableSkusResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listAvailableSkusNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AvailableSkusResult>): void; listAvailableSkusNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AvailableSkusResult>, callback?: msRest.ServiceCallback<Models.AvailableSkusResult>): Promise<Models.ServiceListAvailableSkusNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listAvailableSkusNextOperationSpec, callback) as Promise<Models.ServiceListAvailableSkusNextResponse>; } /** * This method provides the list of available skus for the given subscription, resource group and * location. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.ServiceListAvailableSkusByResourceGroupNextResponse> */ listAvailableSkusByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ServiceListAvailableSkusByResourceGroupNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listAvailableSkusByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.AvailableSkusResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listAvailableSkusByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AvailableSkusResult>): void; listAvailableSkusByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AvailableSkusResult>, callback?: msRest.ServiceCallback<Models.AvailableSkusResult>): Promise<Models.ServiceListAvailableSkusByResourceGroupNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listAvailableSkusByResourceGroupNextOperationSpec, callback) as Promise<Models.ServiceListAvailableSkusByResourceGroupNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listAvailableSkusOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/providers/Microsoft.DataBox/locations/{location}/availableSkus", urlParameters: [ Parameters.subscriptionId, Parameters.location ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "availableSkuRequest", mapper: { ...Mappers.AvailableSkuRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.AvailableSkusResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listAvailableSkusByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBox/locations/{location}/availableSkus", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.location ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "availableSkuRequest", mapper: { ...Mappers.AvailableSkuRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.AvailableSkusResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const validateAddressMethodOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/providers/Microsoft.DataBox/locations/{location}/validateAddress", urlParameters: [ Parameters.subscriptionId, Parameters.location ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "validateAddress", mapper: { ...Mappers.ValidateAddress, required: true } }, responses: { 200: { bodyMapper: Mappers.AddressValidationOutput }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const validateInputsByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataBox/locations/{location}/validateInputs", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.location ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "validationRequest", mapper: { ...Mappers.ValidationRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.ValidationResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const validateInputsOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/providers/Microsoft.DataBox/locations/{location}/validateInputs", urlParameters: [ Parameters.subscriptionId, Parameters.location ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "validationRequest", mapper: { ...Mappers.ValidationRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.ValidationResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const regionConfigurationOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/providers/Microsoft.DataBox/locations/{location}/regionConfiguration", urlParameters: [ Parameters.subscriptionId, Parameters.location ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: { scheduleAvailabilityRequest: [ "options", "scheduleAvailabilityRequest" ], transportAvailabilityRequest: [ "options", "transportAvailabilityRequest" ] }, mapper: { ...Mappers.RegionConfigurationRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.RegionConfigurationResponse }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listAvailableSkusNextOperationSpec: msRest.OperationSpec = { httpMethod: "POST", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.AvailableSkusResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listAvailableSkusByResourceGroupNextOperationSpec: msRest.OperationSpec = { httpMethod: "POST", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.AvailableSkusResult }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
// WebRPC description and code-gen version export const WebRPCVersion = "v1" // Schema version of your RIDL schema export const WebRPCSchemaVersion = "v0.4.0" // Schema hash generated from your RIDL schema export const WebRPCSchemaHash = "d44c148ecd843665eba71e66908382e569d8821a" // // Types // export enum ContractType { UNKNOWN = 'UNKNOWN', ERC20 = 'ERC20', ERC721 = 'ERC721', ERC1155 = 'ERC1155', SEQUENCE_WALLET = 'SEQUENCE_WALLET', ERC20_BRIDGE = 'ERC20_BRIDGE', ERC721_BRIDGE = 'ERC721_BRIDGE', ERC1155_BRIDGE = 'ERC1155_BRIDGE' } export enum EventLogType { UNKNOWN = 'UNKNOWN', BLOCK_ADDED = 'BLOCK_ADDED', BLOCK_REMOVED = 'BLOCK_REMOVED' } export enum EventLogDataType { UNKNOWN = 'UNKNOWN', TOKEN_TRANSFER = 'TOKEN_TRANSFER', SEQUENCE_TXN = 'SEQUENCE_TXN' } export enum TxnTransferType { UNKNOWN = 'UNKNOWN', SEND = 'SEND', RECEIVE = 'RECEIVE' } export enum SortOrder { DESC = 'DESC', ASC = 'ASC' } export interface Version { webrpcVersion: string schemaVersion: string schemaHash: string appVersion: string } export interface RuntimeStatus { healthOK: boolean indexerEnabled: boolean startTime: string uptime: number ver: string branch: string commitHash: string chainID: number checks: RuntimeChecks } export interface RuntimeChecks { running: boolean syncMode: string lastBlockNum: number } export interface EtherBalance { accountAddress: string balanceWei: string } export interface IndexState { chainId: string lastBlockNum: number } export interface EventLog { id: number type: EventLogType blockNumber: number blockHash: string contractAddress: string contractType: ContractType txnHash: string txnIndex: number txnLogIndex: number logDataType: EventLogDataType ts: string logData: string } export interface TokenBalance { id: number contractAddress: string contractType: ContractType accountAddress: string tokenID: string balance: string blockHash: string blockNumber: number updateId: number chainId: number } export interface TokenHistory { id: number blockNumber: number blockHash: string contractAddress: string contractType: ContractType fromAddress: string toAddress: string txnHash: string txnIndex: number txnLogIndex: number logData: string ts: string } export interface TokenSupply { tokenID: string supply: string chainId: number } export interface Transaction { txnHash: string blockNumber: number blockHash: string chainId: number metaTxnID?: string transfers?: Array<TxnTransfer> timestamp: string } export interface TxnTransfer { transferType: TxnTransferType contractAddress: string contractType: ContractType from: string to: string tokenIds?: Array<string> amounts: Array<string> } export interface TransactionHistoryFilter { accountAddress?: string contractAddress?: string accountAddresses?: Array<string> contractAddresses?: Array<string> transactionHashes?: Array<string> metaTransactionIDs?: Array<string> fromBlock?: number toBlock?: number } export interface Page { pageSize?: number page?: number more?: boolean column?: string before?: any after?: any sort?: Array<SortBy> } export interface SortBy { column: string order: SortOrder } export interface Indexer { ping(headers?: object): Promise<PingReturn> version(headers?: object): Promise<VersionReturn> runtimeStatus(headers?: object): Promise<RuntimeStatusReturn> getChainID(headers?: object): Promise<GetChainIDReturn> getEtherBalance(args: GetEtherBalanceArgs, headers?: object): Promise<GetEtherBalanceReturn> getTokenBalances(args: GetTokenBalancesArgs, headers?: object): Promise<GetTokenBalancesReturn> getTokenSupplies(args: GetTokenSuppliesArgs, headers?: object): Promise<GetTokenSuppliesReturn> getTokenSuppliesMap(args: GetTokenSuppliesMapArgs, headers?: object): Promise<GetTokenSuppliesMapReturn> getBalanceUpdates(args: GetBalanceUpdatesArgs, headers?: object): Promise<GetBalanceUpdatesReturn> getTransactionHistory(args: GetTransactionHistoryArgs, headers?: object): Promise<GetTransactionHistoryReturn> } export interface PingArgs { } export interface PingReturn { status: boolean } export interface VersionArgs { } export interface VersionReturn { version: Version } export interface RuntimeStatusArgs { } export interface RuntimeStatusReturn { status: RuntimeStatus } export interface GetChainIDArgs { } export interface GetChainIDReturn { chainID: number } export interface GetEtherBalanceArgs { accountAddress?: string } export interface GetEtherBalanceReturn { balance: EtherBalance } export interface GetTokenBalancesArgs { accountAddress?: string contractAddress?: string } export interface GetTokenBalancesReturn { balances: Array<TokenBalance> } export interface GetTokenSuppliesArgs { contractAddress: string } export interface GetTokenSuppliesReturn { contractType: ContractType tokenIDs: Array<TokenSupply> } export interface GetTokenSuppliesMapArgs { tokenMap: {[key: string]: Array<string>} } export interface GetTokenSuppliesMapReturn { supplies: {[key: string]: Array<TokenSupply>} } export interface GetBalanceUpdatesArgs { contractAddress: string lastUpdateID: number page?: Page } export interface GetBalanceUpdatesReturn { page?: Page balances: Array<TokenBalance> } export interface GetTransactionHistoryArgs { filter: TransactionHistoryFilter page?: Page } export interface GetTransactionHistoryReturn { page: Page transactions: Array<Transaction> } // // Client // export class Indexer implements Indexer { protected hostname: string protected fetch: Fetch protected path = '/rpc/Indexer/' constructor(hostname: string, fetch: Fetch) { this.hostname = hostname this.fetch = fetch } private url(name: string): string { return this.hostname + this.path + name } ping = (headers?: object): Promise<PingReturn> => { return this.fetch( this.url('Ping'), createHTTPRequest({}, headers) ).then((res) => { return buildResponse(res).then(_data => { return { status: <boolean>(_data.status) } }) }) } version = (headers?: object): Promise<VersionReturn> => { return this.fetch( this.url('Version'), createHTTPRequest({}, headers) ).then((res) => { return buildResponse(res).then(_data => { return { version: <Version>(_data.version) } }) }) } runtimeStatus = (headers?: object): Promise<RuntimeStatusReturn> => { return this.fetch( this.url('RuntimeStatus'), createHTTPRequest({}, headers) ).then((res) => { return buildResponse(res).then(_data => { return { status: <RuntimeStatus>(_data.status) } }) }) } getChainID = (headers?: object): Promise<GetChainIDReturn> => { return this.fetch( this.url('GetChainID'), createHTTPRequest({}, headers) ).then((res) => { return buildResponse(res).then(_data => { return { chainID: <number>(_data.chainID) } }) }) } getEtherBalance = (args: GetEtherBalanceArgs, headers?: object): Promise<GetEtherBalanceReturn> => { return this.fetch( this.url('GetEtherBalance'), createHTTPRequest(args, headers)).then((res) => { return buildResponse(res).then(_data => { return { balance: <EtherBalance>(_data.balance) } }) }) } getTokenBalances = (args: GetTokenBalancesArgs, headers?: object): Promise<GetTokenBalancesReturn> => { return this.fetch( this.url('GetTokenBalances'), createHTTPRequest(args, headers)).then((res) => { return buildResponse(res).then(_data => { return { balances: <Array<TokenBalance>>(_data.balances) } }) }) } getTokenSupplies = (args: GetTokenSuppliesArgs, headers?: object): Promise<GetTokenSuppliesReturn> => { return this.fetch( this.url('GetTokenSupplies'), createHTTPRequest(args, headers)).then((res) => { return buildResponse(res).then(_data => { return { contractType: <ContractType>(_data.contractType), tokenIDs: <Array<TokenSupply>>(_data.tokenIDs) } }) }) } getTokenSuppliesMap = (args: GetTokenSuppliesMapArgs, headers?: object): Promise<GetTokenSuppliesMapReturn> => { return this.fetch( this.url('GetTokenSuppliesMap'), createHTTPRequest(args, headers)).then((res) => { return buildResponse(res).then(_data => { return { supplies: <{[key: string]: Array<TokenSupply>}>(_data.supplies) } }) }) } getBalanceUpdates = (args: GetBalanceUpdatesArgs, headers?: object): Promise<GetBalanceUpdatesReturn> => { return this.fetch( this.url('GetBalanceUpdates'), createHTTPRequest(args, headers)).then((res) => { return buildResponse(res).then(_data => { return { page: <Page>(_data.page), balances: <Array<TokenBalance>>(_data.balances) } }) }) } getTransactionHistory = (args: GetTransactionHistoryArgs, headers?: object): Promise<GetTransactionHistoryReturn> => { return this.fetch( this.url('GetTransactionHistory'), createHTTPRequest(args, headers)).then((res) => { return buildResponse(res).then(_data => { return { page: <Page>(_data.page), transactions: <Array<Transaction>>(_data.transactions) } }) }) } } export interface WebRPCError extends Error { code: string msg: string status: number } const createHTTPRequest = (body: object = {}, headers: object = {}): object => { return { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) } } const buildResponse = (res: Response): Promise<any> => { return res.text().then(text => { let data try { data = JSON.parse(text) } catch(err) { throw { code: 'unknown', msg: `expecting JSON, got: ${text}`, status: res.status } as WebRPCError } if (!res.ok) { throw data // webrpc error response } return data }) } export type Fetch = (input: RequestInfo, init?: RequestInit) => Promise<Response>
the_stack
import React, { Component, useState } from "react"; import { Tag, Popover, Tooltip, ConfigProvider, Table, Progress, Button, Modal, Slider, Popconfirm, Checkbox, Skeleton, message } from "antd"; import { LazyMap } from "../../../../utils/LazyMap"; import { Broker, ConfigEntry, Partition, PartitionReassignmentsPartition } from "../../../../state/restInterfaces"; import { api, brokerMap } from "../../../../state/backendApi"; import { computed, makeObservable, observable } from "mobx"; import { DefaultSkeleton, findPopupContainer, QuickTable } from "../../../../utils/tsxUtils"; import { makePaginationConfig, sortField } from "../../../misc/common"; import { uiSettings } from "../../../../state/ui"; import { ColumnProps } from "antd/lib/table"; import { TopicWithPartitions } from "../Step1.Partitions"; import { DebugTimerStore, Message, prettyBytesOrNA, prettyMilliseconds } from "../../../../utils/utils"; import { BrokerList } from "./BrokerList"; import { ReassignmentState, ReassignmentTracker } from "../logic/reassignmentTracker"; import { observer } from "mobx-react"; import { EllipsisOutlined } from "@ant-design/icons"; import { strictEqual } from "assert"; import { reassignmentTracker } from "../ReassignPartitions"; import { BandwidthSlider } from "./BandwidthSlider"; import { KowlTable } from "../../../misc/KowlTable"; @observer export class ActiveReassignments extends Component<{ throttledTopics: string[], onRemoveThrottleFromTopics: () => void }> { pageConfig = { defaultPageSize: 5 }; // When set, a modal will be shown for the reassignment state @observable reassignmentDetails: ReassignmentState | null = null; @observable showThrottleDialog = false; constructor(p: any) { super(p); api.refreshCluster(true); makeObservable(this); } render() { const columnsActiveReassignments: ColumnProps<ReassignmentState>[] = [ { title: 'Topic', width: '1%', render: (v, t) => <TopicNameCol state={t} />, sorter: sortField('topicName') }, { title: 'Progress', // ProgressBar, Percent, ETA render: (v, t) => <ProgressCol state={t} />, sorter: (a, b) => { if (a.progressPercent == null && b.progressPercent != null) return 1; if (a.progressPercent != null && b.progressPercent == null) return -1; if (a.progressPercent == null || b.progressPercent == null) return 0; return a.progressPercent - b.progressPercent; } }, { title: 'ETA', width: '100px', align: 'right', render: (v, t) => <ETACol state={t} />, sorter: (a, b) => { if (a.estimateCompletionTime == null && b.estimateCompletionTime != null) return 1; if (a.estimateCompletionTime != null && b.estimateCompletionTime == null) return -1; if (a.estimateCompletionTime == null || b.estimateCompletionTime == null) return 0; return a.estimateCompletionTime.getTime() - b.estimateCompletionTime.getTime(); }, defaultSortOrder: 'ascend' }, { title: 'Brokers', width: '0.1%', render: (v, t) => <BrokersCol state={t} />, }, ]; const minThrottle = this.minThrottle; const throttleText = minThrottle === undefined ? <>Throttle: Not set (unlimited)</> : <>Throttle: {prettyBytesOrNA(minThrottle)}/s</> const currentReassignments = reassignmentTracker.trackingReassignments ?? []; return <> {/* Title */} <div className='currentReassignments' style={{ display: 'flex', placeItems: 'center', marginBottom: '.5em' }}> <span className='title'>Current Reassignments</span> <Button type='link' size='small' style={{ fontSize: 'smaller', padding: '0px 8px' }} onClick={() => this.showThrottleDialog = true} >{throttleText}</Button> </div> {/* Table */} <KowlTable className='activeReassignments' dataSource={currentReassignments} columns={columnsActiveReassignments} rowKey={r => r.topicName} onRow={(state, index) => { return { onClick: e => this.reassignmentDetails = state, }; }} pagination={this.pageConfig} observableSettings={uiSettings.reassignment.activeReassignments} emptyText={<div style={{ color: '#00000059', margin: '.4em 0' }}>No reassignments currently in progress</div>} /> <ReassignmentDetailsDialog state={this.reassignmentDetails} onClose={() => this.reassignmentDetails = null} /> <ThrottleDialog visible={this.showThrottleDialog} lastKnownMinThrottle={minThrottle} onClose={() => this.showThrottleDialog = false} /> {this.props.throttledTopics.length > 0 && <Button type='link' size='small' style={{ fontSize: 'smaller', padding: '0px 8px' }} onClick={this.props.onRemoveThrottleFromTopics} > <span>There are <b>{this.props.throttledTopics.length}</b> throttled topics - click here to fix</span> </Button> } </> } @computed get throttleSettings(): ({ followerThrottle: number | undefined, leaderThrottle: number | undefined }) { const leaderThrottle = [...api.brokerConfigs.values()] .filter(c => typeof c != 'string') .flatMap(c => c as ConfigEntry[]) .first(e => e.name == 'leader.replication.throttled.rate'); const followerThrottle = [...api.brokerConfigs.values()] .filter(c => typeof c != 'string') .flatMap(c => c as ConfigEntry[]) .first(e => e.name == 'follower.replication.throttled.rate'); const result = { leaderThrottle: leaderThrottle ? Number(leaderThrottle.value) : undefined, followerThrottle: followerThrottle ? Number(followerThrottle.value) : undefined }; return result; } @computed get minThrottle(): number | undefined { const t = this.throttleSettings; if (t.followerThrottle !== undefined || t.leaderThrottle !== undefined) return Math.min( t.followerThrottle ?? Number.POSITIVE_INFINITY, t.leaderThrottle ?? Number.POSITIVE_INFINITY ); return undefined; } } @observer export class ThrottleDialog extends Component<{ visible: boolean, lastKnownMinThrottle: number | undefined, onClose: () => void }> { @observable newThrottleValue: number | null = null; constructor(p: any) { super(p); this.newThrottleValue = this.props.lastKnownMinThrottle ?? null; makeObservable(this); } render() { const throttleValue = this.newThrottleValue ?? 0; const noChange = (this.newThrottleValue === this.props.lastKnownMinThrottle) || (this.newThrottleValue == null); // console.log('nochange:', { noChange, newVal: this.newThrottleValue, lastKnown: this.props.lastKnownMinThrottle }) return <Modal title="Throttle Settings" visible={this.props.visible} maskClosable={true} closeIcon={<></>} width="700px" onCancel={this.props.onClose} footer={<div style={{ display: 'flex' }}> <Button danger onClick={() => { this.newThrottleValue = null; this.applyBandwidthThrottle(); }} >Remove throttle</Button> <Button style={{ marginLeft: 'auto' }} onClick={this.props.onClose} >Close</Button> <Button disabled={noChange} type='primary' onClick={() => this.applyBandwidthThrottle()} >Apply</Button> </div>} > <div style={{ display: 'flex', flexDirection: 'column', gap: '1em', }}> <div style={{ margin: '0 1em' }}> <p style={{ margin: 0 }}>Using throttling you can limit the network traffic for reassignments.</p> <ul style={{ marginTop: '0.5em', padding: '0 1.5em' }}> <li>Throttling applies to all replication traffic, not just to active reassignments.</li> <li>Once the reassignment completes you'll have to remove the throttling configuration. <br /> Kowl will show a warning below the "Current Reassignments" table when there are throttled topics that are no longer being reassigned. </li> </ul> </div> <BandwidthSlider value={throttleValue} onChange={x => this.newThrottleValue = x} /> </div> </Modal> } async applyBandwidthThrottle() { const msg = new Message("Setting throttle rate..."); try { const allBrokers = api.clusterInfo?.brokers.map(b => b.brokerId); if (!allBrokers) { message.error('Error: Cluster info not available'); return; } if (this.newThrottleValue && this.newThrottleValue > 0) { await api.setReplicationThrottleRate(allBrokers, this.newThrottleValue); } else { await api.resetReplicationThrottleRate(allBrokers); } setImmediate(() => { // need to update actual value after changing api.refreshCluster(true); }); msg.setSuccess("Setting throttle rate... done"); } catch (err) { console.error("error in applyBandwidthThrottle: " + err); msg.setError(); } this.props.onClose(); } } @observer export class ReassignmentDetailsDialog extends Component<{ state: ReassignmentState | null, onClose: () => void }> { lastState: ReassignmentState | null; @observable shouldThrottle = false; wasVisible = false; constructor(p: any) { super(p); makeObservable(this); } render() { if (this.props.state == null) return null; const state = this.props.state; if (this.lastState != state) this.lastState = state; const visible = this.props.state != null; if (this.wasVisible != visible) { // became visible or invisible // force update of topic config, so isThrottle has up to date information setImmediate(async () => { api.topicConfig.delete(state.topicName); await api.refreshTopicConfig(state.topicName, true); this.shouldThrottle = this.isThrottled(); }); } this.wasVisible = visible; const topicConfig = api.topicConfig.get(state.topicName); if (!topicConfig) setImmediate(() => { api.refreshTopicConfig(state.topicName); }); const replicas = state.partitions.flatMap(p => p.replicas).distinct(); const addingReplicas = state.partitions.flatMap(p => p.addingReplicas).distinct(); const removingReplicas = state.partitions.flatMap(p => p.removingReplicas).distinct(); const modalContent = Boolean(topicConfig) ? ( <div style={{ display: 'flex', flexDirection: 'column', gap: '3em', }}> {/* Info */} <div style={{ display: 'flex', flexDirection: 'column', gap: '1em', }}> <div> {QuickTable([ ["Replicas", replicas], ["Adding", addingReplicas], ["Removing", removingReplicas], ])} </div> </div> {/* Throttle */} <div style={{ display: 'flex', gap: '1em' }}> <Checkbox checked={this.shouldThrottle} onChange={e => this.shouldThrottle = e.target.checked}> <span> <span>Throttle Reassignment</span><br /> <span style={{ fontSize: 'smaller', opacity: '0.6', marginLeft: '2em' }}>Using global throttle limit for all replication traffic</span> </span> </Checkbox> </div> {/* Cancel */} <Popconfirm title="Are you sure you want to stop the reassignment?" okText="Yes" cancelText="No" onConfirm={() => this.cancelReassignment()} > <Button type='dashed' danger>Cancel Reassignment</Button> </Popconfirm> </div> ) : <Skeleton loading={true} active={true} paragraph={{ rows: 5 }} />; return <Modal title={"Reassignment: " + state.topicName} visible={visible} okText="Apply &amp; Close" onOk={() => { this.applyBandwidthThrottle(); this.props.onClose(); }} cancelText="Close" onCancel={this.props.onClose} maskClosable={true} > {modalContent} </Modal> } isThrottled(): boolean { // Reassignment is throttled when the topic contains any partition/broker pair that is currently being reassigned if (!this.lastState) { return false; } const config = api.topicConfig.get(this.lastState.topicName); if (!config) { return false; } // partitionId:brokerId, ... const leaderThrottleValue = config.configEntries.first(e => e.name == 'leader.replication.throttled.replicas'); const leaderThrottleEntries = leaderThrottleValue?.value?.split(',').map(e => { const ar = e.split(':'); if (ar.length != 2) return null; return { partitionId: Number(ar[0]), brokerId: Number(ar[1]) }; }).filterNull(); if (leaderThrottleEntries) { // Go through all partitions that are being reassigned for (const p of this.lastState.partitions) { const sourceBrokers = p.replicas; // ...and check if this broker-partition combo is being throttled const hasThrottle = leaderThrottleEntries.any(e => e.partitionId == p.partitionId && sourceBrokers.includes(e.brokerId) ); if (hasThrottle) return true; } } // partitionId:brokerId, ... const followerThrottleValue = config.configEntries.first(e => e.name == 'follower.replication.throttled.replicas'); const followerThrottleEntries = followerThrottleValue?.value?.split(',').map(e => { const ar = e.split(':'); if (ar.length != 2) return null; return { partitionId: Number(ar[0]), brokerId: Number(ar[1]) }; }).filterNull(); if (followerThrottleEntries) { // Go through all partitions that are being reassigned for (const p of this.lastState.partitions) { const targetBrokers = p.addingReplicas; // ...and check if this broker-partition combo is being throttled const hasThrottle = followerThrottleEntries.any(e => e.partitionId == p.partitionId && targetBrokers.includes(e.brokerId) ); if (hasThrottle) return true; } } return false; } applyBandwidthThrottle() { const state = this.props.state; if (state == null) { console.error("apply bandwidth throttle: this.props.state is null"); return; } if (this.shouldThrottle) { const leaderReplicas: { partitionId: number, brokerId: number }[] = []; const followerReplicas: { partitionId: number, brokerId: number }[] = []; for (const p of state.partitions) { const partitionId = p.partitionId; const brokersOld = p.replicas; const brokersNew = p.addingReplicas; if (brokersOld == null || brokersNew == null) { console.warn("active reassignments, traffic limit: skipping partition because old or new brokers can't be found", { state: state }); continue; } // leader throttling is applied to all sources (all brokers that have a replica of this partition) for (const sourceBroker of brokersOld) leaderReplicas.push({ partitionId: partitionId, brokerId: sourceBroker }); // follower throttling is applied only to target brokers that do not yet have a copy const newBrokers = brokersNew.except(brokersOld); for (const targetBroker of newBrokers) followerReplicas.push({ partitionId: partitionId, brokerId: targetBroker }); } api.setThrottledReplicas([{ topicName: state.topicName, leaderReplicas: leaderReplicas, followerReplicas: followerReplicas, }]); } else { api.resetThrottledReplicas([state.topicName]); } } async cancelReassignment() { const state = this.props.state; if (state == null) { console.error("cancel reassignment: this.props.state is null"); return; } const partitions = state.partitions.map(p => p.partitionId); const msg = new Message(`Cancelling reassignment of '${state.topicName}'...`); try { const cancelRequest = { topics: [ { topicName: state.topicName, partitions: partitions.map(p => ({ partitionId: p, replicas: null, // cancel })), } ] }; const response = await api.startPartitionReassignment(cancelRequest); console.log('cancel reassignment result', { request: cancelRequest, response: response }); msg.setSuccess(); this.props.onClose(); } catch (err) { console.error("cancel reassignment: " + String(err)); msg.setError(); } } } @observer export class TopicNameCol extends Component<{ state: ReassignmentState }> { render() { const { state } = this.props; return <span style={{ paddingRight: '2em' }}>{state.topicName}</span>; // return <><span className='partitionReassignmentSpinner' style={{ marginRight: '6px' }} />{state.topicName}</>; } } @observer export class ProgressCol extends Component<{ state: ReassignmentState }> { render() { const { state } = this.props; if (state.remaining == null) return "..."; const transferred = state.totalTransferSize - state.remaining.value; let progressBar: JSX.Element; if (state.progressPercent === null) { // Starting progressBar = <ProgressBar percent={0} state='active' left='Starting...' right={prettyBytesOrNA(state.totalTransferSize)} /> } else if (state.progressPercent < 100) { // Progressing progressBar = <ProgressBar percent={state.progressPercent} state='active' left={<span>{state.progressPercent.toFixed(1) + '%'}</span>} right={<> {state.estimateSpeed != null && <span style={{ paddingRight: '1em', opacity: '0.6' }}>({prettyBytesOrNA(state.estimateSpeed)}/s)</span> } <span> {prettyBytesOrNA(transferred)} / {prettyBytesOrNA(state.totalTransferSize)} </span> </>} /> } else { // Completed progressBar = <ProgressBar percent={100} state='success' left='Complete' right={prettyBytesOrNA(state.totalTransferSize)} /> } return <div style={{ marginBottom: '-6px' }}> {progressBar} </div> } } @observer export class ETACol extends Component<{ state: ReassignmentState }> { render() { const { state } = this.props; if (state.estimateSpeed == null || state.estimateCompletionTime == null) return "..."; const remainingMs = (state.estimateCompletionTime.getTime() - new Date().getTime()).clamp(0, undefined); return <span > {prettyMilliseconds(remainingMs, { secondsDecimalDigits: 0, unitCount: 2 })} </span> } } @observer export class BrokersCol extends Component<{ state: ReassignmentState }> { render() { const { state } = this.props; const allBrokerIds = state.partitions.map(p => [p.addingReplicas, p.removingReplicas, p.replicas]).flat(2).distinct(); return <BrokerList brokerIds={allBrokerIds} /> } } const ProgressBar = function (p: { percent: number, state: 'active' | 'success', left?: React.ReactNode, right?: React.ReactNode }) { const { percent, state, left, right } = p; return <> <Progress percent={percent} status={state} size='small' showInfo={false} style={{ lineHeight: 0.1, display: 'block' }} /> <div style={{ display: 'flex', marginTop: '1px', fontFamily: '"Open Sans", sans-serif', fontWeight: 600, fontSize: '75%' }}> {left && <div>{left}</div>} {right && <div style={{ marginLeft: 'auto' }}>{right}</div>} </div> </> }
the_stack
import { WebElement } from 'selenium-webdriver'; import { Browser } from './browser'; import { Collection } from './collection'; import { Element } from './element'; import { ConditionNotMatchedError } from './errors/conditionDoesNotMatchError'; import { query } from './queries'; import { predicate } from './utils/predicates'; import { Condition, Lambda } from './wait'; export type ElementCondition = Condition<Element>; export type CollectionCondition = Condition<Collection>; export type BrowserCondition = Condition<Browser>; /** * The list of predefined conditions for all type of entities: * - condition.element.* * - condition.collection.* * - condition.browser.* * * Can be used in the following way: * ``` * await browser.all('.google-result').should(condition.collection.have.size(10)) * ``` * * Yet there are more handy aliases in be.* and have.* namespaces: * ``` * await browser.all('.google-result').should(have.size(10)) * ``` * * All conditions (Condition<T>) are just predicate-like functions on entity of corresponding type (T), * wrapped into Condition object: `new Condition(description, predicateLikeFn)` * The "predicate-like" function should: * - pass (returning void) in case when a "normal predicate" version would return true * - throw Error in case when a "normal predicate" would return false * * The following example shows how a condition can be implemented: * ```ts * export function hasText(expected: string): ElementCondition { * return new Condition(`has text: ${expected}`, async (element: Element) => { * const actual = await element.getWebElement().then(it => it.getText()); * if (!actual.includes(expected)) { * throw new Error(`actual text: ${actual}`); * } * }) * } * ``` * * Or more concise by using arrow functions: * ```ts * export const hasText = (expected: string): ElementCondition => * new Condition(`has text: ${expected}`, async (element: Element) => { * const actual = await element.getWebElement().then(it => it.getText()); * if (!actual.includes(expected)) { * throw new Error(`actual text: ${actual}`); * } * }); * ``` * * We can refactor the code above even more, if notice, * that the actual condition reflects a simple rule: * - throw error if actual value (returned from some query on element like "getting its text") * does not satisfy the predicate (like includes expected text) * If we abstract this "throw error if not predicate(actual)" into some function like throwIfNotActual, * The code will become very concise and declarative: * ```ts * export const hasText = (expected: string): ElementCondition => * new Condition(`has text: ${expected}`, * throwIfNotActual(query.text, predicate.includes(expected))); * ``` * * This is how predefined in selenidejs conditions are implemented below. * * Have fun;) */ export namespace condition { /** * Creates condition from async query * @param {(entity: E) => Promise<boolean>} predicate * @returns {Condition<E>} */ function throwIfNot<E>(predicate: (entity: E) => Promise<boolean>): Lambda<E, void> { return async (entity: E) => { if (!await predicate(entity)) { throw new ConditionNotMatchedError(); } }; } /** * Transforms an entity query compared through predicate - to Condition * Example: throwIfNotActual(query.text, predicate.equals(text)) */ function throwIfNotActual<E, A>( query: (entity: E) => Promise<A>, predicate: (actual: A) => boolean) : Lambda<E, void> { return async (entity: E) => { const actual = await query(entity); if (!predicate(actual)) { throw new Error(`actual ${query}: ${actual}`); } }; } export namespace element { export const isVisible = new Condition( 'is visible', throwIfNot(async (element: Element) => element.getWebElement().then(webelement => webelement.isDisplayed())) ); export const isHidden = Condition.not(isVisible, 'is hidden'); export const hasAttribute = (name: string) => new Condition( `has attribute '${name}'`, throwIfNotActual(query.attribute(name), predicate.isTruthy) ); export const isSelected = hasAttribute('elementIsSelected'); export const isEnabled = new Condition( 'is enabled', throwIfNot(async (element: Element) => element.getWebElement().then(webelement => webelement.isEnabled())) ); export const isDisabled = Condition.not(isEnabled, 'is disabled'); export const isPresent = new Condition( 'is present', throwIfNot(async (element: Element) => element.getWebElement().then(_ => true, _ => false) )); export const isAbsent = Condition.not(isPresent, 'is absent'); export const isFocused = new Condition( 'is focused', throwIfNot(async (element: Element) => WebElement.equals( await element.executeScript('return document.activeElement') as WebElement, await element.getWebElement() )) ); export const hasText = (expected: string | number | RegExp) => new Condition( `has text: ${expected}`, throwIfNotActual(query.text, typeof expected === 'string' ? predicate.includes(expected) : predicate.matches(expected) ) ); export const hasExactText = (expected: string | number) => new Condition(`has exact text: ${expected}`, throwIfNotActual(query.text, predicate.equals(expected))); export const hasAttributeWithValue = (name: string, value: string | number) => new Condition( `has attribute '${name}' with value '${value}'`, throwIfNotActual(query.attribute(name), predicate.equals(value)) ); export const hasAttributeWithValueContaining = (name: string, partialValue: string | number) => new Condition( `has attribute '${name}' with value '${partialValue}'`, throwIfNotActual(query.attribute(name), predicate.includes(partialValue)) ); export const hasCssClass = (cssClass: string) => new Condition( `has css class '${cssClass}'`, throwIfNotActual(query.attribute('class'), predicate.includesWord(cssClass)) ); export const hasValue = (expected: string | number) => hasAttributeWithValue('value', expected); export const hasValueContaining = (expected: string | number) => hasAttributeWithValueContaining('value', expected); // TODO do we need to have message `should have text '' but was ... and value '' but was ...` // or we can do just `should be blank` ? export const isBlank = hasExactText('').and(hasValue('')); } export namespace collection { // todo: collection vs Collection in collection.ts ? export const hasSize = (expected: number): CollectionCondition => new Condition( `has size ${expected}`, throwIfNotActual(query.size, predicate.equals(expected)) ); export const hasSizeGreaterThan = (size: number): CollectionCondition => new Condition( `has size more than ${size}`, throwIfNotActual(query.size, predicate.isGreaterThan(size)) ); export const hasSizeGreaterThanOrEqual = (size: number): CollectionCondition => new Condition( `has size more than ${size}`, throwIfNotActual(query.size, predicate.isGreaterThanOrEqual(size)) ); export const hasSizeLessThan = (size: number): CollectionCondition => new Condition( `has size less than ${size}`, throwIfNotActual(query.size, predicate.isLessThan(size)) ); export const hasSizeLessThanOrEqual = (size: number): CollectionCondition => new Condition( `has size less than ${size}`, throwIfNotActual(query.size, predicate.isLessThanOrEqual(size)) ); // todo: should we filter collection for visibility before applying this condition? // update: for invisible element `getText` will return error or empty string, and // it can be confused with message like `but was 'foo', '', 'bar'` when he see on // screen only 'foo', 'bar' export const hasTexts = (texts: string[] | number[]): CollectionCondition => new Condition( `has texts ${texts}`, throwIfNotActual(query.texts, predicate.equalsByContainsToArray(texts)) ); export const hasExactTexts = (texts: string[] | number[]): CollectionCondition => new Condition( `has exact texts ${texts}`, throwIfNotActual(query.texts, predicate.equalsByContainsToArray(texts)) ); } export namespace browser { // todo: do we need string | number export const hasUrlContaining = (partialUrl: string): BrowserCondition => new Condition( `has url containing ${partialUrl}`, throwIfNotActual(query.url, predicate.includes(partialUrl)) ); export const hasUrl = (url: string): BrowserCondition => new Condition( `has url ${url}`, throwIfNotActual(query.url, predicate.equals(url)) ); export const hasTitle = (title: string): BrowserCondition => new Condition( `has title ${title}`, throwIfNotActual(query.title, predicate.equals(title)) ); export const hasTitleContaining = (partialTitle: string): BrowserCondition => new Condition( `has title containing ${partialTitle}`, throwIfNotActual(query.title, predicate.includes(partialTitle)) ); export const hasTabsNumber = (num: number): BrowserCondition => new Condition( `has tabs number ${num}`, throwIfNotActual(query.tabsNumber, predicate.equals(num)) ); export const hasTabsNumberMoreThan = (num: number): BrowserCondition => new Condition( `has tabs number more than ${num}`, throwIfNotActual(query.tabsNumber, predicate.isGreaterThan(num)) ); export const hasTabsNumberLessThan = (num: number): BrowserCondition => new Condition( `has tabs number less than ${num}`, throwIfNotActual(query.tabsNumber, predicate.isLessThan(num)) ); export const hasJsReturned = (expected: any, script: string | ((document: Document) => any), ...args: any[]): BrowserCondition => new Condition( `has execute script returned ${JSON.stringify(expected)}`, async (browser: Browser) => { const actual = await browser.executeScript(script, ...args); if (typeof expected === 'number' || typeof expected === 'string') { if (expected !== actual) { throw new Error(`actual: ${actual}`); } } else { if (predicate.equals(expected)(actual)) { throw new Error(`actual: ${JSON.stringify(actual)}`); } } } ); } }
the_stack
import { module, test } from 'qunit'; import { click, visit, currentURL, waitFor } from '@ember/test-helpers'; import { setupApplicationTest } from 'ember-qunit'; import { setupMirage } from 'ember-cli-mirage/test-support'; import { MirageTestContext } from 'ember-cli-mirage/test-support'; import Layer2TestWeb3Strategy from '@cardstack/web-client/utils/web3-strategies/test-layer2'; import WorkflowPersistence from '@cardstack/web-client/services/workflow-persistence'; import { buildState } from '@cardstack/web-client/models/workflow/workflow-session'; import { setupHubAuthenticationToken } from '../helpers/setup'; import { createDepotSafe, createMerchantSafe, createPrepaidCardSafe, createSafeToken, } from '@cardstack/web-client/utils/test-factories'; import { MILESTONE_TITLES, WORKFLOW_VERSION, } from '@cardstack/web-client/components/card-pay/create-merchant-workflow'; interface Context extends MirageTestContext {} module('Acceptance | create merchant persistence', function (hooks) { setupApplicationTest(hooks); setupMirage(hooks); setupHubAuthenticationToken(hooks); let workflowPersistenceService: WorkflowPersistence; let layer2AccountAddress = '0x182619c6Ea074C053eF3f1e1eF81Ec8De6Eb6E44'; const prepaidCardAddress = '0x81c89274Dc7C9BAcE082d2ca00697d2d2857D2eE'; const merchantName = 'Mandello'; const merchantId = 'mandello1'; const merchantBgColor = '#FF5050'; const merchantDID = 'did:cardstack:1pfsUmRoNRYTersTVPYgkhWE62b2cd7ce12b5fff'; const merchantAddress = '0xaeFbA62A2B3e90FD131209CC94480E722704E1F8'; const merchantRegistrationFee = 150; const merchantSafe = createMerchantSafe({ address: merchantAddress, merchant: merchantName, infoDID: merchantDID, owners: [layer2AccountAddress], }); hooks.beforeEach(async function () { let layer2Service = this.owner.lookup('service:layer2-network') .strategy as Layer2TestWeb3Strategy; let depotAddress = '0xB236ca8DbAB0644ffCD32518eBF4924ba8666666'; layer2Service.test__simulateRemoteAccountSafes(layer2AccountAddress, [ createDepotSafe({ address: depotAddress, owners: [layer2AccountAddress], tokens: [ createSafeToken('DAI.CPXD', '250000000000000000000'), createSafeToken('CARD.CPXD', '250000000000000000000'), ], }), createPrepaidCardSafe({ address: prepaidCardAddress, owners: [layer2AccountAddress], spendFaceValue: 2324, prepaidCardOwner: layer2AccountAddress, issuer: layer2AccountAddress, }), ]); await layer2Service.test__simulateAccountsChanged([layer2AccountAddress]); layer2Service.authenticate(); layer2Service.test__simulateHubAuthentication('abc123--def456--ghi789'); workflowPersistenceService = this.owner.lookup( 'service:workflow-persistence' ); workflowPersistenceService.clear(); }); test('Generates a flow uuid query parameter used as a persistence identifier and can be dismissed via the header button', async function (this: Context, assert) { await visit('/card-pay/payments'); await click('[data-test-workflow-button="create-business"]'); assert.equal( // @ts-ignore (complains object is possibly null) new URL('http://domain.test/' + currentURL()).searchParams.get('flow-id') .length, 22 ); await click('[data-test-return-to-dashboard]'); assert.dom('[data-test-workflow-thread]').doesNotExist(); }); module('Restoring from a previously saved state', function () { test('it restores an unfinished workflow', async function (this: Context, assert) { let state = buildState({ meta: { version: WORKFLOW_VERSION, completedCardNames: ['LAYER2_CONNECT', 'MERCHANT_CUSTOMIZATION'], }, merchantName, merchantId, merchantBgColor, merchantRegistrationFee, prepaidCardAddress, }); workflowPersistenceService.persistData('abc123', { name: 'MERCHANT_CREATION', state, }); await visit('/card-pay/payments?flow=create-business&flow-id=abc123'); assert.dom('[data-test-milestone="0"]').exists(); // L2 assert.dom('[data-test-milestone="1"]').exists(); // Merchant info assert .dom('[data-test-prepaid-card-choice-merchant-id]') .containsText(merchantId); assert .dom( `[data-test-prepaid-card-choice-selected-card] [data-test-prepaid-card="${prepaidCardAddress}"]` ) .exists(); assert.dom('[data-test-card-picker-dropdown]').exists(); assert.dom('[data-test-create-merchant-button]').isNotDisabled(); }); test('it restores a finished workflow', async function (this: Context, assert) { const state = buildState({ meta: { version: WORKFLOW_VERSION, completedCardNames: [ 'LAYER2_CONNECT', 'MERCHANT_CUSTOMIZATION', 'PREPAID_CARD_CHOICE', ], }, merchantName, merchantId, merchantBgColor, merchantInfo: { did: merchantDID, }, merchantRegistrationFee, prepaidCardAddress, txnHash: '0x8bcc3e419d09a0403d1491b5bb8ac8bee7c67f85cc37e6e17ef8eb77f946497b', merchantSafe, }); workflowPersistenceService.persistData('abc123', { name: 'MERCHANT_CREATION', state, }); await visit('/card-pay/payments?flow=create-business&flow-id=abc123'); assert.dom('[data-test-milestone="0"]').exists(); // L2 assert.dom('[data-test-milestone="1"]').exists(); // Merchant info assert .dom('[data-test-milestone-completed][data-test-milestone="2"]') .exists(); // Prepaid card choice assert .dom('[data-test-prepaid-card-choice-merchant-address]') .containsText(merchantAddress); assert .dom( '[data-test-prepaid-card-choice-is-complete] [data-test-boxel-button]' ) .hasText('View on Blockscout'); assert .dom('[data-test-epilogue][data-test-postable="0"]') .includesText('Congratulations! You have created a business account.'); await click('[data-test-create-merchant-next-step="dashboard"]'); assert.dom('[data-test-workflow-thread]').doesNotExist(); }); test('it restores a canceled workflow', async function (this: Context, assert) { const state = buildState({ meta: { version: WORKFLOW_VERSION, completedCardNames: ['LAYER2_CONNECT', 'MERCHANT_CUSTOMIZATION'], milestonesCount: 3, completedMilestonesCount: 2, isCanceled: true, cancelationReason: 'DISCONNECTED', }, merchantName, merchantId, merchantBgColor, merchantRegistrationFee, prepaidCardAddress, }); workflowPersistenceService.persistData('abc123', { name: 'MERCHANT_CREATION', state, }); await visit('/card-pay/payments?flow=create-business&flow-id=abc123'); assert.dom('[data-test-milestone="0"]').exists(); // L2 assert.dom('[data-test-milestone="1"]').exists(); // Merchant info assert .dom('[data-test-cancelation]') .includesText( 'It looks like your L2 test chain wallet got disconnected. If you still want to create a business account, please start again by connecting your wallet.' ); await waitFor( '[data-test-workflow-default-cancelation-restart="create-business"]' ); assert .dom( '[data-test-workflow-default-cancelation-restart="create-business"]' ) .exists(); }); test('it cancels a persisted flow when trying to restore while unauthenticated', async function (this: Context, assert) { const state = buildState({ meta: { version: WORKFLOW_VERSION, completedCardNames: ['LAYER2_CONNECT', 'MERCHANT_CUSTOMIZATION'], }, merchantName, merchantId, merchantBgColor, merchantRegistrationFee, }); workflowPersistenceService.persistData('abc123', { name: 'MERCHANT_CREATION', state, }); window.TEST__AUTH_TOKEN = undefined; await visit('/card-pay/payments?flow=create-business&flow-id=abc123'); assert.dom('[data-test-milestone="0"]').doesNotExist(); // L2 assert.dom('[data-test-milestone="1"]').doesNotExist(); // Merchant info assert .dom('[data-test-cancelation]') .includesText( 'You attempted to restore an unfinished workflow, but you are no longer authenticated. Please restart the workflow.' ); await click('[data-test-workflow-default-cancelation-restart]'); // Starts over assert.dom('[data-test-milestone="0"]').exists(); // L2 assert.dom('[data-test-milestone="1"]').exists(); // Merchant info assert.dom('[data-test-milestone="2"]').doesNotExist(); // Prepaid card choice const workflowPersistenceId = new URL( 'http://domain.test/' + currentURL() ).searchParams.get('flow-id'); assert.notEqual(workflowPersistenceId!, 'abc123'); // flow-id param should be regenerated assert.equal(workflowPersistenceId!.length, 22); }); test('it should reset the persisted card names when editing one of the previous steps', async function (this: Context, assert) { const state = buildState({ meta: { version: WORKFLOW_VERSION, completedCardNames: ['LAYER2_CONNECT', 'MERCHANT_CUSTOMIZATION'], }, merchantName, merchantId, merchantBgColor, merchantRegistrationFee, prepaidCardAddress, txnHash: '0x8bcc3e419d09a0403d1491b5bb8ac8bee7c67f85cc37e6e17ef8eb77f946497b', merchantSafe, }); workflowPersistenceService.persistData('abc123', { name: 'MERCHANT_CREATION', state, }); await visit('/card-pay/payments?flow=create-business&flow-id=abc123'); assert.dom('[data-test-milestone="0"]').exists(); // L2 assert.dom('[data-test-milestone="1"]').exists(); // Merchant info assert.dom('[data-test-milestone="2"]').exists(); // Prepaid card choice await waitFor('[data-test-milestone="1"] [data-test-boxel-button]'); await click('[data-test-milestone="1"] [data-test-boxel-button]'); await visit('/card-pay/payments?flow=create-business&flow-id=abc123'); assert.dom('[data-test-milestone="0"]').exists(); // L2 assert.dom('[data-test-milestone="1"]').exists(); // Merchant info assert.dom('[data-test-milestone="2"]').doesNotExist(); // Prepaid card choice }); test('it cancels a persisted flow when card wallet address is different', async function (this: Context, assert) { const state = buildState({ meta: { version: WORKFLOW_VERSION, completedCardNames: ['LAYER2_CONNECT', 'MERCHANT_CUSTOMIZATION'], }, merchantName, merchantId, merchantBgColor, merchantRegistrationFee, layer2WalletAddress: '0xaaaaaaaaaaaaaaa', // Differs from layer2AccountAddress set in beforeEach }); workflowPersistenceService.persistData('abc123', { name: 'MERCHANT_CREATION', state, }); await visit('/card-pay/payments?flow=create-business&flow-id=abc123'); assert.dom('[data-test-milestone="0"]').doesNotExist(); // L2 assert.dom('[data-test-milestone="1"]').doesNotExist(); // Merchant info assert.dom('[data-test-milestone="2"]').doesNotExist(); // Prepaid card choice assert .dom('[data-test-cancelation]') .includesText( 'You attempted to restore an unfinished workflow, but you changed your Card Wallet address. Please restart the workflow.' ); }); test('it allows interactivity after restoring previously saved state', async function (this: Context, assert) { const state = buildState({ meta: { version: WORKFLOW_VERSION, completedCardNames: ['LAYER2_CONNECT'], }, merchantName, merchantId, merchantBgColor, merchantRegistrationFee, }); workflowPersistenceService.persistData('abc123', { name: 'MERCHANT_CREATION', state, }); await visit('/card-pay/payments?flow=create-business&flow-id=abc123'); assert.dom('[data-test-milestone="0"]').exists(); // L2 assert.dom('[data-test-milestone="1"]').exists(); // Merchant info assert.dom('[data-test-milestone="2"]').doesNotExist(); await waitFor(`[data-test-merchant="${merchantName}"]`); await click('[data-test-merchant-customization-save-details]'); assert .dom('[data-test-milestone="2"] [data-test-boxel-card-container]') .exists(); }); test('it cancels a persisted flow when version is old', async function (this: Context, assert) { const state = buildState({ meta: { version: WORKFLOW_VERSION - 1, completedMilestonesCount: 2, milestonesCount: MILESTONE_TITLES.length, completedCardNames: ['LAYER2_CONNECT', 'MERCHANT_CUSTOMIZATION'], }, merchantName, merchantId, merchantBgColor, merchantRegistrationFee, prepaidCardAddress, }); workflowPersistenceService.persistData('abc123', { name: 'MERCHANT_CREATION', state, }); await visit('/card-pay/payments?flow=create-business&flow-id=abc123'); assert.dom('[data-test-milestone="0"]').doesNotExist(); // L2 assert.dom('[data-test-milestone="1"]').doesNotExist(); // Merchant info assert.dom('[data-test-milestone="2"]').doesNotExist(); // Prepaid card choice assert .dom('[data-test-cancelation]') .includesText( 'You attempted to restore an unfinished workflow, but the workflow has been upgraded by the Cardstack development team since then, so you will need to start again. Sorry about that!' ); }); }); });
the_stack
import { triggerEvent, domData } from '@tko/utils' import { computed } from '@tko/computed' import { observable, observableArray } from '@tko/observable' import { applyBindings } from '@tko/bind' import { DataBindProvider } from '@tko/provider.databind' import { options } from '@tko/utils' import {bindings as coreBindings} from '../dist' import '@tko/utils/helpers/jasmine-13-helper' describe('Binding: Value', function () { beforeEach(jasmine.prepareTestNode) beforeEach(function () { var provider = new DataBindProvider() options.bindingProviderInstance = provider provider.bindingHandlers.set(coreBindings) }) it('Should assign the value to the node', function () { testNode.innerHTML = "<input data-bind='value:123' />" applyBindings(null, testNode) expect(testNode.childNodes[0].value).toEqual('123') }) it('Should treat null values as empty strings', function () { testNode.innerHTML = "<input data-bind='value:myProp' />" applyBindings({ myProp: observable(0) }, testNode) expect(testNode.childNodes[0].value).toEqual('0') }) it('Should assign an empty string as value if the model value is null', function () { testNode.innerHTML = "<input data-bind='value:(null)' />" applyBindings(null, testNode) expect(testNode.childNodes[0].value).toEqual('') }) it('Should assign an empty string as value if the model value is undefined', function () { testNode.innerHTML = "<input data-bind='value:undefined' />" applyBindings(null, testNode) expect(testNode.childNodes[0].value).toEqual('') }) it('For observable values, should unwrap the value and update on change', function () { var myObservable = observable(123) testNode.innerHTML = "<input data-bind='value:someProp' />" applyBindings({ someProp: myObservable }, testNode) expect(testNode.childNodes[0].value).toEqual('123') myObservable(456) expect(testNode.childNodes[0].value).toEqual('456') }) it('For observable values, should update on change if new value is \'strictly\' different from previous value', function () { var myObservable = observable('+123') testNode.innerHTML = "<input data-bind='value:someProp' />" applyBindings({ someProp: myObservable }, testNode) expect(testNode.childNodes[0].value).toEqual('+123') myObservable(123) expect(testNode.childNodes[0].value).toEqual('123') }) it('For writeable observable values, should catch the node\'s onchange and write values back to the observable', function () { var myObservable = observable(123) testNode.innerHTML = "<input data-bind='value:someProp' />" applyBindings({ someProp: myObservable }, testNode) testNode.childNodes[0].value = 'some user-entered value' triggerEvent(testNode.childNodes[0], 'change') expect(myObservable()).toEqual('some user-entered value') }) it('For writeable observable values, should always write when triggered, even when value is the same', function () { var validValue = observable(123) var isValid = observable(true) var valueForEditing = computed({ read: validValue, write: function (newValue) { if (!isNaN(newValue)) { isValid(true) validValue(newValue) } else { isValid(false) } } }) testNode.innerHTML = "<input data-bind='value: valueForEditing' />" applyBindings({ valueForEditing: valueForEditing}, testNode) // set initial valid value testNode.childNodes[0].value = '1234' triggerEvent(testNode.childNodes[0], 'change') expect(validValue()).toEqual('1234') expect(isValid()).toEqual(true) // set to an invalid value testNode.childNodes[0].value = '1234a' triggerEvent(testNode.childNodes[0], 'change') expect(validValue()).toEqual('1234') expect(isValid()).toEqual(false) // set to a valid value where the current value of the writeable computed is the same as the written value testNode.childNodes[0].value = '1234' triggerEvent(testNode.childNodes[0], 'change') expect(validValue()).toEqual('1234') expect(isValid()).toEqual(true) }) it('Should ignore node changes when bound to a read-only observable', function () { var computedValue = computed(function () { return 'zzz' }) var vm = { prop: computedValue } testNode.innerHTML = "<input data-bind='value: prop' />" applyBindings(vm, testNode) expect(testNode.childNodes[0].value).toEqual('zzz') // Change the input value and trigger change event; verify that the view model wasn't changed testNode.childNodes[0].value = 'yyy' triggerEvent(testNode.childNodes[0], 'change') expect(vm.prop).toEqual(computedValue) expect(computedValue()).toEqual('zzz') }) it('For non-observable property values, should catch the node\'s onchange and write values back to the property', function () { var model = { modelProperty123: 456 } testNode.innerHTML = "<input data-bind='value: modelProperty123' />" applyBindings(model, testNode) expect(testNode.childNodes[0].value).toEqual('456') testNode.childNodes[0].value = 789 triggerEvent(testNode.childNodes[0], 'change') expect(model.modelProperty123).toEqual('789') }) it('Should be able to read and write to a property of an object returned by a function', function () { var mySetter = { set: 666 } var model = { getSetter: function () { return mySetter } } testNode.innerHTML = "<input data-bind='value: getSetter().set' />" + "<input data-bind='value: getSetter()[\"set\"]' />" + "<input data-bind=\"value: getSetter()['set']\" />" applyBindings(model, testNode) expect(testNode.childNodes[0].value).toEqual('666') expect(testNode.childNodes[1].value).toEqual('666') expect(testNode.childNodes[2].value).toEqual('666') // .property testNode.childNodes[0].value = 667 triggerEvent(testNode.childNodes[0], 'change') expect(mySetter.set).toEqual('667') // ["property"] testNode.childNodes[1].value = 668 triggerEvent(testNode.childNodes[1], 'change') expect(mySetter.set).toEqual('668') // ['property'] testNode.childNodes[0].value = 669 triggerEvent(testNode.childNodes[0], 'change') expect(mySetter.set).toEqual('669') }) it('Should be able to write to observable subproperties of an observable, even after the parent observable has changed', function () { // This spec represents https://github.com/SteveSanderson/knockout/issues#issue/13 var originalSubproperty = observable('original value') var newSubproperty = observable() var model = { myprop: observable({ subproperty: originalSubproperty }) } // Set up a text box whose value is linked to the subproperty of the observable's current value testNode.innerHTML = "<input data-bind='value: myprop().subproperty' />" applyBindings(model, testNode) expect(testNode.childNodes[0].value).toEqual('original value') model.myprop({ subproperty: newSubproperty }) // Note that myprop (and hence its subproperty) is changed *after* the bindings are applied testNode.childNodes[0].value = 'Some new value' triggerEvent(testNode.childNodes[0], 'change') // Verify that the change was written to the *new* subproperty, not the one referenced when the bindings were first established expect(newSubproperty()).toEqual('Some new value') expect(originalSubproperty()).toEqual('original value') }) it('Should only register one single onchange handler', function () { var notifiedValues = [] var myObservable = observable(123) myObservable.subscribe(function (value) { notifiedValues.push(value) }) expect(notifiedValues.length).toEqual(0) testNode.innerHTML = "<input data-bind='value:someProp' />" applyBindings({ someProp: myObservable }, testNode) // Implicitly observe the number of handlers by seeing how many times "myObservable" // receives a new value for each onchange on the text box. If there's just one handler, // we'll see one new value per onchange event. More handlers cause more notifications. testNode.childNodes[0].value = 'ABC' triggerEvent(testNode.childNodes[0], 'change') expect(notifiedValues.length).toEqual(1) testNode.childNodes[0].value = 'DEF' triggerEvent(testNode.childNodes[0], 'change') expect(notifiedValues.length).toEqual(2) }) it('Should be able to catch updates after specific events (e.g., keyup) instead of onchange', function () { var myObservable = observable(123) testNode.innerHTML = "<input data-bind='value:someProp, valueUpdate: \"keyup\"' />" applyBindings({ someProp: myObservable }, testNode) testNode.childNodes[0].value = 'some user-entered value' triggerEvent(testNode.childNodes[0], 'keyup') expect(myObservable()).toEqual('some user-entered value') }) it('Should catch updates on change as well as the nominated valueUpdate event', function () { // Represents issue #102 (https://github.com/SteveSanderson/knockout/issues/102) var myObservable = observable(123) testNode.innerHTML = "<input data-bind='value:someProp, valueUpdate: \"keyup\"' />" applyBindings({ someProp: myObservable }, testNode) testNode.childNodes[0].value = 'some user-entered value' triggerEvent(testNode.childNodes[0], 'change') expect(myObservable()).toEqual('some user-entered value') }) it('Should delay reading value and updating observable when prefixing an event with "after"', function () { jasmine.Clock.useMock() var myObservable = observable('123') testNode.innerHTML = "<input data-bind='value:someProp, valueUpdate: \"afterkeyup\"' />" applyBindings({ someProp: myObservable }, testNode) triggerEvent(testNode.childNodes[0], 'keyup') testNode.childNodes[0].value = 'some user-entered value' expect(myObservable()).toEqual('123') // observable is not changed yet jasmine.Clock.tick(20) expect(myObservable()).toEqual('some user-entered value') // it's changed after a delay }) it('Should ignore "unchanged" notifications from observable during delayed event processing', function () { jasmine.Clock.useMock() var myObservable = observable('123') testNode.innerHTML = "<input data-bind='value:someProp, valueUpdate: \"afterkeyup\"' />" applyBindings({ someProp: myObservable }, testNode) triggerEvent(testNode.childNodes[0], 'keyup') testNode.childNodes[0].value = 'some user-entered value' // Notification of previous value (unchanged) is ignored myObservable.valueHasMutated() expect(testNode.childNodes[0].value).toEqual('some user-entered value') // Observable is updated to new element value jasmine.Clock.tick(20) expect(myObservable()).toEqual('some user-entered value') }) it('Should not ignore actual change notifications from observable during delayed event processing', function () { jasmine.Clock.useMock() var myObservable = observable('123') testNode.innerHTML = "<input data-bind='value:someProp, valueUpdate: \"afterkeyup\"' />" applyBindings({ someProp: myObservable }, testNode) triggerEvent(testNode.childNodes[0], 'keyup') testNode.childNodes[0].value = 'some user-entered value' // New value is written to input element myObservable('some value from the server') expect(testNode.childNodes[0].value).toEqual('some value from the server') // New value remains when event is processed jasmine.Clock.tick(20) expect(myObservable()).toEqual('some value from the server') }) it('On IE < 10, should handle autofill selection by treating "propertychange" followed by "blur" as a change event', function () { // This spec describes the awkward choreography of events needed to detect changes to text boxes on IE < 10, // because it doesn't fire regular "change" events when the user selects an autofill entry. It isn't applicable // on IE 10+ or other browsers, because they don't have that problem with autofill. var isOldIE = jasmine.ieVersion && jasmine.ieVersion < 10 if (isOldIE) { var myObservable = observable(123).extend({ notify: 'always' }) var numUpdates = 0 myObservable.subscribe(function () { numUpdates++ }) testNode.innerHTML = "<input data-bind='value:someProp' />" applyBindings({ someProp: myObservable }, testNode) // Simulate a blur occurring before the first real property change. // See that no 'update' event fires. triggerEvent(testNode.childNodes[0], 'focus') triggerEvent(testNode.childNodes[0], 'blur') expect(numUpdates).toEqual(0) // Simulate: // 1. Select from autofill // 2. Modify the textbox further // 3. Tab out of the textbox // --- should be treated as a single change testNode.childNodes[0].value = 'some user-entered value' triggerEvent(testNode.childNodes[0], 'propertychange') triggerEvent(testNode.childNodes[0], 'change') expect(myObservable()).toEqual('some user-entered value') expect(numUpdates).toEqual(1) triggerEvent(testNode.childNodes[0], 'blur') expect(numUpdates).toEqual(1) // Simulate: // 1. Select from autofill // 2. Tab out of the textbox // 3. Reselect, edit, then tab out of the textbox // --- should be treated as two changes (one after step 2, one after step 3) testNode.childNodes[0].value = 'different user-entered value' triggerEvent(testNode.childNodes[0], 'propertychange') triggerEvent(testNode.childNodes[0], 'blur') expect(myObservable()).toEqual('different user-entered value') expect(numUpdates).toEqual(2) triggerEvent(testNode.childNodes[0], 'change') expect(numUpdates).toEqual(3) } }) it('Should bind to file inputs but not allow setting an non-empty value', function () { var prop = observable('zzz') var vm = { prop } testNode.innerHTML = "<input type='file' data-bind='value: prop' />" applyBindings(vm, testNode) expect(testNode.childNodes[0].value).toEqual('') }) describe('For select boxes', function () { it('Should update selectedIndex when the model changes (options specified before value)', function () { var myObservable = observable('B') testNode.innerHTML = "<select data-bind='options:[\"A\", \"B\"], value:myObservable'></select>" applyBindings({ myObservable: myObservable }, testNode) expect(testNode.childNodes[0].selectedIndex).toEqual(1) expect(myObservable()).toEqual('B') myObservable('A') expect(testNode.childNodes[0].selectedIndex).toEqual(0) expect(myObservable()).toEqual('A') }) it('Should update selectedIndex when the model changes (value specified before options)', function () { var myObservable = observable('B') testNode.innerHTML = "<select data-bind='value:myObservable, options:[\"A\", \"B\"]'></select>" applyBindings({ myObservable: myObservable }, testNode) expect(testNode.childNodes[0].selectedIndex).toEqual(1) expect(myObservable()).toEqual('B') myObservable('A') expect(testNode.childNodes[0].selectedIndex).toEqual(0) expect(myObservable()).toEqual('A') // Also check that the selection doesn't change later (see https://github.com/knockout/knockout/issues/2218) waits(10) runs(function () { expect(testNode.childNodes[0].selectedIndex).toEqual(0) }) }) it('Should display the caption when the model value changes to undefined, null, or \"\" when using \'options\' binding', function () { var myObservable = observable('B') testNode.innerHTML = "<select data-bind='options:[\"A\", \"B\"], optionsCaption:\"Select...\", value:myObservable'></select>" applyBindings({ myObservable: myObservable }, testNode) // Caption is selected when observable changed to undefined expect(testNode.childNodes[0].selectedIndex).toEqual(2) myObservable(undefined) expect(testNode.childNodes[0].selectedIndex).toEqual(0) // Caption is selected when observable changed to null myObservable('B') expect(testNode.childNodes[0].selectedIndex).toEqual(2) myObservable(null) expect(testNode.childNodes[0].selectedIndex).toEqual(0) // Caption is selected when observable changed to "" myObservable('B') expect(testNode.childNodes[0].selectedIndex).toEqual(2) myObservable('') expect(testNode.childNodes[0].selectedIndex).toEqual(0) }) it('Should display the caption when the model value changes to undefined, null, or \"\" when options specified directly', function () { var myObservable = observable('B') testNode.innerHTML = "<select data-bind='value:myObservable'><option value=''>Select...</option><option>A</option><option>B</option></select>" applyBindings({ myObservable: myObservable }, testNode) // Caption is selected when observable changed to undefined expect(testNode.childNodes[0].selectedIndex).toEqual(2) myObservable(undefined) expect(testNode.childNodes[0].selectedIndex).toEqual(0) // Caption is selected when observable changed to null myObservable('B') expect(testNode.childNodes[0].selectedIndex).toEqual(2) myObservable(null) expect(testNode.childNodes[0].selectedIndex).toEqual(0) // Caption is selected when observable changed to "" myObservable('B') expect(testNode.childNodes[0].selectedIndex).toEqual(2) myObservable('') expect(testNode.childNodes[0].selectedIndex).toEqual(0) }) it('When size > 1, should unselect all options when value is undefined, null, or \"\"', function () { var myObservable = observable('B') testNode.innerHTML = "<select size='2' data-bind='options:[\"A\", \"B\"], value:myObservable'></select>" applyBindings({ myObservable: myObservable }, testNode) // Nothing is selected when observable changed to undefined expect(testNode.childNodes[0].selectedIndex).toEqual(1) myObservable(undefined) expect(testNode.childNodes[0].selectedIndex).toEqual(-1) // Nothing is selected when observable changed to null myObservable('B') expect(testNode.childNodes[0].selectedIndex).toEqual(1) myObservable(null) expect(testNode.childNodes[0].selectedIndex).toEqual(-1) // Nothing is selected when observable changed to "" myObservable('B') expect(testNode.childNodes[0].selectedIndex).toEqual(1) myObservable('') expect(testNode.childNodes[0].selectedIndex).toEqual(-1) }) it('Should update the model value when the UI is changed (setting it to undefined when the caption is selected)', function () { var myObservable = observable('B') testNode.innerHTML = "<select data-bind='options:[\"A\", \"B\"], optionsCaption:\"Select...\", value:myObservable'></select>" applyBindings({ myObservable: myObservable }, testNode) var dropdown = testNode.childNodes[0] dropdown.selectedIndex = 1 triggerEvent(dropdown, 'change') expect(myObservable()).toEqual('A') dropdown.selectedIndex = 0 triggerEvent(dropdown, 'change') expect(myObservable()).toEqual(undefined) }) it('Should be able to associate option values with arbitrary objects (not just strings)', function () { var x = {}, y = {} var selectedValue = observable(y) testNode.innerHTML = "<select data-bind='options: myOptions, value: selectedValue'></select>" var dropdown = testNode.childNodes[0] applyBindings({ myOptions: [x, y], selectedValue: selectedValue }, testNode) // Check the UI displays the entry corresponding to the chosen value expect(dropdown.selectedIndex).toEqual(1) // Check that when we change the model value, the UI is updated selectedValue(x) expect(dropdown.selectedIndex).toEqual(0) // Check that when we change the UI, this changes the model value dropdown.selectedIndex = 1 triggerEvent(dropdown, 'change') expect(selectedValue()).toEqual(y) }) it('Should automatically initialize the model property to match the first option value if no option value matches the current model property value', function () { // The rationale here is that we always want the model value to match the option that appears to be selected in the UI // * If there is *any* option value that equals the model value, we'd initalise the select box such that *that* option is the selected one // * If there is *no* option value that equals the model value (often because the model value is undefined), we should set the model // value to match an arbitrary option value to avoid inconsistency between the visible UI and the model var myObservable = observable() // Undefined by default // Should work with options specified before value testNode.innerHTML = "<select data-bind='options:[\"A\", \"B\"], value:myObservable'></select>" applyBindings({ myObservable: myObservable }, testNode) expect(myObservable()).toEqual('A') // ... and with value specified before options domData.clear(testNode) testNode.innerHTML = "<select data-bind='value:myObservable, options:[\"A\", \"B\"]'></select>" myObservable(undefined) expect(myObservable()).toEqual(undefined) applyBindings({ myObservable: myObservable }, testNode) expect(myObservable()).toEqual('A') }) it('When non-empty, should reject model values that don\'t match any option value, resetting the model value to whatever is visibly selected in the UI', function () { var myObservable = observable('B') testNode.innerHTML = "<select data-bind='options:[\"A\", \"B\", \"C\"], value:myObservable'></select>" applyBindings({ myObservable: myObservable }, testNode) expect(testNode.childNodes[0].selectedIndex).toEqual(1) myObservable('D') // This change should be rejected, as there's no corresponding option in the UI expect(myObservable()).toEqual('B') myObservable(null) // This change should also be rejected expect(myObservable()).toEqual('B') }) it('Should support numerical option values, which are not implicitly converted to strings', function () { var myObservable = observable(30) testNode.innerHTML = "<select data-bind='options:[10,20,30,40], value:myObservable'></select>" applyBindings({ myObservable: myObservable }, testNode) // First check that numerical model values will match a dropdown option expect(testNode.childNodes[0].selectedIndex).toEqual(2) // 3rd element, zero-indexed // Then check that dropdown options map back to numerical model values testNode.childNodes[0].selectedIndex = 1 triggerEvent(testNode.childNodes[0], 'change') expect(typeof myObservable()).toEqual('number') expect(myObservable()).toEqual(20) }) it('Should always use value (and not text) when options have value attributes', function () { var myObservable = observable('A') testNode.innerHTML = "<select data-bind='value:myObservable'><option value=''>A</option><option value='A'>B</option></select>" applyBindings({ myObservable: myObservable }, testNode) var dropdown = testNode.childNodes[0] expect(dropdown.selectedIndex).toEqual(1) dropdown.selectedIndex = 0 triggerEvent(dropdown, 'change') expect(myObservable()).toEqual('') }) it('Should use text value when options have text values but no value attribute', function () { var myObservable = observable('B') testNode.innerHTML = "<select data-bind='value:myObservable'><option>A</option><option>B</option><option>C</option></select>" applyBindings({ myObservable: myObservable }, testNode) var dropdown = testNode.childNodes[0] expect(dropdown.selectedIndex).toEqual(1) dropdown.selectedIndex = 0 triggerEvent(dropdown, 'change') expect(myObservable()).toEqual('A') myObservable('C') expect(dropdown.selectedIndex).toEqual(2) }) it('Should not throw an exception for value binding on multiple select boxes', function () { testNode.innerHTML = "<select data-bind=\"options: ['abc','def','ghi'], value: x\"></select><select data-bind=\"options: ['xyz','uvw'], value: x\"></select>" var myObservable = observable() expect(function () { applyBindings({ x: myObservable }, testNode) }).not.toThrow() expect(myObservable()).not.toBeUndefined() // The spec doesn't specify which of the two possible values is actually set }) describe('Using valueAllowUnset option', function () { it('Should display the caption when the model value changes to undefined, null, or \"\" when using \'options\' binding', function () { var myObservable = observable('B') testNode.innerHTML = "<select data-bind='options:[\"A\", \"B\"], optionsCaption:\"Select...\", value:myObservable, valueAllowUnset:true'></select>" applyBindings({ myObservable: myObservable }, testNode) var select = testNode.childNodes[0] select.selectedIndex = 2 myObservable(undefined) expect(select.selectedIndex).toEqual(0) select.selectedIndex = 2 myObservable(null) expect(select.selectedIndex).toEqual(0) select.selectedIndex = 2 myObservable('') expect(select.selectedIndex).toEqual(0) }) it('Should display the caption when the model value changes to undefined, null, or \"\" when options specified directly', function () { var myObservable = observable('B') testNode.innerHTML = "<select data-bind='value:myObservable, valueAllowUnset:true'><option value=''>Select...</option><option>A</option><option>B</option></select>" applyBindings({ myObservable: myObservable }, testNode) var select = testNode.childNodes[0] select.selectedIndex = 2 myObservable(undefined) expect(select.selectedIndex).toEqual(0) select.selectedIndex = 2 myObservable(null) expect(select.selectedIndex).toEqual(0) select.selectedIndex = 2 myObservable('') expect(select.selectedIndex).toEqual(0) }) it('Should display the caption when the model value changes to undefined after having no selection', function () { var myObservable = observable('B') testNode.innerHTML = "<select data-bind='options:[\"A\", \"B\"], optionsCaption:\"Select...\", value:myObservable, valueAllowUnset:true'></select>" applyBindings({ myObservable }, testNode) var select = testNode.childNodes[0] select.selectedIndex = -1 myObservable(undefined) expect(select.selectedIndex).toEqual(0) }) it('Should select no option value if no option value matches the current model property value', function () { var myObservable = observable() testNode.innerHTML = "<select data-bind='options:[\"A\", \"B\"], value:myObservable, valueAllowUnset:true'></select>" applyBindings({ myObservable: myObservable }, testNode) expect(testNode.childNodes[0].selectedIndex).toEqual(-1) expect(myObservable()).toEqual(undefined) }) it('Should select no option value if model value does\'t match any option value', function () { var myObservable = observable('B') testNode.innerHTML = "<select data-bind='options:[\"A\", \"B\", \"C\"], value:myObservable, valueAllowUnset:true'></select>" applyBindings({ myObservable: myObservable }, testNode) expect(testNode.childNodes[0].selectedIndex).toEqual(1) myObservable('D') expect(testNode.childNodes[0].selectedIndex).toEqual(-1) }) it('Should maintain model value and update selection when options change', function () { var myObservable = observable('D') var options = observableArray(['A', 'B']) testNode.innerHTML = "<select data-bind='options:myOptions, value:myObservable, valueAllowUnset:true'></select>" applyBindings({ myObservable: myObservable, myOptions: options }, testNode) // Initially nothing is selected because the value isn't in the options list expect(testNode.childNodes[0].selectedIndex).toEqual(-1) expect(myObservable()).toEqual('D') // Replace with new options that still don't contain the value options(['B', 'C']) expect(testNode.childNodes[0].selectedIndex).toEqual(-1) expect(myObservable()).toEqual('D') // Now update with options that do contain the value options(['C', 'D']) expect(testNode.childNodes[0].selectedIndex).toEqual(1) expect(myObservable()).toEqual('D') // Update back to options that don't contain the value options(['E', 'F']) expect(testNode.childNodes[0].selectedIndex).toEqual(-1) expect(myObservable()).toEqual('D') }) it('Should maintain model value and update selection when changing observable option text or value', function () { var selected = observable('B') var people = [ { name: observable('Annie'), id: observable('A') }, { name: observable('Bert'), id: observable('B') } ] testNode.innerHTML = "<select data-bind=\"options:people, optionsText:'name', optionsValue:'id', value:selected, valueAllowUnset:true\"></select>" applyBindings({people: people, selected: selected}, testNode) expect(testNode.childNodes[0].selectedIndex).toEqual(1) expect(testNode.childNodes[0]).toHaveTexts(['Annie', 'Bert']) expect(selected()).toEqual('B') // Changing an option name shouldn't change selection people[1].name('Charles') expect(testNode.childNodes[0].selectedIndex).toEqual(1) expect(testNode.childNodes[0]).toHaveTexts(['Annie', 'Charles']) expect(selected()).toEqual('B') // Changing the selected option value should clear selection people[1].id('C') expect(testNode.childNodes[0].selectedIndex).toEqual(-1) expect(selected()).toEqual('B') // Changing an option name while nothing is selected won't select anything people[0].name('Amelia') expect(testNode.childNodes[0].selectedIndex).toEqual(-1) expect(selected()).toEqual('B') }) it('Should select no options if model value is null and option value is 0', function () { var myObservable = observable(null) var options = [ { name: 'B', id: 1 }, { name: 'A', id: 0 } ] testNode.innerHTML = "<select data-bind='options:options, optionsValue:\"id\", optionsText:\"name\", value:myObservable, valueAllowUnset:true'></select>" applyBindings({ myObservable, options }, testNode) expect(testNode.childNodes[0].selectedIndex).toEqual(-1) expect(myObservable()).toEqual(undefined) }) }) }) describe('Acts like \'checkedValue\' on a checkbox or radio', function () { it('Should update value, but not respond to events when on a checkbox', function () { var myObservable = observable('B') testNode.innerHTML = "<input type='checkbox' data-bind='value: myObservable' />" applyBindings({ myObservable: myObservable }, testNode) var checkbox = testNode.childNodes[0] expect(checkbox.value).toEqual('B') myObservable('C') expect(checkbox.value).toEqual('C') checkbox.value = 'D' triggerEvent(checkbox, 'change') // observable does not update, as we are not handling events when on a checkbox/radio expect(myObservable()).toEqual('C') }) it('Should update value, but not respond to events when on a radio', function () { var myObservable = observable('B') testNode.innerHTML = "<input type='radio' data-bind='value: myObservable' />" applyBindings({ myObservable: myObservable }, testNode) var radio = testNode.childNodes[0] expect(radio.value).toEqual('B') myObservable('C') expect(radio.value).toEqual('C') radio.value = 'D' triggerEvent(radio, 'change') // observable does not update, as we are not handling events when on a checkbox/radio expect(myObservable()).toEqual('C') }) }) })
the_stack
import * as models from '../models'; /* generated type guards */ export function isAcl(arg: any): arg is models.Acl { return ( arg != null && typeof arg === 'object' && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // name?: string ( typeof arg.name === 'undefined' || typeof arg.name === 'string' ) && // parrentId?: number ( typeof arg.parrentId === 'undefined' || typeof arg.parrentId === 'number' ) && true ); } export function isAclItem(arg: any): arg is models.AclItem { return ( arg != null && typeof arg === 'object' && // permissions?: string[] ( typeof arg.permissions === 'undefined' || ( Array.isArray(arg.permissions) && arg.permissions.every((item: any) => typeof item === 'string') ) ) && // role?: string ( typeof arg.role === 'undefined' || typeof arg.role === 'string' ) && true ); } export function isAuthForm(arg: any): arg is models.AuthForm { return ( arg != null && typeof arg === 'object' && // email: string typeof arg.email === 'string' && // password: string typeof arg.password === 'string' && // rememberMe?: boolean ( typeof arg.rememberMe === 'undefined' || typeof arg.rememberMe === 'boolean' ) && true ); } export function isColumn(arg: any): arg is models.Column { return ( arg != null && typeof arg === 'object' && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // title?: string ( typeof arg.title === 'undefined' || typeof arg.title === 'string' ) && true ); } export function isColumnMapping(arg: any): arg is models.ColumnMapping { return ( arg != null && typeof arg === 'object' && // reportColumnId?: number ( typeof arg.reportColumnId === 'undefined' || typeof arg.reportColumnId === 'number' ) && // templateColumnId?: number ( typeof arg.templateColumnId === 'undefined' || typeof arg.templateColumnId === 'number' ) && true ); } export function isCriticality(arg: any): arg is models.Criticality { return arg != null || arg === models.Criticality.Low || arg === models.Criticality.Medium || arg === models.Criticality.High ; } export function isFrequency(arg: any): arg is models.Frequency { return arg != null || arg === models.Frequency.Daily || arg === models.Frequency.Weekly || arg === models.Frequency.Yearly ; } export function isImportHistoryItem(arg: any): arg is models.ImportHistoryItem { return ( arg != null && typeof arg === 'object' && // datetime?: string ( typeof arg.datetime === 'undefined' || typeof arg.datetime === 'string' ) && // details?: string ( typeof arg.details === 'undefined' || typeof arg.details === 'string' ) && // filename?: string ( typeof arg.filename === 'undefined' || typeof arg.filename === 'string' ) && // status?: Status ( typeof arg.status === 'undefined' || isStatus(arg.status) ) && // type?: ImportType ( typeof arg.type === 'undefined' || isImportType(arg.type) ) && // user?: string ( typeof arg.user === 'undefined' || typeof arg.user === 'string' ) && true ); } export function isImportResponse(arg: any): arg is models.ImportResponse { return ( arg != null && typeof arg === 'object' && // skipperRows?: number ( typeof arg.skipperRows === 'undefined' || typeof arg.skipperRows === 'number' ) && // status?: boolean ( typeof arg.status === 'undefined' || typeof arg.status === 'boolean' ) && true ); } export function isImportStats(arg: any): arg is models.ImportStats { return ( arg != null && typeof arg === 'object' && // late?: number ( typeof arg.late === 'undefined' || typeof arg.late === 'number' ) && // onTime?: number ( typeof arg.onTime === 'undefined' || typeof arg.onTime === 'number' ) && true ); } export function isImportStatsGroup(arg: any): arg is models.ImportStatsGroup { return ( arg != null && typeof arg === 'object' && // imported?: ImportStats[] ( typeof arg.imported === 'undefined' || ( Array.isArray(arg.imported) && arg.imported.every((item: any) => isImportStats(item)) ) ) && // pending?: ImportStats[] ( typeof arg.pending === 'undefined' || ( Array.isArray(arg.pending) && arg.pending.every((item: any) => isImportStats(item)) ) ) && true ); } export function isImportStatus(arg: any): arg is models.ImportStatus { return arg != null || arg === models.ImportStatus.Live || arg === models.ImportStatus.PastDeadline ; } export function isImportStatusDetailsItem(arg: any): arg is models.ImportStatusDetailsItem { return ( arg != null && typeof arg === 'object' && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // issues?: number ( typeof arg.issues === 'undefined' || typeof arg.issues === 'number' ) && // progress?: number ( typeof arg.progress === 'undefined' || typeof arg.progress === 'number' ) && // status?: Status ( typeof arg.status === 'undefined' || isStatus(arg.status) ) && // subtitle?: string ( typeof arg.subtitle === 'undefined' || typeof arg.subtitle === 'string' ) && // title?: string ( typeof arg.title === 'undefined' || typeof arg.title === 'string' ) && true ); } export function isImportStatusItem(arg: any): arg is models.ImportStatusItem { return ( arg != null && typeof arg === 'object' && // criticality?: Criticality ( typeof arg.criticality === 'undefined' || isCriticality(arg.criticality) ) && // details?: ImportStatusDetailsItem[] ( typeof arg.details === 'undefined' || ( Array.isArray(arg.details) && arg.details.every((item: any) => isImportStatusDetailsItem(item)) ) ) && // dueDate?: string ( typeof arg.dueDate === 'undefined' || typeof arg.dueDate === 'string' ) && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // issues?: number ( typeof arg.issues === 'undefined' || typeof arg.issues === 'number' ) && // progress?: number ( typeof arg.progress === 'undefined' || typeof arg.progress === 'number' ) && // title?: string ( typeof arg.title === 'undefined' || typeof arg.title === 'string' ) && true ); } export function isImportType(arg: any): arg is models.ImportType { return arg != null || arg === models.ImportType.ThirdParty || arg === models.ImportType.File ; } export function isIssue(arg: any): arg is models.Issue { return ( arg != null && typeof arg === 'object' && // alert?: IssueAlertType ( typeof arg.alert === 'undefined' || isIssueAlertType(arg.alert) ) && // description?: string ( typeof arg.description === 'undefined' || typeof arg.description === 'string' ) && // dueDate?: string ( typeof arg.dueDate === 'undefined' || typeof arg.dueDate === 'string' ) && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // name?: string ( typeof arg.name === 'undefined' || typeof arg.name === 'string' ) && // reportName?: string ( typeof arg.reportName === 'undefined' || typeof arg.reportName === 'string' ) && // rootCause?: string ( typeof arg.rootCause === 'undefined' || typeof arg.rootCause === 'string' ) && // school?: string ( typeof arg.school === 'undefined' || typeof arg.school === 'string' ) && true ); } export function isIssueAlertType(arg: any): arg is models.IssueAlertType { return arg != null || arg === models.IssueAlertType.Validation || arg === models.IssueAlertType.Data ; } export function isIssueStatus(arg: any): arg is models.IssueStatus { return arg != null || arg === models.IssueStatus.Pending || arg === models.IssueStatus.Resolved ; } export function isNotificationEditable(arg: any): arg is models.NotificationEditable { return ( arg != null && typeof arg === 'object' && // description?: string ( typeof arg.description === 'undefined' || typeof arg.description === 'string' ) && // frequency?: Frequency ( typeof arg.frequency === 'undefined' || isFrequency(arg.frequency) ) && // moduleId?: number ( typeof arg.moduleId === 'undefined' || typeof arg.moduleId === 'number' ) && // name?: string ( typeof arg.name === 'undefined' || typeof arg.name === 'string' ) && // priority?: Criticality ( typeof arg.priority === 'undefined' || isCriticality(arg.priority) ) && // triggerId?: number ( typeof arg.triggerId === 'undefined' || typeof arg.triggerId === 'number' ) && true ); } export function isNotificationEditableListItem(arg: any): arg is models.NotificationEditableListItem { return ( arg != null && typeof arg === 'object' && // enabled?: boolean ( typeof arg.enabled === 'undefined' || typeof arg.enabled === 'boolean' ) && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // extends NotificationEditable isNotificationEditable(arg) && true ); } export function isNotificationListItem(arg: any): arg is models.NotificationListItem { return ( arg != null && typeof arg === 'object' && // date?: string ( typeof arg.date === 'undefined' || typeof arg.date === 'string' ) && // description?: string ( typeof arg.description === 'undefined' || typeof arg.description === 'string' ) && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // name?: string ( typeof arg.name === 'undefined' || typeof arg.name === 'string' ) && // priority?: Criticality ( typeof arg.priority === 'undefined' || isCriticality(arg.priority) ) && true ); } export function isNotificationModule(arg: any): arg is models.NotificationModule { return ( arg != null && typeof arg === 'object' && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // name?: string ( typeof arg.name === 'undefined' || typeof arg.name === 'string' ) && // notificationsCount?: number ( typeof arg.notificationsCount === 'undefined' || typeof arg.notificationsCount === 'number' ) && true ); } export function isNotificationTrigger(arg: any): arg is models.NotificationTrigger { return ( arg != null && typeof arg === 'object' && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // name?: string ( typeof arg.name === 'undefined' || typeof arg.name === 'string' ) && true ); } export function isOrder(arg: any): arg is models.Order { return arg != null || arg === models.Order.asc || arg === models.Order.desc ; } export function isOrderableTable(arg: any): arg is models.OrderableTable { return ( arg != null && typeof arg === 'object' && // order?: Order ( typeof arg.order === 'undefined' || isOrder(arg.order) ) && // orderBy?: number ( typeof arg.orderBy === 'undefined' || typeof arg.orderBy === 'number' ) && // extends Table isTable(arg) && true ); } export function isOtherSecuritySettings(arg: any): arg is models.OtherSecuritySettings { return ( arg != null && typeof arg === 'object' && // inactivityTimeout?: number ( typeof arg.inactivityTimeout === 'undefined' || typeof arg.inactivityTimeout === 'number' ) && true ); } export function isPagedTable(arg: any): arg is models.PagedTable { return ( arg != null && typeof arg === 'object' && // totalRows?: number ( typeof arg.totalRows === 'undefined' || typeof arg.totalRows === 'number' ) && // extends Table isTable(arg) && true ); } export function isPasswordCreationPolicies(arg: any): arg is models.PasswordCreationPolicies { return ( arg != null && typeof arg === 'object' && // passwordMinChars?: number ( typeof arg.passwordMinChars === 'undefined' || typeof arg.passwordMinChars === 'number' ) && // passwordMinDigits?: number ( typeof arg.passwordMinDigits === 'undefined' || typeof arg.passwordMinDigits === 'number' ) && // passwordMinLength?: number ( typeof arg.passwordMinLength === 'undefined' || typeof arg.passwordMinLength === 'number' ) && // passwordMinSpecialChars?: number ( typeof arg.passwordMinSpecialChars === 'undefined' || typeof arg.passwordMinSpecialChars === 'number' ) && // passwordMinUpperChars?: number ( typeof arg.passwordMinUpperChars === 'undefined' || typeof arg.passwordMinUpperChars === 'number' ) && // passwordNotMatchPrevious?: number ( typeof arg.passwordNotMatchPrevious === 'undefined' || typeof arg.passwordNotMatchPrevious === 'number' ) && // passwordResetLinkExpiration?: number ( typeof arg.passwordResetLinkExpiration === 'undefined' || typeof arg.passwordResetLinkExpiration === 'number' ) && // preventOldPasswordReuse?: boolean ( typeof arg.preventOldPasswordReuse === 'undefined' || typeof arg.preventOldPasswordReuse === 'boolean' ) && true ); } export function isPasswordVerificationPolicies(arg: any): arg is models.PasswordVerificationPolicies { return ( arg != null && typeof arg === 'object' && // changePasswordInterval?: number ( typeof arg.changePasswordInterval === 'undefined' || typeof arg.changePasswordInterval === 'number' ) && // lockAfterAttempts?: number ( typeof arg.lockAfterAttempts === 'undefined' || typeof arg.lockAfterAttempts === 'number' ) && // passwordExpiryNotification?: number ( typeof arg.passwordExpiryNotification === 'undefined' || typeof arg.passwordExpiryNotification === 'number' ) && // reenableTimeout?: number ( typeof arg.reenableTimeout === 'undefined' || typeof arg.reenableTimeout === 'number' ) && true ); } export function isPeriod(arg: any): arg is models.Period { return arg != null || arg === models.Period.Year || arg === models.Period.Month || arg === models.Period.Week ; } export function isPrivilegeTreeItem(arg: any): arg is models.PrivilegeTreeItem { return ( arg != null && typeof arg === 'object' && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // name?: string ( typeof arg.name === 'undefined' || typeof arg.name === 'string' ) && // parentId?: number ( typeof arg.parentId === 'undefined' || typeof arg.parentId === 'number' ) && true ); } export function isReportItem(arg: any): arg is models.ReportItem { return ( arg != null && typeof arg === 'object' && // description?: string ( typeof arg.description === 'undefined' || typeof arg.description === 'string' ) && // groups?: ReportTemplateGroup[] ( typeof arg.groups === 'undefined' || ( Array.isArray(arg.groups) && arg.groups.every((item: any) => isReportTemplateGroup(item)) ) ) && // progress?: number ( typeof arg.progress === 'undefined' || typeof arg.progress === 'number' ) && // extends ReportListItem isReportListItem(arg) && true ); } export function isReportListItem(arg: any): arg is models.ReportListItem { return ( arg != null && typeof arg === 'object' && // criticality?: Criticality ( typeof arg.criticality === 'undefined' || isCriticality(arg.criticality) ) && // deadline?: string ( typeof arg.deadline === 'undefined' || typeof arg.deadline === 'string' ) && // description?: string ( typeof arg.description === 'undefined' || typeof arg.description === 'string' ) && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // issues?: number ( typeof arg.issues === 'undefined' || typeof arg.issues === 'number' ) && // status?: Status ( typeof arg.status === 'undefined' || isStatus(arg.status) ) && // subtitle?: string ( typeof arg.subtitle === 'undefined' || typeof arg.subtitle === 'string' ) && // title?: string ( typeof arg.title === 'undefined' || typeof arg.title === 'string' ) && true ); } export function isReportTemplate(arg: any): arg is models.ReportTemplate { return ( arg != null && typeof arg === 'object' && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // issues?: number ( typeof arg.issues === 'undefined' || typeof arg.issues === 'number' ) && // sampleFileUrl?: string ( typeof arg.sampleFileUrl === 'undefined' || typeof arg.sampleFileUrl === 'string' ) && // status?: Status ( typeof arg.status === 'undefined' || isStatus(arg.status) ) && // subtitle?: string ( typeof arg.subtitle === 'undefined' || typeof arg.subtitle === 'string' ) && // title?: string ( typeof arg.title === 'undefined' || typeof arg.title === 'string' ) && true ); } export function isReportTemplateGroup(arg: any): arg is models.ReportTemplateGroup { return ( arg != null && typeof arg === 'object' && // imports?: ReportTemplate[] ( typeof arg.imports === 'undefined' || ( Array.isArray(arg.imports) && arg.imports.every((item: any) => isReportTemplate(item)) ) ) && // issues?: number ( typeof arg.issues === 'undefined' || typeof arg.issues === 'number' ) && // title?: string ( typeof arg.title === 'undefined' || typeof arg.title === 'string' ) && true ); } export function isRestoreForm(arg: any): arg is models.RestoreForm { return ( arg != null && typeof arg === 'object' && // 'password\u0421onfirm': string typeof arg['passwordСonfirm'] === 'string' && // guid?: string ( typeof arg.guid === 'undefined' || typeof arg.guid === 'string' ) && // password: string typeof arg.password === 'string' && true ); } export function isRestoreRequestForm(arg: any): arg is models.RestoreRequestForm { return ( arg != null && typeof arg === 'object' && // email: string typeof arg.email === 'string' && true ); } export function isRoleDetailsItem(arg: any): arg is models.RoleDetailsItem { return ( arg != null && typeof arg === 'object' && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // name?: string ( typeof arg.name === 'undefined' || typeof arg.name === 'string' ) && // privileges?: number[] ( typeof arg.privileges === 'undefined' || ( Array.isArray(arg.privileges) && arg.privileges.every((item: any) => typeof item === 'number') ) ) && // status?: RoleStatus ( typeof arg.status === 'undefined' || isRoleStatus(arg.status) ) && // users?: number[] ( typeof arg.users === 'undefined' || ( Array.isArray(arg.users) && arg.users.every((item: any) => typeof item === 'number') ) ) && true ); } export function isRoleListItem(arg: any): arg is models.RoleListItem { return ( arg != null && typeof arg === 'object' && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // name?: string ( typeof arg.name === 'undefined' || typeof arg.name === 'string' ) && // privileges?: string ( typeof arg.privileges === 'undefined' || typeof arg.privileges === 'string' ) && // status?: RoleStatus ( typeof arg.status === 'undefined' || isRoleStatus(arg.status) ) && true ); } export function isRoleStatus(arg: any): arg is models.RoleStatus { return ( arg != null && typeof arg === 'object' && // extends UserStatus isUserStatus(arg) && true ); } export function isRoleUpdateDetails(arg: any): arg is models.RoleUpdateDetails { return ( arg != null && typeof arg === 'object' && // privilegesToAssing?: number[] ( typeof arg.privilegesToAssing === 'undefined' || ( Array.isArray(arg.privilegesToAssing) && arg.privilegesToAssing.every((item: any) => typeof item === 'number') ) ) && // privilegesToUnassing?: number[] ( typeof arg.privilegesToUnassing === 'undefined' || ( Array.isArray(arg.privilegesToUnassing) && arg.privilegesToUnassing.every((item: any) => typeof item === 'number') ) ) && // status?: RoleStatus ( typeof arg.status === 'undefined' || isRoleStatus(arg.status) ) && // usersToAssing?: number[] ( typeof arg.usersToAssing === 'undefined' || ( Array.isArray(arg.usersToAssing) && arg.usersToAssing.every((item: any) => typeof item === 'number') ) ) && // usersToUnassing?: number[] ( typeof arg.usersToUnassing === 'undefined' || ( Array.isArray(arg.usersToUnassing) && arg.usersToUnassing.every((item: any) => typeof item === 'number') ) ) && true ); } export function isSchoolImportStats(arg: any): arg is models.SchoolImportStats { return ( arg != null && typeof arg === 'object' && // stats?: ImportStatsGroup ( typeof arg.stats === 'undefined' || isImportStatsGroup(arg.stats) ) && // title?: string ( typeof arg.title === 'undefined' || typeof arg.title === 'string' ) && true ); } export function isStatus(arg: any): arg is models.Status { return arg != null || arg === models.Status.Pending || arg === models.Status.InProgress || arg === models.Status.Complete ; } export function isStructure(arg: any): arg is models.Structure { return ( arg != null && typeof arg === 'object' && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // parentId?: number ( typeof arg.parentId === 'undefined' || typeof arg.parentId === 'number' ) && // extends StructureForm isStructureForm(arg) && true ); } export function isStructureAddParameters(arg: any): arg is models.StructureAddParameters { return ( arg != null && typeof arg === 'object' && // parentId?: number ( typeof arg.parentId === 'undefined' || typeof arg.parentId === 'number' ) && // extends StructureForm isStructureForm(arg) && true ); } export function isStructureForm(arg: any): arg is models.StructureForm { return ( arg != null && typeof arg === 'object' && // address?: string ( typeof arg.address === 'undefined' || typeof arg.address === 'string' ) && // code: string typeof arg.code === 'string' && // description?: string ( typeof arg.description === 'undefined' || typeof arg.description === 'string' ) && // name: string typeof arg.name === 'string' && true ); } export function isTable(arg: any): arg is models.Table { return ( arg != null && typeof arg === 'object' && // tableData?: TableCell[][] ( typeof arg.tableData === 'undefined' || ( Array.isArray(arg.tableData) && arg.tableData.every((item: any) => ( Array.isArray(item) && item.every((item: any) => isTableCell(item)) )) ) ) && // tableHead?: Column[] ( typeof arg.tableHead === 'undefined' || ( Array.isArray(arg.tableHead) && arg.tableHead.every((item: any) => isColumn(item)) ) ) && true ); } export function isTableCell(arg: any): arg is models.TableCell { return ( arg != null && typeof arg === 'object' && // columnId?: number ( typeof arg.columnId === 'undefined' || typeof arg.columnId === 'number' ) && // value?: string ( typeof arg.value === 'undefined' || typeof arg.value === 'string' ) && true ); } export function isTotalImportStats(arg: any): arg is models.TotalImportStats { return ( arg != null && typeof arg === 'object' && // bySchools?: SchoolImportStats[] ( typeof arg.bySchools === 'undefined' || ( Array.isArray(arg.bySchools) && arg.bySchools.every((item: any) => isSchoolImportStats(item)) ) ) && // total?: ImportStatsGroup ( typeof arg.total === 'undefined' || isImportStatsGroup(arg.total) ) && true ); } export function isUserDetails(arg: any): arg is models.UserDetails { return ( arg != null && typeof arg === 'object' && // email?: string ( typeof arg.email === 'undefined' || typeof arg.email === 'string' ) && // entities?: number[] ( typeof arg.entities === 'undefined' || ( Array.isArray(arg.entities) && arg.entities.every((item: any) => typeof item === 'number') ) ) && // firstName?: string ( typeof arg.firstName === 'undefined' || typeof arg.firstName === 'string' ) && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // imageData?: string ( typeof arg.imageData === 'undefined' || typeof arg.imageData === 'string' ) && // imageUrl?: string ( typeof arg.imageUrl === 'undefined' || typeof arg.imageUrl === 'string' ) && // lastName?: string ( typeof arg.lastName === 'undefined' || typeof arg.lastName === 'string' ) && // login?: string ( typeof arg.login === 'undefined' || typeof arg.login === 'string' ) && // phone?: string ( typeof arg.phone === 'undefined' || typeof arg.phone === 'string' ) && // roleId?: number ( typeof arg.roleId === 'undefined' || typeof arg.roleId === 'number' ) && // status?: UserStatus ( typeof arg.status === 'undefined' || isUserStatus(arg.status) ) && // title?: string ( typeof arg.title === 'undefined' || typeof arg.title === 'string' ) && true ); } export function isUserListItem(arg: any): arg is models.UserListItem { return ( arg != null && typeof arg === 'object' && // entityIds?: number[] ( typeof arg.entityIds === 'undefined' || ( Array.isArray(arg.entityIds) && arg.entityIds.every((item: any) => typeof item === 'number') ) ) && // id?: number ( typeof arg.id === 'undefined' || typeof arg.id === 'number' ) && // name?: string ( typeof arg.name === 'undefined' || typeof arg.name === 'string' ) && // roleId?: number ( typeof arg.roleId === 'undefined' || typeof arg.roleId === 'number' ) && // status?: UserStatus ( typeof arg.status === 'undefined' || isUserStatus(arg.status) ) && true ); } export function isUserStatus(arg: any): arg is models.UserStatus { return arg != null || arg === models.UserStatus.Active || arg === models.UserStatus.Blocked ; } export function isValidatedTable(arg: any): arg is models.ValidatedTable { return ( arg != null && typeof arg === 'object' && // tableData?: ValidatedTableCell[][] ( typeof arg.tableData === 'undefined' || ( Array.isArray(arg.tableData) && arg.tableData.every((item: any) => ( Array.isArray(item) && item.every((item: any) => isValidatedTableCell(item)) )) ) ) && // tableHead?: Column[] ( typeof arg.tableHead === 'undefined' || ( Array.isArray(arg.tableHead) && arg.tableHead.every((item: any) => isColumn(item)) ) ) && true ); } export function isValidatedTableCell(arg: any): arg is models.ValidatedTableCell { return ( arg != null && typeof arg === 'object' && // error?: string ( typeof arg.error === 'undefined' || typeof arg.error === 'string' ) && // extends TableCell isTableCell(arg) && true ); }
the_stack
// clang-format off import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BaseMixin, getSearchManager, SearchManager} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; // clang-format on suite('SearchSettingsTest', function() { let searchManager: SearchManager; setup(function() { searchManager = getSearchManager(); document.body.innerHTML = ''; }); /** * Test that the DOM of a node is modified as expected when a search hit * occurs within that node. */ test('normal highlighting', function() { const optionText = 'FooSettingsFoo'; document.body.innerHTML = `<settings-section hidden-by-search> <div id="mydiv">${optionText}</div> </settings-section>`; const section = document.querySelector('settings-section')!; const div = document.querySelector('#mydiv')!; assertTrue(section.hiddenBySearch); return searchManager.search('settings', section) .then(function() { assertFalse(section.hiddenBySearch); const highlightWrapper = div.querySelector('.search-highlight-wrapper'); assertTrue(!!highlightWrapper); const originalContent = highlightWrapper!.querySelector( '.search-highlight-original-content'); assertTrue(!!originalContent); assertEquals(optionText, originalContent!.textContent); const searchHits = highlightWrapper!.querySelectorAll<HTMLElement>( '.search-highlight-hit'); assertEquals(1, searchHits.length); assertEquals('Settings', searchHits[0]!.textContent); // Check that original DOM structure is restored when search // highlights are cleared. return searchManager.search('', section); }) .then(function() { assertEquals(0, div.children.length); assertEquals(optionText, div.textContent); }); }); /** * Tests that a search hit within a <select> node causes the parent * settings-section to be shown and the <select> to be highlighted by a * bubble. */ test('<select> highlighting', function() { document.body.innerHTML = `<settings-section hidden-by-search> <select> <option>Foo</option> <option>Settings</option> <option>Baz</option> </select> </settings-section>`; const section = document.querySelector('settings-section')!; const select = section.querySelector('select')!; assertTrue(section.hiddenBySearch); return searchManager.search('settings', section) .then(function() { assertFalse(section.hiddenBySearch); assertEquals(1, document.querySelectorAll('.search-bubble').length); // Check that original DOM structure is present even after search // highlights are cleared. return searchManager.search('', section); }) .then(function() { const options = select.querySelectorAll('option'); assertEquals(3, options.length); assertEquals('Foo', options[0]!.textContent); assertEquals('Settings', options[1]!.textContent); assertEquals('Baz', options[2]!.textContent); }); }); test('ignored elements are ignored', function() { const text = 'hello'; document.body.innerHTML = `<settings-section hidden-by-search> <cr-action-menu>${text}</cr-action-menu> <cr-dialog>${text}</cr-dialog> <cr-icon-button>${text}</cr-icon-button> <cr-slider>${text}</cr-slider> <dialog>${text}</dialog> <iron-icon>${text}</iron-icon> <iron-list>${text}</iron-list> <paper-ripple>${text}</paper-ripple> <paper-spinner-lite>${text}</paper-spinner-lite> <slot>${text}</slot> <content>${text}</content> <style>${text}</style> <template>${text}</template> </settings-section>`; const section = document.querySelector('settings-section')!; assertTrue(section.hiddenBySearch); return searchManager.search(text, section).then(function() { assertTrue(section.hiddenBySearch); }); }); test('no-search elements are ignored', function() { // Define a dummy test element with the necessary structure for testing. const DummyTestElementBase = BaseMixin(PolymerElement); class DummyTestElement extends DummyTestElementBase { get is() { return 'dummy-test-element'; } static get template() { return html` <button></button> <settings-section hidden-by-search> <!-- Test case were no-search is part of a data binding. --> <template is="dom-if" route-path="/myPath0" no-search="[[noSearch]]"> <settings-subpage associated-control="[[$$('button')]]"> hello </settings-subpage> </template> <!-- Test case were no-search is not part of any data binding.--> <template is="dom-if" route-path="/myPath1" no-search> <settings-subpage associated-control="[[$$('button')]]"> hello </settings-subpage> </template> </settings-section> `; } get properties() { return { noSearch: Boolean, }; } noSearch: boolean = true; } customElements.define('dummy-test-element', DummyTestElement); const text = 'hello'; document.body.innerHTML = `<dummy-test-element></dummy-test-element>`; const element = document.body.querySelector<DummyTestElement>('dummy-test-element')!; const section = element.shadowRoot!.querySelector('settings-section')!; // Ensure that no settings-subpage instance exists. assertEquals(null, element.shadowRoot!.querySelector('settings-subpage')); return searchManager.search(text, section) .then(function() { assertTrue(section.hiddenBySearch); // Check that searching did not cause a settings-subpage instance to // be forced rendered. assertEquals( null, element.shadowRoot!.querySelector('settings-subpage')); element.noSearch = false; return searchManager.search(text, section); }) .then(function() { // Check that searching caused a settings-subpage instance to be // forced rendered. assertFalse(section.hiddenBySearch); assertTrue(!!element.shadowRoot!.querySelector('settings-subpage')); }); }); // Test that multiple requests for the same text correctly highlight their // corresponding part of the tree without affecting other parts of the tree. test('multiple simultaneous requests for the same text', function() { document.body.innerHTML = `<settings-section hidden-by-search> <div><span>Hello there</span></div> </settings-section> <settings-section hidden-by-search> <div><span>Hello over there</span></div> </settings-section> <settings-section hidden-by-search> <div><span>Nothing</span></div> </settings-section>`; const sections = Array.prototype.slice.call( document.querySelectorAll('settings-section')); return Promise.all(sections.map(s => searchManager.search('there', s))) .then(function(requests) { assertTrue(requests[0]!.didFindMatches()); assertFalse(sections[0]!.hiddenBySearch); assertTrue(requests[1]!.didFindMatches()); assertFalse(sections[1]!.hiddenBySearch); assertFalse(requests[2]!.didFindMatches()); assertTrue(sections[2]!.hiddenBySearch); }); }); test('highlight removed when text is changed', function() { const originalText = 'FooSettingsFoo'; document.body.innerHTML = `<settings-section hidden-by-search> <div id="mydiv">${originalText}</div> </settings-section>`; const section = document.querySelector('settings-section')!; const div = document.querySelector('#mydiv')!; assertTrue(section.hiddenBySearch); return searchManager.search('settings', document.body).then(() => { assertFalse(section.hiddenBySearch); assertEquals(1, div.childNodes.length); const highlightWrapper = div.firstChild as HTMLElement; assertTrue( highlightWrapper.classList.contains('search-highlight-wrapper')); const originalContent = highlightWrapper.querySelector('.search-highlight-original-content'); assertTrue(!!originalContent); originalContent!.childNodes[0]!.nodeValue = 'Foo'; return new Promise<void>(resolve => { setTimeout(() => { assertFalse(section.hiddenBySearch); assertEquals(1, div.childNodes.length); assertEquals('Foo', div.innerHTML); resolve(); }, 1); }); }); }); test('match text outside of a settings section', async function() { document.body.innerHTML = ` <div id="mydiv">Match</div> <settings-section></settings-section>`; const section = document.querySelector('settings-section')!; const mydiv = document.querySelector('#mydiv')!; await searchManager.search('Match', document.body); assertTrue(section.hiddenBySearch); const highlight = mydiv.querySelector('.search-highlight-wrapper'); assertTrue(!!highlight); const searchHits = highlight!.querySelectorAll('.search-highlight-hit'); assertEquals(1, searchHits.length); assertEquals('Match', searchHits[0]!.textContent); }); test('associated control causes search highlight bubble', async () => { document.body.innerHTML = ` <settings-section> <button></button> <settings-subpage> hello </settings-subpage> </settings-section>`; const subpage = document.querySelector('settings-subpage')!; subpage.associatedControl = document.querySelector('button'); await searchManager.search('hello', document.body); assertEquals(1, document.querySelectorAll('.search-bubble').length); }); test('bubble result count', async () => { document.body.innerHTML = ` <settings-section> <select> <option>nohello</option> <option>hello dolly!</option> <option>hello to you, too!</option> <option>you say goodbye, I say hello!</option> </select> <button></button> <settings-subpage> hello there! </settings-subpage> </setting-section>`; const subpage = document.querySelector('settings-subpage')!; subpage.associatedControl = document.querySelector('button'); await searchManager.search('hello', document.body); const bubbles = document.querySelectorAll('.search-bubble'); assertEquals(2, bubbles.length); assertEquals('4 results', bubbles[1]!.textContent); assertEquals('1 result', bubbles[0]!.textContent); }); test('diacritics', async () => { document.body.innerHTML = ` <settings-section> <select> <option>año de oro</option> </select> <button></button> <settings-subpage> malibu cañon </settings-subpage> danger zone </setting-section>`; const subpage = document.querySelector('settings-subpage')!; subpage.associatedControl = document.querySelector('button'); await searchManager.search('an', document.body); const highlights = document.querySelectorAll('.search-highlight-wrapper'); assertEquals(2, highlights.length); assertEquals(2, document.querySelectorAll('.search-bubble').length); }); });
the_stack
import PagingProperties from '@DataContracts/PagingPropertiesContract'; import PartialFindResultContract from '@DataContracts/PartialFindResultContract'; import SongApiContract from '@DataContracts/Song/SongApiContract'; import SongContract from '@DataContracts/Song/SongContract'; import IEntryWithIdAndName from '@Models/IEntryWithIdAndName'; import PVServiceIcons from '@Models/PVServiceIcons'; import SongType from '@Models/Songs/SongType'; import ArtistRepository from '@Repositories/ArtistRepository'; import ReleaseEventRepository from '@Repositories/ReleaseEventRepository'; import SongRepository from '@Repositories/SongRepository'; import UserRepository from '@Repositories/UserRepository'; import GlobalValues from '@Shared/GlobalValues'; import UrlMapper from '@Shared/UrlMapper'; import BasicEntryLinkStore from '@Stores/BasicEntryLinkStore'; import PVPlayerStore from '@Stores/PVs/PVPlayerStore'; import PVPlayersFactory from '@Stores/PVs/PVPlayersFactory'; import PlayListRepositoryForSongsAdapter, { ISongSearchStore, } from '@Stores/Song/PlayList/PlayListRepositoryForSongsAdapter'; import PlayListStore from '@Stores/Song/PlayList/PlayListStore'; import SongWithPreviewStore from '@Stores/Song/SongWithPreviewStore'; import _ from 'lodash'; import { computed, makeObservable, observable } from 'mobx'; import moment from 'moment'; import AdvancedSearchFilter from './AdvancedSearchFilter'; import ArtistFilters from './ArtistFilters'; import { ICommonSearchStore } from './CommonSearchStore'; import SearchCategoryBaseStore from './SearchCategoryBaseStore'; import { SearchType } from './SearchStore'; import SongBpmFilter from './SongBpmFilter'; import SongLengthFilter from './SongLengthFilter'; // Corresponds to the SongSortRule enum in C#. export enum SongSortRule { None = 'None', Name = 'Name', AdditionDate = 'AdditionDate', PublishDate = 'PublishDate', FavoritedTimes = 'FavoritedTimes', RatingScore = 'RatingScore', TagUsageCount = 'TagUsageCount', } export interface SongSearchRouteParams { advancedFilters?: AdvancedSearchFilter[]; artistId?: number | number[]; artistParticipationStatus?: string /* TODO: enum */; autoplay?: boolean; childTags?: boolean; childVoicebanks?: boolean; dateYear?: number; dateMonth?: number; dateDay?: number; draftsOnly?: boolean; eventId?: number; filter?: string; includeMembers?: boolean; maxLength?: number; maxMilliBpm?: number; minLength?: number; minMilliBpm?: number; minScore?: number; onlyWithPVs?: boolean; onlyRatedSongs?: boolean; page?: number; pageSize?: number; parentVersionId?: number; searchType?: SearchType.Song; shuffle?: boolean; since?: number; songType?: string /* TODO: enum */; sort?: SongSortRule; tag?: string; tagId?: number | number[]; unifyEntryTypesAndTags?: boolean; viewMode?: string /* TODO: enum */; } export interface ISongSearchItem extends SongApiContract { previewStore?: SongWithPreviewStore; } export default class SongSearchStore extends SearchCategoryBaseStore<ISongSearchItem> implements ISongSearchStore { public readonly artistFilters: ArtistFilters; @observable public dateDay?: number = undefined; @observable public dateMonth?: number = undefined; @observable public dateYear?: number = undefined; public readonly releaseEvent: BasicEntryLinkStore<IEntryWithIdAndName>; @observable public minScore?: number; @observable public onlyRatedSongs = false; public readonly parentVersion: BasicEntryLinkStore<SongContract>; public readonly playListStore: PlayListStore; public readonly pvPlayerStore: PVPlayerStore; @observable public pvsOnly = false; private readonly pvServiceIcons: PVServiceIcons; @observable public since?: number; @observable public songType = SongType[SongType.Unspecified] /* TODO: enum */; @observable public sort = SongSortRule.Name; @observable public unifyEntryTypesAndTags = false; @observable public viewMode = 'Details' /* TODO: enum */; public readonly minBpmFilter = new SongBpmFilter(); public readonly maxBpmFilter = new SongBpmFilter(); public readonly minLengthFilter = new SongLengthFilter(); public readonly maxLengthFilter = new SongLengthFilter(); public constructor( commonSearchStore: ICommonSearchStore, private readonly values: GlobalValues, urlMapper: UrlMapper, private readonly songRepo: SongRepository, private readonly userRepo: UserRepository, private readonly eventRepo: ReleaseEventRepository, artistRepo: ArtistRepository, pvPlayersFactory: PVPlayersFactory, ) { super(commonSearchStore); makeObservable(this); this.pvServiceIcons = new PVServiceIcons(urlMapper); this.artistFilters = new ArtistFilters(values, artistRepo); this.releaseEvent = new BasicEntryLinkStore<IEntryWithIdAndName>( (entryId) => this.eventRepo ? eventRepo.getOne({ id: entryId }) : Promise.resolve(undefined), ); this.parentVersion = new BasicEntryLinkStore<SongContract>((entryId) => songRepo.getOne({ id: entryId, lang: values.languagePreference }), ); this.pvPlayerStore = new PVPlayerStore( values, songRepo, userRepo, pvPlayersFactory, ); const songsRepoAdapter = new PlayListRepositoryForSongsAdapter( values, songRepo, this, ); this.playListStore = new PlayListStore( values, urlMapper, songsRepoAdapter, this.pvPlayerStore, ); } // Remember, JavaScript months start from 0 (who came up with that??) // The answer song: https://stackoverflow.com/questions/2552483/why-does-the-month-argument-range-from-0-to-11-in-javascripts-date-constructor/41992352#41992352 private toDateOrUndefined = (mom: moment.Moment): Date | undefined => mom.isValid() ? mom.toDate() : undefined; @computed public get afterDate(): Date | undefined { return this.dateYear ? this.toDateOrUndefined( moment.utc([ this.dateYear, (this.dateMonth || 1) - 1, this.dateDay || 1, ]), ) : undefined; } @computed public get beforeDate(): Date | undefined { if (!this.dateYear) return undefined; const mom = moment.utc([ this.dateYear, (this.dateMonth || 12) - 1, this.dateDay || 1, ]); return this.toDateOrUndefined( this.dateMonth && this.dateDay ? mom.add(1, 'd') : mom.add(1, 'M'), ); } @computed public get fields(): string { return this.showTags ? 'AdditionalNames,ThumbUrl,Tags' : 'AdditionalNames,ThumbUrl'; } @computed public get showUnifyEntryTypesAndTags(): boolean { return ( this.songType !== SongType[SongType.Unspecified] && this.songType !== SongType[SongType.Original] ); } public loadResults = ( pagingProperties: PagingProperties, searchTerm: string, tags: number[], childTags: boolean, status?: string, ): Promise<PartialFindResultContract<ISongSearchItem>> => { if (this.viewMode === 'PlayList') { this.playListStore.updateResultsWithTotalCount(); return Promise.resolve({ items: [], totalCount: 0 }); } else { return this.songRepo .getList({ paging: pagingProperties, lang: this.values.languagePreference, query: searchTerm, sort: this.sort, songTypes: this.songType !== SongType[SongType.Unspecified] ? this.songType : undefined, afterDate: this.afterDate, beforeDate: this.beforeDate, tagIds: tags, childTags: childTags, unifyTypesAndTags: this.unifyEntryTypesAndTags, artistIds: this.artistFilters.artistIds, artistParticipationStatus: this.artistFilters .artistParticipationStatus, childVoicebanks: this.artistFilters.childVoicebanks, includeMembers: this.artistFilters.includeMembers, eventId: this.releaseEvent.id, onlyWithPvs: this.pvsOnly, pvServices: undefined, since: this.since, minScore: this.minScore, userCollectionId: this.onlyRatedSongs ? this.values.loggedUserId : undefined, parentSongId: this.parentVersion.id, fields: this.fields, status: status, advancedFilters: this.advancedFilters.filters, minMilliBpm: this.minBpmFilter.milliBpm, maxMilliBpm: this.maxBpmFilter.milliBpm, minLength: this.minLengthFilter.length ? this.minLengthFilter.length : undefined, maxLength: this.maxLengthFilter.length ? this.maxLengthFilter.length : undefined, }) .then((result) => { _.each(result.items, (song: ISongSearchItem) => { if (song.pvServices && song.pvServices !== 'Nothing') { song.previewStore = new SongWithPreviewStore( this.songRepo, this.userRepo, song.id, song.pvServices, ); // TODO: song.previewStore.ratingComplete = ui.showThankYouForRatingMessage; } else { song.previewStore = undefined; } }); return result; }); } }; public getPVServiceIcons = ( services: string, ): { service: string; url: string }[] => { return this.pvServiceIcons.getIconUrls(services); }; public readonly clearResultsByQueryKeys: (keyof SongSearchRouteParams)[] = [ 'pageSize', 'filter', 'tagId', 'childTags', 'draftsOnly', 'searchType', 'advancedFilters', 'artistId', 'artistParticipationStatus', 'childVoicebanks', 'includeMembers', 'dateYear', 'dateMonth', 'dateDay', 'eventId', 'minScore', 'onlyRatedSongs', 'parentVersionId', 'onlyWithPVs', 'since', 'songType', 'sort', 'unifyEntryTypesAndTags', 'viewMode', 'minMilliBpm', 'maxMilliBpm', 'minLength', 'maxLength', ]; @computed.struct public get routeParams(): SongSearchRouteParams { return { searchType: SearchType.Song, advancedFilters: this.advancedFilters.filters.map((filter) => ({ description: filter.description, filterType: filter.filterType, negate: filter.negate, param: filter.param, })), artistId: this.artistFilters.artistIds, artistParticipationStatus: this.artistFilters.artistParticipationStatus, // TODO: autoplay childTags: this.childTags, childVoicebanks: this.artistFilters.childVoicebanks, dateDay: this.dateDay, dateMonth: this.dateMonth, dateYear: this.dateYear, draftsOnly: this.draftsOnly, eventId: this.releaseEvent.id, filter: this.searchTerm, maxLength: this.maxLengthFilter.length, maxMilliBpm: this.maxBpmFilter.milliBpm, minLength: this.minLengthFilter.length, minMilliBpm: this.minBpmFilter.milliBpm, minScore: this.minScore, onlyRatedSongs: this.onlyRatedSongs, onlyWithPVs: this.pvsOnly, page: this.paging.page, pageSize: this.paging.pageSize, parentVersionId: this.parentVersion.id, // TODO: shuffle since: this.since, songType: this.songType, sort: this.sort, tagId: this.tagIds, unifyEntryTypesAndTags: this.unifyEntryTypesAndTags, viewMode: this.viewMode, }; } public set routeParams(value: SongSearchRouteParams) { this.advancedFilters.filters = value.advancedFilters ?? []; this.artistFilters.artistIds = ([] as number[]).concat( value.artistId ?? [], ); this.artistFilters.artistParticipationStatus = value.artistParticipationStatus ?? 'Everything'; // TODO: autoplay this.childTags = value.childTags ?? false; this.artistFilters.childVoicebanks = value.childVoicebanks ?? false; this.dateDay = value.dateDay; this.dateMonth = value.dateMonth; this.dateYear = value.dateYear; this.draftsOnly = value.draftsOnly ?? false; this.releaseEvent.selectEntry(value.eventId); this.searchTerm = value.filter ?? ''; this.maxLengthFilter.length = value.maxLength ?? 0; this.maxBpmFilter.milliBpm = value.maxMilliBpm; this.minLengthFilter.length = value.minLength ?? 0; this.minBpmFilter.milliBpm = value.minMilliBpm; this.minScore = value.minScore; this.onlyRatedSongs = value.onlyRatedSongs ?? false; this.pvsOnly = value.onlyWithPVs ?? false; this.paging.page = value.page ?? 1; this.paging.pageSize = value.pageSize ?? 10; this.parentVersion.selectEntry(value.parentVersionId); // TODO: shuffle this.since = value.since; this.songType = value.songType ?? 'Unspecified'; this.sort = value.sort ?? SongSortRule.Name; this.tagIds = ([] as number[]).concat(value.tagId ?? []); this.unifyEntryTypesAndTags = value.unifyEntryTypesAndTags ?? false; this.viewMode = value.viewMode ?? 'Details'; } }
the_stack
import { Field, Label } from "@components/field"; import { act, waitFor } from "@testing-library/react"; import { NumberInput } from "@components/number-input"; import { createRef } from "react"; import { renderWithTheme } from "@jest-utils"; import userEvent from "@testing-library/user-event"; // ***** Behaviors ***** test("accept numbers", async () => { const { getByTestId } = renderWithTheme( <NumberInput aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.type(getByTestId("input"), "1"); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(1)); }); test("accept negative numbers", async () => { const { getByTestId } = renderWithTheme( <NumberInput aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.type(getByTestId("input"), "-1"); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(-1)); }); // test("accept floating numbers", async () => { // const { getByTestId } = renderWithTheme( // <NumberInput data-testid="input" /> // ); // act(() => { // getByTestId("input").focus(); // }); // act(() => { // userEvent.type(getByTestId("input"), "0.1"); // }); // await waitFor(() => expect(getByTestId("input")).toHaveValue(0.1)); // }); test("do not accept non numeric characters", async () => { const { getByTestId } = renderWithTheme( <NumberInput aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.type(getByTestId("input"), "a"); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(null)); act(() => { userEvent.type(getByTestId("input"), "$"); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(null)); }); test("increment value on increment button click", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput defaultValue={1} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Increment value")); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(2)); }); test("when a value has been entered, increment the entered value on increment button click", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.type(getByTestId("input"), "10"); }); act(() => { userEvent.click(getByLabelText("Increment value")); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(11)); }); test("decrement value on decrement button click", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput defaultValue={1} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Decrement value")); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(0)); }); test("when a value has been entered, decrement the entered value on decrement button click", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.type(getByTestId("input"), "10"); }); act(() => { userEvent.click(getByLabelText("Decrement value")); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(9)); }); test("when no value has been entered yet and the increment button is clicked, set value to 1", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Increment value")); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(1)); }); test("when no value has been entered yet and the decrement button is clicked, set value to -1", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Decrement value")); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(-1)); }); test("when a max value is specified, do not increment over the max value", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput defaultValue={1} max={2} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Increment value")); }); act(() => { userEvent.click(getByLabelText("Increment value")); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(2)); }); test("when a max value is specified and no value has been set yet, do not increment over the max value", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput max={0} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Increment value")); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(0)); }); test("when a min value is specified, do not decrement under the min value", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput defaultValue={5} min={4} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Decrement value")); }); act(() => { userEvent.click(getByLabelText("Decrement value")); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(4)); }); test("when a min value is specified and no value has been set yet, do not decrement under the max value", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput min={4} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Decrement value")); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(4)); }); test("when the entered value is lower than the min value, reset value to min value on blur", async () => { const { getByTestId } = renderWithTheme( <NumberInput min={3} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.type(getByTestId("input"), "2"); }); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(3)); }); test("when the entered value is greater than the max value, reset the value to the max value on blur", async () => { const { getByTestId } = renderWithTheme( <NumberInput max={1} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.type(getByTestId("input"), "2"); }); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("input")).toHaveValue(1)); }); test("when the entered value is equal to the min value, the decrement stepper is disabled", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput min={2} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); await waitFor(() => expect(getByLabelText("Decrement value")).not.toHaveAttribute("disabled")); act(() => { userEvent.type(getByTestId("input"), "2"); }); await waitFor(() => expect(getByLabelText("Decrement value")).toHaveAttribute("disabled")); }); test("when the entered value is equal to the max value, the increment stepper is disabled", async () => { const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput max={2} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); await waitFor(() => expect(getByLabelText("Increment value")).not.toHaveAttribute("disabled")); act(() => { userEvent.type(getByTestId("input"), "2"); }); await waitFor(() => expect(getByLabelText("Increment value")).toHaveAttribute("disabled")); }); test("when autofocus is true, the input is focused on render", async () => { const { getByTestId } = renderWithTheme( <NumberInput autoFocus aria-label="Label" data-testid="input" /> ); await waitFor(() => expect(getByTestId("input")).toHaveFocus()); }); test("when autofocus is true and the input is disabled, the input is not focused on render", async () => { const { getByTestId } = renderWithTheme( <NumberInput disabled autoFocus aria-label="Label" data-testid="input" /> ); await waitFor(() => expect(getByTestId("input")).not.toHaveFocus()); }); test("when autofocus is true and the input is readonly, the input is not focused on render", async () => { const { getByTestId } = renderWithTheme( <NumberInput readOnly autoFocus aria-label="Label" data-testid="input" /> ); await waitFor(() => expect(getByTestId("input")).not.toHaveFocus()); }); test("when autofocus is specified with a delay, the input is focused after the delay", async () => { const { getByTestId } = renderWithTheme( <NumberInput autoFocus={10} aria-label="Label" data-testid="input" /> ); expect(getByTestId("input")).not.toHaveFocus(); await waitFor(() => expect(getByTestId("input")).toHaveFocus()); }); test("when in a field, clicking on the field label focus the input", async () => { const { getByTestId } = renderWithTheme( <Field> <Label data-testid="label">Label</Label> <NumberInput aria-label="Label" data-testid="input" /> </Field> ); act(() => { userEvent.click(getByTestId("label")); }); await waitFor(() => expect(getByTestId("input")).toHaveFocus()); }); // ***** Api ***** test("call onChange when the value change", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <NumberInput onChange={handler} aria-label="Label" data-testid="input" /> ); act(() => { userEvent.type(getByTestId("input"), "2"); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything())); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); }); test("call onValueChange when the value change and the input lose focus", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <NumberInput onValueChange={handler} aria-label="Label" data-testid="input" /> ); act(() => { userEvent.type(getByTestId("input"), "2"); }); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything(), 2)); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); }); test("call onValueChange when the value is incremented", async () => { const handler = jest.fn(); const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput onValueChange={handler} defaultValue={1} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Increment value")); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything(), 2)); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); }); test("call onValueChange when the value is decremented", async () => { const handler = jest.fn(); const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput onValueChange={handler} defaultValue={1} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Decrement value")); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything(), 0)); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); }); test("call onFocus when the input receive focus", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <NumberInput onFocus={handler} defaultValue={1} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything())); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); }); test("do not call onFocus again when a spinner arrow is clicked", async () => { const handler = jest.fn(); const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput onFocus={handler} defaultValue={1} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Decrement value")); }); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); }); test("call onBlur when the input lose focus", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <NumberInput onBlur={handler} defaultValue={1} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handler).toHaveBeenLastCalledWith(expect.anything())); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); }); test("do not call onBlur when a spinner arrow is clicked", async () => { const handler = jest.fn(); const { getByTestId, getByLabelText } = renderWithTheme( <NumberInput onBlur={handler} defaultValue={1} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.click(getByLabelText("Decrement value")); }); await waitFor(() => expect(handler).not.toHaveBeenCalled()); }); test("can focus the input with the focus api", async () => { let refNode: HTMLElement = null; renderWithTheme( <NumberInput ref={node => { refNode = node; }} aria-label="Label" /> ); act(() => { refNode.focus(); }); await waitFor(() => expect(refNode).toHaveFocus()); }); test("when the entered value exceed the specified min or max value, onValueChange is called with the clamped value before onBlur is called", async () => { const handleValueChange = jest.fn(); // eslint-disable-next-line @typescript-eslint/no-empty-function const onBlur = () => { }; const { getByTestId } = renderWithTheme( <NumberInput onValueChange={handleValueChange} onBlur={onBlur} min={5} aria-label="Label" data-testid="input" /> ); act(() => { getByTestId("input").focus(); }); act(() => { userEvent.type(getByTestId("input"), "4"); }); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handleValueChange).toHaveBeenLastCalledWith(expect.anything(), 5)); await waitFor(() => expect(handleValueChange).toHaveBeenCalledTimes(1)); }); // ***** Refs ***** test("ref is a DOM element", async () => { const ref = createRef<HTMLElement>(); renderWithTheme( <NumberInput ref={ref} aria-label="Label" /> ); await waitFor(() => expect(ref.current).not.toBeNull()); await waitFor(() => expect(ref.current instanceof HTMLElement).toBeTruthy()); await waitFor(() => expect(ref.current.tagName).toBe("INPUT")); }); test("when using a callback ref, ref is a DOM element", async () => { let refNode: HTMLElement = null; renderWithTheme( <NumberInput ref={node => { refNode = node; }} aria-label="Label" /> ); await waitFor(() => expect(refNode).not.toBeNull()); await waitFor(() => expect(refNode instanceof HTMLElement).toBeTruthy()); await waitFor(() => expect(refNode.tagName).toBe("INPUT")); }); test("set ref once", async () => { const handler = jest.fn(); renderWithTheme( <NumberInput ref={handler} aria-label="Label" /> ); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); });
the_stack
import { AmbientLight, Box3, BufferAttribute, BufferGeometry, Color, DataTexture, HemisphereLight, Material, Matrix3, Mesh, MeshDepthMaterial, MeshLambertMaterial, MeshNormalMaterial, Object3D, Scene, Vector3, } from "three"; import SceneMesh from "./SceneParts/SceneMesh"; import SceneMaterial from "./SceneParts/SceneMaterial"; import SceneRoom from "./SceneParts/SceneRoom"; import SceneFurniture from "./SceneParts/SceneFurniture"; import BaseChunk from "./SceneParts/BaseParts/BaseChunk"; import BaseFurniture from "./SceneParts/BaseParts/BaseFurniture"; import CompositeFurniture from "./SceneParts/CompositeParts/CompositeFurniture"; import {MaterialData, MeshData, ModelData} from "./DataFormat"; import {fetchObj, fetchTexture} from "./Utils/Utils"; import createCamera from './CameraCreateor'; import {join} from "path"; import {Response} from "node-fetch"; const nodeFetch = require("node-fetch"); const BufferGeometryUtils = require("./ThirdLib/BufferGeometryUtils").BufferGeometryUtils; export interface ShapeRemoteSource { objUrls: Array<string>; textureUrls: Array<string>; } function toFetchAPI(remoteOrLocalFile: string, serverHost: any): string { return `http://${serverHost}/fetch?file=${remoteOrLocalFile}`; } async function fetchResourceFromRemoteOrLocal(jid: string, localSource: string, remoteSource: Array<string>, serverHost: string, fileName: string) { let fetchMethod; if ('texture.png' === fileName) fetchMethod = fetchTexture; else if ('raw_model.obj' === fileName) fetchMethod = fetchObj; else return undefined; const localFiles = localSource ? [join(localSource, jid, fileName)] : []; const remoteFiles = remoteSource ? remoteSource.map(e => e.replace('@{id}@', jid)) : []; const files = [...localFiles, ...remoteFiles]; for (const file of files) { const result = await fetchMethod(toFetchAPI(file, serverHost)); if (result) return result; } return undefined; } async function loadModelData(uid: string, sceneModelData: Map<string, ModelData>, furnitureScale: number, shapeLocalSource: string, shapeRemoteSource: ShapeRemoteSource, renderType: string, serverHost: string, entityMap: Map<string, BaseChunk | BaseFurniture | CompositeFurniture>, depthMaterial: MeshDepthMaterial, normalMaterial: MeshNormalMaterial) { const modelData = sceneModelData.get(uid) as ModelData; let objModel = await fetchResourceFromRemoteOrLocal(modelData.extendid, shapeLocalSource, shapeRemoteSource.objUrls, serverHost, 'raw_model.obj') as Object3D; if (objModel && objModel.children.length > 0) { let geometryArray: Array<any> = []; objModel.children.forEach((value) => { const meshValue = value as Mesh; if (furnitureScale !== 1) { const bGeometry = meshValue.geometry as BufferGeometry; const position = bGeometry.attributes.position.array; const newArray = new Float32Array(position.length); for (let index = 0; index < position.length; index++) { let value = position[index]; value *= furnitureScale; newArray[index] = value; } bGeometry.setAttribute("position", new BufferAttribute(newArray, 3)); } geometryArray.push(meshValue.geometry); }); const bufferGeometry = BufferGeometryUtils.mergeBufferGeometries(geometryArray, false); const model = modelData.geometry; model.status = 2; model.value = bufferGeometry; let material: Material | undefined; if (renderType === 'depth') { material = depthMaterial; } else if (renderType === 'normal') { material = normalMaterial; } else { let texture = await fetchResourceFromRemoteOrLocal(modelData.extendid, shapeLocalSource, shapeRemoteSource.textureUrls, serverHost, 'texture.png') as DataTexture; if (texture) { material = new MeshLambertMaterial({map: texture}); material.transparent = true; } } const instanceids = modelData.instanceids; for (let i = 0, j = instanceids.length; i < j; i++) { const instancedId = instanceids[i]; const baseFurniture = entityMap.get(instancedId) as BaseFurniture; baseFurniture.geometry = bufferGeometry; if (material) baseFurniture.material = material; } } } async function loadMaterialForMesh(materialData: MaterialData, shapeLocalSource: string, shapeRemoteSource: ShapeRemoteSource, serverHost: string, entityMap: Map<string, BaseChunk | BaseFurniture | CompositeFurniture>) { const material = new MeshLambertMaterial(); const colorData = materialData.color; const color = colorData.length > 0 ? new Color(colorData[0] / 255, colorData[1] / 255, colorData[2] / 255) : new Color(1, 1, 1); const opacity = colorData.length > 0 ? colorData[3] : 1; material.color = color; material.opacity = opacity; material.transparent = opacity < 1; const texture = await fetchResourceFromRemoteOrLocal(materialData.extendid, shapeLocalSource, shapeRemoteSource.textureUrls, serverHost, 'texture.png') as DataTexture; if (texture) { material.map = texture; if (materialData.UVTransform) { let uvTransformMatrix = new Matrix3(); uvTransformMatrix = uvTransformMatrix.fromArray(materialData.UVTransform); texture.matrixAutoUpdate = false; texture.updateMatrix(); texture.matrix = uvTransformMatrix; texture.needsUpdate = true; } } materialData.status = 2; materialData.value = material; const instanceids = materialData.instanceids; for (let i = 0, j = instanceids.length; i < j; i++) { const instancedId = instanceids[i]; const temp = entityMap.get(instancedId); if (temp) { const baseFurniture = temp as BaseChunk; baseFurniture.material = material; } } } function createSceneInternal(jsonData: any, shapeLocalSource: string, shapeRemoteSource: ShapeRemoteSource, view: string, camera: any, aspect: number, unit: string, hiddenMeshes: Array<string>, renderType: string, serverHost: string) { const furnitureScale = unit === 'cm' ? 0.01 : 1; const defaultGeometry: BufferGeometry = new BufferGeometry(), defaultMaterial: MeshLambertMaterial = new MeshLambertMaterial(), depthMaterial: MeshDepthMaterial = new MeshDepthMaterial(), normalMaterial: MeshNormalMaterial = new MeshNormalMaterial(); const loadingPromises: Array<Promise<any>> = []; const entityMap: Map<string, BaseChunk | BaseFurniture | CompositeFurniture> = new Map(); const sceneMesh = new SceneMesh(jsonData, hiddenMeshes); const sceneFurniture = new SceneFurniture(jsonData); const sceneMaterial = new SceneMaterial(jsonData); const scene = new Scene(); const sceneMeshBox: Box3 = new Box3(); const rooms = jsonData.scene.room as Array<any>; rooms.forEach((roomData) => { const room = new SceneRoom(); room.parse(roomData); const children = roomData.children as Array<any>; children.forEach((childData) => { const uid = childData.ref; const instanceid = childData.instanceid; let child: | BaseChunk | BaseFurniture | CompositeFurniture | null = null; let customData: MeshData | ModelData | null = null; if (sceneMesh.sceneMeshData.has(uid)) { customData = sceneMesh.sceneMeshData.get(uid) as MeshData; const materialId = customData.materialId; const materialData = sceneMaterial.materialData.get(materialId) as MaterialData; if ('color' === renderType && materialData) { const meshMat = materialData.value; const material = meshMat ? meshMat : defaultMaterial; child = new BaseChunk(customData.geometry, material); materialData.instanceids.push(instanceid); if (!meshMat && materialData.status === 0) { materialData.status = 1; loadingPromises.push(loadMaterialForMesh(materialData, shapeLocalSource, shapeRemoteSource, serverHost, entityMap)); } } else { const material: Material = 'depth' === renderType ? depthMaterial : ('normal' === renderType ? normalMaterial : defaultMaterial); child = new BaseChunk(customData.geometry, material); } sceneMeshBox.union(new Box3().setFromObject(child)); } else if (sceneFurniture.sceneModelData.has(uid)) { customData = sceneFurniture.sceneModelData.get(uid) as ModelData; const model = customData.geometry; const modelGeometry = model.value; const geometry = modelGeometry ? modelGeometry : defaultGeometry; child = new BaseFurniture(geometry, defaultMaterial); customData.instanceids.push(instanceid); if (!modelGeometry && model.status === 0) { model.status = 1; loadingPromises.push(loadModelData(uid, sceneFurniture.sceneModelData, furnitureScale, shapeLocalSource, shapeRemoteSource, renderType, serverHost, entityMap, depthMaterial, normalMaterial)); } child.parseCustomProp(customData); } if (child) { entityMap.set(instanceid, child); child.parse(childData); child.roomId = room.instanceid; room.add(child); if (child.entityType === "BaseFurniture") { // const fChild = child as BaseFurniture; // const category = fChild.category ? fChild.category : ""; // const lightTypes = SceneLights.getAllLightsType(); // lightTypes.forEach((light) => { // if (light.name === category) { // const pointLight = new PointLight(light.color, light.intensity, light.distance, light.decay); // pointLight.position.set(fChild.position.x, fChild.position.y, fChild.position.z); // room.add(pointLight); // } // }); } } }); room.updateMatrixWorld(true); scene.add(room); }); if ('color' === renderType) { scene.add(new AmbientLight(new Color(0xffffff), .3)); const hemisphereLight = new HemisphereLight(0xffffff, 0x000000, .8); hemisphereLight.position.set(0, sceneMeshBox.getSize(new Vector3()).y / 2, 0); scene.add(hemisphereLight); } const cameraInfo = createCamera(view, camera, sceneMeshBox, aspect); return {scene, ...cameraInfo, loadingPromises}; } export function createScene(houseLayoutFile: string, shapeLocalSource: string, shapeRemoteSource: ShapeRemoteSource, view: string, camera: any, aspect: number, unit: string, hiddenMeshes: Array<string>, renderType: string, serverHost: string) { return nodeFetch(`http://${serverHost}/fetch?file=${houseLayoutFile}`) .then((response: Response) => response.json()) .then((jsonData: any) => createSceneInternal(jsonData, shapeLocalSource, shapeRemoteSource, view, camera, aspect, unit, hiddenMeshes, renderType, serverHost)); }
the_stack
import * as vscode from "vscode"; import { Editors } from "./editors"; import { Modes } from "./modes"; import { Recorder } from "./recorder"; import { Register, Registers } from "./registers"; import { StatusBar } from "./status-bar"; import { Menu, validateMenu } from "../api"; import type { Commands } from "../commands"; import { extensionName } from "../utils/constants"; import { AutoDisposable } from "../utils/disposables"; import { assert, CancellationError } from "../utils/errors"; import { SettingsValidator } from "../utils/settings-validator"; // =============================================================================================== // == EXTENSION ================================================================================ // =============================================================================================== /** * Global state of the extension. */ export class Extension implements vscode.Disposable { // Misc. private readonly _configurationChangeHandlers = new Map<string, () => void>(); private readonly _subscriptions: vscode.Disposable[] = []; // Configuration. // ========================================================================== private readonly _gotoMenus = new Map<string, Menu>(); public get menus() { return this._gotoMenus as ReadonlyMap<string, Menu>; } // State. // ========================================================================== /** * `StatusBar` for this instance of the extension. */ public readonly statusBar = new StatusBar(); /** * `Registers` for this instance of the extension. */ public readonly registers = new Registers(); /** * `Modes` for this instance of the extension. */ public readonly modes = new Modes(this); /** * `Recorder` for this instance of the extension. */ public readonly recorder: Recorder; // Needs to be initialized later. /** * `Editors` for this instance of the extension. */ public readonly editors = new Editors(this); // Ephemeral state needed by commands. // ========================================================================== private _currentCount = 0; private _currentRegister?: Register; /** * The counter for the next command. */ public get currentCount() { return this._currentCount; } public set currentCount(count: number) { this._currentCount = count; if (count !== 0) { this.statusBar.countSegment.setContent(count.toString()); } else { this.statusBar.countSegment.setContent(); } } /** * The register to use in the next command. */ public get currentRegister() { return this._currentRegister; } public set currentRegister(register: Register | undefined) { this._currentRegister = register; if (register !== undefined) { this.statusBar.registerSegment.setContent(register.name); } else { this.statusBar.registerSegment.setContent(); } } public constructor(public readonly commands: Commands) { this.recorder = new Recorder(this); // Configuration: menus. this.observePreference<Record<string, Menu>>( ".menus", (value, validator, inspect) => { this._gotoMenus.clear(); if (typeof value !== "object" || value === null) { validator.reportInvalidSetting("must be an object"); return; } for (const menuName in value) { const menu = value[menuName], validationErrors = validateMenu(menu); if (validationErrors.length === 0) { if (!vscode.workspace.isTrusted) { const globalConfig = inspect.globalValue?.[menuName], defaultConfig = inspect.defaultValue?.[menuName]; if (globalConfig !== undefined || defaultConfig !== undefined) { // Menu is a global menu; make sure that the local workspace does // not override its items. for (const key in menu.items) { if (globalConfig !== undefined && key in globalConfig.items) { menu.items[key] = globalConfig.items[key]; } else if (defaultConfig !== undefined && key in defaultConfig.items) { menu.items[key] = defaultConfig.items[key]; } } } } this._gotoMenus.set(menuName, menu); } else { validator.enter(menuName); for (const error of validationErrors) { validator.reportInvalidSetting(error); } validator.leave(); } } }, true, ); this._subscriptions.push( // Update configuration automatically. vscode.workspace.onDidChangeConfiguration((e) => { for (const [section, handler] of this._configurationChangeHandlers.entries()) { if (e.affectsConfiguration(section)) { handler(); } } }), ); // Register all commands. for (const descriptor of Object.values(commands)) { this._subscriptions.push(descriptor.register(this)); } } /** * Disposes of the extension and all of its resources and subscriptions. */ public dispose() { this._cancellationTokenSource.cancel(); this._cancellationTokenSource.dispose(); this._autoDisposables.forEach((disposable) => disposable.dispose()); assert(this._autoDisposables.size === 0); this.statusBar.dispose(); } /** * Listen for changes to the specified preference and calls the given handler * when a change occurs. * * Must be called in the constructor. * * @param triggerNow If `true`, the handler will also be triggered immediately * with the current value. */ public observePreference<T>( section: string, handler: (value: T, validator: SettingsValidator, inspect: InspectType<T>) => void, triggerNow = false, ) { let configuration: vscode.WorkspaceConfiguration, fullName: string; if (section[0] === ".") { fullName = extensionName + section; section = section.slice(1); configuration = vscode.workspace.getConfiguration(extensionName); } else { fullName = section; configuration = vscode.workspace.getConfiguration(); } const defaultValue = configuration.inspect<T>(section)!.defaultValue!; this._configurationChangeHandlers.set(fullName, () => { const validator = new SettingsValidator(fullName), configuration = vscode.workspace.getConfiguration(extensionName); handler( configuration.get<T>(section, defaultValue), validator, handler.length > 2 ? configuration.inspect<T>(section)! : undefined!, ); validator.displayErrorIfNeeded(); }); if (triggerNow) { const validator = new SettingsValidator(fullName); handler( configuration.get(section, defaultValue), validator, handler.length > 2 ? configuration.inspect<T>(section)! : undefined!, ); validator.displayErrorIfNeeded(); } } // ============================================================================================= // == CANCELLATION =========================================================================== // ============================================================================================= private _cancellationTokenSource = new vscode.CancellationTokenSource(); private readonly _cancellationReasons = new WeakMap<vscode.CancellationToken, CancellationError.Reason>(); /** * The token for the next command. */ public get cancellationToken() { return this._cancellationTokenSource.token; } /** * The reason why the `cancellationToken` was cancelled. */ public cancellationReasonFor(token: vscode.CancellationToken) { return this._cancellationReasons.get(token); } /** * Requests the cancellation of the last operation. */ public cancelLastOperation(reason: CancellationError.Reason) { this._cancellationReasons.set(this._cancellationTokenSource.token, reason); this._cancellationTokenSource.cancel(); this._cancellationTokenSource.dispose(); this._cancellationTokenSource = new vscode.CancellationTokenSource(); } // ============================================================================================= // == DISPOSABLES ============================================================================ // ============================================================================================= private readonly _autoDisposables = new Set<AutoDisposable>(); /** * Returns an `AutoDisposable` bound to this extension. It is ensured that any * disposable added to it will be disposed of when the extension is unloaded. */ public createAutoDisposable() { const disposable = new AutoDisposable(); disposable.addDisposable({ dispose: () => this._autoDisposables.delete(disposable), }); this._autoDisposables.add(disposable); return disposable; } // ============================================================================================= // == ERRORS ================================================================================= // ============================================================================================= private _dismissErrorMessage?: () => void; private _lastErrorMessage?: string; /** * The last error message reported via `showDismissibleErrorMessage`. */ public get lastErrorMessage() { return this._lastErrorMessage; } /** * Dismisses a currently shown error message, if any. */ public dismissErrorMessage() { if (this._dismissErrorMessage !== undefined) { this._dismissErrorMessage(); this._dismissErrorMessage = undefined; } } /** * Displays a dismissible error message in the status bar. */ public showDismissibleErrorMessage(message: string) { // Log the error so that long error messages and stacktraces can still be // accessed by the user. this._lastErrorMessage = message; console.error(message); message = message.replace(/^error executing command "(.+?)": /, ""); if (this.statusBar.errorSegment.content !== undefined) { return this.statusBar.errorSegment.setContent(message); } this.statusBar.errorSegment.setContent(message); const dispose = () => { this.statusBar.errorSegment.setContent(); this._dismissErrorMessage = undefined; subscriptions.splice(0).forEach((d) => d.dispose()); }; const subscriptions = [ vscode.window.onDidChangeActiveTextEditor(dispose), vscode.window.onDidChangeTextEditorSelection(dispose), ]; this._dismissErrorMessage = dispose; } /** * Runs the given function, displaying an error message and returning the * specified value if it throws an exception during its execution. */ public runSafely<T>( f: () => T, errorValue: () => T, errorMessage: (error: any) => T extends Thenable<any> ? never : string, ) { this.dismissErrorMessage(); try { return f(); } catch (e) { if (!(e instanceof CancellationError)) { this.showDismissibleErrorMessage(errorMessage(e)); } return errorValue(); } } /** * Runs the given async function, displaying an error message and returning * the specified value if it throws an exception during its execution. */ public async runPromiseSafely<T>( f: () => Thenable<T>, errorValue: () => T, errorMessage: (error: any) => string, ) { this.dismissErrorMessage(); try { return await f(); } catch (e) { if (!(e instanceof CancellationError)) { this.showDismissibleErrorMessage(errorMessage(e)); } return errorValue(); } } } type InspectUnknown = Exclude<ReturnType<vscode.WorkspaceConfiguration["inspect"]>, undefined>; type InspectType<T> = { // Replace all properties that are `unknown` by `T | undefined`. readonly [K in keyof InspectUnknown]: (InspectUnknown[K] & null) extends never ? InspectUnknown[K] : T | undefined; }
the_stack
* Resources: * https://promisesaplus.com/ * https://github.com/kriskowal/q */ import Type from "../Types"; import {deferImmediate} from "../Threading/deferImmediate"; import {DisposableBase} from "../Disposable/DisposableBase"; import {InvalidOperationException} from "../Exceptions/InvalidOperationException"; import {ArgumentException} from "../Exceptions/ArgumentException"; import {ArgumentNullException} from "../Exceptions/ArgumentNullException"; import {ObjectPool} from "../Disposable/ObjectPool"; import {Set} from "../Collections/Set"; import {defer} from "../Threading/defer"; import {ObjectDisposedException} from "../Disposable/ObjectDisposedException"; import __extendsImport from "../../extends"; import {Closure, Selector} from "../FunctionTypes"; //noinspection JSUnusedLocalSymbols const __extends = __extendsImport; const VOID0:any = void 0, NULL:any = null, PROMISE = "Promise", PROMISE_STATE = PROMISE + "State", THEN = "then", TARGET = "target"; function isPromise<T>(value:any):value is PromiseLike<T> { return Type.hasMemberOfType(value, THEN, Type.FUNCTION); } export type Resolver = Selector<TSDNPromise.Resolution<any>,any> | null | undefined; function resolve<T>( value:TSDNPromise.Resolution<T>, resolver:Resolver, promiseFactory:(v:any) => PromiseBase<any>):PromiseBase<any> { let nextValue = resolver ? resolver(value) : value; return nextValue && isPromise(nextValue) ? TSDNPromise.wrap(nextValue) : promiseFactory(nextValue); } function handleResolution( p:TSDNPromise<any> | null | undefined, value:TSDNPromise.Resolution<any>, resolver?:Resolver):any { try { let v = resolver ? resolver(value) : value; if(p) { //noinspection JSIgnoredPromiseFromCall p.resolve(v); } return null; } catch(ex) { if(p) { //noinspection JSIgnoredPromiseFromCall p.reject(ex); } return ex; } } function handleResolutionMethods( targetFulfill:TSDNPromise.Fulfill<any, any> | null | undefined, targetReject:TSDNPromise.Reject<any> | null | undefined, value:TSDNPromise.Resolution<any>, resolver?:Resolver | null | undefined):void { try { let v = resolver ? resolver(value) : value; if(targetFulfill) targetFulfill(v); } catch(ex) { if(targetReject) targetReject(ex); } } function handleDispatch<T, TFulfilled = T, TRejected = never>( p:PromiseLike<T>, onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null, onRejected?:TSDNPromise.Reject<TRejected> | null):void { // noinspection SuspiciousInstanceOfGuard if(p instanceof PromiseBase) { p.doneNow(onFulfilled, onRejected); } else { p.then(<any>onFulfilled, onRejected); } } function handleSyncIfPossible<T, TFulfilled = T, TRejected = never>( p:PromiseLike<T>, onFulfilled:TSDNPromise.Fulfill<T, TFulfilled>, onRejected?:TSDNPromise.Reject<TRejected>):PromiseLike<TFulfilled | TRejected> { // noinspection SuspiciousInstanceOfGuard if(p instanceof PromiseBase) return p.thenSynchronous(onFulfilled, onRejected); else return p.then(onFulfilled, onRejected); } function newODE() { return new ObjectDisposedException("TSDNPromise", "An underlying promise-result was disposed."); } export class PromiseState<T> extends DisposableBase { constructor( protected _state:TSDNPromise.State, protected _result?:T, protected _error?:any) { super(PROMISE_STATE); } protected _onDispose():void { this._state = VOID0; this._result = VOID0; this._error = VOID0; } protected getState():TSDNPromise.State { return this._state; } get state():TSDNPromise.State { return this._state; } get isPending():boolean { return this.getState()===TSDNPromise.State.Pending; } get isSettled():boolean { return this.getState()!=TSDNPromise.State.Pending; // Will also include undefined==0 aka disposed!=resolved. } get isFulfilled():boolean { return this.getState()===TSDNPromise.State.Fulfilled; } get isRejected():boolean { return this.getState()===TSDNPromise.State.Rejected; } /* * Providing overrides allows for special defer or lazy sub classes. */ protected getResult():T | undefined { return this._result; } get result():T | undefined { this.throwIfDisposed(); return this.getResult(); } protected getError():any { return this._error; } get error():any { this.throwIfDisposed(); return this.getError(); } } export abstract class PromiseBase<T> extends PromiseState<T> implements PromiseLike<T>// , Promise<T> { //readonly [Symbol.toStringTag]: "Promise"; protected constructor() { super(TSDNPromise.State.Pending); // @ts-ignore this._disposableObjectName = PROMISE; } /** * .doneNow is provided as a non-standard means that synchronously resolves as the end of a promise chain. * As stated by promisejs.org: 'then' is to 'done' as 'map' is to 'forEach'. * It is the underlying method by which propagation occurs. * @param onFulfilled * @param onRejected */ abstract doneNow( onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null, onRejected?:TSDNPromise.Reject<any> | null):void; /** * Calls the respective handlers once the promise is resolved. * @param onFulfilled * @param onRejected */ abstract thenSynchronous<TFulfilled = T, TRejected = never>( onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null, onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected>; /** * Same as 'thenSynchronous' but does not return the result. Returns the current promise instead. * You may not need an additional promise result, and this will not create a new one. * @param onFulfilled * @param onRejected */ thenThis( onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null, onRejected?:TSDNPromise.Reject<any> | null):this { this.doneNow(onFulfilled, onRejected); return this; } /** * Standard .then method that defers execution until resolved. * @param onFulfilled * @param onRejected * @returns {TSDNPromise} */ then<TFulfilled = T, TRejected = never>( onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null, onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected> { this.throwIfDisposed(); return new TSDNPromise<TFulfilled | TRejected>((resolve, reject) => { this.doneNow( result => handleResolutionMethods(resolve, reject, result, onFulfilled), error => onRejected ? handleResolutionMethods(resolve, reject, error, onRejected) : reject(error) ); }); } /** * Same as .then but doesn't trap errors. Exceptions may end up being fatal. * @param onFulfilled * @param onRejected * @returns {TSDNPromise} */ thenAllowFatal<TFulfilled = T, TRejected = never>( onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null, onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected> { this.throwIfDisposed(); return new TSDNPromise<TFulfilled | TRejected>((resolve, reject) => { this.doneNow( result => resolve(<any>(onFulfilled ? onFulfilled(result) : result)), error => reject(onRejected ? onRejected(error) : error) ); }); } /** * .done is provided as a non-standard means that maps to similar functionality in other promise libraries. * As stated by promisejs.org: 'then' is to 'done' as 'map' is to 'forEach'. * @param onFulfilled * @param onRejected */ done( onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null, onRejected?:TSDNPromise.Reject<any> | null):void { defer(() => this.doneNow(onFulfilled, onRejected)); } /** * Will yield for a number of milliseconds from the time called before continuing. * @param milliseconds * @returns A promise that yields to the current execution and executes after a delay. */ delayFromNow(milliseconds:number = 0):PromiseBase<T> { this.throwIfDisposed(); return new TSDNPromise<T>( (resolve, reject) => { defer(() => { this.doneNow( v => resolve(v), e => reject(e)); }, milliseconds) }, true // Since the resolve/reject is deferred. ); } /** * Will yield for a number of milliseconds from after this promise resolves. * If the promise is already resolved, the delay will start from now. * @param milliseconds * @returns A promise that yields to the current execution and executes after a delay. */ delayAfterResolve(milliseconds:number = 0):PromiseBase<T> { this.throwIfDisposed(); if(this.isSettled) return this.delayFromNow(milliseconds); return new TSDNPromise<T>( (resolve, reject) => { this.doneNow( v => defer(() => resolve(v), milliseconds), e => defer(() => reject(e), milliseconds)) }, true // Since the resolve/reject is deferred. ); } /** * Shortcut for trapping a rejection. * @param onRejected * @returns {PromiseBase<TResult>} */ 'catch'<TResult = never>(onRejected:TSDNPromise.Reject<TResult>):PromiseBase<T | TResult> { return this.then(VOID0, onRejected) } /** * Shortcut for trapping a rejection but will allow exceptions to propagate within the onRejected handler. * @param onRejected * @returns {PromiseBase<TResult>} */ catchAllowFatal<TResult = never>(onRejected:TSDNPromise.Reject<TResult>):PromiseBase<T | TResult> { return this.thenAllowFatal(VOID0, onRejected) } /** * Shortcut to for handling either resolve or reject. * @param fin * @returns {PromiseBase<TResult>} */ 'finally'<TResult = never>(fin:() => TSDNPromise.Resolution<TResult>):PromiseBase<TResult> { return this.then(fin, fin); } /** * Shortcut to for handling either resolve or reject but will allow exceptions to propagate within the handler. * @param fin * @returns {PromiseBase<TResult>} */ finallyAllowFatal<TResult = never>(fin:() => TSDNPromise.Resolution<TResult>):PromiseBase<TResult> { return this.thenAllowFatal(fin, fin); } /** * Shortcut to for handling either resolve or reject. Returns the current promise instead. * You may not need an additional promise result, and this will not create a new one. * @param fin * @param synchronous * @returns {PromiseBase} */ finallyThis(fin:Closure, synchronous?:boolean):this { const f:Closure = synchronous ? fin : () => deferImmediate(fin); this.doneNow(f, f); return this; } } export abstract class Resolvable<T> extends PromiseBase<T> { doneNow( onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null, onRejected?:TSDNPromise.Reject<any> | null):void { this.throwIfDisposed(); switch(this.state) { case TSDNPromise.State.Fulfilled: if(onFulfilled) onFulfilled(this._result!); break; case TSDNPromise.State.Rejected: if(onRejected) onRejected(this._error); break; } } thenSynchronous<TFulfilled = T, TRejected = never>( onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null, onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected> { this.throwIfDisposed(); try { switch(this.state) { case TSDNPromise.State.Fulfilled: return onFulfilled ? resolve(this._result, onFulfilled, TSDNPromise.resolve) : <any>this; // Provided for catch cases. case TSDNPromise.State.Rejected: return onRejected ? resolve(this._error, onRejected, TSDNPromise.resolve) : <any>this; } } catch(ex) { return new Rejected<any>(ex); } throw new Error("Invalid state for a resolved promise."); } } /** * The simplest usable version of a promise which returns synchronously the resolved state provided. */ export abstract class Resolved<T> extends Resolvable<T> { protected constructor(state:TSDNPromise.State, result:T, error?:any) { super(); this._result = result; this._error = error; this._state = state; } } /** * A fulfilled Resolved<T>. Provided for readability. */ export class Fulfilled<T> extends Resolved<T> { constructor(value:T) { super(TSDNPromise.State.Fulfilled, value); } } /** * A rejected Resolved<T>. Provided for readability. */ export class Rejected<T> extends Resolved<T> { constructor(error:any) { super(TSDNPromise.State.Rejected, VOID0, error); } } /** * Provided as a means for extending the interface of other PromiseLike<T> objects. */ class PromiseWrapper<T> extends Resolvable<T> { constructor(private _target:PromiseLike<T>) { super(); if(!_target) throw new ArgumentNullException(TARGET); if(!isPromise(_target)) throw new ArgumentException(TARGET, "Must be a promise-like object."); _target.then( (v:T) => { this._state = TSDNPromise.State.Fulfilled; this._result = v; this._error = VOID0; this._target = VOID0; }, e => { this._state = TSDNPromise.State.Rejected; this._error = e; this._target = VOID0; }) } thenSynchronous<TFulfilled = T, TRejected = never>( onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null, onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected> { this.throwIfDisposed(); let t = this._target; if(!t) return super.thenSynchronous(onFulfilled, onRejected); return new TSDNPromise<TFulfilled | TRejected>((resolve, reject) => { handleDispatch(t, result => handleResolutionMethods(resolve, reject, result, onFulfilled), error => onRejected ? handleResolutionMethods(resolve, null, error, onRejected) : reject(error) ); }, true); } doneNow( onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null, onRejected?:TSDNPromise.Reject<any> | null):void { this.throwIfDisposed(); let t = this._target; if(t) handleDispatch(t, onFulfilled, onRejected); else super.doneNow(onFulfilled, onRejected); } protected _onDispose():void { super._onDispose(); this._target = VOID0; } } /** * This promise class that facilitates pending resolution. */ export class TSDNPromise<T> extends Resolvable<T> { private _waiting:IPromiseCallbacks<any>[] | null | undefined; /* * A note about deferring: * The caller can set resolveImmediate to true if they intend to initialize code that will end up being deferred itself. * This eliminates the extra defer that will occur internally. * But for the most part, resolveImmediate = false (the default) will ensure the constructor will not block. * * resolveUsing allows for the same ability but does not defer by default: allowing the caller to take on the work load. * If calling resolve or reject and a deferred response is desired, then use deferImmediate with a closure to do so. */ constructor( resolver?:TSDNPromise.Executor<T>, forceSynchronous:boolean = false) { super(); if(resolver) this.resolveUsing(resolver, forceSynchronous); } thenSynchronous<TFulfilled = T, TRejected = never>( onFulfilled:TSDNPromise.Fulfill<T, TFulfilled> | undefined | null, onRejected?:TSDNPromise.Reject<TRejected> | null):PromiseBase<TFulfilled | TRejected> { this.throwIfDisposed(); // Already fulfilled? if(this._state) return super.thenSynchronous(onFulfilled, onRejected); const p = new TSDNPromise<TFulfilled | TRejected>(); (this._waiting || (this._waiting = [])) .push(pools.PromiseCallbacks.init(onFulfilled, onRejected, p)); return p; } doneNow( onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null, onRejected?:TSDNPromise.Reject<any> | null):void { this.throwIfDisposed(); // Already fulfilled? if(this._state) return super.doneNow(onFulfilled, onRejected); (this._waiting || (this._waiting = [])) .push(pools.PromiseCallbacks.init(onFulfilled, onRejected)); } protected _onDispose() { super._onDispose(); this._resolvedCalled = VOID0; } // Protects against double calling. protected _resolvedCalled:boolean | undefined; resolveUsing( resolver:TSDNPromise.Executor<T>, forceSynchronous:boolean = false):void { if(!resolver) throw new ArgumentNullException("resolver"); if(this._resolvedCalled) throw new InvalidOperationException(".resolve() already called."); if(this.state) throw new InvalidOperationException("Already resolved: " + TSDNPromise.State[this.state]); this._resolvedCalled = true; let state = 0; const rejectHandler = (reason:any) => { if(state) { // Someone else's promise handling down stream could double call this. :\ console.warn(state== -1 ? "Rejection called multiple times" : "Rejection called after fulfilled."); } else { state = -1; this._resolvedCalled = false; this.reject(reason); } }; const fulfillHandler = (v:any) => { if(state) { // Someone else's promise handling down stream could double call this. :\ console.warn(state==1 ? "Fulfill called multiple times" : "Fulfill called after rejection."); } else { state = 1; this._resolvedCalled = false; this.resolve(v); } }; // There are some performance edge cases where there caller is not blocking upstream and does not need to defer. if(forceSynchronous) resolver(fulfillHandler, rejectHandler); else deferImmediate(() => resolver(fulfillHandler, rejectHandler)); } private _emitDisposalRejection(p:PromiseBase<any>):boolean { const d = p.wasDisposed; if(d) this._rejectInternal(newODE()); return d; } private _resolveInternal(result?:T | PromiseLike<T>):void { if(this.wasDisposed) return; // Note: Avoid recursion if possible. // Check ahead of time for resolution and resolve appropriately // noinspection SuspiciousInstanceOfGuard while(result instanceof PromiseBase) { let r:PromiseBase<T> = <any>result; if(this._emitDisposalRejection(r)) return; switch(r.state) { case TSDNPromise.State.Pending: r.doneNow( v => this._resolveInternal(v), e => this._rejectInternal(e) ); return; case TSDNPromise.State.Rejected: this._rejectInternal(r.error); return; case TSDNPromise.State.Fulfilled: result = r.result; break; } } if(isPromise(result)) { result.then( v => this._resolveInternal(v), e => this._rejectInternal(e) ); } else { this._state = TSDNPromise.State.Fulfilled; this._result = result; this._error = VOID0; const o = this._waiting; if(o) { this._waiting = VOID0; for(let c of o) { let {onFulfilled, promise} = c; pools.PromiseCallbacks.recycle(c); //let ex = handleResolution(<any>promise, result, onFulfilled); //if(!p && ex) console.error("Unhandled exception in onFulfilled:",ex); } o.length = 0; } } } private _rejectInternal(error:any):void { if(this.wasDisposed) return; this._state = TSDNPromise.State.Rejected; this._error = error; const o = this._waiting; if(o) { this._waiting = null; // null = finished. undefined = hasn't started. for(let c of o) { let {onRejected, promise} = c; pools.PromiseCallbacks.recycle(c); if(onRejected) { //let ex = handleResolution(promise, error, onRejected); //if(!p && ex) console.error("Unhandled exception in onRejected:",ex); } else if(promise) { //noinspection JSIgnoredPromiseFromCall promise.reject(error); } } o.length = 0; } } resolve(result?:T | PromiseLike<T>, throwIfSettled:boolean = false):void { this.throwIfDisposed(); if(<any>result==this) throw new InvalidOperationException("Cannot resolve a promise as itself."); if(this._state) { // Same value? Ignore... if(!throwIfSettled || this._state==TSDNPromise.State.Fulfilled && this._result===result) return; throw new InvalidOperationException("Changing the fulfilled state/value of a promise is not supported."); } if(this._resolvedCalled) { if(throwIfSettled) throw new InvalidOperationException(".resolve() already called."); return; } this._resolveInternal(result); } reject(error:any, throwIfSettled:boolean = false):void { this.throwIfDisposed(); if(this._state) { // Same value? Ignore... if(!throwIfSettled || this._state==TSDNPromise.State.Rejected && this._error===error) return; throw new InvalidOperationException("Changing the rejected state/value of a promise is not supported."); } if(this._resolvedCalled) { if(throwIfSettled) throw new InvalidOperationException(".resolve() already called."); return; } this._rejectInternal(error); } } /** * By providing an ArrayPromise we expose useful methods/shortcuts for dealing with array results. */ export class ArrayPromise<T> extends TSDNPromise<T[]> { /** * Simplifies the use of a map function on an array of results when the source is assured to be an array. * @param transform * @returns {PromiseBase<Array<any>>} */ map<U>(transform:(value:T) => U):ArrayPromise<U> { this.throwIfDisposed(); return new ArrayPromise<U>(resolve => { this.doneNow(result => resolve(result.map(transform))); }, true); } reduce( reduction:(previousValue:T, currentValue:T, i?:number, array?:T[]) => T, initialValue?:T):PromiseBase<T> reduce<U>( reduction:(previousValue:U, currentValue:T, i?:number, array?:T[]) => U, initialValue:U):PromiseBase<U> /** * Simplifies the use of a reduce function on an array of results when the source is assured to be an array. * @param reduction * @param initialValue * @returns {PromiseBase<any>} */ reduce<U>( reduction:(previousValue:U, currentValue:T, i?:number, array?:T[]) => U, initialValue?:U):PromiseBase<U> { return this .thenSynchronous(result => result.reduce(reduction, <any>initialValue)); } static fulfilled<T>(value:T[]):ArrayPromise<T> { return new ArrayPromise<T>(resolve => value, true); } } const PROMISE_COLLECTION = "PromiseCollection"; /** * A Promise collection exposes useful methods for handling a collection of promises and their results. */ export class PromiseCollection<T> extends DisposableBase { private readonly _source:PromiseLike<T>[]; constructor(source:PromiseLike<T>[] | null | undefined) { super(PROMISE_COLLECTION); this._source = source && source.slice() || []; } protected _onDispose() { super._onDispose(); this._source.length = 0; (<any>this)._source = null; } /** * Returns a copy of the source promises. * @returns {PromiseLike<PromiseLike<any>>[]} */ get promises():PromiseLike<T>[] { this.throwIfDisposed(); return this._source.slice(); } /** * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. * @returns {PromiseBase<any>} */ all():ArrayPromise<T> { this.throwIfDisposed(); return TSDNPromise.all(this._source); } /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @returns {PromiseBase<any>} A new Promise. */ race():PromiseBase<T> { this.throwIfDisposed(); return TSDNPromise.race(this._source); } /** * Returns a promise that is fulfilled with array of provided promises when all provided promises have resolved (fulfill or reject). * Unlike .all this method waits for all rejections as well as fulfillment. * @returns {PromiseBase<PromiseLike<any>[]>} */ waitAll():ArrayPromise<PromiseLike<T>> { this.throwIfDisposed(); return TSDNPromise.waitAll(this._source); } /** * Waits for all the values to resolve and then applies a transform. * @param transform * @returns {PromiseBase<Array<any>>} */ map<U>(transform:(value:T) => U):ArrayPromise<U> { this.throwIfDisposed(); return new ArrayPromise<U>(resolve => { this.all() .doneNow(result => resolve(result.map(transform))); }, true); } /** * Applies a transform to each promise and defers the result. * Unlike map, this doesn't wait for all promises to resolve, ultimately improving the async nature of the request. * @param transform * @returns {PromiseCollection<U>} */ pipe<U>(transform:(value:T) => U | PromiseLike<U>):PromiseCollection<U> { this.throwIfDisposed(); return new PromiseCollection<U>( this._source.map(p => handleSyncIfPossible(p, transform)) ); } reduce( reduction:(previousValue:T, currentValue:T, i?:number, array?:PromiseLike<T>[]) => T, initialValue?:T | PromiseLike<T>):PromiseBase<T> reduce<U>( reduction:(previousValue:U, currentValue:T, i?:number, array?:PromiseLike<T>[]) => U, initialValue:U | PromiseLike<U>):PromiseBase<U> /** * Behaves like array reduce. * Creates the promise chain necessary to produce the desired result. * @param reduction * @param initialValue * @returns {PromiseBase<PromiseLike<any>>} */ reduce<U>( reduction:(previousValue:U, currentValue:T, i?:number, array?:PromiseLike<T>[]) => U, initialValue?:U | PromiseLike<U>):PromiseBase<U> { this.throwIfDisposed(); return TSDNPromise.wrap<U>(this._source .reduce( ( previous:PromiseLike<U>, current:PromiseLike<T>, i:number, array:PromiseLike<T>[]) => handleSyncIfPossible(previous, (p:U) => handleSyncIfPossible(current, (c:T) => reduction(p, c, i, array))), isPromise(initialValue) ? initialValue : new Fulfilled(<any>initialValue) ) ); } } module pools { // export module pending // { // // // var pool:ObjectPool<Promise<any>>; // // function getPool() // { // return pool || (pool = new ObjectPool<Promise<any>>(40, factory, c=>c.dispose())); // } // // function factory():Promise<any> // { // return new Promise(); // } // // export function get():Promise<any> // { // var p:any = getPool().take(); // p.__wasDisposed = false; // p._state = Promise.State.Pending; // return p; // } // // export function recycle<T>(c:Promise<T>):void // { // if(c) getPool().add(c); // } // // } // // export function recycle<T>(c:PromiseBase<T>):void // { // if(!c) return; // if(c instanceof Promise && c.constructor==Promise) pending.recycle(c); // else c.dispose(); // } export module PromiseCallbacks { let pool:ObjectPool<IPromiseCallbacks<any>>; //noinspection JSUnusedLocalSymbols function getPool() { return pool || (pool = new ObjectPool<IPromiseCallbacks<any>>(40, factory, c => { c.onFulfilled = NULL; c.onRejected = NULL; c.promise = NULL; })); } function factory():IPromiseCallbacks<any> { return { onFulfilled: NULL, onRejected: NULL, promise: NULL } } export function init<T>( onFulfilled:TSDNPromise.Fulfill<T, any> | undefined | null, onRejected?:TSDNPromise.Reject<any> | undefined | null, promise?:TSDNPromise<any>):IPromiseCallbacks<T> { const c = getPool().take(); c.onFulfilled = onFulfilled || undefined; c.onRejected = onRejected || undefined; c.promise = promise; return c; } export function recycle<T>(c:IPromiseCallbacks<T>):void { getPool().add(c); } } } export module TSDNPromise { /** * The state of a promise. * https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md * If a promise is disposed the value will be undefined which will also evaluate (promise.state)==false. */ export enum State { Pending = 0, Fulfilled = 1, Rejected = -1 } Object.freeze(State); export type Resolution<TResult> = TResult | PromiseLike<TResult>; export interface Fulfill<T, TResult> { (value:T):Resolution<TResult>; } export interface Reject<TResult> { (reason:any):Resolution<TResult>; } export interface Then<T, TResult> { ( onfulfilled?:Fulfill<T, TResult> | undefined | null, onrejected?:Reject<TResult> | undefined | null):PromiseLike<TResult>; ( onfulfilled?:Fulfill<T, TResult> | undefined | null, onrejected?:Reject<void> | undefined | null):PromiseLike<TResult>; } export interface Executor<T> { ( resolve:(value?:T | PromiseLike<T>) => void, reject:(reason?:any) => void):void; } //noinspection JSUnusedGlobalSymbols export interface Factory { <T>(executor:Executor<T>):PromiseLike<T>; } export function factory<T>(e:Executor<T>):TSDNPromise<T> { return new TSDNPromise(e); } /** * Takes a set of promises and returns a PromiseCollection. * @param promises */ export function group<T>(promises:PromiseLike<T>[]):PromiseCollection<T> export function group<T>( promise:PromiseLike<T>, ...rest:PromiseLike<T>[]):PromiseCollection<T> export function group( first:PromiseLike<any> | PromiseLike<any>[], ...rest:PromiseLike<any>[]):PromiseCollection<any> { if(!first && !rest.length) throw new ArgumentNullException("promises"); return new PromiseCollection( ((first) instanceof (Array) ? first : [first]) .concat(rest) ); } /** * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. */ export function all<T>(promises:PromiseLike<T>[]):ArrayPromise<T> export function all<T>(promise:PromiseLike<T>, ...rest:PromiseLike<T>[]):ArrayPromise<T> export function all( first:PromiseLike<any> | PromiseLike<any>[], ...rest:PromiseLike<any>[]):ArrayPromise<any> { if(!first && !rest.length) throw new ArgumentNullException("promises"); let promises = ((first) instanceof (Array) ? first : [first]).concat(rest); // yay a copy! if(!promises.length || promises.every(v => !v)) return new ArrayPromise<any>( r => r(promises), true); // it's a new empty, reuse it. :| // Eliminate deferred and take the parent since all .then calls happen on next cycle anyway. return new ArrayPromise<any>((resolve, reject) => { let result:any[] = []; let len = promises.length; result.length = len; // Using a set instead of -- a number is more reliable if just in case one of the provided promises resolves twice. let remaining = new Set(promises.map((v, i) => i)); // get all the indexes... let cleanup = () => { reject = VOID0; resolve = VOID0; promises.length = 0; promises = VOID0; remaining.dispose(); remaining = VOID0; }; let checkIfShouldResolve = () => { let r = resolve; if(r && !remaining.count) { cleanup(); r(result); } }; let onFulfill = (v:any, i:number) => { if(resolve) { result[i] = v; remaining.remove(i); checkIfShouldResolve(); } }; let onReject = (e?:any) => { let r = reject; if(r) { cleanup(); r(e); } }; for(let i = 0; remaining && i<len; i++) { let p = promises[i]; if(p) p.then(v => onFulfill(v, i), onReject); else remaining.remove(i); checkIfShouldResolve(); } }); } /** * Returns a promise that is fulfilled with array of provided promises when all provided promises have resolved (fulfill or reject). * Unlike .all this method waits for all rejections as well as fulfillment. */ export function waitAll<T>(promises:PromiseLike<T>[]):ArrayPromise<PromiseLike<T>> export function waitAll<T>( promise:PromiseLike<T>, ...rest:PromiseLike<T>[]):ArrayPromise<PromiseLike<T>> export function waitAll( first:PromiseLike<any> | PromiseLike<any>[], ...rest:PromiseLike<any>[]):ArrayPromise<PromiseLike<any>> { if(!first && !rest.length) throw new ArgumentNullException("promises"); const promises = ((first) instanceof (Array) ? first : [first]).concat(rest); // yay a copy! if(!promises.length || promises.every(v => !v)) return new ArrayPromise<any>( r => r(promises), true); // it's a new empty, reuse it. :| // Eliminate deferred and take the parent since all .then calls happen on next cycle anyway. return new ArrayPromise<any>((resolve, reject) => { let len = promises.length; // Using a set instead of -- a number is more reliable if just in case one of the provided promises resolves twice. let remaining = new Set(promises.map((v, i) => i)); // get all the indexes... let cleanup = () => { reject = NULL; resolve = NULL; remaining.dispose(); remaining = NULL; }; let checkIfShouldResolve = () => { let r = resolve; if(r && !remaining.count) { cleanup(); r(promises); } }; let onResolved = (i:number) => { if(remaining) { remaining.remove(i); checkIfShouldResolve(); } }; for(let i = 0; remaining && i<len; i++) { let p = promises[i]; if(p) p.then(v => onResolved(i), e => onResolved(i)); else onResolved(i); } }); } /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param promises An array of Promises. * @returns A new Promise. */ export function race<T>(promises:PromiseLike<T>[]):PromiseBase<T> export function race<T>(promise:PromiseLike<T>, ...rest:PromiseLike<T>[]):PromiseBase<T> export function race( first:PromiseLike<any> | PromiseLike<any>[], ...rest:PromiseLike<any>[]):PromiseBase<any> { let promises = first && ((first) instanceof (Array) ? first : [first]).concat(rest); // yay a copy? if(!promises || !promises.length || !(promises = promises.filter(v => v!=null)).length) throw new ArgumentException("Nothing to wait for."); const len = promises.length; // Only one? Nothing to race. if(len==1) return wrap(promises[0]); // Look for already resolved promises and the first one wins. for(let i = 0; i<len; i++) { const p:any = promises[i]; if(p instanceof PromiseBase && p.isSettled) return p; } return new TSDNPromise((resolve, reject) => { let cleanup = () => { reject = NULL; resolve = NULL; promises.length = 0; promises = NULL; }; let onResolve = (r:(x:any) => void, v:any) => { if(r) { cleanup(); r(v); } }; let onFulfill = (v:any) => onResolve(resolve, v); let onReject = (e?:any) => onResolve(reject, e); for(let p of promises) { if(!resolve) break; p.then(onFulfill, onReject); } }); } // // race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>; /** * Creates a new resolved promise . * @returns A resolved promise. */ export function resolve():PromiseBase<void> /** * Creates a new resolved promise for the provided value. * @param value A value or promise. * @returns A promise whose internal state matches the provided promise. */ export function resolve<T>(value:T | PromiseLike<T>):PromiseBase<T>; export function resolve(value?:any):PromiseBase<any> { return isPromise(value) ? wrap(value) : new Fulfilled(value); } /** * Syntactic shortcut for avoiding 'new'. * @param resolver * @param forceSynchronous * @returns {TSDNPromise} */ export function using<T>( resolver:TSDNPromise.Executor<T>, forceSynchronous:boolean = false):PromiseBase<T> { return new TSDNPromise<T>(resolver, forceSynchronous); } /** * Takes a set of values or promises and returns a PromiseCollection. * Similar to 'group' but calls resolve on each entry. * @param resolutions */ export function resolveAll<T>(resolutions:Array<T | PromiseLike<T>>):PromiseCollection<T>; export function resolveAll<T>( promise:T | PromiseLike<T>, ...rest:Array<T | PromiseLike<T>>):PromiseCollection<T> export function resolveAll( first:any | PromiseLike<any> | Array<any | PromiseLike<any>>, ...rest:Array<any | PromiseLike<any>>):PromiseCollection<any> { if(!first && !rest.length) throw new ArgumentNullException("resolutions"); return new PromiseCollection( ((first) instanceof (Array) ? first : [first]) .concat(rest) .map((v:any) => resolve(v))); } /** * Creates a PromiseCollection containing promises that will resolve on the next tick using the transform function. * This utility function does not chain promises together to create the result, * it only uses one promise per transform. * @param source * @param transform * @returns {PromiseCollection<T>} */ export function map<T, U>(source:T[], transform:(value:T) => U):PromiseCollection<U> { return new PromiseCollection<U>( source.map(d => new TSDNPromise<U>((r, j) => { try { r(transform(d)); } catch(ex) { j(ex); } })) ); } /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ export function reject<T>(reason:T):PromiseBase<T> { return new Rejected<T>(reason); } /** * Takes any Promise-Like object and ensures an extended version of it from this module. * @param target The Promise-Like object * @returns A new target that simply extends the target. */ export function wrap<T>(target:T | PromiseLike<T>):PromiseBase<T> { if(!target) throw new ArgumentNullException(TARGET); // noinspection SuspiciousInstanceOfGuard return isPromise(target) ? (target instanceof PromiseBase ? target : new PromiseWrapper(target)) : new Fulfilled<T>(target); } /** * A function that acts like a 'then' method (aka then-able) can be extended by providing a function that takes an onFulfill and onReject. * @param then * @returns {PromiseWrapper<T>} */ export function createFrom<T>(then:Then<T, any>):PromiseBase<T> { if(!then) throw new ArgumentNullException(THEN); return new PromiseWrapper<T>({then: then}); } } interface IPromiseCallbacks<T> { onFulfilled?:TSDNPromise.Fulfill<T, any>; onRejected?:TSDNPromise.Reject<any>; promise?:TSDNPromise<any>; } export {TSDNPromise as Promise}; export default TSDNPromise;
the_stack
import { observable, action, runInAction } from 'mobx'; import { FsApi, Fs, getFS, File, Credentials, needsConnection, FileID } from '../services/Fs'; import { Deferred } from '../utils/deferred'; import { i18next } from '../locale/i18n'; import { getLocalizedError } from '../locale/error'; import { shell, ipcRenderer } from 'electron'; import { AppState } from './appState'; import { TSORT_METHOD_NAME, TSORT_ORDER } from '../services/FsSort'; export type TStatus = 'busy' | 'ok' | 'login' | 'offline'; export class FileState { /* observable properties start here */ @observable path = ''; previousPath: string; readonly files = observable<File>([]); readonly selected = observable<File>([]); // scroll position of fileCache: we need to restore it on // cache reload scrollTop = -1; // last element that was selected (ie: cursor position) selectedId: FileID = null; // element that's being edited editingId: FileID = null; @observable sortMethod: TSORT_METHOD_NAME = 'name'; @observable sortOrder: TSORT_ORDER = 'asc'; @observable server = ''; credentials: Credentials; @observable status: TStatus = 'ok'; @observable error = false; cmd = ''; // @observable // active = false; @observable isVisible = false; @observable viewId = -1; // history stuff history = observable<string>([]); @observable current = -1; @action setStatus(status: TStatus, error = false): void { this.status = status; this.error = error; } @action addPathToHistory(path: string): void { const keep = this.history.slice(0, this.current + 1); this.history.replace(keep.concat([path])); this.current++; } @action navHistory(dir = -1, force = false): Promise<string | void> { if (!this.history.length) { debugger; console.warn('attempting to nav in empty history'); return; } if (force) { debugger; } const history = this.history; const current = this.current; const length = history.length; let newCurrent = current + dir; if (newCurrent < 0) { newCurrent = 0; } else if (newCurrent >= length) { newCurrent = length - 1; } if (newCurrent === this.current) { return; } this.current = newCurrent; const path = history[newCurrent]; return this.cd(path, '', true, true).catch(() => { // whatever happens, we want switch to that folder this.updatePath(path, true); this.emptyCache(); }); // if (path !== this.path || force) { // // console.log('opening path from history', path); // this.cd(path, '', true, true); // } else { // console.warn('preventing endless loop'); // } } // /history /* fs API */ private api: FsApi; private fs: Fs; private prevFs: Fs; private prevApi: FsApi; private prevServer: string; private loginDefer: Deferred<void>; constructor(path: string, viewId = -1) { this.viewId = viewId; this.path = path; this.getNewFS(path); console.log('this.fs', this.fs); // console.log(`new FileState('${path}'') -> fs = ${this.fs.name}`); } private saveContext(): void { this.prevServer = this.server; this.prevApi = this.api; this.prevFs = this.fs; } private restoreContext(): void { this.freeFsEvents(); this.api = this.prevApi; this.bindFsEvents(); this.fs = this.prevFs; this.server = this.prevServer; } private bindFsEvents(): void { this.api.on('close', () => this.setStatus('offline')); // this.api.on('connect', () => this.setStatus('ok')); } private freeFsEvents(): void { if (this.api) { this.api.off(); } } onFSChange = (filename: string): void => { console.log('fsChanged', filename, this.isVisible); this.reload(); }; private getNewFS(path: string, skipContext = false): Fs { const newfs = getFS(path); if (newfs) { !skipContext && this.api && this.saveContext(); // we need to free events in any case this.freeFsEvents(); this.fs = newfs; this.api = new newfs.API(path, this.onFSChange); this.bindFsEvents(); } return newfs; } public getAPI(): FsApi { return this.api; } public getFS(): Fs { return this.fs; } @action private updatePath(path: string, skipHistory = false): void { this.previousPath = this.path; this.path = path; if (!skipHistory && this.status !== 'login') { this.addPathToHistory(path); this.scrollTop = 0; this.selectedId = null; this.editingId = null; } } @action revertPath(): void { // first revert fs/path this.restoreContext(); // only reload directory if connection hasn't been lost otherwise we enter // into an infinite loop if (this.api.isConnected()) { debugger; this.navHistory(0); this.setStatus('ok'); } } @action waitForConnection(): Promise<void> { if (!this.api) { debugger; } if (!this.api.isConnected()) { this.loginDefer = new Deferred(); // automatially reconnect if we got credentials if (this.api.loginOptions) { this.doLogin(); } else { // otherwise show login dialog this.setStatus('login'); } return this.loginDefer.promise; } else { this.setStatus('busy'); return Promise.resolve(); } } @action onLoginSuccess(): void { this.setStatus('ok'); this.loginDefer.resolve(); } @action async doLogin(server?: string, credentials?: Credentials): Promise<void> { console.log('logging in'); // this.status = 'busy'; if (server) { this.server = this.fs.serverpart(server); } try { await this.api.login(server, credentials); this.onLoginSuccess(); } catch (err) { const error = getLocalizedError(err); this.loginDefer.reject(error); } // .then(() => ).catch((err) => { // console.log('error while connecting', err); // }); return this.loginDefer.promise; } @action clearSelection(): void { this.selected.clear(); } @action reset(): void { this.clearSelection(); this.scrollTop = -1; this.selectedId = null; this.editingId = null; } @action setSort(sortMethod: TSORT_METHOD_NAME, sortOrder: TSORT_ORDER): void { this.sortMethod = sortMethod; this.sortOrder = sortOrder; } @action updateSelection(isSameDir: boolean): void { if (isSameDir) { const newSelection = []; // cache.selected contains files that can be outdated: // files may have been removed on reload // so we filter the list and remove outdated files. for (const selection of this.selected) { // use inode/dev to retrieve files that were selected before reload: // we cannot use fullname anymore since files may have been renamed const newFile = this.files.find( (file) => file.id.dev === selection.id.dev && file.id.ino === selection.id.ino, ); if (newFile) { newSelection.push(newFile); } } if ( this.selectedId && !this.files.find((file) => file.id.dev === this.selectedId.dev && file.id.ino === this.selectedId.ino) ) { this.selectedId = null; } // Do not change the selectedId here, we want to keep it if (newSelection.length) { const selectedFile = newSelection[newSelection.length - 1]; this.selected.replace(newSelection); this.selectedId = { ...selectedFile.id, }; } else { this.selected.clear(); this.selectedId = null; } } else { this.selected.clear(); this.selectedId = null; this.scrollTop = 0; } } @action setSelectedFile(file: File): void { console.log('setSelectedFile', file); if (file) { this.selectedId = { ...file.id, }; } else { this.selectedId = null; } } @action setEditingFile(file: File): void { console.log('setEditingFile', file); if (file) { this.editingId = { ...file.id, }; } else { this.editingId = null; } } reload(): void { if (this.status !== 'busy') { this.cd(this.path, '', true, true).catch(this.emptyCache); } } @action emptyCache = (): void => { this.files.clear(); this.clearSelection(); this.setStatus('ok', true); console.log('emptycache'); }; // eslint-disable-next-line @typescript-eslint/no-explicit-any handleError = (error: any): Promise<void> => { console.log('handleError', error); this.setStatus('ok'); const niceError = getLocalizedError(error); console.log('orignalCode', error.code, 'newCode', niceError.code); return Promise.reject(niceError); }; @action cd(path: string, path2 = '', skipHistory = false, skipContext = false): Promise<string> { // first updates fs (eg. was local fs, is now ftp) console.log('fileState: cd', path, this.path); if (this.path !== path) { if (this.getNewFS(path, skipContext)) { this.server = this.fs.serverpart(path); this.credentials = this.fs.credentials(path); } else { debugger; // this.navHistory(0); return Promise.reject({ message: i18next.t('ERRORS.CANNOT_READ_FOLDER', { folder: path }), code: 'NO_FS', }); } } return this.cwd(path, path2, skipHistory); } @action @needsConnection // changes current path and retrieves file list cwd(path: string, path2 = '', skipHistory = false): Promise<string> { const joint = path2 ? this.api.join(path, path2) : this.api.sanityze(path); this.cmd = 'cwd'; return this.api .cd(joint) .then((path) => { return this.list(path).then((files) => { runInAction(() => { const isSameDir = this.path === path; this.files.replace(files as File[]); this.updatePath(path, skipHistory); this.cmd = ''; // update the cache's selection, keeping files that were previously selected this.updateSelection(isSameDir); this.setStatus('ok'); }); return path; }); }) .catch((error) => { this.cmd = ''; console.log('error cd/list for path', joint, 'error was', error); this.setStatus('ok', true); const localizedError = getLocalizedError(error); //return Promise.reject(localizedError); throw localizedError; }); } @action @needsConnection async list(path: string): Promise<File[] | void> { return this.api.list(path, true).catch(this.handleError); } @action @needsConnection async rename(source: string, file: File, newName: string): Promise<string | void> { // // TODO: check for valid filenames // try { // await this.waitForConnection(); // } catch (err) { // return this.rename(source, file, newName); // } return this.api .rename(source, file, newName) .then((newName: string) => { runInAction(() => { file.fullname = newName; this.setStatus('ok'); }); return newName; }) .catch(this.handleError); } @action @needsConnection async exists(path: string): Promise<boolean | void> { // await this.waitForConnection(); return this.api .exists(path) .then((exists) => { runInAction(() => { this.setStatus('ok'); }); return exists; }) .catch(this.handleError); } @action @needsConnection async makedir(parent: string, dirName: string): Promise<string | void> { return this.api .makedir(parent, dirName) .then((newDir) => { runInAction(() => { this.setStatus('ok'); }); return newDir; }) .catch(this.handleError); } @action @needsConnection async delete(source: string, files: File[]): Promise<number | void> { return this.api .delete(source, files) .then((num) => { runInAction(() => { this.setStatus('ok'); }); return num; }) .catch(this.handleError); } @needsConnection async size(source: string, files: string[]): Promise<number | void> { // try { // await this.waitForConnection(); // } catch (err) { // return this.size(source, files); // } return this.api.size(source, files).catch(this.handleError); } async isDir(path: string): Promise<boolean> { await this.waitForConnection(); return this.api.isDir(path); } isDirectoryNameValid = (dirName: string): boolean => { return this.api.isDirectoryNameValid(dirName); }; join(path: string, path2: string): string { return this.api.join(path, path2); } async openFile(appState: AppState, cache: FileState, file: File): Promise<void> { try { const path = await appState.prepareLocalTransfer(cache, [file]); const error = await this.shellOpenFile(path); if (error !== false) { throw { message: i18next.t('ERRORS.SHELL_OPEN_FAILED', { path }), code: 'NO_CODE', }; } } catch (err) { return Promise.reject(err); } } async shellOpenFile(path: string): Promise<boolean> { console.log('need to open file', path); const error = await shell.openPath(path); return !!error; } openDirectory(file: { dir: string; fullname: string }): Promise<string | void> { return this.cd(file.dir, file.fullname).catch(this.handleError); } async openTerminal(path: string): Promise<boolean> { if (this.getFS().name === 'local') { const error: { code: number } = await ipcRenderer.invoke('openTerminal', path); return !!error; } } openParentDirectory(): void { if (!this.isRoot()) { const parent = { dir: this.path, fullname: '..' }; this.openDirectory(parent).catch(() => { this.updatePath(this.api.join(this.path, '..'), true); this.emptyCache(); }); } } isRoot(path = this.path): boolean { console.log('FileCache.isRoot', this.api ? path && this.api.isRoot(path) : false, this.api); return this.api ? path && this.api.isRoot(path) : false; } }
the_stack
import { ok, strictEqual } from "assert"; import { addComponent, addEntity, createWorld, entityExists, removeComponent } from "bitecs"; import { Transform } from "../../../src/engine/component/transform"; import { GameState } from "../../../src/engine/GameTypes"; import { createNetworkId, deserializeCreates, deserializeDeletes, deserializeTransformChanged, deserializeUpdatesChanged, getPeerIdFromNetworkId, getLocalIdFromNetworkId, remoteNetworkedQuery, Owned, Networked, ownedNetworkedQuery, serializeCreates, serializeDeletes, serializeTransformChanged, serializeUpdatesChanged, serializeTransformSnapshot, deserializeTransformSnapshot, serializeUpdatesSnapshot, deserializeUpdatesSnapshot, NetworkModule, } from "../../../src/engine/network/network.game"; import { createCursorView, readFloat32, readString, readUint32, readUint8, } from "../../../src/engine/allocator/CursorView"; import { mockGameState } from "../mocks"; import { getModule } from "../../../src/engine/module/module.common"; describe("Network Tests", () => { describe("networkId", () => { it("should #getPeerIdFromNetworkId()", () => { const nid = 0xfff0_000f; strictEqual(getPeerIdFromNetworkId(nid), 0x000f); }); it("should #getLocalIdFromNetworkId()", () => { const nid = 0xfff0_000f; strictEqual(getLocalIdFromNetworkId(nid), 0xfff0); }); // hack - remove for id layer it.skip("should #createNetworkId", () => { const state = { network: { peerId: "abc", peerIdToIndex: new Map([["abc", 0x00ff]]), localIdCount: 0x000f, removedLocalIds: [], }, } as unknown as GameState; const nid = createNetworkId(state); strictEqual(nid, 0x000f_00ff); }); }); describe("tranform serialization", () => { it("should #serializeTransformSnapshot()", () => { const writer = createCursorView(); const eid = 0; const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([1, 2, 3]); quaternion.set([4, 5, 6]); serializeTransformSnapshot(writer, eid); const reader = createCursorView(writer.buffer); const posX = readFloat32(reader); strictEqual(posX, 1); const posY = readFloat32(reader); strictEqual(posY, 2); const posZ = readFloat32(reader); strictEqual(posZ, 3); const rotX = readFloat32(reader); strictEqual(rotX, 4); const rotY = readFloat32(reader); strictEqual(rotY, 5); const rotZ = readFloat32(reader); strictEqual(rotZ, 6); }); it("should #deserializeTransformSnapshot()", () => { const writer = createCursorView(); const eid = 0; const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([1, 2, 3]); quaternion.set([4, 5, 6]); serializeTransformSnapshot(writer, eid); position.set([0, 0, 0]); quaternion.set([0, 0, 0]); const reader = createCursorView(writer.buffer); deserializeTransformSnapshot(reader, eid); strictEqual(position[0], 1); strictEqual(position[1], 2); strictEqual(position[2], 3); strictEqual(quaternion[0], 4); strictEqual(quaternion[1], 5); strictEqual(quaternion[2], 6); }); it("should #serializeTransformChanged() with all values", () => { const writer = createCursorView(); const eid = 0; const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([1, 2, 3]); quaternion.set([4, 5, 6]); serializeTransformChanged(writer, eid); const reader = createCursorView(writer.buffer); const changeMask = readUint8(reader); strictEqual(changeMask, 0b111111); const posX = readFloat32(reader); strictEqual(posX, 1); const posY = readFloat32(reader); strictEqual(posY, 2); const posZ = readFloat32(reader); strictEqual(posZ, 3); const rotX = readFloat32(reader); strictEqual(rotX, 4); const rotY = readFloat32(reader); strictEqual(rotY, 5); const rotZ = readFloat32(reader); strictEqual(rotZ, 6); }); it("should #serializeTransformChanged() with some values", () => { const writer = createCursorView(); const eid = 0; const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([0, 2, 0]); quaternion.set([4, 0, 6]); serializeTransformChanged(writer, eid); const reader = createCursorView(writer.buffer); const changeMask = readUint8(reader); strictEqual(changeMask, 0b00101010); // const posX = readFloat32(reader); // strictEqual(posX, 0); const posY = readFloat32(reader); strictEqual(posY, 2); // const posZ = readFloat32(reader); // strictEqual(posZ, 0); const quatX = readFloat32(reader); strictEqual(quatX, 4); // const rotY = readFloat32(reader); // strictEqual(rotY, 0); const quatZ = readFloat32(reader); strictEqual(quatZ, 6); }); it("should #deserializeTransformChanged() with all values", () => { const writer = createCursorView(); const eid = 1; const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([1, 2, 3]); quaternion.set([4, 5, 6]); serializeTransformChanged(writer, eid); position.set([0, 0, 0]); quaternion.set([0, 0, 0]); const reader = createCursorView(writer.buffer); deserializeTransformChanged(reader, eid); strictEqual(position[0], 1); strictEqual(position[1], 2); strictEqual(position[2], 3); strictEqual(quaternion[0], 4); strictEqual(quaternion[1], 5); strictEqual(quaternion[2], 6); strictEqual(quaternion[3], 0); }); it("should #deserializeTransformChanged() with some values", () => { const writer = createCursorView(); const eid = 1; const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([0, 2, 0]); quaternion.set([4, 0, 6]); serializeTransformChanged(writer, eid); position.set([0, 0, 0]); quaternion.set([0, 0, 0]); const reader = createCursorView(writer.buffer); deserializeTransformChanged(reader, eid); strictEqual(position[0], 0); strictEqual(position[1], 2); strictEqual(position[2], 0); strictEqual(quaternion[0], 4); strictEqual(quaternion[1], 0); strictEqual(quaternion[2], 6); strictEqual(quaternion[3], 0); }); }); describe("updates serialization", () => { it("should #serializeUpdatesSnapshot()", () => { const state = { world: createWorld() } as unknown as GameState; const writer = createCursorView(); const ents = Array(3) .fill(0) .map(() => addEntity(state.world)); ents.forEach((eid) => { addComponent(state.world, Transform, eid); const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([1, 2, 3]); quaternion.set([4, 5, 6]); addComponent(state.world, Networked, eid); Networked.networkId[eid] = eid; addComponent(state.world, Owned, eid); }); serializeUpdatesSnapshot([state, writer]); const reader = createCursorView(writer.buffer); const count = readUint32(reader); strictEqual(count, 3); ents.forEach((eid) => { const nid = Networked.networkId[eid]; strictEqual(nid, readUint32(reader)); const position = Transform.position[eid]; strictEqual(position[0], readFloat32(reader)); strictEqual(position[1], readFloat32(reader)); strictEqual(position[2], readFloat32(reader)); const quaternion = Transform.quaternion[eid]; strictEqual(quaternion[0], readFloat32(reader)); strictEqual(quaternion[1], readFloat32(reader)); strictEqual(quaternion[2], readFloat32(reader)); strictEqual(quaternion[3], readFloat32(reader)); }); }); it("should #deserializeUpdatesSnapshot()", () => { const state = mockGameState(); const network = getModule(state, NetworkModule); const writer = createCursorView(); const ents = Array(3) .fill(0) .map(() => addEntity(state.world)); ents.forEach((eid) => { addComponent(state.world, Transform, eid); const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([1, 2, 3]); quaternion.set([4, 5, 6]); addComponent(state.world, Networked, eid); Networked.networkId[eid] = eid; network.networkIdToEntityId.set(eid, eid); addComponent(state.world, Owned, eid); }); serializeUpdatesSnapshot([state, writer]); ents.forEach((eid) => { const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([0, 0, 0]); quaternion.set([0, 0, 0]); }); const reader = createCursorView(writer.buffer); deserializeUpdatesSnapshot([state, reader]); ents.forEach((eid) => { const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; strictEqual(position[0], 1); strictEqual(position[1], 2); strictEqual(position[2], 3); strictEqual(quaternion[0], 4); strictEqual(quaternion[1], 5); strictEqual(quaternion[2], 6); strictEqual(quaternion[3], 0); }); }); it("should #serializeUpdatesChanged()", () => { const state = { world: createWorld() } as unknown as GameState; const writer = createCursorView(); const ents = Array(3) .fill(0) .map(() => addEntity(state.world)); ents.forEach((eid) => { addComponent(state.world, Transform, eid); const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([1, 2, 3]); quaternion.set([4, 5, 6]); addComponent(state.world, Networked, eid); Networked.networkId[eid] = eid; addComponent(state.world, Owned, eid); }); serializeUpdatesChanged([state, writer]); const reader = createCursorView(writer.buffer); const count = readUint32(reader); strictEqual(count, 3); ents.forEach((eid) => { const nid = Networked.networkId[eid]; strictEqual(nid, readUint32(reader)); const changeMask = readUint8(reader); strictEqual(changeMask, 0b111111); const position = Transform.position[eid]; strictEqual(position[0], readFloat32(reader)); strictEqual(position[1], readFloat32(reader)); strictEqual(position[2], readFloat32(reader)); const quaternion = Transform.quaternion[eid]; strictEqual(quaternion[0], readFloat32(reader)); strictEqual(quaternion[1], readFloat32(reader)); strictEqual(quaternion[2], readFloat32(reader)); }); }); it("should #deserializeUpdatesChanged()", () => { const state = mockGameState(); const network = getModule(state, NetworkModule); const writer = createCursorView(); const ents = Array(3) .fill(0) .map(() => addEntity(state.world)); ents.forEach((eid) => { addComponent(state.world, Transform, eid); const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([1, 2, 3]); quaternion.set([4, 5, 6]); addComponent(state.world, Networked, eid); Networked.networkId[eid] = eid; network.networkIdToEntityId.set(eid, eid); addComponent(state.world, Owned, eid); }); serializeUpdatesChanged([state, writer]); ents.forEach((eid) => { const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; position.set([0, 0, 0]); quaternion.set([0, 0, 0]); }); const reader = createCursorView(writer.buffer); deserializeUpdatesChanged([state, reader]); ents.forEach((eid) => { const position = Transform.position[eid]; const quaternion = Transform.quaternion[eid]; strictEqual(position[0], 1); strictEqual(position[1], 2); strictEqual(position[2], 3); strictEqual(quaternion[0], 4); strictEqual(quaternion[1], 5); strictEqual(quaternion[2], 6); }); }); }); describe("creates serialization", () => { it("should #serializeCreates()", () => { const state = mockGameState(); const writer = createCursorView(); const ents = Array(3) .fill(0) .map(() => addEntity(state.world)); ents.forEach((eid) => { addComponent(state.world, Networked, eid); Networked.networkId[eid] = eid; addComponent(state.world, Owned, eid); }); strictEqual(ownedNetworkedQuery(state.world).length, 3); serializeCreates([state, writer]); const reader = createCursorView(writer.buffer); const count = readUint32(reader); strictEqual(count, 3); ents.forEach((eid) => { strictEqual(readUint32(reader), eid); strictEqual(readString(reader), "cube"); }); }); it("should #deserializeCreates()", () => { const state = mockGameState(); const network = getModule(state, NetworkModule); const writer = createCursorView(); const ents = Array(3) .fill(0) .map(() => addEntity(state.world)); ents.forEach((eid) => { addComponent(state.world, Networked, eid); Networked.networkId[eid] = eid; addComponent(state.world, Owned, eid); }); const localEntities = ownedNetworkedQuery(state.world); strictEqual(localEntities.length, 3); serializeCreates([state, writer]); const reader = createCursorView(writer.buffer); deserializeCreates([state, reader]); const remoteEntities = remoteNetworkedQuery(state.world); strictEqual(remoteEntities.length, 3); for (let i = 0; i < remoteEntities.length; i++) { const incomingEid = remoteEntities[i]; const outgoingEid = localEntities[i]; ok(incomingEid !== outgoingEid); strictEqual(Networked.networkId[incomingEid], outgoingEid); strictEqual(network.networkIdToEntityId.get(outgoingEid), incomingEid); } }); }); describe("deletes serialization", () => { it("should #serializeDeletes()", () => { const state = mockGameState(); const writer = createCursorView(); const ents = Array(3) .fill(0) .map(() => addEntity(state.world)); ents.forEach((eid) => { addComponent(state.world, Networked, eid); Networked.networkId[eid] = eid; addComponent(state.world, Owned, eid); }); strictEqual(ownedNetworkedQuery(state.world).length, 3); ents.forEach((eid) => { // todo: default removeComponent to not clear component data removeComponent(state.world, Networked, eid, false); }); serializeDeletes([state, writer]); const reader = createCursorView(writer.buffer); const count = readUint32(reader); strictEqual(count, 3); ents.forEach((eid) => { strictEqual(readUint32(reader), eid); }); }); it("should #deserializeDeletes()", () => { const state = mockGameState(); const writer = createCursorView(); const ents = Array(3) .fill(0) .map(() => addEntity(state.world)); ents.forEach((eid) => { addComponent(state.world, Networked, eid); Networked.networkId[eid] = eid; addComponent(state.world, Owned, eid); }); strictEqual(ownedNetworkedQuery(state.world).length, 3); serializeCreates([state, writer]); const reader = createCursorView(writer.buffer); deserializeCreates([state, reader]); const remoteEntities = remoteNetworkedQuery(state.world); strictEqual(remoteEntities.length, 3); ents.forEach((eid) => { removeComponent(state.world, Networked, eid, false); }); strictEqual(ownedNetworkedQuery(state.world).length, 0); // todo: make queue // strictEqual(deletedOwnedNetworkedQuery(state.world).length, 3); const writer2 = createCursorView(); serializeDeletes([state, writer2]); remoteEntities.forEach((eid) => { ok(entityExists(state.world, eid)); }); const reader2 = createCursorView(writer2.buffer); deserializeDeletes([state, reader2]); remoteEntities.forEach((eid) => { ok(!entityExists(state.world, eid)); }); }); }); });
the_stack
import util from 'somes'; import * as fs from 'somes/fs'; import * as child_process from 'child_process'; import keys from 'somes/keys'; import path from 'somes/path'; import paths from './paths'; import { exec } from 'somes/syscall'; const uglify = require('./uglify'); const base64_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'.split(''); const init_code = ` import { GUIApplication, Root, Indep, Text, _CVD } from 'ftr'; new GUIApplication({ multisample: 4 }).start( <Root> <Indep align="center" backgroundColor="#f00"> <Text value="Hello world" /> </Indep> </Root> ); `; const init_code2 = ` // import utils from 'somes'; console.log('When the package has only one file, TSC cannot be compiled. This should be a bug of TSC'); `; const init_editorconfig = ` # top-most EditorConfig file root = true # all files [*] indent_style = tab indent_size = 2 `; export const native_source = [ '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.swift', ]; export const native_header = [ '.h', '.hpp', '.hxx', ]; const skip_files = native_source.concat(native_header, [ '.gyp', '.gypi', ]); const init_tsconfig = { "compileOnSave": true, "compilerOptions": { "module": "commonjs", "target": "ES2018", "moduleResolution": "node", "sourceMap": false, "outDir": "out", "rootDir": ".", "baseUrl": ".", "declaration": true, "alwaysStrict": true, "allowJs": true, "checkJs": false, "strict": true, "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictPropertyInitialization": false, "emitDecoratorMetadata": false, "experimentalDecorators": true, "removeComments": true, "jsx": "react", "jsxFactory": "_CVD", // "typeRoots" : ["../libs"], // "types" : ["node", "lodash", "express"] }, "include": [ "**/*", ], "exclude": [ "out", "var", ".git", ".svn", "node_modules", "_.js", ] }; function resolveLocal(...args: string[]) { return path.fallbackPath(path.resolve(...args)); } function exec_cmd(cmd: string) { var r = child_process.spawnSync('sh', ['-c', cmd]); if (r.status != 0) { if (r.stdout.length) { console.log(r.stdout + ''); } if (r.stderr.length) { console.error(r.stderr + ''); } process.exit(0); } else { var rv = []; if (r.stdout.length) { rv.push(r.stdout); } if (r.stderr.length) { rv.push(r.stderr); } return rv.join('\n'); } } function parse_json_file(filename: string, strict?: boolean) { try { var str = fs.readFileSync(filename, 'utf-8'); if (strict) { return JSON.parse(str); } else { return eval('(\n' + str + '\n)'); } } catch (err) { err.message = filename + ': ' + err.message; throw err; } } function new_zip(cwd: string, sources: string[], target: string) { console.log('Out ', path.basename(target)); exec_cmd('cd ' + cwd + '; rm -r ' + target + '; zip ' + target + ' ' + sources.join(' ')); } function unzip(source: string, target: string) { exec_cmd('cd ' + target + '; unzip ' + source); } function copy_file(source: string, target: string) { fs.mkdirpSync( path.dirname(target) ); // 先创建目录 var rfd = fs.openSync(source, 'r'); var wfd = fs.openSync(target, 'w'); var size = 1024 * 100; // 100 kb var buff = Buffer.alloc(size); var len = 0; var hash = new Hash(); do { len = fs.readSync(rfd, buff, 0, size, null); fs.writeSync(wfd, buff, 0, len, null); hash.update_buff_with_len(buff, len); // 更新hash } while (len == size); fs.closeSync(rfd); fs.closeSync(wfd); return hash.digest(); } function read_file_text(pathname: string) { var buff = fs.readFileSync(pathname); var hash = new Hash(); hash.update_buff(buff); return { value: buff.toString('utf-8'), hash: hash.digest(), }; } export interface PackageJson extends Dict { name: string; main: string; version: string; description?: string; scripts?: Dict<string>; author?: Dict<string>; keywords?: string[]; license?: string; bugs?: Dict<string>; homepage?: string; devDependencies?: Dict<string>; dependencies?: Dict<string>; bin?: string; hash?: string; id?: string; app?: string; detach?: string | string[]; skip?: string | string[]; skipInstall?: boolean; minify?: boolean; } type PkgJson = PackageJson; class Hash { hash = 5381; update_str(input: string) { var hash = this.hash; for (var i = input.length - 1; i > -1; i--) { hash += (hash << 5) + input.charCodeAt(i); } this.hash = hash; } update_buff(input: Buffer) { var hash = this.hash; for (var i = input.length - 1; i > -1; i--) { hash += (hash << 5) + input[i]; } this.hash = hash; } update_buff_with_len(input: Buffer, len: number) { var hash = this.hash; for (var i = len - 1; i > -1; i--) { hash += (hash << 5) + input[i]; } this.hash = hash; } digest() { var value = this.hash & 0x7FFFFFFF; var retValue = ''; do { retValue += base64_chars[value & 0x3F]; } while ( value >>= 6 ); return retValue; } } class Package { private m_output_name = ''; private m_source = ''; private m_target_local = ''; private m_target_public = ''; private m_versions: Dict<string> = {}; private m_detach_file: string[] = []; private m_skip_file: string[] = []; private m_enable_minify = false; private m_tsconfig_outDir = ''; private m_host: FtrBuild; readonly json: PkgJson; private _console_log(tag: string, pathname: string, desc?: string) { console.log(tag, this.m_output_name + '/' + pathname, desc || ''); } constructor(host: FtrBuild, source_path: string, outputName: string, json: PkgJson) { this.m_host = host; this.m_source = source_path; this.json = json; this.m_output_name = outputName; this.m_target_local = this.m_host.target_local + '/' + outputName; this.m_target_public = this.m_host.target_public + '/' + outputName; this.m_skip_file = this._get_skip_files(this.json, outputName); this.m_detach_file = this._get_detach_files(this.json, outputName); host.outputs[outputName] = this; } // 获取跳过文件列表 // "name" pkg 名称 private _get_skip_files(pkg_json: PkgJson, name: string) { var self = this; var rev: string[] = []; if (pkg_json.skip) { if (Array.isArray(pkg_json.skip)) { rev = pkg_json.skip; } else { rev = [ String(pkg_json.skip) ]; } delete pkg_json.skip; } rev.push('tsconfig.json'); rev.push('binding.gyp'); rev.push('node_modules'); rev.push('out'); rev.push('versions.json'); var reg = new RegExp('^:?' + name + '$'); self.m_host.skip.forEach(function (src) { var ls = src.split('/'); if (reg.test(ls.shift() as string) && ls.length) { rev.push(ls.join('/')); } }); return rev; } // 获取分离文件列表 private _get_detach_files(pkg_json: PkgJson, name: string) { var self = this; var rev: string[] = []; if (pkg_json.detach) { if (Array.isArray(pkg_json.detach)) { rev = pkg_json.detach; } else { rev = [ String(pkg_json.detach) ]; } delete pkg_json.detach; } var reg = new RegExp('^:?' + name + '$'); self.m_host.detach.forEach(function (src) { var ls = src.split('/'); if (reg.test(ls.shift() as string) && ls.length) { rev.push(ls.join('/')); } }); return rev; } build() { var self = this; var source_path = self.m_source; var pkg_json = self.json; if ( pkg_json.hash ) { // 已经build过,直接拷贝到目标 self._copy_pkg(pkg_json, source_path); return; } var target_local_path = self.m_target_local; var target_public_path = self.m_target_public; if ( self.m_host.minify == -1 ) { // 使用package.json定义 // package.json 默认不启用 `minify` self.m_enable_minify = 'minify' in pkg_json ? !!pkg_json.minify : false; } else { self.m_enable_minify = !!self.m_host.minify; } fs.removerSync(target_local_path); fs.removerSync(target_public_path); fs.mkdirpSync(target_local_path); fs.mkdirpSync(target_public_path); // build tsc if (fs.existsSync(source_path + '/tsconfig.json')) { self.m_tsconfig_outDir = resolveLocal(self.m_host.target_local, '../tsc', self.m_output_name); exec_cmd(`cd ${source_path} && tsc --outDir ${self.m_tsconfig_outDir}`); } // each dir self._build_each_pkg_dir('', ''); var hash = new Hash(); for (var i in self.m_versions) { // 计算 version code hash.update_str(self.m_versions[i]); } pkg_json.hash = hash.digest(); var cur_pkg_versions = self.m_versions; var versions = { versions: cur_pkg_versions }; delete pkg_json.skipInstall; fs.writeFileSync(target_local_path + '/versions.json', JSON.stringify(versions, null, 2)); fs.writeFileSync(target_local_path + '/package.json', JSON.stringify(pkg_json, null, 2)); // rewrite package.json fs.writeFileSync(target_public_path + '/package.json', JSON.stringify(pkg_json, null, 2)); // rewrite package.json var pkg_files = ['versions.json']; for ( var i in versions.versions ) { if (versions.versions[i].charAt(0) != '.') pkg_files.push('"' + i + '"'); } new_zip(target_local_path, pkg_files, target_public_path + '/' + pkg_json.name + '.pkg'); } private _copy_js(source: string, target_local: string) { var self = this; var data = read_file_text(source); if ( self.m_enable_minify ) { var minify = uglify.minify(data.value, { toplevel: true, keep_fnames: false, mangle: { toplevel: true, reserved: [ '$' ], keep_classnames: true, }, output: { ascii_only: true }, }); if ( minify.error ) { var err = minify.error; err = new SyntaxError( `${err.message}\n` + `line: ${err.line}, col: ${err.col}\n` + `filename: ${source}` ); throw err; } data.value = minify.code; var hash = new Hash(); hash.update_str(data.value); data.hash = hash.digest(); } fs.mkdirpSync( path.dirname(target_local) ); // 先创建目录 fs.writeFileSync(target_local, data.value, 'utf8'); return data.hash; } private _write_string(pathname: string, content: string) { var self = this; var target_local = resolveLocal(self.m_target_local, pathname); // var target_public = resolveLocal(self.m_target_public, pathname); fs.mkdirpSync( path.dirname(target_local) ); // 先创建目录 fs.writeFileSync(target_local, content, 'utf8'); var hash = new Hash(); hash.update_str(content); // fs.cp_sync(target_local, target_public); self.m_versions[pathname] = hash.digest(); // 记录文件 hash } private _build_file(pathname: string) { var self = this; // 跳过文件 for (var i = 0; i < self.m_skip_file.length; i++) { var name = self.m_skip_file[i]; if ( pathname.indexOf(name) == 0 ) { // 跳过这个文件 self._console_log('Skip', pathname); return; } } var source = resolveLocal(self.m_source, pathname); var target_local = resolveLocal(self.m_target_local, pathname); var target_public = resolveLocal(self.m_target_public, pathname); var extname = path.extname(pathname).toLowerCase(); var is_detach = false; var hash = ''; if (skip_files.indexOf(extname) != -1) { return; // skip native file } for (var i = 0; i < self.m_detach_file.length; i++) { var name = self.m_detach_file[i]; if (pathname.indexOf(name) === 0) { is_detach = true; // 分离这个文件 break; } } switch (extname) { case '.js': self._console_log('Out ', pathname); if (self.m_tsconfig_outDir) { if (fs.existsSync(self.m_tsconfig_outDir + '/' + pathname)) source = self.m_tsconfig_outDir + '/' + pathname; } hash = self._copy_js(source, target_local); break; case '.ts': case '.tsx': case '.jsx': if (pathname.substr(-2 - extname.length, 2) == '.d') { // typescript define self._console_log('Copy', pathname); hash = copy_file(source, target_local); } else if (self.m_tsconfig_outDir) { pathname = pathname.substr(0, pathname.length - extname.length) + '.js'; target_local = resolveLocal(self.m_target_local, pathname); target_public = resolveLocal(self.m_target_public, pathname); hash = self._copy_js(self.m_tsconfig_outDir + '/' + pathname, target_local); } else { self._console_log('Ignore', pathname, 'No tsconfig.json'); return; } break; case '.keys': self._console_log('Out ', pathname); var {hash,value} = read_file_text(source); var keys_data = null; try { keys_data = keys.parse(value); } catch(err) { console.error('Parse keys file error: ' + source); throw err; } fs.mkdirpSync( path.dirname(target_local) ); // 先创建目录 fs.writeFileSync(target_local, keys.stringify(keys_data), 'utf8'); break; default: self._console_log('Copy', pathname); hash = copy_file(source, target_local); break; } if ( is_detach ) { fs.cp_sync(target_local, target_public); hash = '.' + hash; // Separate files with "." before hash } self.m_versions[pathname] = hash; // 记录文件 hash } private _build_each_pkg_dir(pathname: string, basename: string) { var self = this; var dir = resolveLocal(self.m_source, pathname); if (self.m_tsconfig_outDir == dir) { // skip ts out dir if (self.m_tsconfig_outDir != self.m_source) { // no skip root source return; } } if (basename == 'node_modules') { var pkgs: Dict<PkgJson> = {}; var ok = false; for (var stat of fs.listSync(dir)) { var pkg_path = dir + '/' + stat.name; if (stat.isDirectory() && fs.existsSync( pkg_path + '/package.json')) { var pkg = self.m_host.solve(pkg_path, true) as Package; var symlink = path.relative(`${self.m_target_local}/${pathname}`, `${self.m_host.target_local}/${pkg.m_output_name}`); self._write_string(pathname + '/' + pkg.json.name + '.link', symlink); pkgs[pkg.json.name] = pkg.json; pkg.json.symlink = symlink; ok = true; } } if (ok) self._write_string(pathname + '/packages.json', JSON.stringify(pkgs, null, 2)); } else { for (var stat of fs.listSync(dir)) { if (stat.name[0] != '.' || !self.m_host.ignore_hide) { var basename = stat.name; let path = pathname ? pathname + '/' + basename : basename; if ( stat.isFile() ) { self._build_file(path); } else if ( stat.isDirectory() ) { self._build_each_pkg_dir(path, basename); } } } } } private _copy(source: string, target: string) { fs.cp_sync(source, target, { ignore_hide: this.m_host.ignore_hide }); } private _copy_pkg(pkg_json: PkgJson, source: string) { var self = this; util.assert(pkg_json.hash, 'Error'); var name = pkg_json.name; var target_local_path = self.m_target_local + '/' + name; var target_public_path = self.m_target_public + '/' + name; var pkg_path = source + '/' + name + '.pkg'; // copy to ramote self._copy(source, target_public_path); // copy to local self._copy(source, target_local_path); if ( fs.existsSync(pkg_path) ) { // local 有.pkg // unzip .pkg unzip(pkg_path, target_local_path); fs.removerSync(target_local_path + '/' + name + '.pkg'); } else { // public 没有.pkg文件 var versions = parse_json_file(source + '/versions.json'); var pkg_files = ['versions.json']; for ( var i in versions.versions ) { if (versions.versions[i].charAt(0) != '.') { pkg_files.push('"' + i + '"'); fs.removerSync(target_public_path + '/' + i); } } new_zip(source, pkg_files, target_public_path + '/' + name + '.pkg'); fs.removerSync(target_public_path + '/versions.json'); fs.cp_sync(source + '/package.json', target_public_path + '/package.json'); } } } export default class FtrBuild { readonly source: string; readonly target_local: string; readonly target_public: string; readonly outputs: Dict<Package>= {}; ignore_hide = true; // 忽略隐藏文件 minify = -1; // 缩小与混淆js代码,-1表示使用package.json定义 skip: string[] = [];// 跳过文件列表 detach: string[] = []; // 分离文件列表 constructor(source: string, target: string) { this.source = resolveLocal(source); this.target_local = resolveLocal(target, 'install'); this.target_public = resolveLocal(target, 'public'); util.assert(fs.existsSync(this.source), `Build source does not exist ,${this.source}`); util.assert(fs.statSync(this.source).isDirectory()); } private _copy_outer_file(items: Dict<string>) { var self = this; for (var source in items) { var target = items[source] || source; console.log('Copy', source); fs.cp_sync(self.source + '/' + source, self.target_local + '/' + target, { ignore_hide: self.ignore_hide }); } } solve(pathname: string, hasFullname?: boolean) { var self = this; var source_path = resolveLocal(pathname); // ignore network pkg if ( /^https?:\/\//i.test(source_path) ) { return null; } var pkg_json: PkgJson | null = null; var __ = ()=>{ if (!pkg_json) { pkg_json = parse_json_file(source_path + '/package.json') as PkgJson; } return pkg_json; }; var outputName = hasFullname ? __().name + '@' + __().version: path.basename(source_path); var pkg = self.outputs[outputName]; if ( !pkg ) { // Already complete pkg = new Package(this, source_path, outputName, __()); pkg.build(); } return pkg; } private _build_result() { var self = this; var result: Dict<PkgJson> = {}; var ok = 0; for ( var name in self.outputs ) { result[name] = self.outputs[name].json; ok = 1; } if ( ok ) { fs.writeFileSync(self.target_public + '/packages.json', JSON.stringify(result, null, 2)); console.log('build ok'); } else { console.log('No package build'); } } async install_depe() { var self = this; var keys_path = self.source + '/proj.keys'; if ( !fs.existsSync(keys_path) ) return []; var proj = keys.parseFile( keys_path ); var apps = []; for (var key in proj) { if (key == '@apps') { for (var name in proj['@apps']) { apps.push(name); } } } try { // npm install console.log(`Install dependencies ...`); fs.writeFileSync('package.json', '{}'); process.stdin.resume(); var r = await exec(`npm install ${apps.map(e=>'./'+e).join(' ')} --save=. --only=prod --ignore-scripts`, { stdout: process.stdout, stderr: process.stderr, stdin: process.stdin, }); process.stdin.pause(); util.assert(r.code === 0); if (!fs.existsSync('node_modules/@types/ftr')) { // copy @types fs.cp_sync(paths.types, this.source + '/node_modules/@types'); } } finally { fs.removerSync('package-lock.json'); fs.removerSync('package.json'); apps.map(e=>'node_modules/' + e) .forEach(e => fs.existsSync(e)&&fs.unlinkSync(e)); // delete uselse file } return apps; } async build() { var self = this; fs.mkdirpSync(this.target_local); fs.mkdirpSync(this.target_public); var keys_path = self.source + '/proj.keys'; if ( !fs.existsSync(keys_path) ) { // No exists proj.keys file // build pkgs // scan each current target directory fs.listSync(self.source).forEach(function(stat) { if ( stat.name[0] != '.' && stat.isDirectory() && fs.existsSync( self.source + '/' + stat.name + '/package.json' ) ) { self.solve(self.source + '/' + stat.name); } }); self._build_result(); return; } var keys_object = keys.parseFile( keys_path ); for (var key in keys.parseFile( keys_path )) { if (key == '@copy') { self._copy_outer_file(keys_object['@copy']); } } var apps = await this.install_depe(); // build application node_modules var node_modules = self.source + '/node_modules'; if ( fs.existsSync(node_modules) && fs.statSync(node_modules).isDirectory() ) { fs.listSync(node_modules).forEach(function(stat) { var source = node_modules + '/' + stat.name; if ( stat.isDirectory() && fs.existsSync(source + '/package.json') ) { self.solve(source); } }); } // build apps for (var app of apps) { self.solve(self.source + '/' + app); } self._build_result(); } /** * @func initialize() init project directory and add examples */ initialize() { var self = this; var project_name = path.basename(process.cwd()) || 'ftrproj'; var proj_keys = this.source + '/proj.keys'; var proj: Dict = { '@projectName': project_name }; var default_modules = paths.default_modules; if ( default_modules && default_modules.length ) { var pkgs_dirname = this.source + '/node_modules'; fs.mkdir_p_sync(pkgs_dirname); // create pkgs dir // copy default pkgs default_modules.forEach(function(pkg) { var pathname = pkgs_dirname + '/' + path.basename(pkg); if ( !fs.existsSync(pathname) ) { // if no exists then copy fs.cp_sync(pkg, pathname); // copy pkgs } }); } if (!fs.existsSync(`${self.source}/.gitignore`)) { fs.writeFileSync(`${self.source}/.gitignore`, ['out', 'node_modules'].join('\n')); } if (!fs.existsSync(`${self.source}/.editorconfig`)) { fs.writeFileSync(`${self.source}/.editorconfig`, init_editorconfig); } if (fs.existsSync(proj_keys)) { // 如果当前目录存在proj.keys文件附加到当前 proj = Object.assign(proj, keys.parseFile(proj_keys)); } else { proj['@apps'] = {}; if (!fs.existsSync(project_name)) { var json = { name: project_name, app: project_name, id: `org.ftr.${project_name}`, main: 'index.js', types: 'index.d.ts', version: '1.0.0', }; init_tsconfig.compilerOptions.outDir = 'out/' + project_name; fs.mkdirSync(project_name); fs.writeFileSync(project_name + '/package.json', JSON.stringify(json, null, 2)); fs.writeFileSync(project_name + '/index.tsx', init_code); fs.writeFileSync(project_name + '/test.ts', init_code2); fs.writeFileSync(project_name + '/tsconfig.json', JSON.stringify(init_tsconfig, null, 2)); } if (!fs.existsSync('examples')) { // copy examples pkg fs.cp_sync(paths.examples, this.source + '/examples'); } proj['@projectName'] = project_name; if (fs.existsSync('examples/package.json')) { proj['@apps']['examples'] = ''; } if (!fs.existsSync('node_modules/@types/ftr')) { // copy @types fs.cp_sync(paths.types, this.source + '/node_modules/@types'); } if (fs.existsSync(project_name + '/package.json')) { proj['@apps'][project_name] = ''; } } // write new proj.keys fs.writeFileSync(proj_keys, keys.stringify(proj)); } }
the_stack
module TDev.RT { export enum SpriteType { Ellipse, Rectangle, Text, Picture, Anchor, } class SpriteContent extends RTValue { constructor() { super() } } //? A sprite //@ icon("fa-rocket") ctx(general,gckey) export class Sprite extends RTValue { public _parent : Board = undefined; public _sheet: SpriteSheet = undefined; public _bubble: Sprite = undefined; private _friction : number = Number.NaN; private _angular_speed : number = 0; public _height : number = undefined; public _location : Location_ = undefined; private _angle : number = 0; public _elasticity : number = 1; public _scale: number = 1; public _shadowBlur: number; public _shadowColor: Color; public _shadowOffsetX: number; public _shadowOffsetY: number; constructor() { super() } private _speed : Vector2 = Vector2.mk(0,0); private _acceleration : Vector2 = Vector2.mk(0,0); public _width : number = undefined; private _mass : number = Number.NaN; public _position : Vector2 = Vector2.mk(0,0); private _color: Color = Colors.light_gray(); private _background: Color = undefined; private _text : string = undefined; private _textBaseline : string = undefined; public _hidden : boolean = false; private _opacity : number = 1; private _clip: number[] = undefined; private _gradient = true; public spriteType : SpriteType; public fontSize : number; private _picture : Picture; private _animations : SpriteAnimation[]; private shapeDirty = true; private hasChanged = true; /// <summary> /// Produced at each step by the wall collision /// Used in the next step to clip forces (reactive forces) /// </summary> public normalTouchPoints : Vector2[] = []; private _lastPosition : Vector2 ; // used in redraw, no serialization private _springs : Spring[] = []; /// <summary> /// newPosition, newSpeed, and midSpeed, newRotation are only used during an update step and need not be serialized /// </summary> public newPosition : Vector2; public newSpeed : Vector2; public midSpeed : Vector2; private newRotation : number; /// <summary> /// Recomputed on demand /// </summary> public boundingMinX : number; public boundingMaxX : number; public boundingMinY : number; public boundingMaxY : number; /// events public onTap: Event_ = new Event_(); public onSwipe: Event_ = new Event_(); public onDrag: Event_ = new Event_(); public onTouchDown: Event_ = new Event_(); public onTouchUp: Event_ = new Event_(); public onEveryFrame: Event_ = new Event_(); static mk(tp:SpriteType, x:number, y:number, w:number, h:number) { var s = new Sprite(); s.spriteType = tp; s._width = w; s._height = h; s._position = new Vector2(x, y); s.computeBoundingBox(); return s; } //? Gets the fraction of speed loss between 0 and 1 //@ readsMutable public friction(): number { if (!this._parent) return NaN; if (isNaN(this._friction)) return this._parent._worldFriction; return this._friction; } //? Sets the shadow information //@ writesMutable [blur].defl(20) [x_offset].defl(5) [y_offset].defl(5) [color].deflExpr('colors->gray') public set_shadow(blur: number, color: Color, x_offset : number, y_offset: number) { this._shadowBlur = blur; this._shadowColor = color; this._shadowOffsetX = x_offset; this._shadowOffsetY = y_offset; } //? Sets the friction to a fraction of speed loss between 0 and 1 //@ writesMutable public set_friction(friction:number) : void { this._friction = Math.min(1, Math.abs(friction)); } //? Gets the scaling applied when rendering the sprite. This scaling does not influence the bounding box. //@ readsMutable public scale() : number { return this._scale; } //? Sets the scaling applied to the sprite on rendering. This scaling does not influence the bounding box. //@ writesMutable [value].defl(1) public set_scale(value : number) { this._scale = value; } //? Gets the rotation speed in degrees/sec //@ readsMutable public angular_speed() : number { return this._angular_speed; } //? Sets the rotation speed in degrees/sec //@ writesMutable public set_angular_speed(speed:number) : void { this._angular_speed = speed; } //? Gets the height in pixels public height() : number { return this._height; } //? Gets the geo location assigned to the sprite //@ readsMutable public location() : Location_ { return this._location; } //? Sets the geo location of the sprite //@ cap(motion) flow(SourceGeoLocation) //@ writesMutable public set_location(location:Location_) : void { this._location = location; } //? Gets the angle of the sprite in degrees //@ readsMutable public angle() : number { return this._angle; } //? Sets the angle of the sprite in degrees //@ writesMutable public set_angle(angle:number) : void { if(this._angle != angle) { this._angle = angle; this.computeBoundingBox(); this.contentChanged(); } } //? Gets the sprite elasticity as a fraction of speed preservation per bounce (0-1) //@ readsMutable public elasticity() : number { return this._elasticity; } //? Sets the sprite elasticity as a fraction of speed preservation per bounce (0-1) //@ writesMutable public set_elasticity(elasticity:number) : void { this._elasticity = Math.abs(elasticity); } //? Gets the speed along x in pixels/sec //@ readsMutable public speed_x() : number { return this._speed.x(); } //? Sets the x speed in pixels/sec //@ writesMutable public set_speed_x(vx:number) : void { this._speed = new Vector2(vx, this._speed.y()); } //? Gets the speed along y in pixels/sec //@ readsMutable public speed_y() : number { return this._speed.y(); } //? Sets the y speed in pixels/sec //@ writesMutable public set_speed_y(vy:number) : void { this._speed = new Vector2(this._speed.x(), vy); } //? Gets the width in pixels public width() : number { return this._width; } //? Sets the height in pixels //@ writesMutable public set_height(height:number) : void { height = Math.max(1, height); if (height != this._height) { this._height = height; if (this._picture) this._width = this._picture.widthSync() / Math.max(1, this._picture.heightSync()) * this._height; this.computeBoundingBox(); this.contentChanged(); } } //? Sets the width in pixels //@ writesMutable public set_width(width:number) : void { width = Math.max(1, width); if(this._width != width) { this._frame = null; this._width = width; if (this._picture) this._height = this._picture.heightSync() / Math.max(1, this._picture.widthSync()) * this._width; this.computeBoundingBox(); this.contentChanged(); } } //? Gets the top position in pixels //@ readsMutable public top(): number { return this._position.y() - this._height / 2; } //? Sets the top position in pixels //@ writesMutable public set_top(y: number): void { this._position = new Vector2(this._position.x(), y + this._height / 2); } //? Gets the bottom position in pixels //@ readsMutable public bottom(): number { return this._position.y() + this._height / 2; } //? Sets the bottom position in pixels //@ writesMutable public set_bottom(y: number): void { this._position = new Vector2(this._position.x(), y - this._height / 2); } //? Gets the right position in pixels //@ readsMutable public right(): number { return this._position.x() + this._width / 2; } //? Sets the right position in pixels //@ writesMutable public set_right(x: number): void { this._position = new Vector2(x - this._width / 2, this._position.y()); } //? Gets the left position in pixels //@ readsMutable public left(): number { return this._position.x() - this._width / 2; } //? Sets the left position in pixels //@ writesMutable public set_left(x: number): void { this._position = new Vector2(x + this._width / 2, this._position.y()); } //? Gets the center horizontal position of in pixels //@ readsMutable public x() : number { return this._position.x(); } //? Sets the center horizontal position in pixels //@ writesMutable public set_x(x:number) : void { this._position = new Vector2(x, this._position.y()); } //? Gets the y position in pixels //@ readsMutable public y() : number { return this._position.y(); } //? Sets the y position in pixels //@ writesMutable public set_y(y:number) : void { this._position = new Vector2(this._position.x(), y); } //? Returns the sprite color. //@ readsMutable public color() : Color { return this._color; } //? Sets the sprite color. //@ writesMutable //@ [color].deflExpr('colors->random') public set_color(color:Color) : void { this._color = color; this.contentChanged(); } //? Gets the opacity (between 0 transparent and 1 opaque) public opacity() : number { return this._opacity; } //? Sets the sprite opacity (between 0 transparent and 1 opaque). //@ writesMutable public set_opacity(opacity:number) : void { this._opacity = Math.min(1,Math.max(0,opacity)); this.contentChanged(); } //? Gets the property that enables or disables gradients //@ readsMutable public gradient() : boolean { return this._gradient; } //? Sets gradient on or off //@ writesMutable public set_gradient(value : boolean) { this._gradient = !!value; } //? Gets the associated sprite sheet public sheet() : SpriteSheet { return this._sheet; } public setSheet(sheet : SpriteSheet) { this._sheet = sheet; this.setPictureInternal(this._sheet._picture); this._width = 0; this._height = 0; } //? Sets the font size in pixels of the sprite (for text sprites) //@ writesMutable [size].defl(20) public set_font_size(size : number, s : IStackFrame) { var size = Math.round(size); if (this.fontSize != size) { this.fontSize = size; this.changed(); } } //? Gets the font size in pixels (for text sprites) //@ readsMutable public font_size() : number { return this.fontSize || 0; } //? Sets the current text baseline used when drawing text (for text sprites) //@ [pos].deflStrings("top", "alphabetic", "hanging", "middle", "ideographic", "bottom") writesMutable public set_text_baseline(pos : string, s : IStackFrame) { pos = pos.trim().toLowerCase(); if (!/^(alphabetic|top|hanging|middle|ideographic|bottom)$/.test(pos)) Util.userError(lf("invalid text baseline value"), s.pc); this._textBaseline = pos; } //? Gets the current text baseline (for text sprites) //@ readsMutable public text_baseline() : string { return this._textBaseline; } //? Fits the bounding box to the size of the text //@ writesMutable public fit_text() { var ctx; if (this._text && this._parent && (ctx = this._parent.renderingContext())) { ctx.save(); ctx.font = this.font(this.fontSize); var lines = this._text.split('\n'); var w = 0, h = this.fontSize *((lines.length - 1) * 1.25 + 1); lines.forEach(line => w = Math.max(w, ctx.measureText(line).width)); ctx.restore(); this.set_width(w); this.set_height(h); this._textBaseline = "middle"; } } //? The text on a text sprite (if it is a text sprite) //@ readsMutable public text() : string { return this._text; } //? Updates text on a text sprite (if it is a text sprite) //@ writesMutable public set_text(text: string): void { if (this.spriteType == SpriteType.Text) { this._text = text; this.contentChanged(); } } //? Gets the background color //@ readsMutable public background(): Color { return this._background ? Colors.transparent() : this._background; } //? Sets the background color //@ writesMutable public set_background(c: Color) { this._background = c; } //? Gets the bubble sprite if any //@ writesMutable public bubble(): Sprite { return this._bubble; } //? Sets the bubble sprite //@ readsMutable public set_bubble(sprite: Sprite) { if (this._bubble != sprite) { this._bubble = sprite; this.changed(); } } //? Displays a text bubble attached to the sprite and returns the bubble sprite. //@ ignoreReturnValue public say(text: string) : Sprite { this.changed(); if (!text) { this._bubble = undefined; return undefined; } var b = this._parent.create_text(10, 10, 16, text); b.fit_text(); b.set_width(b.width() + 8); b.set_height(b.height() + 8); b.set_color(Colors.black()); b.set_background(Colors.white()); b.set_pos(b.width() / 2, -b.height() / 2); b.set_friction(1); // don't participate in physics b.set_opacity(0); var anim = b.create_animation(); anim.fade_in(0.5, "linear"); anim.sleep(text.length * 0.4); anim.fade_out(0.5, "linear"); anim.delete_(); this.set_bubble(b); return b; } //? Gets the mass //@ readsMutable public mass() : number { if (isNaN(this._mass)) { return Math.max(1e-6, this.width() * this.height()); } return this._mass; } //? Sets the sprite mass. //@ writesMutable public set_mass(mass:number) : void { if (isNaN(mass) || isFinite(mass) && mass > 0) { this._mass = mass; } } //? Gets the acceleration along x in pixels/sec^2 //@ readsMutable public acceleration_x():number { return this._acceleration._x; } //? Gets the acceleration along y in pixels/sec^2 //@ readsMutable public acceleration_y():number { return this._acceleration._y; } //? Sets the x acceleration in pixels/sec^2 //@ writesMutable public set_acceleration_x(x:number) { this._acceleration = new Vector2(x, this._acceleration._y); } //? Sets the y acceleration in pixels/sec^2 //@ writesMutable public set_acceleration_y(y:number) { this._acceleration = new Vector2(this._acceleration._x, y); } //? Sets the acceleration in pixels/sec^2 //@ writesMutable public set_acceleration(x:number, y:number) { this._acceleration = new Vector2(x, y); } //? Set the handler invoked when the sprite is tapped //@ ignoreReturnValue public on_tap(tapped: PositionAction) : EventBinding { return this.onTap.addHandler(tapped); } //? Set the handler invoked when the sprite is swiped //@ ignoreReturnValue public on_swipe(swiped: VectorAction) : EventBinding { return this.onSwipe.addHandler(swiped); } //? Set the handler invoked when the sprite is dragged //@ ignoreReturnValue public on_drag(dragged: VectorAction) : EventBinding { return this.onDrag.addHandler(dragged); } //? Set the handler invoked when the sprite is touched initially //@ ignoreReturnValue public on_touch_down(touch_down: PositionAction) : EventBinding { return this.onTouchDown.addHandler(touch_down); } //? Set the handler invoked when the sprite touch is released //@ ignoreReturnValue public on_touch_up(touch_up: PositionAction) : EventBinding { return this.onTouchUp.addHandler(touch_up); } //? Add an action that fires for every display frame //@ ignoreReturnValue public on_every_frame(body: Action, s: IStackFrame): EventBinding { if (this._parent) this._parent.enableEveryFrameOnSprite(s); return this.onEveryFrame.addHandler(body) } public changed(): void { this.hasChanged = true; } private contentChanged(): void { this.changed(); this.shapeDirty = true; } public redraw(ctx : CanvasRenderingContext2D, debug: boolean) { if (!debug && (this._hidden || this._opacity == 0 || this._width <= 0 || this._height <= 0 || this._scale == 0)) return; // don't render hidden sprites //if (!hasChanged) return; //hasChanged = false; this.drawShape(ctx, debug); //self.canvas.style.left = (self.x() - self.width()/2 ) + "px"; //self.canvas.style.top = (self.y() - self.height()/2 ) + "px"; // self.canvas.style.transform = "rotate(30deg)"; } private font(size : number) : string { return size + "px " + '"Segoe UI", "Segoe WP", "Helvetica Neue", Sans-Serif'; } private drawShape(ctx : CanvasRenderingContext2D, debug : boolean) { //if (!shapeDirty) return; //shapeDirty = false; //if (!canvasIsEmpty) // ctx.clearRect(0, 0, canvas.width, canvas.height); //canvasIsEmpty = false; //canvas.width = _width; //canvas.height = _height; var fcolor = this.color().toHtml(); var dcolor = () => this.color().make_transparent(1).toHtml(); // debug color not tranparent var scaledWidth = this._width * this._scale; var scaledHeight = this._height * this._scale; var scaledFontSize = Math_.round_with_precision(this.fontSize * this._scale, 1); ctx.save(); ctx.translate(this.x(), this.y()); var ag = this._angle / 180 * Math.PI; if (this._frame && this._frame.rotated) ag -= 90; ctx.rotate(ag); if (this._shadowBlur > 0 && this._shadowColor) { ctx.shadowBlur = this._shadowBlur; ctx.shadowColor = this._shadowColor.toHtml(); ctx.shadowOffsetX = this._shadowOffsetX; ctx.shadowOffsetY = this._shadowOffsetY; } if (this._background && !this._hidden && this._opacity > 0) { ctx.save(); ctx.translate(-scaledWidth/2, -scaledHeight/2); ctx.fillStyle = this._background.toHtml(); ctx.globalAlpha = this._opacity; ctx.fillRect(0, 0, scaledWidth, scaledHeight); ctx.restore(); } switch (this.spriteType) { case SpriteType.Rectangle: ctx.translate(-scaledWidth/2, -scaledHeight/2); if (debug) { ctx.strokeStyle = dcolor(); ctx.strokeRect(0, 0, scaledWidth, scaledHeight); } // set opacity only after debugging done ctx.globalAlpha = this._opacity; ctx.fillStyle = fcolor; if (!this._hidden) { ctx.fillRect(0, 0, scaledWidth, scaledHeight); } break; case SpriteType.Ellipse: // TODO need to play with createRadialGradient() ctx.scale(scaledWidth/scaledHeight, 1); ctx.translate(-scaledHeight/2, -scaledHeight/2); // debug rectangle around ellipse if (debug) { ctx.strokeStyle = dcolor(); ctx.strokeRect(0, 0, scaledHeight, scaledHeight); } // set opacity only after debugging done ctx.globalAlpha = this._opacity; if (!this._hidden) { ctx.beginPath(); ctx.arc(scaledHeight/2, scaledHeight/2, scaledHeight/2, 0, 2*Math.PI); if (Browser.brokenGradient || !this._gradient) { ctx.fillStyle = fcolor; } else { try { var radgrad = ctx.createRadialGradient(scaledHeight * 0.75, scaledHeight * 0.25, 1, scaledHeight / 2, scaledHeight / 2, scaledHeight / 2); radgrad.addColorStop(0, '#FFFFFF'); radgrad.addColorStop(1, fcolor); ctx.fillStyle = radgrad; } catch (e) { Util.log("draw shape crash, color: " + fcolor); throw e; } } ctx.closePath(); ctx.fill(); } break; case SpriteType.Picture: ctx.translate(- scaledWidth/2, -scaledHeight/2); // debug rectangle around ellipse if (debug) { ctx.strokeStyle = dcolor(); ctx.strokeRect(0, 0, scaledWidth, scaledHeight); } // this may be called by screen resize before _picture is actually set if (this._opacity > 0 && this._picture) { // set opacity only after debugging done ctx.globalAlpha = this._opacity; if (!this._hidden) { if (this._clip) { if(this._clip[2] > 0 && this._clip[3] > 0) ctx.drawImage( this._picture.getCanvas(), this._clip[0], this._clip[1], this._clip[2], this._clip[3], 0, 0, scaledWidth, scaledHeight); } else { ctx.drawImage( this._picture.getCanvas(), 0, 0, this._picture.widthSync(), this._picture.heightSync(), 0, 0, scaledWidth, scaledHeight); } } } break; case SpriteType.Text: ctx.translate(-scaledWidth/2, -scaledHeight/2); // debug rectangle around ellipse ctx.fillStyle = fcolor; if (debug) { ctx.strokeStyle = dcolor(); ctx.strokeRect(0, 0, scaledWidth, scaledHeight); } if (!this._hidden) { // set opacity only after debugging done ctx.globalAlpha = this._opacity; ctx.font = this.font(scaledFontSize); var lines = this._text.split("\n"); ctx.textBaseline = this._textBaseline || "top"; // adjust y to match phone layout if (!this._textBaseline) ctx.translate(0, scaledFontSize * 0.2); else ctx.translate(0, scaledHeight /2); //ctx.translate(offset, this.fontSize); for (var line = 0; line < lines.length; line++) { var msr = ctx.measureText(lines[line]); ctx.save(); var offset = scaledWidth - msr.width; if (offset > 0) { offset = offset / 2; } else { offset = 0; } ctx.translate(offset, 0); ctx.fillText(lines[line], 0, 0); ctx.restore(); ctx.translate(0, scaledFontSize * 1.25); } } break; case SpriteType.Anchor: ctx.translate(- scaledWidth/2, - scaledHeight/2); // debug rectangle around ellipse if (debug) { ctx.strokeStyle = dcolor(); ctx.strokeRect(0, 0, scaledWidth, scaledHeight); } break; } if (debug) { ctx.restore(); ctx.save(); ctx.translate(this.x() + this.boundingMaxX + 2, this.y()+this.boundingMinY); ctx.font = "10px sans-serif"; ctx.fillStyle = dcolor(); ctx.fillText("x:" + this.x().toFixed(1), 0, 0); ctx.translate(0, 10); ctx.fillText("y:" + this.y().toFixed(1), 0, 0); if (this.speed_x() != 0 || this.speed_y() != 0) { ctx.translate(0, 10); ctx.fillText("vx:" + this.speed_x().toFixed(1), 0, 0); ctx.translate(0, 10); ctx.fillText("vy:" + this.speed_y().toFixed(1), 0, 0); } // draw capsule ctx.restore(); ctx.save(); ctx.strokeStyle = "green"; ctx.beginPath(); var cap = this.capsule(); ctx.moveTo(cap.x(), cap.y()); ctx.lineWidth = 5; ctx.lineTo(cap.x() + cap.z(), cap.y() + cap.w()); ctx.lineWidth = 1; ctx.moveTo(this.x() + this.boundingMinX, this.y() + this.boundingMinY); ctx.lineTo(this.x() + this.boundingMaxX, this.y() + this.boundingMinY); ctx.lineTo(this.x() + this.boundingMaxX, this.y() + this.boundingMaxY); ctx.lineTo(this.x() + this.boundingMinX, this.y() + this.boundingMaxY); ctx.lineTo(this.x() + this.boundingMinX, this.y() + this.boundingMinY); // draw center ctx.moveTo(this.x() - 3, this.y()); ctx.lineTo(this.x() + 3, this.y()); ctx.moveTo(this.x(), this.y() - 3); ctx.lineTo(this.x(), this.y() + 3); ctx.stroke(); } ctx.restore(); if (this._bubble && this._bubble.is_deleted()) this._bubble = null; if (this._bubble && this._bubble.is_visible() && this._bubble.opacity() > 0) { ctx.save(); ctx.translate(this.x() + this.width() / 2, this.y() - this.height() / 2); this._bubble.redraw(ctx, debug); ctx.restore(); } } public computeBoundingBox() : void { var rx = this.radiusX(); var ry = this.radiusY(); if (this._angle == 0 || this._angle == 180) { this.boundingMinX = -rx; this.boundingMaxX = rx; this.boundingMinY = -ry; this.boundingMaxY = ry; return; } if (this._angle == 90 || this._angle == 270 || this._angle == -90) { this.boundingMinX = -ry; this.boundingMaxX = ry; this.boundingMinY = -rx; this.boundingMaxY = rx; return; } // rotate the 4 corners according to the rotation and figure out min/max values this.boundingMinX = Number.MAX_VALUE; this.boundingMaxX = Number.MIN_VALUE; this.boundingMinY = Number.MAX_VALUE; this.boundingMaxY = Number.MIN_VALUE; var sine = Math.sin(Math.PI * this._angle / 180); var cosine = Math.cos(Math.PI * this._angle / 180); // upper right corner this.updateBoundingX(this.rotateX(rx, -ry, sine, cosine)); this.updateBoundingY(this.rotateY(rx, -ry, sine, cosine)); // lower right corner this.updateBoundingX(this.rotateX(rx, ry, sine, cosine)); this.updateBoundingY(this.rotateY(rx, ry, sine, cosine)); // lower left corner this.updateBoundingX(this.rotateX(-rx, ry, sine, cosine)); this.updateBoundingY(this.rotateY(-rx, ry, sine, cosine)); // upper left corner this.updateBoundingX(this.rotateX(-rx, -ry, sine, cosine)); this.updateBoundingY(this.rotateY(-rx, -ry, sine, cosine)); } private rotateX(x : number, y : number, sine :number, cosine:number) : number { return x * cosine - y * sine; } private rotateY(x : number, y : number, sine : number, cosine : number) : number { return x * sine + y * cosine; } private rotate(v: Vector2): Vector2 { var sine = Math.sin(Math.PI * this._angle / 180); var cosine = Math.cos(Math.PI * this._angle / 180); var x = this.rotateX(v.x(), v.y(), sine, cosine); var y = this.rotateY(v.x(), v.y(), sine, cosine); return new Vector2(x, y); } /// /// Project p0-p1 onto d0 and subtract from p0-p1 to get vector /// returns the closest vector rooted at x1,y1 to the segment private minPointSegment(x0:number, y0:number, dx0:number, dy0:number, x1:number, y1:number) : Vector2 { var wx = x0 - x1; var wy = y0 - y1; var d = dx0 * dx0 + dy0 * dy0; if (Math.abs(d) < 0.00001) { // zero // point to point var result = new Vector2(wx, wy); (<any>result).from = 0; return result; } var from = 1; var t = -(wx * dx0 + wy * dy0) / d; if (t < 0) { t = 0; from = 2; } else if (t > 1) { t = 1; from = 3; } var result = new Vector2(wx + t * dx0, wy + t * dy0); (<any>result).from = from; return result; } /// <summary> /// Consider segments o0 + d0*s and o1 + d1*t, parametrized by s and t in [0,1] /// Either the segments overlap, i.e., we can find both s and t in the range [0,1], in which case, the /// closest segment is 0 length. /// /// Otherwise the closest distance will be rooted at one of the four endpoints of these segments. /// Thus, compute 4 point/segment distances and pick the smallest one. /// </summary> private minConnectingSegment(x0: number, y0: number, dx0: number, dy0: number, x1: number, y1: number, dx1: number, dy1: number) : Vector4 { var b = dx0 * dy1 - dy0 * dx1; if (b != 0) { var wx = x0 - x1; var wy = y0 - y1; var d = dx0 * wy - dy0 * wx; var e = dx1 * wy - dy1 * wx; var t = d / b; var s = e / b; if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { var result = new Vector4(x0 + s * dx0, y0 + s * dy0, 0, 0); (<any>result).from = 32; return result; } } var v1 = this.minPointSegment(x0, y0, dx0, dy0, x1, y1); var v2 = this.minPointSegment(x0, y0, dx0, dy0, x1 + dx1, y1 + dy1); var v3 = this.minPointSegment(x1, y1, dx1, dy1, x0, y0); var v4 = this.minPointSegment(x1, y1, dx1, dy1, x0 + dx0, y0 + dy0); var d1 = v1.length(); var d2 = v2.length(); var d3 = v3.length(); var d4 = v4.length(); var m = Math.min(d1, d2, d3, d4); if (m == d1) { var result = new Vector4(x1, y1, v1.x(), v1.y()); (<any>result).from = (<any>v1).from + 4; return result; } if (m == d2) { var result = new Vector4(x1 + dx1, y1 + dy1, v2.x(), v2.y()); (<any>result).from = (<any>v1).from + 8; return result; } if (m == d3) { var result = new Vector4(x0, y0, v3.x(), v3.y()); (<any>result).from = (<any>v1).from + 12; return result; } //if (m == d4) { var result = new Vector4(x0 + dx0, y0 + dy0, v4.x(), v4.y()); (<any>result).from = (<any>v1).from + 16; return result; //} } private updateBoundingX(newX : number) : void { this.boundingMaxX = Math.max(this.boundingMaxX, newX); this.boundingMinX = Math.min(this.boundingMinX, newX); } private updateBoundingY(newY : number) : void { this.boundingMaxY = Math.max(this.boundingMaxY, newY); this.boundingMinY = Math.min(this.boundingMinY, newY); } private bbRadius(unitNormal : Vector2) : number { // rotate unitNormal into rotation of box of this sprite by adding -angle to it var angle = Math.atan(unitNormal.y()/unitNormal.x()); angle = angle - Math.PI * this._angle / 180; // find intersect with horizontals of bb var tan = Math.tan(angle); var horiz = Math.abs(this.radiusY()/tan); if (horiz <= this.radiusX()) { // dist to bb return Math.abs(this.radiusY()/Math.sin(angle)); } // find intersect with verticals of bb var vert = Math.abs(this.radiusX() * tan); if (vert > this.radiusY()) { debugger; // something is wrong } return Math.abs(this.radiusX()/Math.cos(angle)); } public radius(unitNormal : Vector2) : number { // TODO: Explain where this funky dot product came from... // return Math.abs(self.boundingMaxX * unitNormal.x() + this.boundingMaxY * unitNormal.y()); // Approximate as ellipse var angle = Math.atan(unitNormal.y() / unitNormal.x()); angle = angle - Math.PI * this._angle / 180; var sin = Math.sin(angle); var cos = Math.cos(angle); // Detect ellipse axis rotation var majorAxis:number, majorAxisMult:number; var minorAxis:number, minorAxisMult:number; if (this.width >= this.height) { majorAxis = this.radiusX(); minorAxis = this.radiusY(); majorAxisMult = sin; minorAxisMult = cos; } else { majorAxis = this.radiusY(); minorAxis = this.radiusX(); majorAxisMult = cos; minorAxisMult = -sin; } var rad = (majorAxis * minorAxis) / (Math.sqrt(majorAxis * majorAxis * majorAxisMult * majorAxisMult + minorAxis * minorAxis * minorAxisMult * minorAxisMult)); return rad; } private radiusX() : number { return this.width() / 2; } private radiusY() : number { return this.height() / 2; } /// <summary> /// Used during a time step to determine collisions etc. /// </summary> public stepDisplacement() : Vector2 { return this.newPosition.subtract(this._position); } /// <summary> /// Apply gravity and user applied force and also repulsive forces due to touching of walls/other objects /// </summary> private computeForces(positionSpeed : Vector4) : Vector2 { var force = (this._parent.gravity().add(this._acceleration)).scale(this.mass()); for (var i = 0; i < this._springs.length; i++) { var spring = this._springs[i]; force = force.add(spring.forceOn(this)); } // compute repulsive forces from walls for (var i = 0; i < this.normalTouchPoints.length; i++) { var unitNormal = this.normalTouchPoints[i]; if (Vector2.dot(unitNormal, force) > 0) continue; // not pointing into the wall if (Vector2.dot(unitNormal, new Vector2(positionSpeed.z(), positionSpeed.w())) > 0) continue; // speeding away from wall. var unitParallel = unitNormal.rotate90Left(); var proj = unitParallel.scale(Vector2.dot(force, unitParallel)); force = proj; } if (Math.abs(force.x()) < 0.1) force = new Vector2(0, force.y()); if (Math.abs(force.y()) < 0.1) force = new Vector2(force.x(), 0); return force; } private isEqualToEpsilon(x:number, p:number) : boolean { return (Math.round((x - p) / 2) == 0.0); } private derivativePosAndSpeed(dT:number, positionSpeed:Vector4) : Vector4 { var accel = this.computeForces(positionSpeed).scale(1 / this.mass()); // apply friction directly (instead of as a force) return new Vector4((positionSpeed.z() + dT * accel.x()), (positionSpeed.w() + dT * accel.y()), accel.x(), accel.y()); } private actualFriction() : number { if (isNaN(this._friction)) return this._parent._worldFriction; return this._friction; } private RungaKutta(dT:number): Vector4 { var yi = Vector4.fromV2V2(this._position, this._speed); var u1 = this.derivativePosAndSpeed(0, yi).scale(dT); var u2 = this.derivativePosAndSpeed(dT / 2, yi.add(u1.scale(.5))).scale(dT); var u3 = this.derivativePosAndSpeed(dT / 2, yi.add(u2.scale(.5))).scale(dT); var u4 = this.derivativePosAndSpeed(dT, yi.add(u3)).scale(dT); var avg = (u1.add(u2.scale(2)).add(u3.scale(2)).add(u4)).scale(1/6); // clean accel var nz = avg.z(); if (avg.z() < 0.1 && avg.z() > -0.1) nz = 0; var nw = avg.w(); if (avg.w() < 0.1 && avg.w() > -0.1) nw = 0; var nx = avg.x() * (1 - this.actualFriction()); var ny = avg.y() * (1 - this.actualFriction()); avg = new Vector4(nx,ny,nz,nw); this.midSpeed = new Vector2(avg.x() / dT, avg.y() / dT); var yip1 = yi.add(avg); // apply friction directly (instead of as a force) yip1 = yip1.withW(yip1.w() * (1 - this.actualFriction())) yip1 = yip1.withZ(yip1.z() * (1 - this.actualFriction())); return yip1; } /// <summary> /// Make a time step. /// - Uses speed, position to create newSpeed and newPosition /// /// CommitUpdate moves the newPosition, newSpeed into position, speed, thereby finalizing it. /// /// Use Euler midpoint method. /// /// This method must be IDEMPOTENT so we can call it a few times during a step with different partial time steps. /// </summary> public update(dT:number):void { Util.assertCode(dT >= 0); if (!this._parent) return; var yip1 = this.RungaKutta(dT); // compute final displacement (position is updated after collision detection) this.newPosition = new Vector2(yip1.x(), yip1.y()); this.newSpeed = new Vector2(yip1.z(), yip1.w()); this.newRotation = this._angle + this._angular_speed * dT; } F public commitUpdate(rt : Runtime, dT : number): void { if (!this._lastPosition || !this._lastPosition.equals(this.newPosition) || this._angle != this.newRotation) this.changed(); this._position = this.newPosition; this._angle = this.newRotation; this._speed = this.newSpeed; if (this._animations) { var anyDone = false; this._animations.forEach(anim => anyDone = !anim.evolve(rt, dT) || anyDone); // cleanup on demand if (anyDone) { this._animations = this._animations.filter(anim => anim.isActive); if (this._animations.length == 0) this._animations = undefined; } } this.computeBoundingBox(); } //? Hide sprite. //@ writesMutable public hide() : void { this._hidden = true; } //? Returns true if sprite is not hidden //@ readsMutable public is_visible() : boolean { return !this._hidden; } //? Moves sprite. //@ writesMutable public move(delta_x:number, delta_y:number) : void { this._position = new Vector2(this._position._x + delta_x, this._position._y + delta_y); } //? Moves sprite towards other sprite. //@ writesMutable [other].readsMutable //@ [fraction].defl(1) public move_towards(other:Sprite, fraction:number) : void { var center1 = this._position; var center2 = other._position; var dir = center2.subtract(center1).scale(fraction); this.move(dir._x, dir._y); } public capsule(): Vector4 { var s0x, s0y, s1x, s1y, d0x, d0y, d1x, d1y; if (this._width > this._height) { d0x = (this._width - this._height); d0y = 0; s0x = -d0x / 2; s0y = 0; } else { d0x = 0; d0y = (this._height - this._width); s0x = 0; s0y = -d0y / 2; } var d0 = this.rotate(new Vector2(d0x, d0y)); var s0 = this.rotate(new Vector2(s0x, s0y)); return new Vector4(this.x() + s0.x(), this.y() + s0.y(), d0.x(), d0.y()); } public capsuleRadius(): number { if (this._width < this._height) { return this._width / 2; } return this._height / 2; } //? Do the sprites overlap //@ readsMutable [other].readsMutable public overlaps_with(other:Sprite) : boolean { if (!this._parent) return false; if (!other._parent) return false; if (isNaN(this.x()) || isNaN(this.y()) || isNaN(other.x()) || isNaN(other.y())) return false; if (this.x() + this.boundingMaxX <= other.x() + other.boundingMinX) return false; if (this.x() + this.boundingMinX >= other.x() + other.boundingMaxX) return false; if (this.y() + this.boundingMaxY <= other.y() + other.boundingMinY) return false; if (this.y() + this.boundingMinY >= other.y() + other.boundingMaxY) return false; // capsule-capsule intersection var cap1 = this.capsule(); var cap2 = other.capsule(); //var dist = this.segmentSegmentDistanceSquared(cap1.x(), cap1.y(), cap1.z(), cap1.w(), cap2.x(), cap2.y(), cap2.z(), cap2.w()); var seg = this.minConnectingSegment(cap1.x(), cap1.y(), cap1.z(), cap1.w(), cap2.x(), cap2.y(), cap2.z(), cap2.w()); if (this._parent) { this._parent._minSegments.push(seg); } var radi = this.capsuleRadius() + other.capsuleRadius(); var dist = seg.z() * seg.z() + seg.w() * seg.w(); if (dist >= radi*radi) { (<any>seg).overlap = false; return false; } (<any>seg).overlap = true; return true; var center1 = this._position; var center2 = other._position; var distVec = center2.subtract(center1); var dist = distVec.length(); if (dist == 0) return true; var norm = distVec.normalize(); var radius1 = this.radius(norm); var radius2 = other.radius(norm); if (radius1 + radius2 >= dist) return true; return false; } //? Returns the subset of sprites in the given set that overlap with sprite. //@ readsMutable [sprites].readsMutable public overlap_with(sprites:SpriteSet) : SpriteSet { if (!this._parent) return new SpriteSet(); return this._parent.overlapWithAny(this, sprites); } //? Are these the same sprite //@ readsMutable [other].readsMutable public equals(other:Sprite) : boolean { return this === other; } //? Updates picture on a picture sprite (if it is a picture sprite) //@ writesMutable picAsync public set_picture(pic:Picture, r:ResumeCtx) : void { if (this.spriteType != SpriteType.Picture) r.resume(); else pic.loadFirst(r, () => { this.setPictureInternal(pic); }) } public setPictureInternal(pic:Picture):void { this._picture = pic; this._width = pic.widthSync(); this._height = pic.heightSync(); this.computeBoundingBox(); this.contentChanged(); } //? The picture on a picture sprite (if it is a picture sprite) //@ readsMutable public picture(): Picture { return this._picture; } //? Sets the position in pixels //@ writesMutable public set_pos(x:number, y:number) : void { this._position = new Vector2(x,y); } //? Sets the speed in pixels/sec //@ writesMutable public set_speed(vx:number, vy:number) : void { this._speed = new Vector2(vx,vy); } //? Show sprite. //@ writesMutable public show() : void { this._hidden = false; } //? Sets sprite speed direction towards other sprite with given magnitude. //@ writesMutable [other].readsMutable public speed_towards(other:Sprite, magnitude:number) : void { var center1 = this._position; var center2 = other._position; var speed = center2.subtract(center1); speed = speed.normalize(); speed = speed.scale(magnitude); this._speed = speed; } //? Sets the clipping area for an image sprite (if it is an image sprite) //@ writesMutable //@ [width].defl(48) [height].defl(48) public set_clip(left: number, top: number, width: number, height: number): void { if (this._picture && isFinite(left) && isFinite(top) && isFinite(width) && isFinite(height)) { this._frame = undefined; this._width = width; this._height = height; this._clip = [left, top, width, height]; this.computeBoundingBox(); this.contentChanged(); } } private _frame : SpriteFrame; public setFrame(frame : SpriteFrame) { if (this._frame != frame) { this._frame = frame; if (this._width <= 0) this._width = frame.width; this._height = frame.width <= 0 ? frame.height : this._width / frame.width * frame.height; this._clip = [frame.x, frame.y, frame.width, frame.height]; // this._angle = frame.rotated ? -90 : 0; this.computeBoundingBox(); this.contentChanged(); } } //? Use `Sprite Sheet` instead. //@ writesMutable obsolete //@ [x].defl(48) public move_clip(x:number, y:number) : void { if (this._clip && this._picture) { var left = (this._clip[0] + x) % this._picture.widthSync(); if (left < 0) left += this._clip[2]; else if (left + this._clip[2] > this._picture.widthSync()) left = 0; var top = (this._clip[1] + y) % this._picture.heightSync(); if (top < 0) top += this._clip[3]; else if (top + this._clip[3] > this._picture.heightSync()) top = 0; this._clip = [left, top, this._clip[2], this._clip[3]]; this.computeBoundingBox(); this.contentChanged(); } } //? Delete sprite. //@ writesMutable public delete_() : void { if (! this._parent) { return; } this._parent.deleteSprite(this); this._parent = null; } //? True if sprite is deleted. //@ readsMutable public is_deleted(): boolean { return !this._parent; } // return true if x, y is within the sprite extent (rotated bounding box) public contains(x:number, y:number) : boolean { var diff = Vector2.mk(x, y).subtract(this._position); var norm = diff.normalize(); var rad = this.bbRadius(norm); if (diff.length() <= rad) return true; return false; } public addSpring(sp:Spring) : void { this._springs.push(sp); } public removeSpring(sp:Spring) : void { var idx = this._springs.indexOf(sp); if (idx > -1) this._springs.splice(idx, 1); } private _z_index : number = undefined; //? Gets the z-index of the sprite //@ readsMutable public z_index() : number { return this._z_index; } //? Sets the z-index of the sprite //@ writesMutable public set_z_index(zindex: number): void { if (this._z_index != zindex) { this._z_index = zindex; if (this._parent) this._parent.spritesChanged(); } } public createAnimation() : SpriteAnimation { var anim = new SpriteAnimation(this); return anim; } public startAnimation(anim : SpriteAnimation) { Util.assert(anim._sprite == this); if(!this._animations) this._animations = []; this._animations.push(anim); } //? Starts a new tween animation. public create_animation() : SpriteAnimation { var anim = this.createAnimation(); this.startAnimation(anim); return anim; } public debuggerChildren() { return { 'Z-index': this.z_index(), Friction: this.friction(), 'Angular speed': this.angular_speed(), Angle: this.angle(), Elasticity: this.elasticity(), 'Speed X': this.speed_x(), 'Speed Y': this.speed_y(), X: this.x(), Y: this.y(), Color: this.color(), Opacity: this.opacity(), Text: this.text(), Picture: this.picture(), Mass: this.mass(), 'Acceleration X': this.acceleration_x(), 'Acceleration Y': this.acceleration_y(), Visible: this.is_visible(), }; } } }
the_stack
import * as https from "@rill/https"; import * as assert from "assert"; import * as fs from "fs"; import * as getPort from "get-port"; import * as path from "path"; import * as agent from "supertest"; import Rill from "../src"; import { respond } from "./util"; describe("Router", () => { describe("#listen", () => { it("should listen for a request and callback function when started", done => { new Rill() .listen(function() { (agent(this) as any) .get("/") .expect(404) .end(done); }) .unref(); }); it("should use provided port", () => { return getPort().then(port => { new Rill().listen({ port }).unref(); return (agent("localhost:" + port) as any).get("/").expect(404); }); }); it("should use https server with tls option", () => { process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; const server = new Rill() .listen({ tls: { cert: fs.readFileSync(path.join(__dirname, "/cert/cert.pem")), key: fs.readFileSync(path.join(__dirname, "/cert/privkey.pem")) } }) .unref(); const request = agent(server) as any; assert.ok( server instanceof (https as any).Server, "should be an https server." ); return request.get("/").expect(404); }); }); describe("#setup", () => { it("should run setup functions", done => { const app = new Rill(); app.setup( // Ignores falsey values false, // provides self. self => { assert.equal(self, app, "should provide the app"); done(); } ); }); it("should should error with an invalid setup", () => { assert.throws( () => { new Rill().setup("hello" as any); }, TypeError, "Rill#setup: Setup must be a function or falsey." ); }); }); describe("#use", () => { it("should run middleware", () => { const request = agent( new Rill() .use(respond(200)) .listen() .unref() ) as any; return request.get("/").expect(200); }); }); describe("#at", () => { it("should match a pathname", () => { const request = agent( new Rill() .at("/test", respond(200)) .listen() .unref() ) as any; return Promise.all([ request.get("/").expect(404), request.get("/test").expect(200) ]); }); it("should match a pathname", () => { const request = agent( new Rill() .at("/test", respond(200)) .listen() .unref() ) as any; return Promise.all([ request.get("/").expect(404), request.get("/test").expect(200) ]); }); it("should mount a pathname", () => { const request = agent( new Rill() .at( "/test/*", new Rill().at("/1/*", new Rill().at("/2", respond(200))) ) .at("/test2/*", respond(200)) .listen() .unref() ) as any; return Promise.all([ request.get("/test").expect(404), request.get("/test/1").expect(404), request.get("/test/1/2").expect(200), request.get("/test2").expect(200) ]); }); it("should error without a pathname", () => { assert.throws( () => { // tslint:disable-next-line new Rill().at((() => {}) as any); }, TypeError, "Rill#at: Path name must be a string." ); }); }); describe("#host", () => { it("should match a hostname", () => { const request = agent( new Rill() .host("*test.com", respond(200)) .listen() .unref() ) as any; return Promise.all([ request.get("/").expect(404), request .get("/") .set("host", "fake.com") .expect(404), request .get("/") .set("host", "test.com") .expect(200), request .get("/") .set("host", "www.test.com") .expect(200) ]); }); it("should mount a subdomain/hostname", () => { const request = agent( new Rill() .host( "*.test.com", new Rill().host("*.api", new Rill().host("test", respond(200))) ) .listen() .unref() ) as any; return Promise.all([ request.get("/").expect(404), request .get("/") .set("host", "test.com") .expect(404), request .get("/") .set("host", "api.test.com") .expect(404), request .get("/") .set("host", "test.api.test.com") .expect(200) ]); }); it("should error without a hostname", () => { assert.throws( () => { // tslint:disable-next-line new Rill().host((() => {}) as any); }, TypeError, "Rill#host: Host name must be a string." ); }); }); describe("#|METHOD|", () => { it("should match a method", () => { const request = agent( new Rill() .post(respond(200)) .listen() .unref() ) as any; return Promise.all([ request.get("/").expect(404), request.post("/").expect(200) ]); }); it("should match a method and a pathname", () => { const request = agent( new Rill() .get("/test", respond(200)) .listen() .unref() ) as any; return Promise.all([ request.get("/test").expect(200), request.get("/").expect(404) ]); }); }); describe("#handler", () => { it("should return 500 status on unknown error", () => { const request = agent( new Rill() .use(() => { throw new Error("Fail"); }) .listen() .unref() ) as any; return request.get("/").expect(500); }); it("should default status to 200 with body", () => { const request = agent( new Rill() .use(ctx => { ctx.res.body = "hello"; }) .listen() .unref() ) as any; return request .get("/") .expect(200) .expect(res => { assert.equal(res.text, "hello", "should have sent response body."); }); }); it("should default status to 302 on redirect", () => { const request = agent( new Rill() .use(ctx => { ctx.res.set("Location", "localhost"); }) .listen() .unref() ) as any; return request.get("/").expect(302); }); it("should respond as json with object body", () => { const request = agent( new Rill() .use(ctx => { ctx.res.body = { hello: "world" }; }) .listen() .unref() ) as any; return request .get("/") .expect(200) .expect("content-type", "application/json; charset=UTF-8") .expect("content-length", "17"); }); it("should respond with content-type for stream body", () => { const request = agent( new Rill() .use(ctx => { ctx.res.body = fs.createReadStream( require.resolve("../package.json") ); }) .listen() .unref() ) as any; return request .get("/") .expect(200) .expect("content-type", "application/json"); }); it("should be able to override content-type and content-length", () => { const request = agent( new Rill() .use(ctx => { ctx.res.set("Content-Type", "application/custom"); ctx.res.set("Content-Length", "20"); ctx.res.body = { hello: "world" }; }) .listen() .unref() ) as any; return request .get("/") .expect(200) .expect("content-type", "application/custom") .expect("content-length", "20"); }); it("should omit empty headers", () => { const request = agent( new Rill() .use(ctx => { ctx.res.set("X-Test-Header", null); ctx.res.status = 200; }) .listen() .unref() ) as any; return request .get("/") .expect(200) .expect(res => { assert.ok( !("X-Test-Header" in res.headers), "headers should not have empty value" ); }); }); it("should be able to manually respond with original response", () => { const request = agent( new Rill() .use(ctx => { const res = ctx.res.original; res.writeHead(200, { "Content-Type": "text/plain" }); res.end("hello"); }) .listen() .unref() ) as any; return request .get("/") .expect(200) .expect(res => { assert.equal(res.text, "hello", "should have manual text response"); }); }); it("should be able to manually respond with respond=false", () => { const request = agent( new Rill() .use(ctx => { const res = ctx.res.original; ctx.res.respond = false; // Respond later manually. setTimeout(() => { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("hello"); }, 10); }) .listen() .unref() ) as any; return request .get("/") .expect(200) .expect(res => { assert.equal(res.text, "hello", "should have manual text response"); }); }); it("should be able to manually end request with end=false", () => { const request = agent( new Rill() .use( respond(200, ctx => { const res = ctx.res.original; ctx.res.end = false; setTimeout(() => { // Manually end later. res.end("hello"); }, 10); }) ) .listen() .unref() ) as any; return request .get("/") .expect(200) .expect(res => { assert.equal(res.text, "hello", "should have manual text response"); }); }); }); });
the_stack
import * as THREE from 'three'; import * as d3 from 'd3'; import type {ColorMap, Point2D, Point3D} from './types'; import {ColorType} from './types'; import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'; export type ScatterChartOptions = { width: number; height: number; is3D?: boolean; background?: string | number | THREE.Color; }; export default abstract class ScatterChart { static readonly CUBE_LENGTH = 2; static readonly MAX_ZOOM = 5 * ScatterChart.CUBE_LENGTH; static readonly MIN_ZOOM = 0.025 * ScatterChart.CUBE_LENGTH; static readonly PERSP_CAMERA_FOV_VERTICAL = 70; static readonly PERSP_CAMERA_NEAR_CLIP_PLANE = 0.01; static readonly PERSP_CAMERA_FAR_CLIP_PLANE = 100; static readonly ORTHO_CAMERA_FRUSTUM_HALF_EXTENT = 1.2; static readonly ORBIT_MOUSE_ROTATION_SPEED = 1; static readonly ORBIT_ANIMATION_ROTATION_CYCLE_IN_SECONDS = 2; static readonly PERSP_CAMERA_INIT_POSITION: Point3D = [0.45, 0.9, 1.6]; static readonly ORTHO_CAMERA_INIT_POSITION: Point3D = [0, 0, 4]; static readonly VALUE_COLOR_MAP_RANGE = ['#ffffdd', '#1f2d86'] as const; static readonly CATEGORY_COLOR_MAP = [ '#9BB9E8', '#8BB8FF', '#B4CCB7', '#A8E9B8', '#DB989A', '#6DCDE4', '#93C2CA', '#DE7CCE', '#DA96BC', '#309E51', '#D6C482', '#6D7CE4', '#CDCB74', '#2576AD', '#E46D6D', '#CA5353', '#E49D6D', '#E4E06D' ].map(color => new THREE.Color(color)); width: number; height: number; background: string | number | THREE.Color = '#fff'; is3D = true; data: Point3D[] = []; labels: string[] = []; protected abstract readonly vertexShader: string; protected abstract readonly fragmentShader: string; // canvas container protected readonly container: HTMLElement; protected canvas: HTMLCanvasElement | null; protected scene: THREE.Scene; protected renderer: THREE.WebGLRenderer; protected camera: THREE.OrthographicCamera | THREE.PerspectiveCamera; protected controls: OrbitControls; private axes: THREE.AxesHelper | null = null; protected geometry: THREE.BufferGeometry; protected material: THREE.ShaderMaterial | null = null; protected positions: Float32Array = new Float32Array(); protected colors: Float32Array = new Float32Array(); // render target which picking colors will render to protected pickingRenderTarget: THREE.WebGLRenderTarget; protected pickingMaterial: THREE.ShaderMaterial | null = null; protected pickingColors: Float32Array | null = null; protected fog: THREE.Fog | null = null; protected blending: THREE.Blending = THREE.NormalBlending; protected depth = true; protected colorMap: ColorMap = {type: ColorType.Null, labels: []}; protected colorGenerator: ((value: string) => THREE.Color) | null = null; private mouseCoordinates: Point2D | null = null; private onMouseMoveBindThis: (e: MouseEvent) => void; protected focusedDataIndices: number[] = []; protected hoveredDataIndices: number[] = []; protected highLightDataIndices: number[] = []; private rotate = false; private animationId: number | null = null; protected abstract get object(): (THREE.Object3D & {material: THREE.Material | THREE.Material[]}) | null; protected abstract get defaultColor(): THREE.Color; protected abstract get hoveredColor(): THREE.Color; protected abstract get focusedColor(): THREE.Color; protected abstract get highLightColor(): THREE.Color; // eslint-disable-next-line @typescript-eslint/no-explicit-any protected abstract createShaderUniforms(picking: boolean): Record<string, THREE.IUniform<any>>; protected abstract onRender(): void; protected abstract onSetSize(width: number, height: number): void; protected abstract onDataSet(): void; protected abstract onDispose(): void; get dataCount() { return this.data.length; } constructor(container: HTMLElement, options: ScatterChartOptions) { this.container = container; this.width = options.width; this.height = options.height; this.is3D = options.is3D ?? this.is3D; this.background = options.background ?? this.background; this.canvas = this.initCanvas(); this.container.appendChild(this.canvas); this.scene = this.initScene(); this.camera = this.initCamera(); this.renderer = this.initRenderer(); this.controls = this.initControls(); this.pickingRenderTarget = this.initRenderTarget(); this.geometry = this.createGeometry(); this.onMouseMoveBindThis = this.onMouseMove.bind(this); this.bindEventListeners(); if (this.is3D) { this.addAxes(); } this.reset(); } private initCanvas() { const canvas = document.createElement('canvas'); canvas.width = this.width; canvas.height = this.height; return canvas; } private initScene() { const scene = new THREE.Scene(); scene.background = new THREE.Color(this.background); const light = new THREE.PointLight(16772287, 1, 0); light.name = 'light'; scene.add(light); return scene; } private initCamera() { const origin = new THREE.Vector3(0, 0, 0); let camera: THREE.OrthographicCamera | THREE.PerspectiveCamera; if (this.is3D) { camera = new THREE.PerspectiveCamera( ScatterChart.PERSP_CAMERA_FOV_VERTICAL, this.width / this.height, ScatterChart.PERSP_CAMERA_NEAR_CLIP_PLANE, ScatterChart.PERSP_CAMERA_FAR_CLIP_PLANE ); camera.position.set(...ScatterChart.PERSP_CAMERA_INIT_POSITION); } else { camera = new THREE.OrthographicCamera( -ScatterChart.ORTHO_CAMERA_FRUSTUM_HALF_EXTENT, ScatterChart.ORTHO_CAMERA_FRUSTUM_HALF_EXTENT, ScatterChart.ORTHO_CAMERA_FRUSTUM_HALF_EXTENT, -ScatterChart.ORTHO_CAMERA_FRUSTUM_HALF_EXTENT, -1000, 1000 ); camera.position.set(...ScatterChart.ORTHO_CAMERA_INIT_POSITION); camera.up = new THREE.Vector3(0, 1, 0); } camera.lookAt(origin); camera.zoom = 1; camera.updateProjectionMatrix(); return camera; } private initRenderer() { const renderer = new THREE.WebGLRenderer({ canvas: this.canvas ?? undefined, alpha: true, premultipliedAlpha: false, antialias: false }); renderer.setClearColor(this.background, 1); renderer.setPixelRatio(window.devicePixelRatio || 1); renderer.setSize(this.width, this.height); return renderer; } private initControls() { const controls = new OrbitControls(this.camera, this.renderer.domElement); controls.enableRotate = this.is3D; controls.autoRotate = false; controls.rotateSpeed = ScatterChart.ORBIT_MOUSE_ROTATION_SPEED; controls.minDistance = ScatterChart.MIN_ZOOM; controls.maxDistance = ScatterChart.MAX_ZOOM; controls.mouseButtons.LEFT = this.is3D ? THREE.MOUSE.ROTATE : THREE.MOUSE.PAN; controls.reset(); controls.addEventListener('start', () => { this.stopRotate(); }); controls.addEventListener('change', () => { this.render(); }); return controls; } private initRenderTarget() { const renderCanvasSize = new THREE.Vector2(); this.renderer.getSize(renderCanvasSize); const pixelRadio = this.renderer.getPixelRatio(); const renderTarget = new THREE.WebGLRenderTarget( renderCanvasSize.width * pixelRadio, renderCanvasSize.height * pixelRadio ); renderTarget.texture.minFilter = THREE.LinearFilter; return renderTarget; } private createGeometry() { const geometry = new THREE.BufferGeometry(); geometry.computeBoundingSphere(); return geometry; } private createRenderMaterial() { const uniforms = this.createShaderUniforms(false); return new THREE.ShaderMaterial({ transparent: true, depthTest: this.depth, depthWrite: this.depth, fog: this.fog != null, blending: this.blending, uniforms, vertexShader: this.vertexShader, fragmentShader: this.fragmentShader }); } private createPickingMaterial() { const uniforms = this.createShaderUniforms(true); return new THREE.ShaderMaterial({ transparent: true, depthTest: true, depthWrite: true, fog: false, blending: THREE.NormalBlending, uniforms, vertexShader: this.vertexShader, fragmentShader: this.fragmentShader }); } private convertColorMap() { switch (this.colorMap.type) { case ColorType.Value: { const {minValue, maxValue} = this.colorMap; return (label: string) => { const value = Number.parseFloat(label); if (!Number.isFinite(value)) { return this.defaultColor; } const ranger = d3 .scaleLinear<string, string>() .domain([minValue, maxValue]) .range(ScatterChart.VALUE_COLOR_MAP_RANGE); return new THREE.Color(ranger(value)); }; } case ColorType.Category: { const categories = this.colorMap.categories; return (label: string) => { const index = categories.indexOf(label); if (index === -1) { return this.defaultColor; } return ScatterChart.CATEGORY_COLOR_MAP[index % ScatterChart.CATEGORY_COLOR_MAP.length]; }; } default: return null; } } protected getColorByIndex(index: number): THREE.Color { if (this.hoveredDataIndices.includes(index)) { return this.hoveredColor; } if (this.focusedDataIndices.includes(index)) { return this.focusedColor; } if (this.highLightDataIndices.includes(index)) { return this.highLightColor; } if (this.colorGenerator) { return this.colorGenerator(this.colorMap.labels[index]); } return this.defaultColor; } protected createMaterial() { this.material = this.createRenderMaterial(); this.pickingMaterial = this.createPickingMaterial(); } protected setGeometryAttribute(name: string, data: Float32Array, dim: number) { this.geometry.setAttribute(name, new THREE.BufferAttribute(data, dim)); } protected setPosition(positions: Float32Array) { this.setGeometryAttribute('position', positions, 3); } protected setColor(colors: Float32Array) { this.setGeometryAttribute('color', colors, 3); } private convertDataToPosition() { const data = this.data; const xScaler = d3.scaleLinear(); const yScaler = d3.scaleLinear(); let zScaler: d3.ScaleLinear<number, number> | null = null; const xExtent = d3.extent(data, (_p, i) => data[i][0]) as [number, number]; const yExtent = d3.extent(data, (_p, i) => data[i][1]) as [number, number]; const range = [-ScatterChart.CUBE_LENGTH / 2, ScatterChart.CUBE_LENGTH / 2]; xScaler.domain(xExtent).range(range); yScaler.domain(yExtent).range(range); if (this.is3D) { zScaler = d3.scaleLinear(); const zExtent = d3.extent(data, (_p, i) => data[i][2]) as [number, number]; zScaler.domain(zExtent).range(range); } const dataInRange = data.map(d => [xScaler(d[0]) ?? 0, yScaler(d[1]) ?? 0, zScaler?.(d[2]) ?? 0] as Point3D); const positions = new Float32Array(dataInRange.length * 3); let dst = 0; dataInRange.forEach(d => { positions[dst++] = d[0]; positions[dst++] = d[1]; positions[dst++] = d[2]; }); return positions; } private convertDataPickingColor() { const count = this.dataCount; const colors = new Float32Array(count * 3); let dst = 0; for (let i = 0; i < count; i++) { const color = new THREE.Color(i); colors[dst++] = color.r; colors[dst++] = color.g; colors[dst++] = color.b; } return colors; } private updateHoveredPoints() { if (!this.mouseCoordinates) { return; } const dpr = window.devicePixelRatio || 1; const x = Math.floor(this.mouseCoordinates[0] * dpr); const y = Math.floor(this.mouseCoordinates[1] * dpr); const pointCount = this.dataCount; const width = Math.floor(dpr); const height = Math.floor(dpr); const pixelBuffer = new Uint8Array(width * height * 4); this.renderer.readRenderTargetPixels( this.pickingRenderTarget, x, this.pickingRenderTarget.height - y, width, height, pixelBuffer ); const pointIndicesSelection = new Uint8Array(pointCount); const pixels = width * height; for (let i = 0; i < pixels; i++) { const id = (pixelBuffer[i * 4] << 16) | (pixelBuffer[i * 4 + 1] << 8) | pixelBuffer[i * 4 + 2]; if (id !== 16777215 && id < pointCount) { pointIndicesSelection[id] = 1; } } const pointIndices: number[] = []; for (let i = 0; i < pointIndicesSelection.length; i++) { if (pointIndicesSelection[i] === 1) { pointIndices.push(i); } } this.hoveredDataIndices = pointIndices; } private updateLight() { const light = this.scene.getObjectByName('light') as THREE.PointLight; const cameraPos = this.camera.position; const lightPos = cameraPos.clone(); lightPos.x += 1; lightPos.y += 1; light.position.set(lightPos.x, lightPos.y, lightPos.z); } private bindEventListeners() { this.canvas?.addEventListener('mousemove', this.onMouseMoveBindThis); } private removeEventListeners() { this.canvas?.removeEventListener('mousemove', this.onMouseMoveBindThis); } private onMouseMove(e: MouseEvent) { this.mouseCoordinates = [e.offsetX, e.offsetY]; this.render(); } private addAxes() { if (this.axes) { this.removeAxes(); } this.axes = new THREE.AxesHelper(); this.scene.add(this.axes); } private removeAxes() { if (this.axes) { this.scene.remove(this.axes); this.axes = null; } } protected render() { this.updateLight(); this.updateHoveredPoints(); this.onRender(); if (this.pickingMaterial) { if (this.axes) { this.scene.remove(this.axes); } if (this.object && this.pickingMaterial) { this.object.material = this.pickingMaterial; } if (this.pickingColors) { this.setColor(this.pickingColors); } this.renderer.setRenderTarget(this.pickingRenderTarget); this.renderer.render(this.scene, this.camera); if (this.axes) { this.scene.add(this.axes); } if (this.object && this.material) { this.object.material = this.material; } } if (this.colors.length) { this.setColor(this.colors); } this.renderer.setRenderTarget(null); this.renderer.render(this.scene, this.camera); } startRotate() { if (this.rotate) { return; } this.rotate = true; this.controls.autoRotate = true; this.controls.autoRotateSpeed = ScatterChart.ORBIT_ANIMATION_ROTATION_CYCLE_IN_SECONDS; const rotate = () => { this.controls.update(); this.animationId = requestAnimationFrame(rotate); }; rotate(); } stopRotate() { if (this.rotate) { this.rotate = false; this.controls.autoRotate = false; this.controls.rotateSpeed = ScatterChart.ORBIT_MOUSE_ROTATION_SPEED; if (this.animationId != null) { cancelAnimationFrame(this.animationId); this.animationId = null; } } } reset() { this.controls.reset(); if (this.is3D && !this.animationId) { this.startRotate(); } } setSize(width: number, height: number) { this.width = width; this.height = height; this.onSetSize(width, height); if (this.is3D) { const camera = this.camera as THREE.PerspectiveCamera; camera.aspect = width / height; camera.updateProjectionMatrix(); } this.renderer.setSize(width, height); this.pickingRenderTarget = this.initRenderTarget(); this.controls.update(); } setDimension(is3D: boolean) { if (this.is3D === is3D) { return; } this.is3D = is3D; this.stopRotate(); this.controls.dispose(); this.camera = this.initCamera(); this.controls = this.initControls(); if (is3D) { this.addAxes(); this.startRotate(); } else { this.removeAxes(); } this.setData(this.data, this.labels, this.colorMap); } setData(data: Point3D[], labels: string[], colorMap?: ColorMap | null) { if (this.object) { this.scene.remove(this.object); } this.labels = labels; this.colorMap = colorMap ?? {type: ColorType.Null, labels: []}; this.data = data; this.colorGenerator = this.convertColorMap(); this.positions = this.convertDataToPosition(); this.pickingColors = this.convertDataPickingColor(); this.onDataSet(); if (this.object) { this.scene.add(this.object); } this.render(); } setHighLightIndices(highLightIndices: number[]) { this.highLightDataIndices = highLightIndices; this.render(); } setFocusedPointIndices(focusedPointIndices: number[]) { this.focusedDataIndices = focusedPointIndices; this.render(); } dispose() { this.removeEventListeners(); this.onDispose(); if (this.canvas) { this.container.removeChild(this.canvas); this.canvas = null; } this.renderer.dispose(); this.controls.dispose(); this.pickingRenderTarget.dispose(); this.geometry.dispose(); this.material?.dispose(); this.pickingMaterial?.dispose(); } }
the_stack
 module RW.TextureEditor { export class TextureDefinition { private _isEnabled: boolean; public init: boolean; public numberOfImages: number; public babylonTextureType: BabylonTextureType; public propertyInMaterial: string; public canvasId: string; private _isMirror: boolean; private _mirrorPlane: BABYLON.Plane; public textureVariable: BABYLON.BaseTexture; constructor(public name: string, private _material: BABYLON.Material, onSuccess?: () => void) { this.propertyInMaterial = this.name.toLowerCase() + "Texture"; this.canvasId = this.name + "Canvas"; this.numberOfImages = 1; this._mirrorPlane = new BABYLON.Plane(0, 0, 0, 0); if (this._material[this.propertyInMaterial]) { if (this._material[this.propertyInMaterial] instanceof BABYLON.MirrorTexture) { this.babylonTextureType = BabylonTextureType.MIRROR; } else if (this._material[this.propertyInMaterial] instanceof BABYLON.VideoTexture) { this.babylonTextureType = BabylonTextureType.MIRROR; } else if (this._material[this.propertyInMaterial] instanceof BABYLON.CubeTexture) { this.babylonTextureType = BabylonTextureType.CUBE; } else { this.babylonTextureType = BabylonTextureType.NORMAL; } this.initFromMaterial(onSuccess); } else { this.babylonTextureType = BabylonTextureType.NORMAL; this.enabled(false); this.init = false; //clean canvas var canvasElement = <HTMLCanvasElement> document.getElementById(this.canvasId + "-0"); if (canvasElement) { var context = canvasElement.getContext("2d"); context.clearRect(0, 0, canvasElement.width, canvasElement.height); } if (onSuccess) { onSuccess(); } } } private initTexture() { if (this.textureVariable) { this.textureVariable.dispose(); } if (this.numberOfImages == 1) { var canvasElement = <HTMLCanvasElement> document.getElementById(this.canvasId + "-0"); var base64 = canvasElement.toDataURL(); this.textureVariable = new BABYLON.Texture(base64, this._material.getScene(), false, undefined, undefined, undefined, undefined, base64, false); if (this.name != "reflection") { this.coordinatesMode(CoordinatesMode.EXPLICIT); } else { this.coordinatesMode(CoordinatesMode.PLANAR); } this.babylonTextureType = BabylonTextureType.NORMAL; this.init = true; } else { var urls = []; for (var i = 0; i < 6; i++) { var canvasElement = <HTMLCanvasElement> document.getElementById(this.canvasId + "-"+i); urls.push(canvasElement.toDataURL()); } this.textureVariable = new BABYLON.ExtendedCubeTexture(urls, this._material.getScene(), false); this.babylonTextureType = BabylonTextureType.CUBE; this.init = true; } } private initFromMaterial(onSuccess?: () => void) { this.textureVariable = this._material[this.propertyInMaterial]; this.updateCanvas(() => { this.canvasUpdated(); this.enabled(true); if (onSuccess) { onSuccess(); } }); } public coordinatesMode(mode: CoordinatesMode) { if (angular.isDefined(mode)) { var shouldInit: boolean = mode != CoordinatesMode.CUBIC && this.numberOfImages == 6; this.textureVariable.coordinatesMode = mode; if (mode === CoordinatesMode.CUBIC) { this.numberOfImages = 6; } else { this.numberOfImages = 1; } if (shouldInit) { //this.initTexture(); } } else { return this.textureVariable ? this.textureVariable.coordinatesMode : 0; } } public setMirrorPlane(plane: BABYLON.Plane) { //if (this.babylonTextureType == BabylonTextureType.MIRROR) { this._mirrorPlane.normal = plane.normal; this._mirrorPlane.d = plane.d; //} } public mirrorEnabled(enabled: boolean) { if (angular.isDefined(enabled)) { if (enabled) { if (this.name != "reflection") { throw new Error("wrong texture for mirror! Should be reflection!"); } this.babylonTextureType = BabylonTextureType.MIRROR; //create the mirror this.textureVariable = new BABYLON.MirrorTexture("mirrorTex", 512, this._material.getScene()); this.textureVariable['renderList'] = this._material.getScene().meshes; this.textureVariable['mirrorPlane'] = this._mirrorPlane; this.init = true; //if (!this._isEnabled) { this.enabled(true); //} } else { this.babylonTextureType = BabylonTextureType.NORMAL; this._material[this.propertyInMaterial] = null; this.init = false; this.initTexture(); } } else { return this._isEnabled && this.babylonTextureType == BabylonTextureType.MIRROR; } } public enabled(enabled?: boolean) { if (angular.isDefined(enabled)) { if (enabled) { if (!this.init) { this.initTexture(); } if (this.textureVariable) this._material[this.propertyInMaterial] = this.textureVariable; this._isEnabled = true; //update the canvas from the texture, is possible this.updateCanvas(); } else { this._material[this.propertyInMaterial] = null; this._isEnabled = false; } } else { return this._isEnabled; } } public canvasUpdated() { this.initTexture(); if (this._isEnabled) { this._material[this.propertyInMaterial] = this.textureVariable; } } public getCanvasImageUrls(onUpdateSuccess : (urls:string[]) => void) { var urls = []; if (!(this.textureVariable instanceof BABYLON.MirrorTexture || this.textureVariable instanceof BABYLON.CubeTexture)) { this.updateCanvas(() => { for (var i = 0; i < this.numberOfImages; i++) { var canvas = <HTMLCanvasElement> document.getElementById(this.canvasId + "-" + i); if (this.getExtension() == ".png") urls.push(canvas.toDataURL("image/png", 0.8)); else urls.push(canvas.toDataURL("image/jpeg", 0.8)); } if (urls.length == this.numberOfImages) { onUpdateSuccess(urls); } }); } } public updateCanvas(onSuccess?: () => void) { if (this.textureVariable instanceof BABYLON.Texture) { var texture = <BABYLON.Texture> this.textureVariable; var canvas = <HTMLCanvasElement> document.getElementById(this.canvasId + "-0"); this.updateCanvasFromUrl(canvas, texture.url, onSuccess); } else if (this.textureVariable instanceof BABYLON.ExtendedCubeTexture) { var cubeTexture = <BABYLON.ExtendedCubeTexture> this.textureVariable; for (var i = 0; i < this.numberOfImages; i++) { var canvas = <HTMLCanvasElement> document.getElementById(this.canvasId + "-" + i); this.updateCanvasFromUrl(canvas, cubeTexture.urls[i], onSuccess); } } } public updateCanvasFromUrl(canvas: HTMLCanvasElement, url: string, onSuccess?: () => void) { if (!url) { return; } var image = new Image(); image.onload = function () { var ctx = canvas.getContext("2d"); //todo use canvas.style.height and width to keep aspect ratio ctx.clearRect(0, 0, canvas.width, canvas.height); var width = BABYLON.Tools.GetExponantOfTwo(image.width, 1024); var height = BABYLON.Tools.GetExponantOfTwo(image.height, 1024); var max = Math.max(width, height); if (width > height) { image.width *= height / image.height; image.height = height; } else { image.height *= width / image.width; image.width = width; } canvas.width = max; canvas.height = max; ctx.drawImage(image, 0, 0, max, max); if (onSuccess) { onSuccess(); } }; image.src = url; } //TODO implement video support etc'. At the moment only dynamic is supported. /*public setBabylonTextureType(type: BabylonTextureType) { this.babylonTextureType = type; if (type === BabylonTextureType.CUBE) { this.coordinatesMode(CoordinatesMode.CUBIC); } }*/ public exportAsJavascript(sceneVarName:string, materialVarName:string) : string { var strings: Array<string> = []; var varName = materialVarName + "_" + this.name + "Texture"; //init the variable if (this.babylonTextureType == BabylonTextureType.MIRROR) { strings.push("var " + varName + " = new BABYLON.MirrorTexture('MirrorTexture', 512," + sceneVarName + " )"); var plane: BABYLON.Plane = this.textureVariable['mirrorPlane']; var array = plane.asArray(); strings.push(varName + ".mirrorPlane = new BABYLON.Plane(" + array[0] + "," + array[1] + "," + array[2] + "," + array[3] + ")"); strings.push("// Change the render list to fit your needs. The scene's meshes is being used per default"); strings.push(varName + ".renderList = " + sceneVarName + ".meshes"); } else if (this.babylonTextureType == BabylonTextureType.CUBE) { strings.push("//TODO change the root URL for your cube reflection texture!"); strings.push("var " + varName + " = new BABYLON.CubeTexture(rootUrl, " + sceneVarName + " )"); } else { strings.push("//TODO change the filename to fit your needs!"); strings.push("var " + varName + " = new BABYLON.Texture('textures/"+ materialVarName+ "_" + this.name + this.getExtension() +"', " + sceneVarName + ")"); } //uvw stuff ["uScale", "vScale", "coordinatesMode", "uOffset", "vOffset", "uAng", "vAng", "level", "coordinatesIndex", "hasAlpha", "getAlphaFromRGB"].forEach((param) => { strings.push(varName + "." + param + " = " + this.textureVariable[param]); }); strings.push(""); strings.push(materialVarName + "."+this.propertyInMaterial+ " = " + varName); return strings.join(";\n"); } public exportAsBabylonScene(materialId: string) { var textureObject = { name: "textures/" + materialId + "_" + this.name + this.getExtension() }; ["uScale", "vScale", "coordinatesMode", "uOffset", "vOffset", "uAng", "vAng", "level", "coordinatesIndex", "hasAlpha", "getAlphaFromRGB"].forEach((param) => { textureObject[param] = this.textureVariable[param]; }); return textureObject; } public getExtension() { return this.textureVariable.hasAlpha ? ".png" : ".jpg"; } //for ng-repeat public getCanvasNumber = () => { return new Array(this.numberOfImages); } } }
the_stack
import { Map, Set } from 'immutable' import { BulletRecord, ExplosionRecord, FlickerRecord, MapRecord, PowerUpRecord, ScoreRecord, StageConfig, TankRecord, TextRecord, } from '../types' export enum A { Move = 'Move', Tick = 'Tick', AfterTick = 'AfterTick', AddBullet = 'AddBullet', SetCooldown = 'SetCooldown', SetHelmetDuration = 'SetHelmetDuration', SetFrozenTimeout = 'SetFrozenTimeout', SetBotFrozenTimeout = 'SetBotFrozenTimeout', BeforeRemoveBullet = 'BeforeRemoveBullet', RemoveBullet = 'RemoveBullet', RemoveSteels = 'RemoveSteels', RemoveBricks = 'RemoveBricks', UpdateMap = 'UpdateMap', UpdateBullets = 'UpdateBullets', LoadStageMap = 'LoadStageMap', BeforeStartStage = 'BeforeStartStage', StartStage = 'StartStage', BeforeEndStage = 'BeforeEndStage', EndStage = 'EndStage', BeforeEndGame = 'BeforeEndGame', EndGame = 'EndGame', StartGame = 'StartGame', ResetGame = 'ResetGame', GamePause = 'GamePause', GameResume = 'GameResume', ShowHud = 'ShowHud', HideHud = 'HideHud', ShowStatistics = 'ShowStatistics', HideStatistics = 'HideStatistics', RemoveFirstRemainingBot = 'RemoveFirstRemainingBot', IncrementPlayerLife = 'IncrementPlayerLife', DecrementPlayerLife = 'DecrementPlayerLife', BorrowPlayerLife = 'BorrowPlayerLife', ActivatePlayer = 'ActivatePlayer', ReqAddPlayerTank = 'ReqAddPlayerTank', ReqAddBot = 'ReqAddAIPlayer', SetExplosion = 'AddOrUpdateExplosion', RemoveExplosion = 'RemoveExplosion', SetText = 'SetText', MoveTexts = 'UpdateTextPosition', DestroyEagle = 'DestroyEagle', StartSpawnTank = 'StartSpawnTank', SetPlayerTankSpawningStatus = 'SetPlayerTankSpawningStatus', SetIsSpawningBotTank = 'SetIsSpawningBotTankStatus', AddTank = 'AddTank', StartMove = 'StartMove', SetTankToDead = 'SetTankToDead', StopMove = 'StopMove', RemoveText = 'RemoveText', RemoveFlicker = 'RemoveFlicker', SetFlicker = 'AddOrUpdateFlicker', Hit = 'Hit', Hurt = 'Hurt', Kill = 'Kill', IncKillCount = 'IncKillCount', IncPlayerScore = 'IncPlayerScore', UpdateTransientKillInfo = 'UpdateTransientKillInfo', ShowTotalKillCount = 'ShowTotalKillCount', SetPowerUp = 'SetPowerUp', RemovePowerUp = 'RemovePowerUp', RemovePowerUpProperty = 'RemovePowerUpProperty', ClearAllPowerUps = 'ClearAllPowerUps', PickPowerUp = 'PickPowerUp', AddScore = 'AddScore', RemoveScore = 'RemoveScore', UpgardeTank = 'UpgardeTank', UpdateCurtain = 'UpdateCurtain', SetReservedTank = 'SetReversedTank', SetTankVisibility = 'SetTankVisibility', ClearBullets = 'ClearBullets', UpdateComingStageName = 'UpdateComingStageName', AddRestrictedArea = 'AddRestrictedArea', RemoveRestrictedArea = 'RemoveRestrictedArea', SetAITankPath = 'SetAITankPath', RemoveAITankPath = 'RemoveAITankPath', SetCustomStage = 'SetCustomStage', RemoveCustomStage = 'RemoveCustomStage', SetEditorContent = 'SetEditorContent', SyncCustomStages = 'SyncCustomStages', LeaveGameScene = 'LeaveGameScene', PlaySound = 'PlaySound', } export type Move = ReturnType<typeof move> export function move(tank: TankRecord) { return { type: A.Move as A.Move, tankId: tank.tankId, x: tank.x, y: tank.y, rx: tank.rx, ry: tank.ry, direction: tank.direction, } } export type StartMove = ReturnType<typeof startMove> export function startMove(tankId: TankId) { return { type: A.StartMove as A.StartMove, tankId, } } export type Tick = ReturnType<typeof tick> export function tick(delta: number) { return { type: A.Tick as A.Tick, delta, } } export type AfterTick = ReturnType<typeof afterTick> export function afterTick(delta: number) { return { type: A.AfterTick as A.AfterTick, delta, } } export type AddBullet = ReturnType<typeof addBullet> export function addBullet(bullet: BulletRecord) { return { type: A.AddBullet as A.AddBullet, bullet, } } export type SetHelmetDuration = ReturnType<typeof setHelmetDuration> export function setHelmetDuration(tankId: TankId, duration: number) { return { type: A.SetHelmetDuration as A.SetHelmetDuration, tankId, duration, } } export type SetFrozenTimeout = ReturnType<typeof setFrozenTimeout> export function setFrozenTimeout(tankId: TankId, frozenTimeout: number) { return { type: A.SetFrozenTimeout as A.SetFrozenTimeout, tankId, frozenTimeout, } } export type Hit = ReturnType<typeof hit> export function hit(bullet: BulletRecord, targetTank: TankRecord, sourceTank: TankRecord) { return { type: A.Hit as A.Hit, bullet, targetTank, sourceTank, } } export type Hurt = ReturnType<typeof hurt> export function hurt(targetTank: TankRecord) { return { type: A.Hurt as A.Hurt, targetTank, } } export type Kill = ReturnType<typeof kill> export function kill(targetTank: TankRecord, sourceTank: TankRecord, method: 'bullet' | 'grenade') { return { type: A.Kill as A.Kill, targetTank, sourceTank, method, } } export type UpdateTransientKillInfo = ReturnType<typeof updateTransientKillInfo> export function updateTransientKillInfo(info: Map<PlayerName, Map<TankLevel, number>>) { return { type: A.UpdateTransientKillInfo as A.UpdateTransientKillInfo, info, } } export type IncKillCount = ReturnType<typeof incKillCount> export function incKillCount(playerName: PlayerName, level: TankLevel) { return { type: A.IncKillCount as A.IncKillCount, playerName, level, } } export type IncPlayerScore = ReturnType<typeof incPlayerScore> export function incPlayerScore(playerName: PlayerName, count: number) { return { type: A.IncPlayerScore as A.IncPlayerScore, playerName, count, } } export type StopMove = ReturnType<typeof stopMove> export function stopMove(tankId: TankId) { return { type: A.StopMove as A.StopMove, tankId, } } export type SetCooldown = ReturnType<typeof setCooldown> export function setCooldown(tankId: TankId, cooldown: number) { return { type: A.SetCooldown as A.SetCooldown, tankId, cooldown, } } export type SetBotFrozenTimeout = ReturnType<typeof setBotFrozenTimeout> export function setBotFrozenTimeout(timeout: number) { return { type: A.SetBotFrozenTimeout as A.SetBotFrozenTimeout, timeout, } } export type BeforeRemoveBullet = ReturnType<typeof beforeRemoveBullet> export function beforeRemoveBullet(bulletId: BulletId) { return { type: A.BeforeRemoveBullet as A.BeforeRemoveBullet, bulletId, } } export type RemoveBullet = ReturnType<typeof removeBullet> export function removeBullet(bulletId: BulletId) { return { type: A.RemoveBullet as A.RemoveBullet, bulletId, } } export type RemoveSteels = ReturnType<typeof removeSteels> export function removeSteels(ts: Set<SteelIndex>) { return { type: A.RemoveSteels as A.RemoveSteels, ts, } } export type RemoveBricks = ReturnType<typeof removeBricks> export function removeBricks(ts: Set<BrickIndex>) { return { type: A.RemoveBricks as A.RemoveBricks, ts, } } export type UpdateMap = ReturnType<typeof updateMap> export function updateMap(map: MapRecord) { return { type: A.UpdateMap as A.UpdateMap, map, } } export type UpdateBulelts = ReturnType<typeof updateBullets> export function updateBullets(updatedBullets: Map<BulletId, BulletRecord>) { return { type: A.UpdateBullets as A.UpdateBullets, updatedBullets, } } export type LoadStageMap = ReturnType<typeof loadStageMap> export function loadStageMap(stage: StageConfig) { return { type: A.LoadStageMap as A.LoadStageMap, stage, } } export type UpdateComingStageName = ReturnType<typeof updateComingStageName> export function updateComingStageName(stageName: string) { return { type: A.UpdateComingStageName as A.UpdateComingStageName, stageName, } } export type BeforeStartStage = ReturnType<typeof beforeStartStage> export function beforeStartStage(stage: StageConfig) { return { type: A.BeforeStartStage as A.BeforeStartStage, stage, } } export type StartStage = ReturnType<typeof startStage> export function startStage(stage: StageConfig) { return { type: A.StartStage as A.StartStage, stage, } } export type SetExplosion = ReturnType<typeof setExplosion> export function setExplosion(explosion: ExplosionRecord) { return { type: A.SetExplosion as A.SetExplosion, explosion, } } export type RemoveExplosion = ReturnType<typeof removeExplosion> export function removeExplosion(explosionId: ExplosionId) { return { type: A.RemoveExplosion as A.RemoveExplosion, explosionId, } } export type SetFlicker = ReturnType<typeof setFlicker> export function setFlicker(flicker: FlickerRecord) { return { type: A.SetFlicker as A.SetFlicker, flicker, } } export type RemoveFlicker = ReturnType<typeof removeFlicker> export function removeFlicker(flickerId: FlickerId) { return { type: A.RemoveFlicker as A.RemoveFlicker, flickerId, } } /** 坦克开始生成的信号,用于清理场上的 power-ups */ export type StartSpawnTank = ReturnType<typeof startSpawnTank> export function startSpawnTank(tank: TankRecord) { return { type: A.StartSpawnTank as A.StartSpawnTank, tank, } } export type SetPlayerTankSpawningStatus = ReturnType<typeof setPlayerTankSpawningStatus> export function setPlayerTankSpawningStatus(playerName: PlayerName, isSpawning: boolean) { return { type: A.SetPlayerTankSpawningStatus as A.SetPlayerTankSpawningStatus, playerName, isSpawning, } } export type SetIsSpawningBotTank = ReturnType<typeof setIsSpawningBotTank> export function setIsSpawningBotTank(isSpawning: boolean) { return { type: A.SetIsSpawningBotTank as A.SetIsSpawningBotTank, isSpawning, } } export type AddTank = ReturnType<typeof addTank> export function addTank(tank: TankRecord) { return { type: A.AddTank as A.AddTank, tank, } } export type SetTankToDead = ReturnType<typeof setTankToDead> export function setTankToDead(tankId: TankId) { return { type: A.SetTankToDead as A.SetTankToDead, tankId, } } export type ActivatePlayer = ReturnType<typeof activatePlayer> export function activatePlayer(playerName: PlayerName, tankId: TankId) { return { type: A.ActivatePlayer as A.ActivatePlayer, playerName, tankId, } } export type ReqAddPlayerTank = ReturnType<typeof reqAddPlayerTank> export function reqAddPlayerTank(playerName: PlayerName) { return { type: A.ReqAddPlayerTank as A.ReqAddPlayerTank, playerName, } } export type ReqAddBot = ReturnType<typeof reqAddBot> export const reqAddBot = () => ({ type: A.ReqAddBot as A.ReqAddBot }) export type SetText = ReturnType<typeof setText> export function setText(text: TextRecord) { return { type: A.SetText as A.SetText, text, } } export type RemoveText = ReturnType<typeof removeText> export function removeText(textId: TextId) { return { type: A.RemoveText as A.RemoveText, textId, } } export type MoveTexts = ReturnType<typeof moveTexts> export function moveTexts(textIds: TextId[], direction: Direction, distance: number) { return { type: A.MoveTexts as A.MoveTexts, textIds, direction, distance, } } export type DecrementPlayerLife = ReturnType<typeof decrementPlayerLife> export function decrementPlayerLife(playerName: PlayerName) { return { type: A.DecrementPlayerLife as A.DecrementPlayerLife, playerName, } } export type BorrowPlayerLife = ReturnType<typeof borrowPlayerLife> export function borrowPlayerLife(borrower: PlayerName, lender: PlayerName) { return { type: A.BorrowPlayerLife as A.BorrowPlayerLife, borrower, lender, } } export type StartGame = ReturnType<typeof startGame> export function startGame(stageIndex: number) { return { type: A.StartGame as A.StartGame, stageIndex, } } export type SetPowerUp = ReturnType<typeof setPowerUp> export function setPowerUp(powerUp: PowerUpRecord) { return { type: A.SetPowerUp as A.SetPowerUp, powerUp, } } export type RemovePowerUp = ReturnType<typeof removePowerUp> export function removePowerUp(powerUpId: PowerUpId) { return { type: A.RemovePowerUp as A.RemovePowerUp, powerUpId, } } export type RemovePowerUpProperty = ReturnType<typeof removePowerUpProperty> export function removePowerUpProperty(tankId: TankId) { return { type: A.RemovePowerUpProperty as A.RemovePowerUpProperty, tankId, } } export type PickPowerUp = ReturnType<typeof pickPowerUp> export function pickPowerUp(playerName: PlayerName, tank: TankRecord, powerUp: PowerUpRecord) { return { type: A.PickPowerUp as A.PickPowerUp, playerName, tank, powerUp, } } export type AddScore = ReturnType<typeof addScore> export function addScore(score: ScoreRecord) { return { type: A.AddScore as A.AddScore, score, } } export type RemoveScore = ReturnType<typeof removeScore> export function removeScore(scoreId: ScoreId) { return { type: A.RemoveScore as A.RemoveScore, scoreId, } } export type IncrementPlayerLife = ReturnType<typeof incrementPlayerLife> export function incrementPlayerLife(playerName: PlayerName, count = 1) { return { type: A.IncrementPlayerLife as A.IncrementPlayerLife, playerName, count, } } export type UpgardeTank = ReturnType<typeof upgardeTank> export function upgardeTank(tankId: TankId) { return { type: A.UpgardeTank as A.UpgardeTank, tankId, } } export type UpdateCurtain = ReturnType<typeof updateCurtain> export function updateCurtain(curtainName: 'stage-enter-curtain', t: number) { return { type: A.UpdateCurtain as A.UpdateCurtain, curtainName, t, } } export type SetTankVisibility = ReturnType<typeof setTankVisibility> export function setTankVisibility(tankId: TankId, visible: boolean) { return { type: A.SetTankVisibility as A.SetTankVisibility, tankId, visible, } } export type SetReservedTank = ReturnType<typeof setReservedTank> export function setReservedTank(playerName: PlayerName, tank: TankRecord) { return { type: A.SetReservedTank as A.SetReservedTank, playerName, tank, } } export type AddRestrictedArea = ReturnType<typeof addRestrictedArea> export function addRestrictedArea(areaId: AreaId, area: Rect) { return { type: A.AddRestrictedArea as A.AddRestrictedArea, areaId, area, } } export type RemoveRestrictedArea = ReturnType<typeof removeRestrictedArea> export function removeRestrictedArea(areaId: AreaId) { return { type: A.RemoveRestrictedArea as A.RemoveRestrictedArea, areaId, } } export type SetAITankPath = ReturnType<typeof setAITankPath> export function setAITankPath(tankId: TankId, path: number[]) { return { type: A.SetAITankPath as A.SetAITankPath, tankId, path } } export type RemoveAITankPath = ReturnType<typeof removeAITankPath> export function removeAITankPath(tankId: TankId) { return { type: A.RemoveAITankPath as A.RemoveAITankPath, tankId, } } export type SetCustomStage = ReturnType<typeof setCustomStage> export function setCustomStage(stage: StageConfig) { return { type: A.SetCustomStage as A.SetCustomStage, stage, } } export type RemoveCustomStage = ReturnType<typeof removeCustomStage> export function removeCustomStage(stageName: string) { return { type: A.RemoveCustomStage as A.RemoveCustomStage, stageName, } } export type SetEditorContent = ReturnType<typeof setEditorContent> export function setEditorContent(stage: StageConfig) { return { type: A.SetEditorContent as A.SetEditorContent, stage, } } export type PlaySound = ReturnType<typeof playSound> export function playSound(soundName: SoundName) { return { type: A.PlaySound as A.PlaySound, soundName, } } export type BeforeEndStage = ReturnType<typeof beforeEndStage> export const beforeEndStage = () => ({ type: A.BeforeEndStage as A.BeforeEndStage }) export type EndStage = ReturnType<typeof endStage> export const endStage = () => ({ type: A.EndStage as A.EndStage }) export type BeforeEndGame = ReturnType<typeof beforeEndGame> export const beforeEndGame = () => ({ type: A.BeforeEndGame as A.BeforeEndGame }) export type EndGame = ReturnType<typeof endGame> export const endGame = () => ({ type: A.EndGame as A.EndGame }) export type ResetGame = ReturnType<typeof resetGame> export const resetGame = () => ({ type: A.ResetGame as A.ResetGame }) export type GamePause = ReturnType<typeof gamePause> export const gamePause = () => ({ type: A.GamePause as A.GamePause }) export type GameResume = ReturnType<typeof gameResume> export const gameResume = () => ({ type: A.GameResume as A.GameResume }) export type ShowHud = ReturnType<typeof showHud> export const showHud = () => ({ type: A.ShowHud as A.ShowHud }) export type HideHud = ReturnType<typeof hideHud> export const hideHud = () => ({ type: A.HideHud as A.HideHud }) export type ShowStatistics = ReturnType<typeof showStatistics> export const showStatistics = () => ({ type: A.ShowStatistics as A.ShowStatistics }) export type HideStatistics = ReturnType<typeof hideStatistics> export const hideStatistics = () => ({ type: A.HideStatistics as A.HideStatistics }) export type RemoveFirstRemainingBot = ReturnType<typeof removeFirstRemainingBot> export const removeFirstRemainingBot = () => ({ type: A.RemoveFirstRemainingBot as A.RemoveFirstRemainingBot, }) export type DestroyEagle = ReturnType<typeof destroyEagle> export const destroyEagle = () => ({ type: A.DestroyEagle as A.DestroyEagle }) export type ShowTotalKillCount = ReturnType<typeof showTotalKillCount> export const showTotalKillCount = () => ({ type: A.ShowTotalKillCount as A.ShowTotalKillCount }) export type ClearAllPowerUps = ReturnType<typeof clearAllPowerUps> export const clearAllPowerUps = () => ({ type: A.ClearAllPowerUps as A.ClearAllPowerUps }) export type ClearBullets = ReturnType<typeof clearBullets> export const clearBullets = () => ({ type: A.ClearBullets as A.ClearBullets }) export type SyncCustomStages = ReturnType<typeof syncCustomStages> export const syncCustomStages = () => ({ type: A.SyncCustomStages as A.SyncCustomStages }) export type LeaveGameScene = ReturnType<typeof leaveGameScene> export const leaveGameScene = () => ({ type: A.LeaveGameScene as A.LeaveGameScene }) export type Action = | Move | StartMove | Tick | AfterTick | AddBullet | SetCooldown | SetHelmetDuration | SetFrozenTimeout | SetBotFrozenTimeout | BeforeRemoveBullet | RemoveBullet | RemoveSteels | RemoveBricks | UpdateMap | UpdateBulelts | LoadStageMap | BeforeStartStage | StartStage | BeforeEndStage | EndStage | BeforeEndGame | EndGame | StartGame | ResetGame | GamePause | GameResume | ShowHud | HideHud | ShowStatistics | HideStatistics | RemoveFirstRemainingBot | IncrementPlayerLife | DecrementPlayerLife | BorrowPlayerLife | ActivatePlayer | ReqAddPlayerTank | ReqAddBot | SetExplosion | RemoveExplosion | SetText | MoveTexts | DestroyEagle | StartSpawnTank | SetPlayerTankSpawningStatus | SetIsSpawningBotTank | AddTank | SetTankToDead | StopMove | RemoveText | RemoveFlicker | SetFlicker | Hit | Hurt | Kill | IncKillCount | IncPlayerScore | UpdateTransientKillInfo | ShowTotalKillCount | SetPowerUp | RemovePowerUp | RemovePowerUpProperty | ClearAllPowerUps | PickPowerUp | AddScore | RemoveScore | UpgardeTank | UpdateCurtain | SetReservedTank | SetTankVisibility | ClearBullets | UpdateComingStageName | AddRestrictedArea | RemoveRestrictedArea | SetAITankPath | RemoveAITankPath | SetCustomStage | RemoveCustomStage | SetEditorContent | SyncCustomStages | LeaveGameScene | PlaySound
the_stack
import type {Class, ObserverType} from "@swim/util"; import type {MemberFastenerClass} from "@swim/component"; import type {TraitCreator, Trait} from "@swim/model"; import type {PositionGestureInput, ViewCreator} from "@swim/view"; import type {HtmlView} from "@swim/dom"; import type {Graphics} from "@swim/graphics"; import {Controller, TraitViewRef, TraitViewControllerSet} from "@swim/controller"; import type {CellView} from "../cell/CellView"; import {TextCellView} from "../cell/TextCellView"; import type {CellTrait} from "../cell/CellTrait"; import {CellController} from "../cell/CellController"; import type {TextCellController} from "../cell/TextCellController"; import type {IconCellController} from "../cell/IconCellController"; import {LeafView} from "./LeafView"; import {LeafTrait} from "./LeafTrait"; import type {LeafControllerObserver} from "./LeafControllerObserver"; /** @public */ export interface LeafControllerCellExt { attachCellTrait(cellTrait: CellTrait, cellController: CellController): void; detachCellTrait(cellTrait: CellTrait, cellController: CellController): void; attachCellView(cellView: CellView, cellController: CellController): void; detachCellView(cellView: CellView, cellController: CellController): void; attachCellContentView(cellContentView: HtmlView, cellController: CellController): void; detachCellContentView(cellContentView: HtmlView, cellController: CellController): void; } /** @public */ export class LeafController extends Controller { override readonly observerType?: Class<LeafControllerObserver>; @TraitViewRef<LeafController, LeafTrait, LeafView>({ traitType: LeafTrait, observesTrait: true, willAttachTrait(leafTrait: LeafTrait): void { this.owner.callObservers("controllerWillAttachLeafTrait", leafTrait, this.owner); }, didAttachTrait(leafTrait: LeafTrait): void { const cellTraits = leafTrait.cells.traits; for (const traitId in cellTraits) { const cellTrait = cellTraits[traitId]!; this.owner.cells.addTraitController(cellTrait); } }, willDetachTrait(leafTrait: LeafTrait): void { const cellTraits = leafTrait.cells.traits; for (const traitId in cellTraits) { const cellTrait = cellTraits[traitId]!; this.owner.cells.deleteTraitController(cellTrait); } }, didDetachTrait(leafTrait: LeafTrait): void { this.owner.callObservers("controllerDidDetachLeafTrait", leafTrait, this.owner); }, traitWillAttachCell(cellTrait: CellTrait, targetTrait: Trait | null): void { this.owner.cells.addTraitController(cellTrait, targetTrait); }, traitDidDetachCell(cellTrait: CellTrait): void { this.owner.cells.deleteTraitController(cellTrait); }, viewType: LeafView, observesView: true, initView(leafView: LeafView): void { const cellControllers = this.owner.cells.controllers; for (const controllerId in cellControllers) { const cellController = cellControllers[controllerId]!; const cellView = cellController.cell.view; if (cellView !== null && cellView.parent === null) { const cellTrait = cellController.cell.trait; if (cellTrait !== null) { cellController.cell.insertView(leafView, void 0, void 0, cellTrait.key); } } } }, willAttachView(leafView: LeafView): void { this.owner.callObservers("controllerWillAttachLeafView", leafView, this.owner); }, didDetachView(leafView: LeafView): void { this.owner.callObservers("controllerDidDetachLeafView", leafView, this.owner); }, viewWillHighlight(leafView: LeafView): void { this.owner.callObservers("controllerWillHighlightLeafView", leafView, this.owner); }, viewDidHighlight(leafView: LeafView): void { this.owner.callObservers("controllerDidHighlightLeafView", leafView, this.owner); }, viewWillUnhighlight(leafView: LeafView): void { this.owner.callObservers("controllerWillUnhighlightLeafView", leafView, this.owner); }, viewDidUnhighlight(leafView: LeafView): void { this.owner.callObservers("controllerDidUnhighlightLeafView", leafView, this.owner); }, viewDidEnter(leafView: LeafView): void { this.owner.callObservers("controllerDidEnterLeafView", leafView, this.owner); }, viewDidLeave(leafView: LeafView): void { this.owner.callObservers("controllerDidLeaveLeafView", leafView, this.owner); }, viewDidPress(input: PositionGestureInput, event: Event | null, leafView: LeafView): void { this.owner.callObservers("controllerDidPressLeafView", input, event, leafView, this.owner); }, viewDidLongPress(input: PositionGestureInput, leafView: LeafView): void { this.owner.callObservers("controllerDidLongPressLeafView", input, leafView, this.owner); }, }) readonly leaf!: TraitViewRef<this, LeafTrait, LeafView>; static readonly leaf: MemberFastenerClass<LeafController, "leaf">; getCellTrait<F extends abstract new (...args: any) => CellTrait>(key: string, cellTraitClass: F): InstanceType<F> | null; getCellTrait(key: string): CellTrait | null; getCellTrait(key: string, cellTraitClass?: abstract new (...args: any) => CellTrait): CellTrait | null { const leafTrait = this.leaf.trait; return leafTrait !== null ? leafTrait.getCell(key, cellTraitClass!) : null; } getOrCreateCellTrait<F extends TraitCreator<F, CellTrait>>(key: string, cellTraitClass: F): InstanceType<F> { const leafTrait = this.leaf.trait; if (leafTrait === null) { throw new Error("no leaf trait"); } return leafTrait.getOrCreateCell(key, cellTraitClass); } setCellTrait(key: string, cellTrait: CellTrait): void { const leafTrait = this.leaf.trait; if (leafTrait === null) { throw new Error("no leaf trait"); } leafTrait.setCell(key, cellTrait); } getCellView<F extends abstract new (...args: any) => CellView>(key: string, cellViewClass: F): InstanceType<F> | null; getCellView(key: string): CellView | null; getCellView(key: string, cellViewClass?: abstract new (...args: any) => CellView): CellView | null { const leafView = this.leaf.view; return leafView !== null ? leafView.getCell(key, cellViewClass!) : null; } getOrCreateCellView<F extends ViewCreator<F, CellView>>(key: string, cellViewClass: F): InstanceType<F> { let leafView = this.leaf.view; if (leafView === null) { leafView = this.leaf.createView(); if (leafView === null) { throw new Error("no leaf view"); } this.leaf.setView(leafView); } return leafView.getOrCreateCell(key, cellViewClass); } setCellView(key: string, cellView: CellView): void { let leafView = this.leaf.view; if (leafView === null) { leafView = this.leaf.createView(); if (leafView === null) { throw new Error("no leaf view"); } this.leaf.setView(leafView); } leafView.setCell(key, cellView); } @TraitViewControllerSet<LeafController, CellTrait, CellView, CellController, LeafControllerCellExt & ObserverType<CellController | TextCellController | IconCellController>>({ implements: true, type: CellController, binds: true, observes: true, get parentView(): LeafView | null { return this.owner.leaf.view; }, getTraitViewRef(cellController: CellController): TraitViewRef<unknown, CellTrait, CellView> { return cellController.cell; }, willAttachController(cellController: CellController): void { this.owner.callObservers("controllerWillAttachCell", cellController, this.owner); }, didAttachController(cellController: CellController): void { const cellTrait = cellController.cell.trait; if (cellTrait !== null) { this.attachCellTrait(cellTrait, cellController); } const cellView = cellController.cell.view; if (cellView !== null) { this.attachCellView(cellView, cellController); } }, willDetachController(cellController: CellController): void { const cellView = cellController.cell.view; if (cellView !== null) { this.detachCellView(cellView, cellController); } const cellTrait = cellController.cell.trait; if (cellTrait !== null) { this.detachCellTrait(cellTrait, cellController); } }, didDetachController(cellController: CellController): void { this.owner.callObservers("controllerDidDetachCell", cellController, this.owner); }, controllerWillAttachCellTrait(cellTrait: CellTrait, cellController: CellController): void { this.owner.callObservers("controllerWillAttachCellTrait", cellTrait, cellController, this.owner); this.attachCellTrait(cellTrait, cellController); }, controllerDidDetachCellTrait(cellTrait: CellTrait, cellController: CellController): void { this.detachCellTrait(cellTrait, cellController); this.owner.callObservers("controllerDidDetachCellTrait", cellTrait, cellController, this.owner); }, attachCellTrait(cellTrait: CellTrait, cellController: CellController): void { // hook }, detachCellTrait(cellTrait: CellTrait, cellController: CellController): void { // hook }, controllerWillAttachCellView(cellView: CellView, cellController: CellController): void { this.owner.callObservers("controllerWillAttachCellView", cellView, cellController, this.owner); this.attachCellView(cellView, cellController); }, controllerDidDetachCellView(cellView: CellView, cellController: CellController): void { this.detachCellView(cellView, cellController); this.owner.callObservers("controllerDidDetachCellView", cellView, cellController, this.owner); }, attachCellView(cellView: CellView, cellController: CellController): void { if (cellView instanceof TextCellView) { const cellContentView = cellView.content.view; if (cellContentView !== null) { this.attachCellContentView(cellContentView, cellController); } } }, detachCellView(cellView: CellView, cellController: CellController): void { if (cellView instanceof TextCellView) { const cellContentView = cellView.content.view; if (cellContentView !== null) { this.detachCellContentView(cellContentView, cellController); } } cellView.remove(); }, controllerDidPressCellView(input: PositionGestureInput, event: Event | null, cellView: CellView, cellController: CellController): void { this.owner.callObservers("controllerDidPressCellView", input, event, cellView, cellController, this.owner); }, controllerDidLongPressCellView(input: PositionGestureInput, cellView: CellView, cellController: CellController): void { this.owner.callObservers("controllerDidLongPressCellView", input, cellView, cellController, this.owner); }, controllerWillAttachCellContentView(contentView: HtmlView, cellController: CellController): void { this.attachCellContentView(contentView, cellController); this.owner.callObservers("controllerWillAttachCellContentView", contentView, cellController, this.owner); }, controllerDidDetachCellContentView(contentView: HtmlView, cellController: CellController): void { this.owner.callObservers("controllerDidDetachCellContentView", contentView, cellController, this.owner); this.detachCellContentView(contentView, cellController); }, attachCellContentView(cellContentView: HtmlView, cellController: CellController): void { // hook }, detachCellContentView(cellContentView: HtmlView, cellController: CellController): void { // hook }, controllerWillSetCellIcon(newCellIcon: Graphics | null, oldCellIcon: Graphics | null, cellController: CellController): void { this.owner.callObservers("controllerWillSetCellIcon", newCellIcon, oldCellIcon, cellController, this.owner); }, controllerDidSetCellIcon(newCellIcon: Graphics | null, oldCellIcon: Graphics | null, cellController: CellController): void { this.owner.callObservers("controllerDidSetCellIcon", newCellIcon, oldCellIcon, cellController, this.owner); }, createController(cellTrait?: CellTrait): CellController { if (cellTrait !== void 0) { return CellController.fromTrait(cellTrait); } else { return TraitViewControllerSet.prototype.createController.call(this); } }, }) readonly cells!: TraitViewControllerSet<this, CellTrait, CellView, CellController>; static readonly cells: MemberFastenerClass<LeafController, "cells">; }
the_stack
import type Pose from '../../armature/Pose'; import type { IKChain, IKLink } from "../rigs/IKChain"; //import type { IKData } from '..'; import type { ISolver } from './support/ISolver'; import type Bone from '../../armature/Bone'; import { QuatUtil, Transform, Vec3Util } from '../../maths'; import { vec3, quat } from 'gl-matrix'; //#endregion class NaturalCCDSolver implements ISolver{ //#region TARGETTING DATA effectorPos : vec3 = [ 0, 0, 0 ]; _inWorldSpace = false; // Use & Apply changes to pose, else will use bindpose for initial data & updating pose _tries = 30; _minEffRng = 0.001**2; // Min Effector Range Square _chainCnt = 0; _local !: Transform[]; _world !: Transform[]; _kFactor !: any; //#endregion initData( pose?: Pose, chain?: IKChain ): this{ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Get the Chain's Tail Position as the Effector Position if( pose && chain ){ const lnk = chain.last(); const eff : vec3 = [ 0, lnk.len, 0 ]; pose.bones[ lnk.idx ].world.transformVec3( eff ); // The Trail Position in WorldSpace //eff.copyTo( this.effectorPos ); vec3.copy( this.effectorPos, eff ); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Setup Transform Chains to handle Iterative Processing of CCD if( chain ){ const cnt = chain.count; this._chainCnt = cnt; this._world = new Array( cnt + 1 ); // Extra Transform for Final Tail this._local = new Array( cnt + 1 ); // Create a Transform for each link/bone for( let i=0; i < cnt; i++ ){ this._world[ i ] = new Transform(); this._local[ i ] = new Transform(); } // Tail Transform this._world[ cnt ] = new Transform(); this._local[ cnt ] = new Transform( [0,0,0,1], [0,chain.last().len,0], [1,1,1] ); } return this; } //#region SETTING TARGET DATA setTargetPos( v: vec3 ): this{ this.effectorPos[ 0 ] = v[ 0 ]; this.effectorPos[ 1 ] = v[ 1 ]; this.effectorPos[ 2 ] = v[ 2 ]; return this; } useArcSqrFactor( c: number, offset: number, useInv = false ): this{ this._kFactor = new KFactorArcSqr( c, offset, useInv ); return this } inWorldSpace(): this{ this._inWorldSpace = true; return this; } setTries( v: number ){ this._tries = v; return this; } //#endregion resolve( chain: IKChain, pose: Pose, debug?:any ): void{ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if( !this._local ){ const cnt = chain.count; this._world = new Array( cnt + 1 ); // Extra Transform for Final Tail this._local = new Array( cnt + 1 ); for( let i=0; i < cnt; i++ ){ this._world[ i ] = new Transform(); this._local[ i ] = new Transform(); } // Tail Transform this._world[ cnt ] = new Transform(); this._local[ cnt ] = new Transform( [0,0,0,1], [0,chain.last().len,0], [1,1,1] ); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ const root = new Transform(); let lnk: IKLink = chain.first(); // Get the Starting Transform pose.getWorldTransform( lnk.pidx, root ); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ let i: number; // Set the Initial Local Space from the chain Bind Pose for( i=0; i < chain.count; i++ ){ if( !this._inWorldSpace ) this._local[ i ].copy( chain.links[ i ].bind ); else this._local[ i ].copy( pose.bones[ chain.links[ i ].idx ].local ); } this._updateWorld( 0, root ); // Update World Space if( Vec3Util.lenSqr( this.effectorPos, this._getTailPos() ) < this._minEffRng ){ //console.log( 'CCD Chain is already at endEffector at initial call' ); return; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for( i=0; i < this._tries; i++ ){ if( this._iteration( chain, pose, root, debug ) ) break; // Exit early if reaching effector } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Save Results to Pose for( i=0; i < chain.count; i++ ){ pose.setLocalRot( chain.links[ i ].idx, this._local[ i ].rot ); } } // Update the Iteration Transform Chain, helps know the position of // each joint & end effector ( Last point on the chain ) _updateWorld( startIdx: number, root: Transform ){ const w = this._world; const l = this._local; let i : number; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HANDLE ROOT TRANSFORM if( startIdx == 0 ){ w[ 0 ].fromMul( root, l[ 0 ] ); // ( Pose Offset * Chain Parent ) * First Link startIdx++; // Start on the Nex Transform } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // HANDLE MIDDLE TRANSFORMS for( i=startIdx; i < w.length; i++ ){ w[ i ].fromMul( w[ i-1 ], l[ i ] ); // Parent * Child } } _getTailPos(){ return this._world[ this._world.length - 1 ].pos; } _iteration( chain: IKChain, pose: Pose, root: Transform, debug ?:any ): boolean{ const w = this._world; const l = this._local; const cnt = w.length - 1; const tail = w[ cnt ]; const tailDir : vec3 = [0,0,0]; const effDir : vec3 = [0,0,0]; const lerpDir : vec3 = [0,0,0]; const q : quat = [0,0,0,1]; const k = this._kFactor; let i : number; let diff : number; let b : Transform; if( k ) k.reset(); for( i=cnt-1; i >= 0; i-- ){ // Skip End Effector Transform //-------------------------------------- // Check how far tail is from End Effector diff = Vec3Util.lenSqr( tail.pos, this.effectorPos ); // Distance Squared from Tail to Effector if( diff <= this._minEffRng ) return true; // Point Reached, can Stop //-------------------------------------- b = w[ i ]; //tailDir.fromSub( tail.pos, b.pos ).norm(); // Direction from current joint to end effector //effDir.fromSub( this.effectorPos, b.pos ).norm(); // Direction from current joint to target vec3.sub( tailDir, tail.pos, b.pos ); vec3.normalize( tailDir, tailDir ); vec3.sub( effDir, this.effectorPos, b.pos ); vec3.normalize( effDir, effDir ); if( k ) k.apply( chain, chain.links[ i ], tailDir, effDir, lerpDir ); // How Factor to Rotation Movement else vec3.copy( lerpDir, effDir ); //lerpDir.copy( effDir ); //q .fromUnitVecs( tailDir, lerpDir ) // Create Rotation toward target // .mul( b.rot ); // Apply to current World rotation quat.rotationTo( q, tailDir, lerpDir ); quat.mul( q, q, b.rot ); // if( i != 0 ) q.pmulInvert( w[ i-1 ].rot ); // To Local Space // else q.pmulInvert( root.rot ); if( i != 0 ) QuatUtil.pmulInvert( q, q, w[ i-1 ].rot ); // To Local Space else QuatUtil.pmulInvert( q, q, root.rot ); //l[ i ].rot.copy( q ); // Save back to bone quat.copy( l[ i ].rot, q ); //-------------------------------------- this._updateWorld( i, root ); // Update Chain from this bone and up. } return false; } } /* class KFactorCircle{ constructor( c, r ){ this.k = Maths.clamp( c / r, 0, 1 ); // K = Constant / Radius } static fromChainLen( c, chainLen ){ // Radius = ( 180 + ArcLength ) / ( PI * ArcAngle ) let r = ( 180 * chainLen ) / ( Math.PI * Math.PI * 2 ); return new KFactorCircle( c, r ); } static fromChain( c, chain ){ // Radius = ( 180 + ArcLength ) / ( PI * ArcAngle ) let r = ( 180 * chain.len ) / ( Math.PI * Math.PI * 2 ); return new KFactorCircle( c, r ); } reset(){} // No State to reset apply( bone, effDir, tarDir, out ){ out.from_lerp( effDir, tarDir, this.k ).norm(); } } */ class KFactorArcSqr{ c : number; offset : number; arcLen = 0; useInv = false; constructor( c: number, offset: number, useInv = false ){ this.c = c; this.offset = offset; this.useInv = useInv; } reset(){ this.arcLen = 0; } apply( chain: IKChain, lnk: IKLink, tailDir: vec3 , effDir: vec3, out: vec3 ){ // Notes, Can do the inverse of pass in chain's length so chain.len - this.arcLen // This causes the beginning of the chain to move more and the tail less. this.arcLen += lnk.len; // Accumulate the Arc length for each bone //const k = this.c / Math.sqrt( this.arcLen + this.offset ); // k = Constant / sqrt( CurrentArcLen ) const k = ( !this.useInv )? this.c / Math.sqrt( this.arcLen + this.offset ) : this.c / Math.sqrt( ( chain.length - this.arcLen ) + this.offset ) //out.fromLerp( tailDir, effDir, k ).norm(); vec3.lerp( out, tailDir, effDir, k ); vec3.normalize( out, out ); } } /* class KFactorArc{ constructor( c, offset ){ this.c = c; this.arcLen = 0; this.offset = offset; } reset(){ this.arcLen = 0; } apply( bone, effDir, tarDir, out ){ // Notes, Can do the inverse of pass in chain's length so chain.len - this.arcLen // This causes the beginning of the chain to move more and the tail less. this.arcLen += bone.len; //Accumulate the Arc length for each bone let k = this.c / ( this.arcLen + this.offset ); // k = Constant / CurrentArcLen out.from_lerp( effDir, tarDir, k ).norm(); } } class KFactorOther{ constructor( chainLen ){ this.chainLen = chainLen; this.arcLen = 0; this.offset = 0.1; this.scalar = 1.3; } reset(){ this.arcLen = 0; } apply( bone, effDir, tarDir, out ){ // Just messing around with numbers to see if there is ways to alter the movement of the chain this.arcLen += bone.len; let k = ( ( this.chainLen - this.arcLen + this.offset ) / ( this.chainLen*this.scalar ) )**2; out.from_lerp( effDir, tarDir, k ).norm(); } } */ export default NaturalCCDSolver;
the_stack
import * as cp from 'child_process'; import { defaults, noop, startsWith, trimStart } from 'lodash'; import * as readline from 'readline'; import { AsyncSubject, Observable } from 'rxjs'; import { CompositeDisposable, Disposable } from 'ts-disposables'; import { IDriver, IDriverOptions, ILogger, IOmnisharpPlugin } from '../enums'; import { DriverState } from '../enums'; import { isSupportedRuntime, RuntimeContext } from '../helpers/runtime'; import * as OmniSharp from '../omnisharp-server'; let spawn = cp.spawn; if (process.platform === 'win32') { // tslint:disable-next-line:no-var-requires no-require-imports spawn = require('../windows/super-spawn').spawn; } const env: any = defaults({ ATOM_SHELL_INTERNAL_RUN_AS_NODE: '1' }, process.env); export class StdioDriver implements IDriver { public id: string; public currentState: DriverState = DriverState.Disconnected; private _seq: number; private _process: cp.ChildProcess | null; private _outstandingRequests = new Map<number, AsyncSubject<any>>(); private _projectPath: string; private _additionalArguments: string[]; private _disposable = new CompositeDisposable(); private _plugins: IOmnisharpPlugin[]; private _serverPath: string | undefined; private _findProject: boolean; private _logger: ILogger; private _timeout: number; private _version: string | undefined; private _PATH: string; private _runtimeContext: RuntimeContext; private _onEvent: (event: OmniSharp.Stdio.Protocol.EventPacket) => void; private _onCommand: (event: OmniSharp.Stdio.Protocol.ResponsePacket) => void; private _onState: (state: DriverState) => void; public constructor({ projectPath, serverPath, findProject, logger, timeout, additionalArguments, plugins, version, onEvent, onState, onCommand }: Partial<IDriverOptions> & { projectPath: string; }) { this._projectPath = projectPath; this._findProject = findProject || false; this._logger = logger || console; this._serverPath = serverPath; this._timeout = (timeout || 60) * 1000; this._additionalArguments = additionalArguments || []; this._plugins = plugins || []; this._version = version; this._onEvent = onEvent || noop; this._onState = state => { if (state !== this.currentState) { (onState || noop)(state); this.currentState = state; } }; this._onCommand = onCommand || noop; this._runtimeContext = this._getRuntimeContext(); this._disposable.add(Disposable.create(() => { if (this._process) { this._process.removeAllListeners(); } })); this._disposable.add(Disposable.create(() => { this._outstandingRequests.clear(); })); } public dispose() { if (this._disposable.isDisposed) { return; } this.disconnect(); this._disposable.dispose(); } public get serverPath() { if (this._serverPath) { return this._serverPath; } return this._runtimeContext.location; } public get projectPath() { return this._projectPath; } public get outstandingRequests() { return this._outstandingRequests.size; } public connect() { if (this._disposable.isDisposed) { throw new Error('Driver is disposed'); } this._ensureRuntimeExists() .then(() => this._connect()); } public disconnect() { // tslint:disable-next-line:triple-equals if (this._process != null && this._process.pid) { this._process.kill('SIGTERM'); } this._process = null; this._onState(DriverState.Disconnected); } public request<TRequest, TResponse>(command: string, request?: TRequest): PromiseLike<TResponse> { if (!this._process) { return <any>Observable.throw(new Error('Server is not connected, erroring out')); } const sequence = this._seq++; const packet: OmniSharp.Stdio.Protocol.RequestPacket = { // Command: trimStart(command, '/'), Command: command, Seq: sequence, Arguments: request }; const subject = new AsyncSubject<TResponse>(); const response = subject .asObservable(); // Doing a little bit of tickery here // Going to return this Observable, as if it were promise like. // And we will only commit to the promise once someone calls then on it. // This way another client, can cast the result to an observable, and gain cancelation const promiseLike: PromiseLike<TResponse> = <any>response; promiseLike.then = <any>((fulfilled: Function, rejected: Function) => { return response.toPromise().then(<any>fulfilled, <any>rejected); }); this._outstandingRequests.set(sequence, subject); this._process.stdin.write(JSON.stringify(packet) + '\n', 'utf8'); return promiseLike; } public updatePlugins(plugins: IOmnisharpPlugin[]) { this._plugins = plugins; this.disconnect(); this.connect(); } private _getRuntimeContext() { return new RuntimeContext({ platform: process.platform, arch: process.arch, version: this._version || undefined }, this._logger); } private _connect() { this._seq = 1; this._outstandingRequests.clear(); this._onState(DriverState.Connecting); let path = this.serverPath; this._logger.log(`Connecting to child @ ${process.execPath}`); this._logger.log(`Path to server: ${path}`); this._logger.log(`Selected project: ${this._projectPath}`); env.PATH = this._PATH || env.PATH; const serverArguments: any[] = [ '--stdio', '--zero-based-indices', '-s', this._projectPath, '--hostPID', process.pid ].concat(this._additionalArguments || []); if (startsWith(path, 'mono ')) { serverArguments.unshift(path.substr(5)); serverArguments.splice(0, 0, '--assembly-loader=strict'); path = 'mono'; } this._logger.log(`Arguments: ${serverArguments}`); this._process = spawn(path, serverArguments, { env }); if (!this._process.pid) { this._serverErr('failed to connect to connect to server'); return; } this._process.stderr.on('data', (data: any) => this._logger.error(data.toString())); this._process.stderr.on('data', (data: any) => this._serverErr(data)); const rl = readline.createInterface({ input: this._process.stdout, output: undefined }); rl.on('line', (data: any) => this._handleData(data)); this.id = this._process.pid.toString(); this._process.on('error', (data: any) => this._serverErr(data)); this._process.on('close', () => this.disconnect()); this._process.on('exit', () => this.disconnect()); this._process.on('disconnect', () => this.disconnect()); } private _ensureRuntimeExists() { this._onState(DriverState.Downloading); return isSupportedRuntime(this._runtimeContext) .toPromise() .then(ctx => { this._PATH = ctx.path!; this._runtimeContext = this._getRuntimeContext(); return ctx; }) .then(runtime => this._runtimeContext.downloadRuntimeIfMissing() .toPromise() .then(() => { this._onState(DriverState.Downloaded); }) ); } private _serverErr(data: any) { const friendlyMessage = this._parseError(data); this._onState(DriverState.Error); this._process = null; this._onEvent({ Type: 'error', Event: 'error', Seq: -1, Body: { Message: friendlyMessage } }); } private _parseError(data: any) { let message = data.toString(); if (data.code === 'ENOENT' && data.path === 'mono') { message = 'mono could not be found, please ensure it is installed and in your path'; } return message; } private _handleData(data: string) { let packet: OmniSharp.Stdio.Protocol.Packet | undefined; try { packet = JSON.parse(data.trim()); } catch (_error) { this._handleNonPacket(data); } if (packet) { this._handlePacket(packet); } } private _handlePacket(packet: OmniSharp.Stdio.Protocol.Packet) { if (packet.Type === 'response') { this._handlePacketResponse(<OmniSharp.Stdio.Protocol.ResponsePacket>packet); } else if (packet.Type === 'event') { this._handlePacketEvent(<OmniSharp.Stdio.Protocol.EventPacket>packet); } } private _handlePacketResponse(response: OmniSharp.Stdio.Protocol.ResponsePacket) { if (this._outstandingRequests.has(response.Request_seq)) { const observer = this._outstandingRequests.get(response.Request_seq)!; this._outstandingRequests.delete(response.Request_seq); if ((<any>observer).closed) { return; } if (response.Success) { observer.next(response.Body); observer.complete(); } else { observer.error(response.Message); } } else { if (response.Success) { this._onCommand(response); } else { // TODO: make notification? } } } private _handlePacketEvent(event: OmniSharp.Stdio.Protocol.EventPacket) { this._onEvent(event); if (event.Event === 'started') { this._onState(DriverState.Connected); } } private _handleNonPacket(data: any) { const s = data.toString(); this._onEvent({ Type: 'unknown', Event: 'unknown', Seq: -1, Body: { Message: s } }); const ref = s.match(/Detected an OmniSharp instance already running on port/); // tslint:disable-next-line:triple-equals if ((ref != null ? ref.length : 0) > 0) { this.disconnect(); } } // tslint:disable-next-line:max-file-line-count }
the_stack
import { AudioPlayerOptions, AudioRecorderOptions, TNSPlayer, TNSRecorder } from 'nativescript-audio'; import * as app from 'tns-core-modules/application'; import { Observable } from 'tns-core-modules/data/observable'; import { File, knownFolders } from 'tns-core-modules/file-system'; import { isAndroid } from 'tns-core-modules/platform'; import * as timer from 'tns-core-modules/timer'; import * as dialogs from 'tns-core-modules/ui/dialogs'; import { Page } from 'tns-core-modules/ui/page'; import { Slider } from 'tns-core-modules/ui/slider'; import './async-await'; import { Prop } from './prop'; export class AudioDemo extends Observable { @Prop() public isPlaying: boolean; @Prop() public isRecording: boolean; @Prop() public audioMeter = '0'; @Prop() public recordedAudioFile: string; @Prop() public currentVolume; @Prop() public audioTrackDuration; @Prop() public remainingDuration; // used to show the remaining time of the audio track private _recorder; private _player: TNSPlayer; private _audioSessionId; private _page; private _lastRecordedAudioFile: string; private _audioUrls: Array<any> = [ { name: 'Fight Club', pic: '~/pics/canoe_girl.jpeg', url: 'http://www.noiseaddicts.com/samples_1w72b820/2514.mp3' }, { name: 'To The Bat Cave!!!', pic: '~/pics/bears.jpeg', url: 'http://www.noiseaddicts.com/samples_1w72b820/17.mp3' }, { name: 'Marlon Brando', pic: '~/pics/northern_lights.jpeg', url: 'http://www.noiseaddicts.com/samples_1w72b820/47.mp3' } ]; private _meterInterval: any; private _slider: Slider; constructor(page: Page) { super(); this._player = new TNSPlayer(); this._player.debug = true; // set true for tns_player logs this._recorder = new TNSRecorder(); this._recorder.debug = true; // set true for tns_recorder logs this.currentVolume = 1; this._slider = page.getViewById('volumeSlider') as Slider; // Set player volume if (this._slider) { this._slider.on('valueChange', (data: any) => { this._player.volume = this._slider.value / 100; }); } } public async startRecord() { try { if (!TNSRecorder.CAN_RECORD()) { dialogs.alert('This device cannot record audio.'); return; } const audioFolder = knownFolders.currentApp().getFolder('audio'); console.log(JSON.stringify(audioFolder)); let androidFormat; let androidEncoder; if (isAndroid) { // m4a // static constants, using raw values here // androidFormat = android.media.MediaRecorder.OutputFormat.MPEG_4; androidFormat = 2; // androidEncoder = android.media.MediaRecorder.AudioEncoder.AAC; androidEncoder = 3; } const dateTime = this._createDateTimeStamp(); this._lastRecordedAudioFile = `${ audioFolder.path }/recording_${dateTime}.${this.platformExtension()}`; console.log('recorded audio file path', this._lastRecordedAudioFile); const recorderOptions: AudioRecorderOptions = { filename: this._lastRecordedAudioFile, format: androidFormat, encoder: androidEncoder, metering: true, infoCallback: infoObject => { console.log(JSON.stringify(infoObject)); }, errorCallback: errorObject => { console.log(JSON.stringify(errorObject)); } }; await this._recorder.start(recorderOptions); this.isRecording = true; if (recorderOptions.metering) { this._initMeter(); } } catch (err) { this.isRecording = false; this._resetMeter(); dialogs.alert(err); } } public async stopRecord() { this._resetMeter(); await this._recorder.stop().catch(ex => { console.log(ex); this.isRecording = false; this._resetMeter(); }); this.isRecording = false; alert('Recorder stopped.'); this._resetMeter(); } private _initMeter() { this._resetMeter(); this._meterInterval = setInterval(() => { this.audioMeter = this._recorder.getMeters(); console.log(this.audioMeter); }, 300); } private _resetMeter() { if (this._meterInterval) { this.audioMeter = '0'; clearInterval(this._meterInterval); this._meterInterval = undefined; } } public getFile() { try { const audioFolder = knownFolders.currentApp().getFolder('audio'); // get the last recorded audio file const recordedFile = audioFolder.getFile(this._lastRecordedAudioFile); console.log(JSON.stringify(recordedFile)); console.log('recording exists: ' + File.exists(recordedFile.path)); this.recordedAudioFile = recordedFile.path; } catch (ex) { console.log(ex); } } public async playRecordedFile() { const audioFolder = knownFolders.currentApp().getFolder('audio'); console.log('audioFolder', audioFolder); // get the last recorded audio file const recordedFile = audioFolder.getFile(this._lastRecordedAudioFile); console.log('RECORDED FILE : ' + JSON.stringify(recordedFile)); const playerOptions: AudioPlayerOptions = { // audioFile: `~/audio/recording.${this.platformExtension()}`, audioFile: recordedFile.path, loop: false, completeCallback: async () => { alert('Audio file complete.'); this.isPlaying = false; if (!playerOptions.loop) { await this._player.dispose(); console.log('player disposed'); } }, errorCallback: errorObject => { console.log(JSON.stringify(errorObject)); this.isPlaying = false; }, infoCallback: infoObject => { console.log(JSON.stringify(infoObject)); dialogs.alert('Info callback'); } }; await this._player.playFromFile(playerOptions).catch(err => { console.log('error playFromFile'); this.isPlaying = false; }); this.isPlaying = true; } /***** AUDIO PLAYER *****/ public async playAudio(filepath: string, fileType: string) { try { const playerOptions: AudioPlayerOptions = { audioFile: filepath, loop: false, completeCallback: async () => { alert('Audio file complete.'); await this._player.dispose(); this.isPlaying = false; console.log('player disposed'); }, errorCallback: errorObject => { console.log(JSON.stringify(errorObject)); this.isPlaying = false; }, infoCallback: args => { dialogs.alert('Info callback: ' + args.info); console.log(JSON.stringify(args)); } }; this.isPlaying = true; if (fileType === 'localFile') { await this._player.playFromFile(playerOptions).catch(error => { console.log(error); this.isPlaying = false; }); this.isPlaying = true; this.audioTrackDuration = await this._player.getAudioTrackDuration(); // start audio duration tracking this._startDurationTracking(this.audioTrackDuration); this._startVolumeTracking(); } else if (fileType === 'remoteFile') { await this._player.playFromUrl(playerOptions).catch(error => { console.log(error); this.isPlaying = false; }); this.isPlaying = true; } } catch (ex) { console.log(ex); } } /** * PLAY REMOTE AUDIO FILE */ public playRemoteFile() { console.log('playRemoteFile'); const filepath = 'http://www.noiseaddicts.com/samples_1w72b820/2514.mp3'; this.playAudio(filepath, 'remoteFile'); } public resumePlayer() { console.log(JSON.stringify(this._player)); this._player.resume(); } /** * PLAY LOCAL AUDIO FILE from app folder */ public playLocalFile() { const filepath = '~/audio/angel.mp3'; this.playAudio(filepath, 'localFile'); } /** * PAUSE PLAYING */ public async pauseAudio() { try { await this._player.pause(); this.isPlaying = false; } catch (error) { console.log(error); this.isPlaying = true; } } public async stopPlaying() { await this._player.dispose(); alert('Media Player Disposed.'); } /** * RESUME PLAYING */ public resumePlaying() { console.log('START'); this._player.play(); } public muteTap() { this._player.volume = 0; } public unmuteTap() { this._player.volume = 1; } public skipTo8() { this._player.seekTo(8); } public playSpeed1() { this._player.changePlayerSpeed(1); } public playSpeed15() { this._player.changePlayerSpeed(1.5); } public playSpeed2() { this._player.changePlayerSpeed(2); } private platformExtension() { // 'mp3' return `${app.android ? 'm4a' : 'caf'}`; } private async _startDurationTracking(duration) { if (this._player && this._player.isAudioPlaying()) { const timerId = timer.setInterval(() => { this.remainingDuration = duration - this._player.currentTime; // console.log(`this.remainingDuration = ${this.remainingDuration}`); }, 1000); } } private _startVolumeTracking() { if (this._player) { const timerId = timer.setInterval(() => { console.log('volume tracking', this._player.volume); this.currentVolume = this._player.volume; }, 2000); } } /** * Create date time stamp similar to Java Date() */ private _createDateTimeStamp() { let result = ''; const date = new Date(); result = date.getFullYear().toString() + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString()) + (date.getDate() < 10 ? '0' + date.getDate().toString() : date.getDate().toString()) + '_' + date.getHours().toString() + date.getMinutes().toString() + date.getSeconds().toString(); return result; } }
the_stack
import * as ajv from "ajv"; import fetch from "cross-fetch"; import * as debug from "debug"; import * as path from "path"; import "url-search-params-polyfill"; import { AgentAuth } from "./agent-auth"; import { BaseEvent, DataPointValue, DataSourceConfiguration, IMindConnectConfiguration, Mapping, TimeStampedDataPoint, } from "./mindconnect-models"; import { bulkDataTemplate, dataTemplate } from "./mindconnect-template"; import { dataValidator, eventValidator } from "./mindconnect-validators"; import { MindSphereSdk } from "./sdk"; import { fileUploadOptionalParameters, MultipartUploader } from "./sdk/common/multipart-uploader"; import { retry, throwError } from "./utils"; import _ = require("lodash"); const log = debug("mindconnect-agent"); /** * MindConnect Agent implements the V3 of the Mindsphere API. * * * The synchronous methods (IsOnBoarded, HasConfiguration, HasDataMapping...) are operating on agent state storage only. * * The asynchronous methods (GetDataSourceConfiguration, BulkPostData...) are calling MindSphere APIs. * * @see https://opensource.mindsphere.io/docs/mindconnect-nodejs/agent-development/agent-state-storage.html * * @export * @class MindConnectAgent */ export class MindConnectAgent extends AgentAuth { public ClientId() { return this._configuration.content.clientId || "not defined yet"; } /** * * Check in the local storage if the agent is onboarded. * * * This is a local agent state storage setting only. MindSphere API is not called. * * @see https://opensource.mindsphere.io/docs/mindconnect-nodejs/agent-development/agent-state-storage.html * * @returns {boolean} * @memberof MindConnectAgent */ public IsOnBoarded(): boolean { return this._configuration.response ? true : false; } /** * Checks in the local storage if the agent has a data source configuration. * * * This is a local agent state storage setting only. MindSphere API is not called. * * Call await GetDataSourceConfiguration() if you want to check if there is configuration in the mindsphere. * * @see https://opensource.mindsphere.io/docs/mindconnect-nodejs/agent-development/agent-state-storage.html * * @returns {boolean} * @memberof MindConnectAgent */ public HasDataSourceConfiguration(): boolean { if (!this._configuration.dataSourceConfiguration) { return false; } else if (!this._configuration.dataSourceConfiguration.configurationId) { return false; } else { return true; } } /** * Checks in the local storage if the agent has configured mappings. * * * This is a local agent state storage setting only. MindSphere API is not called. * * Call await GetDataMappings() to check if the agent has configured mappings in the MindSphere. * * @see https://opensource.mindsphere.io/docs/mindconnect-nodejs/agent-development/agent-state-storage.html * * @returns {boolean} * @memberof MindConnectAgent */ public HasDataMappings(): boolean { return (this._configuration.mappings || []).length > 0; } /** * Stores the configuration in the mindsphere. * * By default the eTag parameter in the provided configuration is ignored, and the agent just updates the configuration every time the put method is stored * and automatically increases the eTag. * This is why its a good idea to check if the configuration was stored before the data was posted. If the ignoreEtag is set to false then the agent just uses * the eTag which was specified in the configuration. This might throw an "already stored" exception in the mindsphere. * * @param {DataSourceConfiguration} dataSourceConfiguration * @param {boolean} [ignoreEtag=true] * @returns {Promise<DataSourceConfiguration>} * @memberof MindConnectAgent */ public async PutDataSourceConfiguration( dataSourceConfiguration: DataSourceConfiguration, ignoreEtag: boolean = true ): Promise<DataSourceConfiguration> { await this.RenewToken(); this.checkConfiguration(); const eTag: number = this.calculateEtag(ignoreEtag, dataSourceConfiguration); const agentManangement = this.Sdk().GetAgentManagementClient(); try { const storedConfig = await agentManangement.PutDataSourceConfiguration( this.ClientId(), dataSourceConfiguration, { ifMatch: eTag.toString(), } ); this._configuration.dataSourceConfiguration = storedConfig; await retry(5, () => this.SaveConfig()); return storedConfig; } catch (err) { log(err); throw new Error(`Network error occured ${err.message}`); } } private calculateEtag(ignoreEtag: boolean, dataSourceConfiguration: DataSourceConfiguration) { let eTag: number = 0; if (this._configuration.dataSourceConfiguration && this._configuration.dataSourceConfiguration.eTag) { eTag = parseInt(this._configuration.dataSourceConfiguration.eTag); if (isNaN(eTag)) throw new Error("Invalid eTag in configuration!"); } if (!ignoreEtag) { if (!dataSourceConfiguration.eTag) throw new Error("There is no eTag in the provided configuration!"); eTag = parseInt(dataSourceConfiguration.eTag); if (isNaN(eTag)) throw new Error("Invalid eTag in provided configuration!"); } return eTag; } /** * Acquire DataSource Configuration and store it in the Agent Storage. * * @see https://opensource.mindsphere.io/docs/mindconnect-nodejs/agent-development/agent-state-storage.html * * @returns {Promise<DataSourceConfiguration>} * * @memberOf MindConnectAgent */ public async GetDataSourceConfiguration(): Promise<DataSourceConfiguration> { await this.RenewToken(); if (!this._accessToken) throw new Error("The agent doesn't have a valid access token."); if (!this._configuration.content.clientId) throw new Error("No client id in the configuration of the agent."); const agentManagment = this.Sdk().GetAgentManagementClient(); try { const result = await agentManagment.GetDataSourceConfiguration(this.ClientId()); this._configuration.dataSourceConfiguration = result; await retry(5, () => this.SaveConfig()); return result; } catch (err) { log(err); throw new Error(`Network error occured ${err.message}`); } } /** * Acquire the data mappings from the MindSphere and store them in the agent state storage. * * @see https://opensource.mindsphere.io/docs/mindconnect-nodejs/agent-development/agent-state-storage.html * * @returns {Promise<Array<Mapping>>} * * @memberOf MindConnectAgent */ public async GetDataMappings(): Promise<Array<Mapping>> { await this.RenewToken(); this.checkConfiguration(); const mcapi = this.Sdk().GetMindConnectApiClient(); const agentFilter = JSON.stringify({ agentId: `${this._configuration.content.clientId}` }); try { const result = await mcapi.GetDataPointMappings({ size: 2000, filter: agentFilter, }); this._configuration.mappings = result.content; await retry(5, () => this.SaveConfig()); return result.content; } catch (err) { log(err); throw new Error(`Network error occured ${err.message}`); } } private checkConfiguration() { !this._accessToken && throwError("The agent doesn't have a valid access token."); !this._configuration.content.clientId && throwError("No client id in the configuration of the agent."); } /** * Store data mappings in the mindsphere and also in the local agent state storage. * * @see https://opensource.mindsphere.io/docs/mindconnect-nodejs/agent-development/agent-state-storage.html * * @param {Mapping[]} mappings * @returns {Promise<boolean>} * * @memberOf MindConnectAgent */ public async PutDataMappings(mappings: Mapping[]): Promise<boolean> { await this.RenewToken(); this.checkConfiguration(); const mcapi = this.Sdk().GetMindConnectApiClient(); for (const mapping of mappings) { log(`Storing mapping ${mapping}`); try { // we are ignoring the 409 so that method becomes retryable await mcapi.PostDataPointMapping(mapping, { ignoreCodes: [409] }); } catch (err) { log(err); throw new Error(`Network error occured ${err.message}`); } let oldmappings = this._configuration.mappings || []; // there was a deprecation of old mappings in mindsphere, this isn't an array anymore. if ((oldmappings as any).content) { oldmappings = []; } this._configuration.mappings = _.uniqWith([...oldmappings, ...mappings], (a, b) => { return ( a.agentId === b.agentId && a.dataPointId === b.dataPointId && a.entityId === b.entityId && a.propertyName === b.propertyName && a.propertySetName === b.propertySetName ); }); await retry(5, () => this.SaveConfig()); } return true; } /** * Deletes all mappings from the agent * * @memberOf MindConnectAgent */ public async DeleteAllMappings() { const toDeleteMappings = await this.GetDataMappings(); const mcapi = this.Sdk().GetMindConnectApiClient(); for (let index = 0; index < toDeleteMappings.length; index++) { const element = toDeleteMappings[index]; await mcapi.DeleteDataMapping(element.id!, { ignoreCodes: [404] }); } this._configuration.mappings = []; await retry(5, () => this.SaveConfig()); } /** * Posts the Events to the Exchange Endpoint * * @see: https://developer.mindsphere.io/apis/api-advanced-eventmanagement/index.html * * @param {*} events * @param {Date} [timeStamp=new Date()] * @param {boolean} [validateModel=true] * @returns {Promise<boolean>} * @memberof MindConnectAgent */ public async PostEvent( event: BaseEvent | CustomEvent, timeStamp: Date = new Date(), validateModel: boolean = true ): Promise<boolean> { await this.RenewToken(); if (!this._accessToken) throw new Error("The agent doesn't have a valid access token."); const eventManagement = this.Sdk().GetEventManagementClient(); const headers = { ...this._apiHeaders, Authorization: `Bearer ${this._accessToken.access_token}` }; // const url = `${this._configuration.content.baseUrl}/api/mindconnect/v3/exchange`; const url = `${this._configuration.content.baseUrl}/api/eventmanagement/v3/events`; log(`GetDataSourceConfiguration Headers ${JSON.stringify(headers)} Url ${url}`); if (!(event as any).timestamp) { (event as any).timestamp = timeStamp.toISOString(); } if (validateModel) { const validator = this.GetEventValidator(); const isValid = await validator(event); if (!isValid) { throw new Error(`Data doesn't match the configuration! Errors: ${JSON.stringify(validator.errors)}`); } } await eventManagement.PostEvent(event as any); return true; } /** * Post Data Point Values to the Exchange Endpoint * * @see: https://developer.mindsphere.io/howto/howto-upload-agent-data/index.html * * @param {DataPointValue[]} dataPoints * @param {Date} [timeStamp=new Date()] * @param {boolean} [validateModel=true] you can set this to false to speed up the things if your agent is working. * @returns {Promise<boolean>} * @memberof MindConnectAgent */ public async PostData( dataPoints: DataPointValue[], timeStamp: Date = new Date(), validateModel: boolean = true ): Promise<boolean> { await this.RenewToken(); if (!this._accessToken) throw new Error("The agent doesn't have a valid access token."); if (!this._configuration.content.clientId) throw new Error("No client id in the configuration of the agent."); if (!this._configuration.dataSourceConfiguration) throw new Error("No data source configuration for the agent."); if (!this._configuration.dataSourceConfiguration.configurationId) throw new Error("No data source configuration ID for the agent."); if (validateModel) { const validator = this.GetValidator(); const isValid = await validator(dataPoints); if (!isValid) { throw new Error(`Data doesn't match the configuration! Errors: ${JSON.stringify(validator.errors)}`); } } const headers = { ...this._multipartHeaders, Authorization: `Bearer ${this._accessToken.access_token}` }; const url = `${this._configuration.content.baseUrl}/api/mindconnect/v3/exchange`; log(`GetDataSourceConfiguration Headers ${JSON.stringify(headers)} Url ${url}`); const dataMessage = dataTemplate( timeStamp, dataPoints, this._configuration.dataSourceConfiguration.configurationId ); log(dataMessage); const result = await this.SendMessage("POST", url, dataMessage, headers); return <boolean>result; } /** * Post Bulk Data Point Values to the Exchange Endpoint. * * @param {TimeStampedDataPoint[]} timeStampedDataPoints * @param {boolean} [validateModel=true] * @returns {Promise<boolean>} * * @memberOf MindConnectAgent */ public async BulkPostData( timeStampedDataPoints: TimeStampedDataPoint[], validateModel: boolean = true ): Promise<boolean> { await this.RenewToken(); if (!this._accessToken) throw new Error("The agent doesn't have a valid access token."); if (!this._configuration.content.clientId) throw new Error("No client id in the configuration of the agent."); if (!this._configuration.dataSourceConfiguration) throw new Error("No data source configuration for the agent."); if (!this._configuration.dataSourceConfiguration.configurationId) throw new Error("No data source configuration ID for the agent."); if (validateModel) { const validator = this.GetValidator(); for (let index = 0; index < timeStampedDataPoints.length; index++) { const element = timeStampedDataPoints[index]; const isValid = await validator(element.values); if (!isValid) { throw new Error( `Data doesn't match the configuration! Errors: ${JSON.stringify(validator.errors)}` ); } } } const headers = { ...this._multipartHeaders, Authorization: `Bearer ${this._accessToken.access_token}` }; const url = `${this._configuration.content.baseUrl}/api/mindconnect/v3/exchange`; log(`GetDataSourceConfiguration Headers ${JSON.stringify(headers)} Url ${url}`); const bulkDataMessage = bulkDataTemplate( timeStampedDataPoints, this._configuration.dataSourceConfiguration.configurationId ); log(bulkDataMessage); const result = await this.SendMessage("POST", url, bulkDataMessage, headers); return <boolean>result; } /** * Upload file to MindSphere IOTFileService * * * This method is used to upload the files to the MindSphere. * * It supports standard and multipart upload which can be configured with the [optional.chunk] parameter. * * * The method will try to abort the multipart upload if an exception occurs. * * Multipart Upload is done in following steps: * * start multipart upload * * upload in parallel [optional.parallelUploadChunks] the file parts (retrying [optional.retry] times if configured) * * uploading last chunk. * * @param {string} entityId - asset id or agent.ClientId() for agent * @param {string} filepath - mindsphere file path * @param {(string | Buffer)} file - local path or Buffer * @param {fileUploadOptionalParameters} [optional] - optional parameters: enable chunking, define retries etc. * @param {(number | undefined)}[optional.part] multipart/upload part * @param {(Date | undefined)} [optional.timestamp] File timestamp in mindsphere. * @param {(string | undefined)} [optional.description] Description in mindsphere. * @param {(string | undefined)} [optional.type] Mime type in mindsphere. * @param {(number | undefined)} [optional.chunkSize] chunkSize. It must be bigger than 5 MB. Default 8 MB. * @param {(number | undefined)} [optional.retry] Number of retries * @param {(Function | undefined)} [optional.logFunction] log functgion is called every time a retry happens. * @param {(Function | undefined)} [optional.verboseFunction] verboseLog function. * @param {(boolean | undefined)} [optional.chunk] Set to true to enable multipart uploads * @param {(number | undefined)} [optional.parallelUploads] max paralell uploads for parts (default: 3) * @param {(number | undefined)} [optional.ifMatch] The etag for the upload. * @returns {Promise<string>} - md5 hash of the file * * @memberOf MindConnectAgent * * @example await agent.UploadFile (agent.GetClientId(), "some/mindsphere/path/file.txt", "file.txt"); * @example await agent.UploadFile (agent.GetClientId(), "some/other/path/10MB.bin", "bigFile.bin",{ chunked:true, retry:5 }); */ public async UploadFile( entityId: string, filepath: string, file: string | Buffer, optional?: fileUploadOptionalParameters ): Promise<string> { const result = await this.uploader.UploadFile(entityId, filepath, file, optional); await retry(5, () => this.SaveConfig()); return result; } /** * Uploads the file to mindsphere * * @deprecated please use UploadFile method instead this method will probably be removed in version 4.0.0 * * @param {string} file filename or buffer for upload * @param {string} fileType mime type (e.g. image/png) * @param {string} description description of the file * @param {boolean} [chunk=true] if this is set to false the system will only upload smaller files * @param {string} [entityId] entityid can be used to define the asset for upload, otherwise the agent is used. * @param {number} [chunkSize=8 * 1024 * 1024] - at the moment 8MB as per restriction of mindgate * @param {number} [maxSockets=3] - maxSockets for http Upload - number of parallel multipart uploads * @returns {Promise<string>} md5 hash of the uploaded file * * @memberOf MindConnectAgent */ public async Upload( file: string | Buffer, fileType: string, description: string, chunk: boolean = true, entityId?: string, chunkSize: number = 8 * 1024 * 1024, maxSockets: number = 3, filePath?: string ): Promise<string> { const clientId = entityId || this.ClientId(); const filepath = filePath || (file instanceof Buffer ? "no-filepath-for-buffer" : path.basename(file)); return await this.UploadFile(clientId, filepath, file, { type: fileType, description: description, chunk: chunk, chunkSize: chunkSize, parallelUploads: maxSockets, }); } private async SendMessage( method: "POST" | "PUT", url: string, dataMessage: string | ArrayBuffer, headers: {} ): Promise<string | boolean> { try { const response = await fetch(url, { method: method, body: dataMessage, headers: headers, agent: this._proxyHttpAgent, } as RequestInit); if (!response.ok) { log({ method: method, body: dataMessage, headers: headers, agent: this._proxyHttpAgent }); log(response); throw new Error(response.statusText); } const text = await response.text(); if (response.status >= 200 && response.status <= 299) { const etag = response.headers.get("eTag"); return etag ? etag : true; } else { throw new Error(`Error occured response status ${response.status} ${text}`); } // process body } catch (err) { log(err); throw new Error(`Network error occured ${err.message}`); } } /** * Generates a Data Source Configuration for specified Asset Type * * you still have to generate the mappings (or use ConfigureAgentForAssetId method) * * @example * config = await agent.GenerateDataSourceConfiguration("castidev.Engine"); * * @param {string} assetTypeId * @param {("NUMERICAL" | "DESCRIPTIVE")} [mode="DESCRIPTIVE"] * * NUMERICAL MODE will use names like CF0001 for configurationId , DS0001,DS0002,DS0003... for data source ids and DP0001, DP0002... for dataPointIds * * DESCRIPTIVE MODE will use names like CF-assetName for configurationId , DS-aspectName... for data source ids and DP-variableName for data PointIds (default) * @returns {Promise<DataSourceConfiguration>} * * @memberOf MindConnectAgent */ public async GenerateDataSourceConfiguration( assetTypeId: string, mode: "NUMERICAL" | "DESCRIPTIVE" = "DESCRIPTIVE" ): Promise<DataSourceConfiguration> { const assetType = await this.Sdk().GetAssetManagementClient().GetAssetType(assetTypeId, { exploded: true }); const dataSourceConfiguration = this.Sdk() .GetMindConnectApiClient() .GenerateDataSourceConfiguration(assetType, mode); return dataSourceConfiguration; } /** * Generate automatically the mappings for the specified target assetid * * !Important! this only works if you have created the data source coniguration automatically * * @example * config = await agent.GenerateDataSourceConfiguration("castidev.Engine"); * await agent.PutDataSourceConfiguration(config); * const mappings = await agent.GenerateMappings(targetassetId); * await agent.PutDataMappings (mappings); * * @param {string} targetAssetId * @returns {Mapping[]} * * @memberOf MindConnectAgent */ public GenerateMappings(targetAssetId: string): Mapping[] { const mcapi = this.Sdk().GetMindConnectApiClient(); !this._configuration.dataSourceConfiguration && throwError( "no data source configuration! (have you forgotten to create / generate the data source configuration first?" ); const mappings = mcapi.GenerateMappings( this._configuration.dataSourceConfiguration!, this.ClientId(), targetAssetId ); return mappings; } /** * This method can automatically create all necessary configurations and mappings for selected target asset id. * * * This method will automatically create all necessary configurations and mappings to start sending the data * * to an asset with selected assetid in Mindsphere * * @param {string} targetAssetId * @param {("NUMERICAL" | "DESCRIPTIVE")} mode * * * NUMERICAL MODE will use names like CF0001 for configurationId , DS0001,DS0002,DS0003... for data source ids and DP0001, DP0002... for dataPointIds * * DESCRIPTIVE MODE will use names like CF-assetName for configurationId , DS-aspectName... for data source ids and DP-variableName for data PointIds (default) * @param {boolean} [overwrite=true] ignore eTag will overwrite mappings and data source configuration * @memberOf MindConnectAgent */ public async ConfigureAgentForAssetId( targetAssetId: string, mode: "NUMERICAL" | "DESCRIPTIVE" = "DESCRIPTIVE", overwrite: boolean = true ) { const asset = await this.Sdk().GetAssetManagementClient().GetAsset(targetAssetId); const configuration = await this.GenerateDataSourceConfiguration((asset.typeId as unknown) as string, mode); if (overwrite) { await this.GetDataSourceConfiguration(); } await this.PutDataSourceConfiguration(configuration, overwrite); if (overwrite) { await this.DeleteAllMappings(); } const mappings = this.GenerateMappings(targetAssetId); await this.PutDataMappings(mappings); } private _sdk?: MindSphereSdk = undefined; /** * MindSphere SDK using agent authentication * * ! important: not all APIs can be called with agent credentials, however MindSphere is currently working on making this possible. * * * Here is a list of some APIs which you can use: * * * AssetManagementClient (Read Methods) * * MindConnectApiClient * * @returns {MindSphereSdk} * * @memberOf MindConnectAgent */ public Sdk(): MindSphereSdk { if (!this._sdk) { this._sdk = new MindSphereSdk(this); } return this._sdk; } /** * Ajv Validator (@see https://github.com/ajv-validator/ajv) for the data points. Validates if the data points array is only * containing dataPointIds which are configured in the agent configuration. * * @returns {ajv.ValidateFunction} * * @memberOf MindConnectAgent */ public GetValidator(): ajv.ValidateFunction { const model = this._configuration.dataSourceConfiguration; if (!model) { throw new Error("Invalid local configuration, Please get or crete the data source configuration."); } return dataValidator(model); } private _eventValidator?: ajv.ValidateFunction; /** * * Ajv Validator (@see https://github.com/ajv-validator/ajv) for the events. Validates the syntax of the mindsphere events. * * @returns {ajv.ValidateFunction} * * @memberOf MindConnectAgent */ public GetEventValidator(): ajv.ValidateFunction { if (!this._eventValidator) { this._eventValidator = eventValidator(); } return this._eventValidator; } /** * Get local configuration from the agent state storage. * * * This is a local agent state storage setting only. MindSphere API is not called. * * @see https://opensource.mindsphere.io/docs/mindconnect-nodejs/agent-development/agent-state-storage.html * * @returns {IMindConnectConfiguration} * * @memberOf MindConnectAgent */ public GetMindConnectConfiguration(): IMindConnectConfiguration { return this._configuration; } private uploader = new MultipartUploader(this); }
the_stack
import * as Constants from "./Constants"; import Layers from "./collections/Layers"; import HistoryStates from "./collections/HistoryStates"; import HistoryState from "./HistoryState"; import { Bounds } from "./objects/Bounds"; import { JPEGSaveOptions, GIFSaveOptions, PNGSaveOptions, BMPSaveOptions, PhotoshopSaveOptions } from "./Objects"; import { LayerCreateOptions, GroupLayerCreateOptions } from "./objects/CreateOptions"; import Layer from "./Layer"; /** @ignore */ export declare function validateDocument(d: Document): void; /** * @ignore */ export declare function PSDocument(id: number): Document; /** * Represents a single Photoshop document that is currently open * You can access instances of documents using one of these methods: * * ```javascript * // The currently active document from the Photoshop object * const currentDocument = app.activeDocument * * // Choose one of the open documents from the Photoshop object * const secondDocument = app.documents[1] * * // You can also create an instance of a document via a UXP File entry * let fileEntry = require('uxp').storage.localFileSystem.getFileForOpening() * const newDocument = await app.open('/project.psd') * ``` */ export default class Document { /** * The internal ID of this document, valid as long as this document is open * Can be used for batchPlay calls to refer to this document, used internally */ get id(): number; /** * The selected layers in the document */ get activeLayers(): Layers; /** * The artboards in the document */ get artboards(): Layers; /** * All the layers in the document at the top level */ get layers(): Layers; /** * Background layer, if it exists */ get backgroundLayer(): Layer | null; /** * Full file system path to this document, or the identifier if it is a cloud document */ get path(): string; /** * History states of the document */ get historyStates(): HistoryStates; /** * Currently active history state of the document */ get activeHistoryState(): HistoryState; /** * Selects the given history state to be the active one */ set activeHistoryState(historyState: HistoryState); /** * The history state that history brush tool will use as its source */ get activeHistoryBrushSource(): HistoryState; set activeHistoryBrushSource(historyState: HistoryState); /** * Document title */ get title(): string; /** * Document's resolution (in pixels per inch) */ get resolution(): number; /** * Document's width in pixels */ get width(): number; /** * Document's height in pixels */ get height(): number; /** * The (custom) pixel aspect ratio to use */ get pixelAspectRatio(): number; set pixelAspectRatio(newValue: number); /** * @ignore */ constructor(id: number); /** * Closes the document, showing a prompt to save * unsaved changes if specified * * @param saveOptions By default, prompts a save dialog * if there are unsaved changes * * @async */ close(saveDialogOptions?: Constants.SaveOptions): Promise<void>; closeWithoutSaving(): void; /** * Crops the document to given bounds * @async */ crop(bounds: Bounds, angle?: number): Promise<void>; /** * Flatten all layers in the document * @async */ flatten(): Promise<void>; /** * Flattens all visible layers in the document * @async */ mergeVisibleLayers(): Promise<void>; /** * Changes the size of the canvas, but does not change image size * To change the image size, see [[resizeImage]] * * * ```javascript * // grow the canvas by 400px * let width = await document.width * let height = await document.height * await document.resizeCanvas(width + 400, height + 400) * ``` * @param width Numeric value of new width in pixels * @param height Numeric value of new height in pixels * @param anchor Anchor point for resizing, by default will resize an equal amount on all sides. * * @async */ resizeCanvas(width: number, height: number, anchor?: Constants.AnchorPosition): Promise<void>; /** * Changes the size of the image * * ```javascript * await document.resizeImage(800, 600) * ``` * @param width Numeric value of new width in pixels * @param height Numeric value of new height in pixels * @param resolution Image resolution in pixels per inch (ppi) * @param resampleMethod Method used during image interpolation. * * @async */ resizeImage(width: number, height: number, resolution?: number, resampleMethod?: Constants.ResampleMethod): Promise<void>; /** * Rotates the image clockwise in given angle, expanding canvas if necessary * @param angle * * @async */ rotate(angles: number): Promise<void>; /** * Performs a save of the document. The user will be presented with * a Save dialog if the file has yet to be saved on disk. * * ```javascript * // To save a document in the current location * document.save() * * // Shows the save dialog * unsavedDocument.save() * ``` * * @async */ save(): Promise<void>; /** * Save the document to a desired file type. * * For operations that require a UXP File token, use the UXP storage APIs to generate one. * See https://www.adobe.com/go/ps-api-uxp-filesystemprovider. * * * ```javascript * let entry = await require('uxp').storage.localFileSystem.getFileForSaving("target.psd"); * document.saveAs.psd(entry); * * // Save as a Copy (High JPG quality) * document.saveAs.jpg(entryJpg, { quality: 12 }, true); * * // Save a PSB, with some options: * document.saveAs.psb(entryPsb, { embedColorProfile: true }); * * ``` */ saveAs: { /** * Save the document as a PSD file. * @param entry UXP File token generated from the UXP Storage APIs. * @param saveOptions PSD specific save options. See SaveOptions/PhotoshopSaveOptions. * @param asCopy Whether to save as a copy. */ psd(entry: File, saveOptions?: PhotoshopSaveOptions, asCopy?: boolean): Promise<void>; /** * Save the document as a PSB file. * @param entry UXP File token generated from the UXP Storage APIs. * @param saveOptions PSD/PSB specific save options. See SaveOptions/PhotoshopSaveOptions. * @param asCopy Whether to save as a copy. */ psb(entry: File, saveOptions?: PhotoshopSaveOptions, asCopy?: boolean): Promise<void>; /** * @TODO reenable when we get the green-light to script PSDC * Save the document into Cloud Documents (PSDC). * @param path String title or path (separated by slash '/') location to save to. * @param saveOptions PSD/PSB specific save options. See SaveOptions/PhotoshopSaveOptions. */ /** * Save the document as a JPG file. * @param entry UXP File token generated from the UXP Storage APIs. * @param saveOptions JPEG specific save options. See SaveOptions/JPEGSaveOptions. * @param asCopy Whether to save as a copy. */ jpg(entry: File, saveOptions?: JPEGSaveOptions, asCopy?: boolean): Promise<void>; /** * Save the document as a GIF file. * @param entry UXP File token generated from the UXP Storage APIs. * @param saveOptions GIF specific save options. See SaveOptions/GIFSaveOptions. * @param asCopy Whether to save as a copy. */ gif(entry: File, saveOptions?: GIFSaveOptions, asCopy?: boolean): Promise<void>; /** * Save the document as a PNG file. * @param entry UXP File token generated from the UXP Storage APIs. * @param saveOptions PNG specific save options. See SaveOptions/PNGSaveOptions. * @param asCopy Whether to save as a copy. */ png(entry: File, saveOptions?: PNGSaveOptions, asCopy?: boolean): Promise<void>; /** * Save the document as a BMP file. * @param entry UXP File token generated from the UXP Storage APIs. * @param saveOptions JPEG specific save options. See SaveOptions/BMPSaveOptions. * @param asCopy Whether to save as a copy. */ bmp(entry: File, saveOptions?: BMPSaveOptions, asCopy?: boolean): Promise<void>; }; /** * Duplicates given layer(s), creating all copies above the top most one in layer stack, * and returns the newly created layers. * ```javascript * // duplicate some layers * const layerCopies = await document.duplicateLayers([layer1, layer3]) * layerCopies.forEach((layer) => { layer.blendMode = 'multiply' }) * // ...to another document * const finalDoc = await photoshop.open('~/path/to/collated/image.psd') * await document.duplicateLayers([logo1, textLayer1], finalDoc) * await finalDoc.close(SaveOptions.SAVECHANGES) * ``` * @param layers * @param targetDocument if specified, duplicate to a different document target. * * @async */ duplicateLayers(layers: Layer[], targetDocument?: Document): Promise<Layer[]>; /** * Links layers together if possible, and returns a list of linked layers. * @param layers array of layers to link together * @returns array of successfully linked layers */ linkLayers(layers: Layer[]): Layer[]; /** * Create a layer. See @CreateOptions * ```javascript * const myEmptyLayer = await doc.createLayer() * const myLayer = await doc.createLayer({ name: "myLayer", opacity: 80, mode: "colorDodge" }) * ``` * @async */ createLayer(options?: LayerCreateOptions): Promise<Layer | null>; /** * Create a layer group. See @CreateOptions * ```javascript * const myEmptyGroup = await doc.createLayerGroup() * const myGroup = await doc.createLayerGroup({ name: "myLayer", opacity: 80, mode: "colorDodge" }) * const nonEmptyGroup = await doc.createLayerGroup({ name: "group", fromLayers: [layer1, layer2] }) * ``` * @async */ createLayerGroup(options?: GroupLayerCreateOptions): Promise<Layer | null>; /** * Create a layer group from existing layers. * ```javascript * const layers = doc.layers * const group = await doc.groupLayers([layers[1], layers[2], layers[4]]) * ``` * @async */ groupLayers(layers: Layer[]): Promise<Layer | null>; }
the_stack
import { Inject, Injectable, Optional } from '@angular/core'; import { Http, Headers, URLSearchParams } from '@angular/http'; import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; import { Response, ResponseContentType } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import '../rxjs-operators'; import { InlineResponse200 } from '../model/inlineResponse200'; import { InlineResponse2001 } from '../model/inlineResponse2001'; import { InlineResponse2002 } from '../model/inlineResponse2002'; import { InlineResponse2003 } from '../model/inlineResponse2003'; import { InlineResponse2005 } from '../model/inlineResponse2005'; import { Patient } from '../model/patient'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @Injectable() export class PatientService { protected basePath = 'http://localhost:3000/api'; public defaultHeaders: Headers = new Headers(); public configuration: Configuration = new Configuration(); constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { if (basePath) { this.basePath = basePath; } if (configuration) { this.configuration = configuration; this.basePath = basePath || configuration.basePath || this.basePath; } } /** * * Extends object by coping non-existing properties. * @param objA object to be extended * @param objB source object */ private extendObj<T1,T2>(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ (objA as any)[key] = (objB as any)[key]; } } return <T1&T2>objA; } /** * @param consumes string[] mime-types * @return true: consumes contains 'multipart/form-data', false: otherwise */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; for (let consume of consumes) { if (form === consume) { return true; } } return false; } /** * Count instances of the model matched by where from the data source. * * @param where Criteria to match model instances */ public patientCount(where?: string, extraHttpRequestParams?: any): Observable<InlineResponse200> { return this.patientCountWithHttpInfo(where, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Create a new instance of the model and persist it into the data source. * * @param data Model instance data */ public patientCreate(data?: Patient, extraHttpRequestParams?: any): Observable<Patient> { return this.patientCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Create a change stream. * * @param options */ public patientCreateChangeStreamGetPatientsChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> { return this.patientCreateChangeStreamGetPatientsChangeStreamWithHttpInfo(options, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.blob(); } }); } /** * Create a change stream. * * @param options */ public patientCreateChangeStreamPostPatientsChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> { return this.patientCreateChangeStreamPostPatientsChangeStreamWithHttpInfo(options, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.blob(); } }); } /** * Deletes all data. * */ public patientDeleteAllPatients(extraHttpRequestParams?: any): Observable<InlineResponse2003> { return this.patientDeleteAllPatientsWithHttpInfo(extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Delete a model instance by {{id}} from the data source. * * @param id Model id */ public patientDeleteById(id: string, extraHttpRequestParams?: any): Observable<any> { return this.patientDeleteByIdWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public patientExistsGetPatientsidExists(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> { return this.patientExistsGetPatientsidExistsWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public patientExistsHeadPatientsid(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> { return this.patientExistsHeadPatientsidWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find all instances of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public patientFind(filter?: string, extraHttpRequestParams?: any): Observable<Array<Patient>> { return this.patientFindWithHttpInfo(filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find a model instance by {{id}} from the data source. * * @param id Model id * @param filter Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public patientFindById(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Patient> { return this.patientFindByIdWithHttpInfo(id, filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find first instance of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public patientFindOne(filter?: string, extraHttpRequestParams?: any): Observable<Patient> { return this.patientFindOneWithHttpInfo(filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Insert sample data set of test patients. * * @param locale */ public patientInsertTestData(locale?: string, extraHttpRequestParams?: any): Observable<InlineResponse2005> { return this.patientInsertTestDataWithHttpInfo(locale, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Patch an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public patientPatchOrCreate(data?: Patient, extraHttpRequestParams?: any): Observable<Patient> { return this.patientPatchOrCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Patch attributes for a model instance and persist it into the data source. * * @param id Patient id * @param data An object of model property name/value pairs */ public patientPrototypePatchAttributes(id: string, data?: Patient, extraHttpRequestParams?: any): Observable<Patient> { return this.patientPrototypePatchAttributesWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public patientReplaceByIdPostPatientsidReplace(id: string, data?: Patient, extraHttpRequestParams?: any): Observable<Patient> { return this.patientReplaceByIdPostPatientsidReplaceWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public patientReplaceByIdPutPatientsid(id: string, data?: Patient, extraHttpRequestParams?: any): Observable<Patient> { return this.patientReplaceByIdPutPatientsidWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public patientReplaceOrCreatePostPatientsReplaceOrCreate(data?: Patient, extraHttpRequestParams?: any): Observable<Patient> { return this.patientReplaceOrCreatePostPatientsReplaceOrCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public patientReplaceOrCreatePutPatients(data?: Patient, extraHttpRequestParams?: any): Observable<Patient> { return this.patientReplaceOrCreatePutPatientsWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Update instances of the model matched by {{where}} from the data source. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public patientUpdateAll(where?: string, data?: Patient, extraHttpRequestParams?: any): Observable<InlineResponse2002> { return this.patientUpdateAllWithHttpInfo(where, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Update an existing model instance or insert a new one into the data source based on the where criteria. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public patientUpsertWithWhere(where?: string, data?: Patient, extraHttpRequestParams?: any): Observable<Patient> { return this.patientUpsertWithWhereWithHttpInfo(where, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Count instances of the model matched by where from the data source. * * @param where Criteria to match model instances */ public patientCountWithHttpInfo(where?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/count'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a new instance of the model and persist it into the data source. * * @param data Model instance data */ public patientCreateWithHttpInfo(data?: Patient, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a change stream. * * @param options */ public patientCreateChangeStreamGetPatientsChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/change-stream'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (options !== undefined) { queryParameters.set('options', <any>options); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, responseType: ResponseContentType.Blob, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a change stream. * * @param options */ public patientCreateChangeStreamPostPatientsChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/change-stream'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header let consumes: string[] = [ 'application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml' ]; let canConsumeForm = this.canConsumeForm(consumes); let useForm = false; let formParams = new (useForm ? FormData : URLSearchParams as any)() as { set(param: string, value: any): void; }; // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; if (options !== undefined) { formParams.set('options', <any>options); } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: formParams, responseType: ResponseContentType.Blob, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Deletes all data. * */ public patientDeleteAllPatientsWithHttpInfo(extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/deleteAll'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Delete a model instance by {{id}} from the data source. * * @param id Model id */ public patientDeleteByIdWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling patientDeleteById.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public patientExistsGetPatientsidExistsWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/${id}/exists' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling patientExistsGetPatientsidExists.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public patientExistsHeadPatientsidWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling patientExistsHeadPatientsid.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Head, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find all instances of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public patientFindWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find a model instance by {{id}} from the data source. * * @param id Model id * @param filter Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public patientFindByIdWithHttpInfo(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling patientFindById.'); } if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find first instance of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public patientFindOneWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/findOne'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Insert sample data set of test patients. * * @param locale */ public patientInsertTestDataWithHttpInfo(locale?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/insertTestData'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (locale !== undefined) { queryParameters.set('locale', <any>locale); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Patch an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public patientPatchOrCreateWithHttpInfo(data?: Patient, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Patch, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Patch attributes for a model instance and persist it into the data source. * * @param id Patient id * @param data An object of model property name/value pairs */ public patientPrototypePatchAttributesWithHttpInfo(id: string, data?: Patient, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling patientPrototypePatchAttributes.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Patch, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public patientReplaceByIdPostPatientsidReplaceWithHttpInfo(id: string, data?: Patient, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/${id}/replace' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling patientReplaceByIdPostPatientsidReplace.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public patientReplaceByIdPutPatientsidWithHttpInfo(id: string, data?: Patient, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling patientReplaceByIdPutPatientsid.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public patientReplaceOrCreatePostPatientsReplaceOrCreateWithHttpInfo(data?: Patient, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/replaceOrCreate'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public patientReplaceOrCreatePutPatientsWithHttpInfo(data?: Patient, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Update instances of the model matched by {{where}} from the data source. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public patientUpdateAllWithHttpInfo(where?: string, data?: Patient, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/update'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Update an existing model instance or insert a new one into the data source based on the where criteria. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public patientUpsertWithWhereWithHttpInfo(where?: string, data?: Patient, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Patients/upsertWithWhere'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } }
the_stack
import { Column, Editors, FieldType, Filters, GridOption, GridStateChange, Metrics, OperatorType, Pagination, } from '@slickgrid-universal/common'; import { GridOdataService, OdataServiceApi, OdataOption } from '@slickgrid-universal/odata'; import { RxJsResource } from '@slickgrid-universal/rxjs-observable'; import { autoinject } from 'aurelia-framework'; import { HttpClient } from 'aurelia-http-client'; import { Observable, of, Subject } from 'rxjs'; import { AureliaGridInstance } from '../../aurelia-slickgrid'; import './example31.scss'; // provide custom CSS/SASS styling const defaultPageSize = 20; const sampleDataRoot = 'assets/data'; @autoinject() export class Example31 { title = 'Example 31: Grid with OData Backend Service using RxJS Observables'; subTitle = ` Optionally use RxJS instead of Promises, you would typically use this with a Backend Service API (OData/GraphQL) `; aureliaGrid!: AureliaGridInstance; columnDefinitions!: Column[]; gridOptions!: GridOption; dataset = []; metrics!: Metrics; paginationOptions!: Pagination; isCountEnabled = true; odataVersion = 2; odataQuery = ''; processing = false; status = { text: '', class: '' }; isOtherGenderAdded = false; genderCollection = [{ value: 'male', label: 'male' }, { value: 'female', label: 'female' }]; constructor(private http: HttpClient) { this.initializeGrid(); } attached() { } aureliaGridReady(aureliaGrid: AureliaGridInstance) { this.aureliaGrid = aureliaGrid; } initializeGrid() { this.columnDefinitions = [ { id: 'name', name: 'Name', field: 'name', sortable: true, type: FieldType.string, filterable: true, filter: { model: Filters.compoundInput } }, { id: 'gender', name: 'Gender', field: 'gender', filterable: true, editor: { model: Editors.singleSelect, // collection: this.genderCollection, collectionAsync: of(this.genderCollection) }, filter: { model: Filters.singleSelect, collectionAsync: of(this.genderCollection), collectionOptions: { addBlankEntry: true } } }, { id: 'company', name: 'Company', field: 'company' }, ]; this.gridOptions = { enableAutoResize: true, autoResize: { container: '#demo-container', rightPadding: 10 }, checkboxSelector: { // you can toggle these 2 properties to show the "select all" checkbox in different location hideInFilterHeaderRow: false, hideInColumnTitleRow: true }, editable: true, autoEdit: true, autoCommitEdit: true, rowHeight: 33, headerRowHeight: 35, enableCellNavigation: true, enableFiltering: true, enableCheckboxSelector: true, enableRowSelection: true, enablePagination: true, // you could optionally disable the Pagination pagination: { pageSizes: [10, 20, 50, 100, 500], pageSize: defaultPageSize, }, presets: { // you can also type operator as string, e.g.: operator: 'EQ' filters: [ // { columnId: 'name', searchTerms: ['w'], operator: OperatorType.startsWith }, { columnId: 'gender', searchTerms: ['male'], operator: OperatorType.equal }, ], sorters: [ // direction can be written as 'asc' (uppercase or lowercase) and/or use the SortDirection type { columnId: 'name', direction: 'asc' }, ], pagination: { pageNumber: 2, pageSize: 20 } }, backendServiceApi: { service: new GridOdataService(), options: { enableCount: this.isCountEnabled, // add the count in the OData query, which will return a property named "odata.count" (v2) or "@odata.count" (v4) version: this.odataVersion // defaults to 2, the query string is slightly different between OData 2 and 4 }, preProcess: () => this.displaySpinner(true), process: (query) => this.getCustomerApiCall(query), postProcess: (response) => { this.metrics = response.metrics; this.displaySpinner(false); this.getCustomerCallback(response); } } as OdataServiceApi, registerExternalResources: [new RxJsResource()] }; } addOtherGender() { const newGender = { value: 'other', label: 'other' }; const genderColumn = this.columnDefinitions.find((column: Column) => column.id === 'gender'); if (genderColumn) { let editorCollection = genderColumn.editor!.collection; const filterCollectionAsync = genderColumn.filter!.collectionAsync as Subject<any>; if (Array.isArray(editorCollection)) { // refresh the Editor "collection", we have 2 ways of doing it // 1. simply Push to the Editor "collection" // editorCollection.push(newGender); // 2. or replace the entire "collection" genderColumn.editor!.collection = [...this.genderCollection, newGender]; editorCollection = genderColumn.editor!.collection; // However, for the Filter only, we have to trigger an RxJS/Subject change with the new collection // we do this because Filter(s) are shown at all time, while on Editor it's unnecessary since they are only shown when opening them if (filterCollectionAsync?.next) { filterCollectionAsync.next(editorCollection); } } } // don't add it more than once this.isOtherGenderAdded = true; } displaySpinner(isProcessing: boolean) { this.processing = isProcessing; this.status = (isProcessing) ? { text: 'loading...', class: 'alert alert-warning' } : { text: 'finished!!', class: 'alert alert-success' }; } getCustomerCallback(data: any) { // totalItems property needs to be filled for pagination to work correctly // however we need to force Aurelia to do a dirty check, doing a clone object will do just that let countPropName = 'totalRecordCount'; // you can use "totalRecordCount" or any name or "odata.count" when "enableCount" is set if (this.isCountEnabled) { countPropName = (this.odataVersion === 4) ? '@odata.count' : 'odata.count'; } this.paginationOptions = { ...this.gridOptions.pagination, totalItems: data[countPropName] } as Pagination; if (this.metrics) { this.metrics.totalItemCount = data[countPropName]; } // once pagination totalItems is filled, we can update the dataset this.dataset = data['items']; this.odataQuery = data['query']; } getCustomerApiCall(query: string): Observable<any> { // in your case, you will call your WebAPI function (wich needs to return an Observable) // for the demo purpose, we will call a mock WebAPI function return this.getCustomerDataApiMock(query); } /** * This function is only here to mock a WebAPI call (since we are using a JSON file for the demo) * in your case the getCustomer() should be a WebAPI function returning a Promise */ getCustomerDataApiMock(query: string): Observable<any> { // the mock is returning an Observable return new Observable((observer) => { const queryParams = query.toLowerCase().split('&'); let top: number; let skip = 0; let orderBy = ''; let countTotalItems = 100; const columnFilters = {}; for (const param of queryParams) { if (param.includes('$top=')) { top = +(param.substring('$top='.length)); } if (param.includes('$skip=')) { skip = +(param.substring('$skip='.length)); } if (param.includes('$orderby=')) { orderBy = param.substring('$orderby='.length); } if (param.includes('$filter=')) { const filterBy = param.substring('$filter='.length).replace('%20', ' '); if (filterBy.includes('contains')) { const filterMatch = filterBy.match(/contains\(([a-zA-Z\/]+),\s?'(.*?)'/); const fieldName = filterMatch![1].trim(); (columnFilters as any)[fieldName] = { type: 'substring', term: filterMatch![2].trim() }; } if (filterBy.includes('substringof')) { const filterMatch = filterBy.match(/substringof\('(.*?)',([a-zA-Z ]*)/); const fieldName = filterMatch![2].trim(); (columnFilters as any)[fieldName] = { type: 'substring', term: filterMatch![1].trim() }; } if (filterBy.includes('eq')) { const filterMatch = filterBy.match(/([a-zA-Z ]*) eq '(.*?)'/); if (Array.isArray(filterMatch)) { const fieldName = filterMatch![1].trim(); (columnFilters as any)[fieldName] = { type: 'equal', term: filterMatch![2].trim() }; } } if (filterBy.includes('startswith')) { const filterMatch = filterBy.match(/startswith\(([a-zA-Z ]*),\s?'(.*?)'/); const fieldName = filterMatch![1].trim(); (columnFilters as any)[fieldName] = { type: 'starts', term: filterMatch![2].trim() }; } if (filterBy.includes('endswith')) { const filterMatch = filterBy.match(/endswith\(([a-zA-Z ]*),\s?'(.*?)'/); const fieldName = filterMatch![1].trim(); (columnFilters as any)[fieldName] = { type: 'ends', term: filterMatch![2].trim() }; } } } const sort = orderBy.includes('asc') ? 'ASC' : orderBy.includes('desc') ? 'DESC' : ''; let url; switch (sort) { case 'ASC': url = `${sampleDataRoot}/customers_100_ASC.json`; break; case 'DESC': url = `${sampleDataRoot}/customers_100_DESC.json`; break; default: url = `${sampleDataRoot}/customers_100.json`; break; } this.http.createRequest(url) .asGet() .send() .then(response => { const dataArray = response.content as any[]; // Read the result field from the JSON response. const firstRow = skip; let filteredData = dataArray; if (columnFilters) { for (const columnId in columnFilters) { if (columnFilters.hasOwnProperty(columnId)) { filteredData = filteredData.filter(column => { const filterType = (columnFilters as any)[columnId].type; const searchTerm = (columnFilters as any)[columnId].term; let colId = columnId; if (columnId && columnId.indexOf(' ') !== -1) { const splitIds = columnId.split(' '); colId = splitIds[splitIds.length - 1]; } const filterTerm = column[colId]; if (filterTerm) { switch (filterType) { case 'equal': return filterTerm.toLowerCase() === searchTerm; case 'ends': return filterTerm.toLowerCase().endsWith(searchTerm); case 'starts': return filterTerm.toLowerCase().startsWith(searchTerm); case 'substring': return filterTerm.toLowerCase().includes(searchTerm); } } }); } } countTotalItems = filteredData.length; } const updatedData = filteredData.slice(firstRow, firstRow + top); setTimeout(() => { let countPropName = 'totalRecordCount'; if (this.isCountEnabled) { countPropName = (this.odataVersion === 4) ? '@odata.count' : 'odata.count'; } const backendResult = { items: updatedData, [countPropName]: countTotalItems, query }; // console.log('Backend Result', backendResult); observer.next(backendResult); observer.complete(); }, 150); }); }); } clearAllFiltersAndSorts() { this.aureliaGrid?.gridService.clearAllFiltersAndSorts(); } goToFirstPage() { this.aureliaGrid?.paginationService?.goToFirstPage(); } goToLastPage() { this.aureliaGrid?.paginationService?.goToLastPage(); } /** Dispatched event of a Grid State Changed event */ gridStateChanged(gridStateChanges: GridStateChange) { // console.log('Client sample, Grid State changed:: ', gridStateChanges); console.log('Client sample, Grid State changed:: ', gridStateChanges.change); } setFiltersDynamically() { // we can Set Filters Dynamically (or different filters) afterward through the FilterService this.aureliaGrid?.filterService.updateFilters([ // { columnId: 'gender', searchTerms: ['male'], operator: OperatorType.equal }, { columnId: 'name', searchTerms: ['A'], operator: 'a*' }, ]); } setSortingDynamically() { this.aureliaGrid?.sortService.updateSorting([ { columnId: 'name', direction: 'DESC' }, ]); } // THE FOLLOWING METHODS ARE ONLY FOR DEMO PURPOSES DO NOT USE THIS CODE // --- changeCountEnableFlag() { this.isCountEnabled = !this.isCountEnabled; const odataService = this.gridOptions.backendServiceApi!.service as GridOdataService; odataService.updateOptions({ enableCount: this.isCountEnabled } as OdataOption); odataService.clearFilters(); this.aureliaGrid?.filterService.clearFilters(); return true; } setOdataVersion(version: number) { this.odataVersion = version; const odataService = this.gridOptions.backendServiceApi!.service as GridOdataService; odataService.updateOptions({ version: this.odataVersion } as OdataOption); odataService.clearFilters(); this.aureliaGrid?.filterService.clearFilters(); return true; } }
the_stack
import * as React from 'react'; import SelectMimicry from '../SelectMimicry/SelectMimicry'; import { debounce, setRef } from '../../lib/utils'; import { classNames } from '../../lib/classNames'; import { NativeSelectProps } from '../NativeSelect/NativeSelect'; import CustomScrollView from '../CustomScrollView/CustomScrollView'; import { SizeType, withAdaptivity } from '../../hoc/withAdaptivity'; import { withPlatform } from '../../hoc/withPlatform'; import CustomSelectOption, { CustomSelectOptionProps } from '../CustomSelectOption/CustomSelectOption'; import { getClassName } from '../../helpers/getClassName'; import { FormFieldProps } from '../FormField/FormField'; import { HasPlatform } from '../../types'; import Input from '../Input/Input'; import { Icon20Dropdown, Icon24Dropdown } from '@vkontakte/icons'; import Caption from '../Typography/Caption/Caption'; import { warnOnce } from '../../lib/warnOnce'; import Spinner from '../Spinner/Spinner'; import { defaultFilterFn } from '../../lib/select'; import { is } from '../../lib/is'; import './CustomSelect.css'; const findIndexAfter = (options: CustomSelectOptionInterface[], startIndex = -1) => { if (startIndex >= options.length - 1) { return -1; } return options.findIndex((option, i) => i > startIndex && !option.disabled); }; const findIndexBefore = (options: CustomSelectOptionInterface[], endIndex: number = options.length) => { let result = -1; if (endIndex <= 0) { return result; } for (let i = endIndex - 1; i >= 0; i--) { let option = options[i]; if (!option.disabled) { result = i; break; } } return result; }; const warn = warnOnce('CustomSelect'); const checkOptionsValueType = (options: CustomSelectOptionInterface[]) => { if (new Set(options.map((item) => typeof item.value)).size > 1) { warn('Some values of your options have different types. CustomSelect onChange always returns a string type.'); } }; type SelectValue = React.SelectHTMLAttributes<HTMLSelectElement>['value']; export interface CustomSelectOptionInterface { value: SelectValue; label: string; disabled?: boolean; [index: string]: any; } interface CustomSelectState { inputValue?: string; opened?: boolean; focusedOptionIndex?: number; selectedOptionIndex?: number; nativeSelectValue?: SelectValue; options?: CustomSelectOptionInterface[]; } export interface CustomSelectProps extends NativeSelectProps, HasPlatform, FormFieldProps { /** * Если `true`, то при клике на селект в нём появится текстовое поле для поиска по `options`. По умолчанию поиск * производится по `option.label`. */ searchable?: boolean; /** * Текст, который будет отображен, если приходит пустой `options` */ emptyText?: string; onInputChange?: (e: React.ChangeEvent, options: CustomSelectOptionInterface[]) => void | CustomSelectOptionInterface[]; options: Array<{ value: SelectValue; label: string; [index: string]: any; }>; /** * Функция для кастомной фильтрации. По-умолчанию поиск производится по option.label. */ filterFn?: false | ((value: string, option: CustomSelectOptionInterface, getOptionLabel?: (option: Partial<CustomSelectOptionInterface>) => string) => boolean); popupDirection?: 'top' | 'bottom'; /** * Рендер-проп для кастомного рендера опции. * В объекте аргумента приходят [свойства опции](#/CustomSelectOption?id=props) */ renderOption?: (props: CustomSelectOptionProps) => React.ReactNode; /** * Рендер-проп для кастомного рендера содержимого дропдауна. * В defaultDropdownContent содержится список опций в виде скроллящегося блока. */ renderDropdown?: ({ defaultDropdownContent }: { defaultDropdownContent: React.ReactNode }) => React.ReactNode; /** * Если true, то в дропдауне вместо списка опций рисуется спиннер. При переданных renderDropdown и fetching: true, * "победит" renderDropdown */ fetching?: boolean; onClose?: VoidFunction; onOpen?: VoidFunction; } type MouseEventHandler = (event: React.MouseEvent<HTMLElement>) => void; class CustomSelect extends React.Component<CustomSelectProps, CustomSelectState> { static defaultProps: CustomSelectProps = { searchable: false, renderOption({ option, ...props }): React.ReactNode { return ( <CustomSelectOption {...props} /> ); }, options: [], emptyText: 'Ничего не найдено', filterFn: defaultFilterFn, }; public constructor(props: CustomSelectProps) { super(props); const { value, defaultValue } = props; const initialValue = value !== undefined ? value : defaultValue; this.keyboardInput = ''; if (process.env.NODE_ENV === 'development') { checkOptionsValueType(props.options); } this.state = { opened: false, focusedOptionIndex: -1, selectedOptionIndex: this.findSelectedIndex(props.options, initialValue), nativeSelectValue: initialValue, options: props.options, inputValue: '', }; if (props.value !== undefined) { this.isControlledOutside = true; } } public state: CustomSelectState; private keyboardInput: string; private isControlledOutside: boolean; private selectEl: HTMLSelectElement; private readonly scrollBoxRef = React.createRef<HTMLDivElement>(); private readonly resetKeyboardInput = () => { this.keyboardInput = ''; }; private readonly getSelectedItem = () => { const { selectedOptionIndex, options } = this.state; if (!options.length) { return null; } return options[selectedOptionIndex]; }; get areOptionsShown() { return this.scrollBoxRef.current !== null; } filter = (options: CustomSelectProps['options'], inputValue: string, filterFn: CustomSelectProps['filterFn']) => { return typeof filterFn === 'function' ? options.filter((option) => filterFn(inputValue, option)) : options; }; findSelectedIndex(options: CustomSelectOptionInterface[], value: SelectValue) { return options.findIndex((item) => { value = typeof item.value === 'number' ? Number(value) : value; return item.value === value; }); } open = () => { this.setState(({ selectedOptionIndex }) => ({ opened: true, focusedOptionIndex: selectedOptionIndex, }), () => { const { selectedOptionIndex } = this.state; if (this.isValidIndex(selectedOptionIndex)) { this.scrollToElement(selectedOptionIndex, true); } }); typeof this.props.onOpen === 'function' && this.props.onOpen(); }; close = () => { this.resetKeyboardInput(); this.setState(() => ({ inputValue: '', opened: false, focusedOptionIndex: -1, options: this.props.options, })); typeof this.props.onClose === 'function' && this.props.onClose(); }; private isValidIndex(index: number) { return index >= 0 && index < this.state.options.length; } selectFocused = () => { const { focusedOptionIndex } = this.state; this.select(focusedOptionIndex); }; select = (index: number) => { if (!this.isValidIndex(index)) { return; } const item = this.state.options[index]; this.setState({ nativeSelectValue: item.value, }, () => { const event = new Event('change', { bubbles: true }); this.selectEl.dispatchEvent(event); }); this.close(); }; onClick = () => { this.state.opened ? this.close() : this.open(); }; onFocus = () => { const event = new Event('focus'); this.selectEl.dispatchEvent(event); }; onBlur = () => { this.close(); const event = new Event('blur'); this.selectEl.dispatchEvent(event); }; private scrollToElement(index: number, center = false) { const dropdown = this.scrollBoxRef.current; const item = dropdown ? (dropdown.children[index] as HTMLElement) : null; if (!item) { return; } const dropdownHeight = dropdown.offsetHeight; const scrollTop = dropdown.scrollTop; const itemTop = item.offsetTop; const itemHeight = item.offsetHeight; if (center) { dropdown.scrollTop = itemTop - dropdownHeight / 2 + itemHeight / 2; } else if (itemTop + itemHeight > dropdownHeight + scrollTop) { dropdown.scrollTop = itemTop - dropdownHeight + itemHeight; } else if (itemTop < scrollTop) { dropdown.scrollTop = itemTop; } } focusOptionByIndex = (index: number, scrollTo = true) => { if (index < 0 || index > this.state.options.length - 1) { return; } const option = this.state.options[index]; if (option.disabled) { return; } scrollTo && this.scrollToElement(index); this.setState(() => ({ focusedOptionIndex: index, })); }; focusOption = (type: 'next' | 'prev') => { const { focusedOptionIndex } = this.state; let index = focusedOptionIndex; if (type === 'next') { const nextIndex = findIndexAfter(this.state.options, index); index = nextIndex === -1 ? findIndexAfter(this.state.options) : nextIndex; // Следующий за index или первый валидный до index } else if (type === 'prev') { const beforeIndex = findIndexBefore(this.state.options, index); index = beforeIndex === -1 ? findIndexBefore(this.state.options) : beforeIndex; // Предшествующий index или последний валидный после index } this.focusOptionByIndex(index); }; handleOptionHover: MouseEventHandler = (e: React.MouseEvent<HTMLElement>) => { this.focusOptionByIndex(Array.prototype.indexOf.call(e.currentTarget.parentNode.children, e.currentTarget), false); }; handleOptionDown: MouseEventHandler = (e: React.MouseEvent<HTMLElement>) => { e.preventDefault(); }; handleOptionClick: MouseEventHandler = (e: React.MouseEvent<HTMLElement>) => { const index = Array.prototype.indexOf.call(e.currentTarget.parentNode.children, e.currentTarget); const option = this.state.options[index]; if (option && !option.disabled) { this.selectFocused(); } }; resetFocusedOption = () => { this.setState({ focusedOptionIndex: -1 }); }; onKeyboardInput = (key: string) => { const fullInput = this.keyboardInput + key; const optionIndex = this.state.options.findIndex((option) => { return option.label.toLowerCase().includes(fullInput); }); if (optionIndex > -1) { this.focusOptionByIndex(optionIndex); } this.keyboardInput = fullInput; }; /** * Нужен для правильного поведения обработчика onClick на select. Фильтрует клики, которые были сделаны по * выпадающему списку. */ onLabelClick = (e: React.MouseEvent<HTMLLabelElement>) => { if (this.scrollBoxRef.current?.contains(e.target as Node)) { e.preventDefault(); } }; onNativeSelectChange: React.ChangeEventHandler<HTMLSelectElement> = (e) => { const value = e.currentTarget.value; if (!this.isControlledOutside) { this.setState({ selectedOptionIndex: this.findSelectedIndex(this.state.options, value), }); } if (this.props.onChange) { this.props.onChange(e); } }; onInputChange: React.ChangeEventHandler<HTMLInputElement> = (e) => { if (this.props.onInputChange) { const options = this.props.onInputChange(e, this.props.options); if (options) { if (process.env.NODE_ENV === 'development') { warn('This filtration method is deprecated. Return value of onInputChange will' + ' be ignored in v5.0.0. For custom filtration please update props.options by yourself or use filterFn property'); } this.setState({ options, selectedOptionIndex: this.findSelectedIndex(options, this.state.nativeSelectValue), inputValue: e.target.value, }); } else { this.setState({ inputValue: e.target.value }); } } else { const options = this.filter(this.props.options, e.target.value, this.props.filterFn); this.setState({ options, selectedOptionIndex: this.findSelectedIndex(options, this.state.nativeSelectValue), inputValue: e.target.value, }); } }; onInputKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (event) => { ['ArrowUp', 'ArrowDown', 'Escape', 'Enter'].includes(event.key) && this.areOptionsShown && event.preventDefault(); switch (event.key) { case 'ArrowUp': this.areOptionsShown && this.focusOption('prev'); break; case 'ArrowDown': this.areOptionsShown && this.focusOption('next'); break; case 'Escape': this.close(); break; case 'Enter': this.areOptionsShown && this.selectFocused(); break; } }; handleKeyDownSelect = (event: React.KeyboardEvent) => { const { opened } = this.state; if (event.key.length === 1 && event.key !== ' ') { this.onKeyboardInput(event.key); return; } ['ArrowUp', 'ArrowDown', 'Escape', 'Enter'].includes(event.key) && this.areOptionsShown && event.preventDefault(); switch (event.key) { case 'ArrowUp': if (opened) { this.areOptionsShown && this.focusOption('prev'); } else { this.open(); } break; case 'ArrowDown': if (opened) { this.areOptionsShown && this.focusOption('next'); } else { this.open(); } break; case 'Escape': this.close(); break; case 'Enter': case 'Spacebar': case ' ': if (opened) { this.areOptionsShown && this.selectFocused(); } else { this.open(); } break; } }; handleKeyUp = debounce(this.resetKeyboardInput, 1000); componentDidUpdate(prevProps: CustomSelectProps) { // Внутри useEffect и так is, можно убрать if (!is(prevProps.value, this.props.value) || prevProps.options !== this.props.options) { if (process.env.NODE_ENV === 'development') { checkOptionsValueType(this.props.options); } this.isControlledOutside = this.props.value !== undefined; const value = this.props.value === undefined ? this.state.nativeSelectValue : this.props.value; const options = this.props.searchable ? this.filter(this.props.options, this.state.inputValue, this.props.filterFn) : this.props.options; this.setState({ nativeSelectValue: value, selectedOptionIndex: this.findSelectedIndex(options, value), options, }); } } renderOption = (option: CustomSelectOptionInterface, index: number) => { const { focusedOptionIndex, selectedOptionIndex } = this.state; const { renderOption } = this.props; const hovered = index === focusedOptionIndex; const selected = index === selectedOptionIndex; return ( <React.Fragment key={`${option.value}`}> {renderOption({ option, hovered, children: option.label, selected, disabled: option.disabled, onClick: this.handleOptionClick, onMouseDown: this.handleOptionDown, onMouseEnter: this.handleOptionHover, })} </React.Fragment> ); }; selectRef = (element: HTMLSelectElement) => { this.selectEl = element; setRef(element, this.props.getRef); }; render() { const { opened, nativeSelectValue } = this.state; const { searchable, name, className, getRef, getRootRef, popupDirection, options, sizeY, platform, style, onChange, onBlur, onFocus, onClick, renderOption, children, emptyText, onInputChange, filterFn, renderDropdown, onOpen, onClose, fetching, ...restProps } = this.props; const selected = this.getSelectedItem(); const label = selected ? selected.label : undefined; const defaultDropdownContent = ( <CustomScrollView boxRef={this.scrollBoxRef}> {this.state.options.map(this.renderOption)} {this.state.options.length === 0 && <Caption level="1" weight="regular" vkuiClass="CustomSelect__empty"> {this.props.emptyText} </Caption> } </CustomScrollView> ); let resolvedContent; if (typeof renderDropdown === 'function') { resolvedContent = renderDropdown({ defaultDropdownContent }); } else if (fetching) { resolvedContent = ( <div vkuiClass="CustomSelect__fetching"> <Spinner size="small" /> </div> ); } else { resolvedContent = defaultDropdownContent; } return ( <label vkuiClass={getClassName('CustomSelect', platform)} className={className} style={style} ref={getRootRef} onClick={this.onLabelClick} > {opened && searchable ? <Input {...restProps} autoFocus onBlur={this.onBlur} vkuiClass={classNames({ 'CustomSelect__open': opened, 'CustomSelect__open--popupDirectionTop': popupDirection === 'top', })} value={this.state.inputValue} onKeyDown={this.onInputKeyDown} onChange={this.onInputChange} // TODO Ожидается, что клик поймает нативный select, но его перехвает Input. К сожалению, это приводит конфликтам типизации. // TODO Нужно перестать пытаться превратить CustomSelect в select. Тогда эта проблема уйдёт. // @ts-ignore onClick={onClick} after={sizeY === SizeType.COMPACT ? <Icon20Dropdown /> : <Icon24Dropdown />} placeholder={restProps.placeholder} /> : <SelectMimicry {...restProps} aria-hidden={true} onClick={this.onClick} onKeyDown={this.handleKeyDownSelect} onKeyUp={this.handleKeyUp} onFocus={this.onFocus} onBlur={this.onBlur} vkuiClass={classNames({ 'CustomSelect__open': opened, 'CustomSelect__open--popupDirectionTop': popupDirection === 'top', })} > {label} </SelectMimicry> } <select ref={this.selectRef} name={name} onChange={this.onNativeSelectChange} onBlur={onBlur} onFocus={onFocus} onClick={onClick} value={nativeSelectValue} aria-hidden={true} vkuiClass="CustomSelect__control" > {options.map((item) => <option key={`${item.value}`} value={item.value} />)} </select> {opened && <div vkuiClass={classNames('CustomSelect__options', `CustomSelect__options--sizeY-${sizeY}`, { 'CustomSelect__options--popupDirectionTop': popupDirection === 'top', })} onMouseLeave={this.resetFocusedOption} > {resolvedContent} </div> } </label> ); } } export default withPlatform(withAdaptivity(CustomSelect, { sizeY: true, }));
the_stack
import { Data } from '../data'; import { Visitor } from '../visitor'; import { VectorType } from '../interfaces'; import { Schema, Field } from '../schema'; import { DataType, Dictionary, Bool, Null, Utf8, Binary, Decimal, FixedSizeBinary, List, FixedSizeList, Map_, Struct, Float, Float16, Float32, Float64, Int, Uint8, Uint16, Uint32, Uint64, Int8, Int16, Int32, Int64, Date_, DateDay, DateMillisecond, Interval, IntervalDayTime, IntervalYearMonth, Time, TimeSecond, TimeMillisecond, TimeMicrosecond, TimeNanosecond, Timestamp, TimestampSecond, TimestampMillisecond, TimestampMicrosecond, TimestampNanosecond, Union, DenseUnion, SparseUnion, } from '../type'; /** @ignore */ export interface TypeComparator extends Visitor { visit<T extends DataType>(type: T, other?: DataType | null): other is T; visitMany<T extends DataType>(nodes: T[], others?: DataType[] | null): boolean[]; getVisitFn<T extends DataType>(node: VectorType<T> | Data<T> | T): (other?: DataType | null) => other is T; visitNull <T extends Null> (type: T, other?: DataType | null): other is T; visitBool <T extends Bool> (type: T, other?: DataType | null): other is T; visitInt <T extends Int> (type: T, other?: DataType | null): other is T; visitInt8 <T extends Int8> (type: T, other?: DataType | null): other is T; visitInt16 <T extends Int16> (type: T, other?: DataType | null): other is T; visitInt32 <T extends Int32> (type: T, other?: DataType | null): other is T; visitInt64 <T extends Int64> (type: T, other?: DataType | null): other is T; visitUint8 <T extends Uint8> (type: T, other?: DataType | null): other is T; visitUint16 <T extends Uint16> (type: T, other?: DataType | null): other is T; visitUint32 <T extends Uint32> (type: T, other?: DataType | null): other is T; visitUint64 <T extends Uint64> (type: T, other?: DataType | null): other is T; visitFloat <T extends Float> (type: T, other?: DataType | null): other is T; visitFloat16 <T extends Float16> (type: T, other?: DataType | null): other is T; visitFloat32 <T extends Float32> (type: T, other?: DataType | null): other is T; visitFloat64 <T extends Float64> (type: T, other?: DataType | null): other is T; visitUtf8 <T extends Utf8> (type: T, other?: DataType | null): other is T; visitBinary <T extends Binary> (type: T, other?: DataType | null): other is T; visitFixedSizeBinary <T extends FixedSizeBinary> (type: T, other?: DataType | null): other is T; visitDate <T extends Date_> (type: T, other?: DataType | null): other is T; visitDateDay <T extends DateDay> (type: T, other?: DataType | null): other is T; visitDateMillisecond <T extends DateMillisecond> (type: T, other?: DataType | null): other is T; visitTimestamp <T extends Timestamp> (type: T, other?: DataType | null): other is T; visitTimestampSecond <T extends TimestampSecond> (type: T, other?: DataType | null): other is T; visitTimestampMillisecond <T extends TimestampMillisecond> (type: T, other?: DataType | null): other is T; visitTimestampMicrosecond <T extends TimestampMicrosecond> (type: T, other?: DataType | null): other is T; visitTimestampNanosecond <T extends TimestampNanosecond> (type: T, other?: DataType | null): other is T; visitTime <T extends Time> (type: T, other?: DataType | null): other is T; visitTimeSecond <T extends TimeSecond> (type: T, other?: DataType | null): other is T; visitTimeMillisecond <T extends TimeMillisecond> (type: T, other?: DataType | null): other is T; visitTimeMicrosecond <T extends TimeMicrosecond> (type: T, other?: DataType | null): other is T; visitTimeNanosecond <T extends TimeNanosecond> (type: T, other?: DataType | null): other is T; visitDecimal <T extends Decimal> (type: T, other?: DataType | null): other is T; visitList <T extends List> (type: T, other?: DataType | null): other is T; visitStruct <T extends Struct> (type: T, other?: DataType | null): other is T; visitUnion <T extends Union> (type: T, other?: DataType | null): other is T; visitDenseUnion <T extends DenseUnion> (type: T, other?: DataType | null): other is T; visitSparseUnion <T extends SparseUnion> (type: T, other?: DataType | null): other is T; visitDictionary <T extends Dictionary> (type: T, other?: DataType | null): other is T; visitInterval <T extends Interval> (type: T, other?: DataType | null): other is T; visitIntervalDayTime <T extends IntervalDayTime> (type: T, other?: DataType | null): other is T; visitIntervalYearMonth <T extends IntervalYearMonth> (type: T, other?: DataType | null): other is T; visitFixedSizeList <T extends FixedSizeList> (type: T, other?: DataType | null): other is T; visitMap <T extends Map_> (type: T, other?: DataType | null): other is T; } /** @ignore */ export class TypeComparator extends Visitor { compareSchemas<T extends { [key: string]: DataType }>(schema: Schema<T>, other?: Schema | null): other is Schema<T> { return (schema === other) || ( other instanceof schema.constructor && this.compareManyFields(schema.fields, other.fields) ); } compareManyFields<T extends { [key: string]: DataType }>(fields: Field<T[keyof T]>[], others?: Field[] | null): others is Field<T[keyof T]>[] { return (fields === others) || ( Array.isArray(fields) && Array.isArray(others) && fields.length === others.length && fields.every((f, i) => this.compareFields(f, others[i])) ); } compareFields<T extends DataType = any>(field: Field<T>, other?: Field | null): other is Field<T> { return (field === other) || ( other instanceof field.constructor && field.name === other.name && field.nullable === other.nullable && this.visit(field.type, other.type) ); } } function compareConstructor<T extends DataType>(type: T, other?: DataType | null): other is T { return other instanceof type.constructor; } function compareAny<T extends DataType>(type: T, other?: DataType | null): other is T { return (type === other) || compareConstructor(type, other); } function compareInt<T extends Int>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.bitWidth === other.bitWidth && type.isSigned === other.isSigned ); } function compareFloat<T extends Float>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.precision === other.precision ); } function compareFixedSizeBinary<T extends FixedSizeBinary>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.byteWidth === other.byteWidth ); } function compareDate<T extends Date_>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.unit === other.unit ); } function compareTimestamp<T extends Timestamp>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.unit === other.unit && type.timezone === other.timezone ); } function compareTime<T extends Time>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.unit === other.unit && type.bitWidth === other.bitWidth ); } function compareList<T extends List>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.children.length === other.children.length && instance.compareManyFields(type.children, other.children) ); } function compareStruct<T extends Struct>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.children.length === other.children.length && instance.compareManyFields(type.children, other.children) ); } function compareUnion<T extends Union>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.mode === other.mode && type.typeIds.every((x, i) => x === other.typeIds[i]) && instance.compareManyFields(type.children, other.children) ); } function compareDictionary<T extends Dictionary>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.id === other.id && type.isOrdered === other.isOrdered && instance.visit(<any> type.indices, other.indices) && instance.visit(type.dictionary, other.dictionary) ); } function compareInterval<T extends Interval>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.unit === other.unit ); } function compareFixedSizeList<T extends FixedSizeList>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.listSize === other.listSize && type.children.length === other.children.length && instance.compareManyFields(type.children, other.children) ); } function compareMap<T extends Map_>(type: T, other?: DataType | null): other is T { return (type === other) || ( compareConstructor(type, other) && type.keysSorted === other.keysSorted && type.children.length === other.children.length && instance.compareManyFields(type.children, other.children) ); } TypeComparator.prototype.visitNull = compareAny; TypeComparator.prototype.visitBool = compareAny; TypeComparator.prototype.visitInt = compareInt; TypeComparator.prototype.visitInt8 = compareInt; TypeComparator.prototype.visitInt16 = compareInt; TypeComparator.prototype.visitInt32 = compareInt; TypeComparator.prototype.visitInt64 = compareInt; TypeComparator.prototype.visitUint8 = compareInt; TypeComparator.prototype.visitUint16 = compareInt; TypeComparator.prototype.visitUint32 = compareInt; TypeComparator.prototype.visitUint64 = compareInt; TypeComparator.prototype.visitFloat = compareFloat; TypeComparator.prototype.visitFloat16 = compareFloat; TypeComparator.prototype.visitFloat32 = compareFloat; TypeComparator.prototype.visitFloat64 = compareFloat; TypeComparator.prototype.visitUtf8 = compareAny; TypeComparator.prototype.visitBinary = compareAny; TypeComparator.prototype.visitFixedSizeBinary = compareFixedSizeBinary; TypeComparator.prototype.visitDate = compareDate; TypeComparator.prototype.visitDateDay = compareDate; TypeComparator.prototype.visitDateMillisecond = compareDate; TypeComparator.prototype.visitTimestamp = compareTimestamp; TypeComparator.prototype.visitTimestampSecond = compareTimestamp; TypeComparator.prototype.visitTimestampMillisecond = compareTimestamp; TypeComparator.prototype.visitTimestampMicrosecond = compareTimestamp; TypeComparator.prototype.visitTimestampNanosecond = compareTimestamp; TypeComparator.prototype.visitTime = compareTime; TypeComparator.prototype.visitTimeSecond = compareTime; TypeComparator.prototype.visitTimeMillisecond = compareTime; TypeComparator.prototype.visitTimeMicrosecond = compareTime; TypeComparator.prototype.visitTimeNanosecond = compareTime; TypeComparator.prototype.visitDecimal = compareAny; TypeComparator.prototype.visitList = compareList; TypeComparator.prototype.visitStruct = compareStruct; TypeComparator.prototype.visitUnion = compareUnion; TypeComparator.prototype.visitDenseUnion = compareUnion; TypeComparator.prototype.visitSparseUnion = compareUnion; TypeComparator.prototype.visitDictionary = compareDictionary; TypeComparator.prototype.visitInterval = compareInterval; TypeComparator.prototype.visitIntervalDayTime = compareInterval; TypeComparator.prototype.visitIntervalYearMonth = compareInterval; TypeComparator.prototype.visitFixedSizeList = compareFixedSizeList; TypeComparator.prototype.visitMap = compareMap; /** @ignore */ export const instance = new TypeComparator(); export function compareSchemas<T extends { [key: string]: DataType }>(schema: Schema<T>, other?: Schema | null): other is Schema<T> { return instance.compareSchemas(schema, other); } export function compareFields<T extends DataType = any>(field: Field<T>, other?: Field | null): other is Field<T> { return instance.compareFields(field, other); } export function compareTypes<A extends DataType = any>(type: A, other?: DataType): other is A { return instance.visit(type, other); }
the_stack