text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { dirname, basename, extname, join, normalize } from "path"; import * as ts from "typescript"; import { StandardTransform, TransformOperation, collectDeepNodes, AddNodeOperation, ReplaceNodeOperation, makeTransform } from "@ngtools/webpack/src/transformers"; import { AngularCompilerPlugin } from "@ngtools/webpack"; import { findIdentifierNode, getObjectPropertyMatches, getDecoratorMetadata } from "../utils/ast-utils"; import { getResolvedEntryModule } from "../utils/transformers-utils"; export function nsReplaceLazyLoader(getNgCompiler: () => AngularCompilerPlugin, entryPath: string, projectDir: string): ts.TransformerFactory<ts.SourceFile> { const getTypeChecker = () => getNgCompiler().typeChecker; const standardTransform: StandardTransform = function (sourceFile: ts.SourceFile) { let ops: TransformOperation[] = []; const entryModule = getResolvedEntryModule(getNgCompiler(), projectDir); const sourceFilePath = join(dirname(sourceFile.fileName), basename(sourceFile.fileName, extname(sourceFile.fileName))); if (!entryModule || normalize(sourceFilePath) !== normalize(entryModule.path)) { return ops; } try { ops = addArrayPropertyValueToNgModule(sourceFile, "providers", "NgModuleFactoryLoader", "{ provide: nsNgCoreImport_Generated.NgModuleFactoryLoader, useClass: NSLazyModulesLoader_Generated }") || []; } catch (e) { ops = []; } return ops; }; return makeTransform(standardTransform, getTypeChecker); } export function addArrayPropertyValueToNgModule( sourceFile: ts.SourceFile, targetPropertyName: string, newPropertyValueMatch: string, newPropertyValue: string ): TransformOperation[] { const ngModuleConfigNodesInFile = getDecoratorMetadata(sourceFile, "NgModule", "@angular/core"); let ngModuleConfigNode: any = ngModuleConfigNodesInFile && ngModuleConfigNodesInFile[0]; if (!ngModuleConfigNode) { return null; } const importsInFile = collectDeepNodes(sourceFile, ts.SyntaxKind.ImportDeclaration); const lastImport = importsInFile && importsInFile[importsInFile.length - 1]; if (!lastImport) { return null; } const ngLazyLoaderNode = ts.createIdentifier(NgLazyLoaderCode); if (ngModuleConfigNode.kind === ts.SyntaxKind.Identifier) { const ngModuleConfigIndentifierNode = ngModuleConfigNode as ts.Identifier; // cases like @NgModule(myCoolConfig) const configObjectDeclarationNodes = collectDeepNodes<ts.Node>(sourceFile, ts.SyntaxKind.VariableStatement).filter(imp => { return findIdentifierNode(imp, ngModuleConfigIndentifierNode.getText()); }); // will be undefined when the object is imported from another file const configObjectDeclaration = (configObjectDeclarationNodes && configObjectDeclarationNodes[0]); const configObjectName = (<string>ngModuleConfigIndentifierNode.escapedText).trim(); const configObjectSetupCode = getConfigObjectSetupCode(configObjectName, targetPropertyName, newPropertyValueMatch, newPropertyValue); const configObjectSetupNode = ts.createIdentifier(configObjectSetupCode); return [ new AddNodeOperation(sourceFile, lastImport, undefined, ngLazyLoaderNode), new AddNodeOperation(sourceFile, configObjectDeclaration || lastImport, undefined, configObjectSetupNode) ]; } else if (ngModuleConfigNode.kind === ts.SyntaxKind.ObjectLiteralExpression) { // cases like @NgModule({ bootstrap: ... }) const ngModuleConfigObjectNode = ngModuleConfigNode as ts.ObjectLiteralExpression; const matchingProperties: ts.ObjectLiteralElement[] = getObjectPropertyMatches(ngModuleConfigObjectNode, sourceFile, targetPropertyName); if (!matchingProperties) { // invalid object return null; } if (matchingProperties.length === 0) { if (ngModuleConfigObjectNode.properties.length === 0) { // empty object @NgModule({ }) return null; } // the target field is missing, we will insert it @NgModule({ otherProps }) const lastConfigObjPropertyNode = ngModuleConfigObjectNode.properties[ngModuleConfigObjectNode.properties.length - 1]; const newTargetPropertyNode = ts.createPropertyAssignment(targetPropertyName, ts.createIdentifier(`[${newPropertyValue}]`)); return [ new AddNodeOperation(sourceFile, lastConfigObjPropertyNode, undefined, newTargetPropertyNode), new AddNodeOperation(sourceFile, lastImport, undefined, ngLazyLoaderNode) ]; } // the target property is found const targetPropertyNode = matchingProperties[0] as ts.PropertyAssignment; if (targetPropertyNode.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) { // not an array return null; } const targetPropertyValuesNode = targetPropertyNode.initializer as ts.ArrayLiteralExpression; const targetPropertyValues = targetPropertyValuesNode.elements; if (targetPropertyValues.length > 0) { // @NgModule({ targetProperty: [ someValues ] }) const targetPropertyValuesStrings = targetPropertyValues.map(node => node.getText()); const wholeWordPropValueRegex = new RegExp("\\b" + newPropertyValueMatch + "\\b"); if (targetPropertyValuesStrings.some(((value) => wholeWordPropValueRegex.test(value)))) { // already registered return null; } const lastPropertyValueNode = targetPropertyValues[targetPropertyValues.length - 1]; const newPropertyValueNode = ts.createIdentifier(`${newPropertyValue}`); return [ new AddNodeOperation(sourceFile, lastPropertyValueNode, undefined, newPropertyValueNode), new AddNodeOperation(sourceFile, lastImport, undefined, ngLazyLoaderNode) ]; } else { // empty array @NgModule({ targetProperty: [ ] }) const newTargetPropertyValuesNode = ts.createIdentifier(`[${newPropertyValue}]`); return [ new ReplaceNodeOperation(sourceFile, targetPropertyValuesNode, newTargetPropertyValuesNode), new AddNodeOperation(sourceFile, lastImport, undefined, ngLazyLoaderNode) ]; } } } // handles cases like @NgModule(myCoolConfig) by returning a code snippet for processing // the config object and configuring its {{targetPropertyName}} based on the specified arguments // e.g. // if (!myCoolConfig.providers) { // myCoolConfig.providers = []; // } // if (Array.isArray(myCoolConfig.providers)) { // var wholeWordPropertyRegex = new RegExp("\bNgModuleFactoryLoader\b"); // if (!myCoolConfig.providers.some(function (property) { return wholeWordPropertyRegex.test(property); })) { // myCoolConfig.providers.push({ provide: nsNgCoreImport_Generated.NgModuleFactoryLoader, useClass: NSLazyModulesLoader_Generated }); // } // } export function getConfigObjectSetupCode(configObjectName: string, targetPropertyName: string, newPropertyValueMatch: string, newPropertyValue: string) { return ` if (!${configObjectName}.${targetPropertyName}) { ${configObjectName}.${targetPropertyName} = []; } if (Array.isArray(${configObjectName}.${targetPropertyName})) { var wholeWordPropertyRegex = new RegExp("\\b${newPropertyValueMatch}\\b"); if (!${configObjectName}.${targetPropertyName}.some(function (property) { return wholeWordPropertyRegex.test(property); })) { ${configObjectName}.${targetPropertyName}.push(${newPropertyValue}); } } `; } // based on: https://github.com/angular/angular/blob/4c2ce4e8ba4c5ac5ce8754d67bc6603eaad4564a/packages/core/src/linker/system_js_ng_module_factory_loader.ts // when @angular/core is an external module, this fixes https://github.com/NativeScript/nativescript-cli/issues/4024 by including the lazy loader INSIDE the bundle allowing it to access the lazy modules export const NgLazyLoaderCode = ` var nsNgCoreImport_Generated = require("@angular/core"); var NSLazyModulesLoader_Generated = /** @class */ (function () { function NSLazyModulesLoader_Generated(_compiler, config) { this._compiler = _compiler; this._config = config || { factoryPathPrefix: '', factoryPathSuffix: '.ngfactory', }; } NSLazyModulesLoader_Generated.prototype.load = function (path) { var offlineMode = this._compiler instanceof nsNgCoreImport_Generated.Compiler; return offlineMode ? this.loadFactory(path) : this.loadAndCompile(path); }; NSLazyModulesLoader_Generated.prototype.loadAndCompile = function (path) { var _this = this; var _a = path.split('#'), module = _a[0], exportName = _a[1]; if (exportName === undefined) { exportName = 'default'; } return import(module) .then(function (module) { return module[exportName]; }) .then(function (type) { return _this.checkNotEmpty(type, module, exportName); }) .then(function (type) { return _this._compiler.compileModuleAsync(type); }); }; NSLazyModulesLoader_Generated.prototype.loadFactory = function (path) { var _this = this; var _a = path.split('#'), module = _a[0], exportName = _a[1]; var factoryClassSuffix = 'NgFactory'; if (exportName === undefined) { exportName = 'default'; factoryClassSuffix = ''; } return import(this._config.factoryPathPrefix + module + this._config.factoryPathSuffix) .then(function (module) { return module[exportName + factoryClassSuffix]; }) .then(function (factory) { return _this.checkNotEmpty(factory, module, exportName); }); }; NSLazyModulesLoader_Generated.prototype.checkNotEmpty = function (value, modulePath, exportName) { if (!value) { throw new Error("Cannot find '" + exportName + "' in '" + modulePath + "'"); } return value; }; NSLazyModulesLoader_Generated = __decorate([ nsNgCoreImport_Generated.Injectable(), __param(1, nsNgCoreImport_Generated.Optional()), __metadata("design:paramtypes", [nsNgCoreImport_Generated.Compiler, nsNgCoreImport_Generated.SystemJsNgModuleLoaderConfig]) ], NSLazyModulesLoader_Generated); return NSLazyModulesLoader_Generated; }()); `;
the_stack
import type { TimeUnit } from "./Time"; import { Entity, IEntitySettings, IEntityPrivate } from "./Entity" import { TextFormatter } from "./TextFormatter"; import * as $object from "./Object"; import * as $utils from "./Utils"; import * as $type from "./Type"; export interface IDurationFormatterSettings extends IEntitySettings { /** * A universal duration format to use wherever number needs to be formatted * as a duration. */ durationFormat?: string; /** * A base value. Any number below it will be considered "negative". * * @default 0 */ negativeBase?: number; /** * Identifies what values are used in duration. * * Available options: `"millisecond"`, `"second"` (default), `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, and `"year"`. * * @see {@link https://www.amcharts.com/docs/v5/concepts/formatters/formatting-durations/#Base_unit} for more info * @default "second" */ baseUnit?: TimeUnit; /** * Time unit dependent duration formats. * * Used be [[DurationAxis]]. */ durationFormats?: Partial<Record<TimeUnit, Partial<Record<TimeUnit, string>>>>; /** * An array of data fields that hold duration values and should be formatted * with a [[DurationFormatter]]. * * @see {@link https://www.amcharts.com/docs/v5/concepts/formatters/data-placeholders/#Formatting_placeholders} for more info */ durationFields?: string[]; } export interface IDurationFormatterPrivate extends IEntityPrivate { } /** * A class used to format numberic values as time duration. * * @see {@link https://www.amcharts.com/docs/v5/concepts/formatters/formatting-durations/} for more info */ export class DurationFormatter extends Entity { declare public _settings: IDurationFormatterSettings; declare public _privateSettings: IDurationFormatterPrivate; protected _setDefaults() { const dmillisecond = "_duration_millisecond"; const dsecond = "_duration_second"; const dminute = "_duration_minute"; const dhour = "_duration_hour"; const dday = "_duration_day"; const dweek = "_duration_week"; const dmonth = "_duration_month"; const dyear = "_duration_year"; const asecond = "_second"; const aminute = "_minute"; const ahour = "_hour"; const aday = "_day"; const aweek = "_week"; const amonth = "_week"; const ayear = "_year"; // Defaults this._setDefault("negativeBase", 0); this._setDefault("baseUnit", "second"); this._setDefault("durationFormats", { "millisecond": { "millisecond": this._t(dmillisecond), "second": this._t((dmillisecond + asecond) as any), "minute": this._t((dmillisecond + aminute) as any), "hour": this._t((dmillisecond + ahour) as any), "day": this._t((dmillisecond + aday) as any), "week": this._t((dmillisecond + aweek) as any), "month": this._t((dmillisecond + amonth) as any), "year": this._t((dmillisecond + ayear) as any) }, "second": { "second": this._t((dsecond) as any), "minute": this._t((dsecond + aminute) as any), "hour": this._t((dsecond + ahour) as any), "day": this._t((dsecond + aday) as any), "week": this._t((dsecond + aweek) as any), "month": this._t((dsecond + amonth) as any), "year": this._t((dsecond + ayear) as any) }, "minute": { "minute": this._t((dminute) as any), "hour": this._t((dminute + ahour) as any), "day": this._t((dminute + aday) as any), "week": this._t((dminute + aweek) as any), "month": this._t((dminute + amonth) as any), "year": this._t((dminute + ayear) as any) }, "hour": { "hour": this._t((dhour) as any), "day": this._t((dhour + aday) as any), "week": this._t((dhour + aweek) as any), "month": this._t((dhour + amonth) as any), "year": this._t((dhour + ayear) as any) }, "day": { "day": this._t((dday) as any), "week": this._t((dday + aweek) as any), "month": this._t((dday + amonth) as any), "year": this._t((dday + ayear) as any) }, "week": { "week": this._t((dweek) as any), "month": this._t((dweek + amonth) as any), "year": this._t((dweek + ayear) as any) }, "month": { "month": this._t((dmonth) as any), "year": this._t((dmonth + ayear) as any) }, "year": { "year": this._t(dyear) } }); super._setDefaults(); } /** * Collection of aliases for units. */ protected _unitAliases: { [index: string]: string } = { "Y": "y", "D": "d", "H": "h", "K": "h", "k": "h", "n": "S" }; public _beforeChanged() { super._beforeChanged(); } /** * Formats the number as duration. * * For example `1000` (base unit seconds) would be converted to `16:40` as in * 16 minutes and 40 seconds. * * @param value Value to format * @param format Format to apply * @param base Override base unit * @return Formatted number */ public format(value: number | string, format?: string, base?: TimeUnit): string { // no base unit? let baseUnit = base || this.get("baseUnit"); // no format passed in or empty if (typeof format === "undefined" || format === "") { if (this.get("durationFormat") != null) { format = this.get("durationFormat"); } else { format = this.getFormat($type.toNumber(value), undefined, baseUnit); } } // Clean format format = $utils.cleanFormat(format!); // get format info (it will also deal with parser caching) let info = this.parseFormat(format, baseUnit); // cast to number just in case // TODO: maybe use better casting let source: number = Number(value); // format and replace the number let details; if (source > this.get("negativeBase")) { details = info.positive; } else if (source < this.get("negativeBase")) { details = info.negative; } else { details = info.zero; } // Format let formatted = this.applyFormat(source, details); // Apply color? if (details.color !== "") { formatted = "[" + details.color + "]" + formatted + "[/]"; } return formatted; } /** * Parses supplied format into structured object which can be used to format * the number. * * @param format Format string, i.e. "#,###.00" * @param base Override base unit * @return Parsed information */ protected parseFormat(format: string, base?: TimeUnit): any { // Check cache // TODO // let cached = this.getCache(format); // if (cached != null) { // return cached; // } // no base unit? let baseUnit = base || this.get("baseUnit"); // Initialize duration parsing info let info = { "positive": { "color": "", "template": "", "parts": <any>[], "source": "", "baseUnit": baseUnit, "parsed": false, "absolute": false }, "negative": { "color": "", "template": "", "parts": <any>[], "source": "", "baseUnit": baseUnit, "parsed": false, "absolute": false }, "zero": { "color": "", "template": "", "parts": <any>[], "source": "", "baseUnit": baseUnit, "parsed": false, "absolute": false } }; // Escape double vertical bars (that mean display one vertical bar) format = format.replace("||", $type.PLACEHOLDER2); // Split it up and deal with different formats let parts = format.split("|"); info.positive.source = parts[0]; if (typeof parts[2] === "undefined") { info.zero = info.positive; } else { info.zero.source = parts[2]; } if (typeof parts[1] === "undefined") { info.negative = info.positive; } else { info.negative.source = parts[1]; } // Parse each $object.each(info, (_part, item) => { // Already parsed if (item.parsed) { return; } // Check cached // TODO // if (typeof this.getCache(item.source) !== "undefined") { // info[part] = this.getCache(item.source); // return; // } // Begin parsing let partFormat: string = item.source; // Check for [] directives let dirs: string[] | null = []; dirs = item.source.match(/^\[([^\]]*)\]/); if (dirs && dirs.length && dirs[0] !== "") { partFormat = item.source.substr(dirs[0].length); item.color = dirs[1]; } // Let TextFormatter split into chunks let chunks = TextFormatter.chunk(partFormat, true); for (let i: number = 0; i < chunks.length; i++) { let chunk = chunks[i]; // replace back double vertical bar chunk.text = chunk.text.replace($type.PLACEHOLDER2, "|"); if (chunk.type === "value") { // Just "Duration"? // if (chunk.text.toLowerCase() === "duration") { // chunk.text = durationFormat; // } // Check for "a" (absolute) modifier if (chunk.text.match(/[yYMdDwhHKkmsSn]+a/)) { item.absolute = true; chunk.text = chunk.text.replace(/([yYMdDwhHKkmsSn]+)a/, "$1"); } // Find all possible parts let matches = chunk.text.match(/y+|Y+|M+|d+|D+|w+|h+|H+|K+|k+|m+|s+|S+|n+/g); if (matches) { // Populate template for (let x = 0; x < matches.length; x++) { // Is it an alias? if (matches[x] == null) { matches[x] = this._unitAliases[matches[x]]; } item.parts.push(matches[x]); chunk.text = chunk.text.replace(matches[x], $type.PLACEHOLDER); } } } // Apply to template item.template += chunk.text; } // Apply style formatting //item.template = TextFormatter.format(item.template, this.outputFormat); // Save cache // TODO //this.setCache(item.source, item); // Mark this as parsed item.parsed = true; }); // Save cache (the whole thing) // TODO //this.setCache(format, info); return info; } /** * Applies parsed format to a numeric value. * * @param value Value * @param details Parsed format as returned by {parseFormat} * @return Formatted duration */ protected applyFormat(value: number, details: any): string { // Use absolute values let negative = !details.absolute && (value < this.get("negativeBase")); value = Math.abs(value); // Recalculate to milliseconds let tstamp = this.toTimeStamp(value, details.baseUnit); // Init return value let res = details.template; // Iterate through duration parts for (let i = 0, len = details.parts.length; i < len; i++) { // Gather the part let part = details.parts[i]; let unit = this._toTimeUnit(part.substr(0, 1)); let digits = part.length; // Calculate current unit value let ints = Math.floor(tstamp / this._getUnitValue(unit!)); res = res.replace($type.PLACEHOLDER, $utils.padString(ints, digits, "0")); // Reduce timestamp tstamp -= ints * this._getUnitValue(unit!); } // Reapply negative sign if (negative) { res = "-" + res; } return res; } /** * Converts numeric value to timestamp in milliseconds. * * @param value A source value * @param baseUnit Base unit the source value is in: "q", "s", "i", "h", "d", "w", "m", "y" * @return Value representation as a timestamp in milliseconds */ public toTimeStamp(value: number, baseUnit: TimeUnit): number { return value * this._getUnitValue(baseUnit); } protected _toTimeUnit(code: string): TimeUnit | undefined { switch (code) { case "S": return "millisecond"; case "s": return "second"; case "m": return "minute"; case "h": return "hour"; case "d": return "day"; case "w": return "week"; case "M": return "month"; case "y": return "year"; }; } /** * Returns appropriate default format for the value. * * If `maxValue` is sepcified, it will use that value to determine the time * unit for the format. * * For example if your `baseUnit` is `"second"` and you pass in `10`, you * will get `"10"`. * * However, you might want it to be formatted in the context of bigger scale, * say 10 minutes (600 seconds). If you pass in `600` as `maxValue`, all * values, including small ones will use format with minutes, e.g.: * `00:10`, `00:50`, `12: 30`, etc. * * @param value Value to format * @param maxValue Maximum value to be used to determine format * @param baseUnit Base unit of the value * @return Format */ public getFormat(value: number, maxValue?: number, baseUnit?: TimeUnit): string { // Is format override set? if (this.get("durationFormat") != null) { return this.get("durationFormat")!; } // Get base unit if (!baseUnit) { baseUnit = this.get("baseUnit"); } if (maxValue != null && value != maxValue) { value = Math.abs(value); maxValue = Math.abs(maxValue); let maxUnit = this.getValueUnit(Math.max(value, maxValue), baseUnit); //let diffUnit = this.getValueUnit(Math.abs(maxValue - value), baseUnit); //console.log(maxUnit, diffUnit); return (<any>this.get("durationFormats"))[baseUnit!][maxUnit!]; } else { let unit = this.getValueUnit(value, baseUnit); return (<any>this.get("durationFormats"))[baseUnit!][unit!]; } } /** * Returns value's closest denominator time unit, e.g 100 seconds is * `"minute"`, while 59 seconds would still be `second`. * * @param value Source duration value * @param baseUnit Base unit * @return Denominator */ public getValueUnit(value: number, baseUnit?: TimeUnit): TimeUnit | undefined { // Get base unit if (!baseUnit) { baseUnit = this.get("baseUnit"); } // Convert to milliseconds let currentUnit: any; let ms = this.getMilliseconds(value, baseUnit); $object.eachContinue(this._getUnitValues(), (key, val) => { if (key == baseUnit || currentUnit) { let num = ms / val; if (num <= 1) { if (!currentUnit) { currentUnit = key; } return false; } currentUnit = key; } return true; }); return currentUnit; } /** * Converts value to milliseconds according to `baseUnit`. * * @param value Source duration value * @param baseUnit Base unit * @return Value in milliseconds */ public getMilliseconds(value: number, baseUnit?: TimeUnit): number { // Get base unit if (!baseUnit) { baseUnit = this.get("baseUnit"); } return value * this._getUnitValue(baseUnit!); } protected _getUnitValue(timeUnit: TimeUnit): number { return this._getUnitValues()[timeUnit]; } protected _getUnitValues(): any { return { "millisecond": 1, "second": 1000, "minute": 60000, "hour": 3600000, "day": 86400000, "week": 604800000, "month": 2592000000, "year": 31536000000, }; } }
the_stack
import * as assert from 'assert'; import * as vscode from 'vscode'; import { parseSDL, tokenizeSDL } from '../../sdl/sdlparse'; let backslash = "\\"; // Defines a Mocha test suite to group tests of similar kind together suite("sdl parser", () => { test("tokenizer", () => { let tokens = tokenizeSDL(`my_tag person "Akiko" "Johnson" height=60 person name:first-name="Akiko" name:last-name="Johnson" /* * Foo */ my_namespace:person "Akiko" "Johnson" dimensions:height=68 { son "Nouhiro" "Johnson" daughter "Sabrina" "Johnson" location="Italy" { hobbies "swimming" "surfing" smoker false } } ------------------------------------------------------------------ // (notice the separator style comment above...) # a log entry # note - this tag has two values (date_time and string) and an # attribute (error) entry 2005/11/23 10:14:23.253-GMT "Something bad happened" error=true # a long line mylist "something" "another" true "shoe" 2002/12/13 "rock" ${backslash} "morestuff" "sink" "penny" 12:15:23.425 # a long string text "this is a long rambling line of text with a continuation ${backslash} and it keeps going and going..." # anonymous tag examples files { "/folder1/file.txt" "/file2.txt" } # To retrieve the files as a list of strings # # List files = tag.getChild("files").getChildrenValues("content"); # # We us the name "content" because the files tag has two children, each of # which are anonymous tags (values with no name.) These tags are assigned # the name "content" matrix { 1 2 3 4 5 6 }`); // TODO: make test more automatic instead of relying on tokenizer not changing assert.deepStrictEqual(tokens[0], { type: "identifier", range: [0, 6], name: "my_tag" }); }); test("example sdl file", () => { let root = parseSDL(`# a tag having only a name 420 my_tag # three tags acting as name value pairs first_name "Akiko" last_name "Johnson" height 68 "anon2" # a tag with a value list person "Akiko" "Johnson" 68 # a tag with attributes person first_name="Akiko" last_name="Johnson" height=68 # a tag with values and attributes person "Akiko" "Johnson" height=68 # a tag with attributes using namespaces person name:first-name="Akiko" name:last-name="Johnson" # a tag with values, attributes, namespaces, and children my_namespace:person "Akiko" "Johnson" dimensions:height=68 { son "Nouhiro" "Johnson" daughter "Sabrina" "Johnson" location="Italy" { hobbies "swimming" "surfing" languages "English" "Italian" smoker false } } ------------------------------------------------------------------ // (notice the separator style comment above...) # a log entry # note - this tag has two values (date_time and string) and an # attribute (error) entry 2005/11/23 10:14:23.253-GMT "Something bad happened" error=true # a long line mylist "something" "another" true "shoe" 2002/12/13 "rock" ${backslash} "morestuff" "sink" "penny" 12:15:23.425 # a long string text "this is a long rambling line of text with a continuation ${backslash} and it keeps going and going..." # anonymous tag examples files { "/folder1/file.txt" "/file2.txt" } # To retrieve the files as a list of strings # # List files = tag.getChild("files").getChildrenValues("content"); # # We us the name "content" because the files tag has two children, each of # which are anonymous tags (values with no name.) These tags are assigned # the name "content" matrix { 1 2 3 4 5 6 } # To retrieve the values from the matrix (as a list of lists) # # List rows = tag.getChild("matrix").getChildrenValues("content");`); assert.deepStrictEqual(root.tags["my_tag"][0].values.length, 0); assert.deepStrictEqual(root.tags["first_name"][0].values.length, 1); assert.deepStrictEqual(root.tags["first_name"][0].values[0].value, "Akiko"); assert.deepStrictEqual(root.tags["last_name"][0].values.length, 1); assert.deepStrictEqual(root.tags["last_name"][0].values[0].value, "Johnson"); assert.deepStrictEqual(root.tags["height"][0].values.length, 1); assert.deepStrictEqual(root.tags["height"][0].values[0].value, 68); assert.deepStrictEqual(root.tags[""][0].values[0].value, 420); assert.deepStrictEqual(root.tags[""][0].values[1].value, "anon2"); assert.deepStrictEqual(root.tags["person"][0].values.length, 3); assert.deepStrictEqual(root.tags["person"][0].values[0].value, "Akiko"); assert.deepStrictEqual(root.tags["person"][0].values[1].value, "Johnson"); assert.deepStrictEqual(root.tags["person"][0].values[2].value, 68); assert.deepStrictEqual(root.tags["person"][1].values.length, 0); assert.deepStrictEqual(root.tags["person"][1].attributes["first_name"][0].value, "Akiko"); assert.deepStrictEqual(root.tags["person"][1].attributes["last_name"][0].value, "Johnson"); assert.deepStrictEqual(root.tags["person"][1].attributes["height"][0].value, 68); assert.deepStrictEqual(root.tags["person"][2].values.length, 2); assert.deepStrictEqual(root.tags["person"][2].values[0].value, "Akiko"); assert.deepStrictEqual(root.tags["person"][2].values[1].value, "Johnson"); assert.deepStrictEqual(root.tags["person"][2].attributes["height"][0].value, 68); assert.deepStrictEqual(root.tags["person"][3].attributes["first-name"][0].namespace, "name"); assert.deepStrictEqual(root.tags["person"][3].attributes["first-name"][0].value, "Akiko"); assert.deepStrictEqual(root.tags["person"][3].attributes["last-name"][0].namespace, "name"); assert.deepStrictEqual(root.tags["person"][3].attributes["last-name"][0].value, "Johnson"); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].attributes["height"][0].namespace, "dimensions"); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].attributes["height"][0].value, 68); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["son"][0].values.length, 2); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["son"][0].values[0].value, "Nouhiro"); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["son"][0].values[1].value, "Johnson"); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["daughter"][0].values.length, 2); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["daughter"][0].values[0].value, "Sabrina"); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["daughter"][0].values[1].value, "Johnson"); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["daughter"][0].attributes["location"][0].value, "Italy"); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["daughter"][0].tags["hobbies"][0].values.length, 2); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["daughter"][0].tags["hobbies"][0].values[0].value, "swimming"); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["daughter"][0].tags["hobbies"][0].values[1].value, "surfing"); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["daughter"][0].tags["languages"][0].values.length, 2); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["daughter"][0].tags["languages"][0].values[0].value, "English"); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["daughter"][0].tags["languages"][0].values[1].value, "Italian"); assert.deepStrictEqual(root.namespaces["my_namespace"].tags["person"][0].tags["daughter"][0].tags["smoker"][0].values[0].value, false); assert.deepStrictEqual(root.tags["entry"][0].values.length, 2); assert.deepStrictEqual(root.tags["entry"][0].values[0].value, { year: 2005, month: 11, day: 23, hours: 10, minutes: 14, seconds: 23, milliseconds: 253, timezone: "GMT" }); assert.deepStrictEqual(root.tags["entry"][0].values[1].value, "Something bad happened"); assert.deepStrictEqual(root.tags["entry"][0].attributes["error"][0].value, true); assert.deepStrictEqual(root.tags["mylist"][0].values.length, 10); assert.deepStrictEqual(root.tags["mylist"][0].values[0].value, "something"); assert.deepStrictEqual(root.tags["mylist"][0].values[1].value, "another"); assert.deepStrictEqual(root.tags["mylist"][0].values[2].value, true); assert.deepStrictEqual(root.tags["mylist"][0].values[3].value, "shoe"); assert.deepStrictEqual(root.tags["mylist"][0].values[4].value, { year: 2002, month: 12, day: 13 }); assert.deepStrictEqual(root.tags["mylist"][0].values[5].value, "rock"); assert.deepStrictEqual(root.tags["mylist"][0].values[6].value, "morestuff"); assert.deepStrictEqual(root.tags["mylist"][0].values[7].value, "sink"); assert.deepStrictEqual(root.tags["mylist"][0].values[8].value, "penny"); assert.deepStrictEqual(root.tags["mylist"][0].values[9].value, { sign: "+", days: undefined, hours: 12, minutes: 15, seconds: 23, milliseconds: 425 }); assert.deepStrictEqual(root.tags["text"][0].values.length, 1); assert.deepStrictEqual(root.tags["text"][0].values[0].value, "this is a long rambling line of text with a continuation and it keeps going and going..."); assert.deepStrictEqual(root.tags["files"][0].tags[""][0].values.length, 2); assert.deepStrictEqual(root.tags["files"][0].tags[""][0].values[0].value, "/folder1/file.txt"); assert.deepStrictEqual(root.tags["files"][0].tags[""][0].values[1].value, "/file2.txt"); assert.deepStrictEqual(root.tags["matrix"][0].tags[""][0].values.length, 6); assert.deepStrictEqual(root.tags["matrix"][0].tags[""][0].values[0].value, 1); assert.deepStrictEqual(root.tags["matrix"][0].tags[""][0].values[1].value, 2); assert.deepStrictEqual(root.tags["matrix"][0].tags[""][0].values[2].value, 3); assert.deepStrictEqual(root.tags["matrix"][0].tags[""][0].values[3].value, 4); assert.deepStrictEqual(root.tags["matrix"][0].tags[""][0].values[4].value, 5); assert.deepStrictEqual(root.tags["matrix"][0].tags[""][0].values[5].value, 6); }); });
the_stack
import * as Clutter from 'clutter'; import * as Gio from 'gio'; import * as GLib from 'glib'; import * as GObject from 'gobject'; import { MatPanelButton } from 'src/layout/verticalPanel/panelButton'; import { LayoutState, LayoutType, TilingLayoutByKey, } from 'src/manager/layoutManager'; import { assert, assertNotNull } from 'src/utils/assert'; import { registerGObjectClass } from 'src/utils/gjs'; import * as St from 'st'; import { main as Main, popupMenu } from 'ui'; import { MsWorkspace } from '../msWorkspace'; const Animation = imports.ui.animation; /** Extension imports */ const Me = imports.misc.extensionUtils.getCurrentExtension(); @registerGObjectClass export class LayoutSwitcher extends St.BoxLayout { static metaInfo: GObject.MetaInfo = { GTypeName: 'LayoutSwitcher', }; layoutQuickWidgetBin: St.Bin; tilingIcon: St.Icon; switcherButton: MatPanelButton; menuManager: popupMenu.PopupMenuManager; msWorkspace: MsWorkspace; menu: popupMenu.PopupMenu; constructor( msWorkspace: MsWorkspace, panelMenuManager: popupMenu.PopupMenuManager ) { super({}); this.layoutQuickWidgetBin = new St.Bin({ style_class: 'layout-quick-widget-bin', y_align: Clutter.ActorAlign.CENTER, }); this.tilingIcon = new St.Icon({ style_class: 'mat-panel-button-icon', }); this.switcherButton = new MatPanelButton({ child: this.tilingIcon, style_class: 'mat-panel-button', can_focus: true, track_hover: true, }); this.switcherButton.connect('scroll-event', (_, event) => { switch (event.get_scroll_direction()) { case Clutter.ScrollDirection.UP: this.msWorkspace.nextLayout(-1); break; case Clutter.ScrollDirection.DOWN: this.msWorkspace.nextLayout(1); break; } }); this.add_child(this.layoutQuickWidgetBin); this.add_child(this.switcherButton); this.msWorkspace = msWorkspace; this.menuManager = panelMenuManager; this.switcherButton.connect('clicked', (_actor, _button) => { // Go in reverse direction on right click (button: 3) //msWorkspace.nextLayout(button === 3 ? -1 : 1); this.menu.toggle(); }); this.updateLayoutWidget(); const connectId = this.msWorkspace.connect( 'tiling-layout-changed', this.updateLayoutWidget.bind(this) ); this.menu = this.buildMenu(); Main.layoutManager.uiGroup.add_actor(this.menu.actor); this.menuManager.addMenu(this.menu); this.connect('destroy', () => { this.msWorkspace.disconnect(connectId); }); } updateLayoutWidget() { this.layoutQuickWidgetBin.remove_all_children(); if (!this.msWorkspace.layout) { return; } const quickWidget = this.msWorkspace.layout.buildQuickWidget(); if (quickWidget) { this.layoutQuickWidgetBin.set_child(quickWidget); this.layoutQuickWidgetBin.show(); } else { this.layoutQuickWidgetBin.hide(); } this.tilingIcon.gicon = this.msWorkspace.layout.icon; } buildMenu() { const menu = new popupMenu.PopupMenu(this, 0.5, St.Side.TOP); menu.actor.add_style_class_name('horizontal-panel-menu'); menu.actor.hide(); Object.entries(TilingLayoutByKey).forEach( ([layoutKey, layoutConstructor]) => { menu.addMenuItem( new TilingLayoutMenuItem( layoutConstructor, this.msWorkspace.state.layoutStateList.find( (layoutState) => layoutState.key === layoutKey ) != null ) ); } ); menu.addMenuItem(new popupMenu.PopupSeparatorMenuItem()); menu.addMenuItem(new LayoutsToggle(menu)); return menu; } setLayout(layoutKey: string) { this.msWorkspace.setLayoutByKey(layoutKey); } addLayout(layoutKey: string) { if ( this.msWorkspace.state.layoutStateList.find( (layoutState) => layoutState.key === layoutKey ) != null ) return true; // Add the layout in the right order const wantedIndex = Me.layoutManager.layoutList.findIndex((layout) => { return layoutKey === layout.state.key; }); // Note: This cast is safe, typescript is just not good enough to figure that out const newState = Me.layoutManager.getLayoutByKey(layoutKey) .state as LayoutState; if (wantedIndex > this.msWorkspace.state.layoutStateList.length) { this.msWorkspace.state.layoutStateList.push(newState); } else { this.msWorkspace.state.layoutStateList.splice( wantedIndex, 0, newState ); } Me.stateManager.stateChanged(); return true; } removeLayout(layoutKey: string) { if (this.msWorkspace.state.layoutStateList.length === 1) return false; if ( this.msWorkspace.state.layoutStateList.find( (layoutState) => layoutState.key === layoutKey ) === null ) return true; const index = this.msWorkspace.state.layoutStateList.findIndex( (layoutState) => layoutState.key === layoutKey ); this.msWorkspace.state.layoutStateList.splice(index, 1); Me.stateManager.stateChanged(); return true; } vfunc_allocate(...args: [Clutter.ActorBox]) { const box = args[0]; const height = box.get_height() / 2; if (this.tilingIcon && this.tilingIcon.get_icon_size() != height) { GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, () => { this.tilingIcon.set_icon_size(height); return GLib.SOURCE_REMOVE; }); } super.vfunc_allocate(...args); } } @registerGObjectClass export class TilingLayoutMenuItem extends popupMenu.PopupSwitchMenuItem { layoutConstructor: LayoutType; editable = false; constructor( layoutConstructor: LayoutType, active: boolean, params?: popupMenu.PopupBaseMenuItemParams ) { super(layoutConstructor.label, active, params); this.layoutConstructor = layoutConstructor; this._icon = new St.Icon({ style_class: 'popup-menu-icon', gicon: Gio.icon_new_for_string( `${Me.path}/assets/icons/tiling/${layoutConstructor.state.key}-symbolic.svg` ), x_align: Clutter.ActorAlign.END, }); this.insert_child_at_index(this._icon, 1); this.setEditable(false); } get layoutSwitcher(): LayoutSwitcher { const layoutSwitcher = assertNotNull(this._parent).sourceActor; assert( layoutSwitcher instanceof LayoutSwitcher, "expected menu's source actor to be a LayoutSwitcher" ); return layoutSwitcher; } override activate(event: Clutter.Event) { if (!this.editable) { this.layoutSwitcher.setLayout(this.layoutConstructor.state.key); this.emit('activate', event); } else { if (this.state) { if ( this.layoutSwitcher.removeLayout( this.layoutConstructor.state.key ) ) { this.toggle(); } } else { if ( this.layoutSwitcher.addLayout( this.layoutConstructor.state.key ) ) { this.toggle(); } } } return; } setEditable(editable: boolean) { this.editable = editable; if (this.editable) { this.setSwitcherVisible(true); this.setVisible(true); } else { this.setSwitcherVisible(false); if (!this.state) { this.setVisible(false); } } } setSwitcherVisible(visible: boolean) { if (!this.mapped) { return (this._statusBin.opacity = visible ? 255 : 0); } this._statusBin.ease({ opacity: visible ? 255 : 0, duration: 300, }); } setVisible(visible: boolean) { if (!this.mapped) { return (this.height = visible ? -1 : 0); } if (visible) { if (this.height === 0) { this.height = -1; const height = this.height; this.height = 0; this.ease({ height: height, duration: 300, onComplete: () => { this.height = -1; }, }); } } else { this.ease({ height: 0, duration: 300, }); } } } @registerGObjectClass export class LayoutsToggle extends popupMenu.PopupImageMenuItem { editText: string; editIcon: Gio.IconPrototype; confirmText: string; confirmIcon: Gio.IconPrototype; menu: popupMenu.PopupMenu; editable: boolean; constructor( menu: popupMenu.PopupMenu, params?: popupMenu.PopupBaseMenuItemParams ) { const editText = _('Tweak available layouts'); const editIcon = Gio.icon_new_for_string( `${Me.path}/assets/icons/category/settings-symbolic.svg` ); super(editText, editIcon, params); this.editText = editText; this.editIcon = editIcon; this.confirmText = _('Confirm layouts'); this.confirmIcon = Gio.icon_new_for_string( `${Me.path}/assets/icons/check-symbolic.svg` ); this.menu = menu; this.editable = false; } activate(_event: Clutter.Event) { this.toggleEditMode(); } toggleEditMode() { this.editable = !this.editable; this.menu._getMenuItems().forEach((item) => { if (item instanceof TilingLayoutMenuItem) { item.setEditable(this.editable); } }); if (this.editable) { this.label.set_text(this.confirmText); this._icon.gicon = this.confirmIcon; } else { this.label.set_text(this.editText); this._icon.gicon = this.editIcon; } } }
the_stack
'use strict'; import * as vscode from 'vscode'; import {OCamlMerlinSession} from './merlin'; import * as child_process from 'child_process'; import * as Path from 'path'; import * as Fs from 'fs'; import {opamSpawn, wrapOpamExec} from './utils'; let promisify = require('tiny-promisify'); let fsExists = (path: string) => new Promise((resolve) => { Fs.exists(path, resolve); }); let fsWriteFile = promisify(Fs.writeFile); let sleep = (duration) => new Promise((resolve) => { setTimeout(resolve, duration); }); let getStream = require('get-stream'); let ocamlLang = { language: 'ocaml' }; let configuration = vscode.workspace.getConfiguration("ocaml"); let doOcpIndent = async (document: vscode.TextDocument, token: vscode.CancellationToken, range?: vscode.Range) => { let code = document.getText(); let ocpIndentPath = configuration.get<string>('ocpIndentPath'); let cmd = [ocpIndentPath]; if (range) { cmd.push('--lines'); cmd.push(`${range.start.line + 1}-${range.end.line + 1}`); } cmd.push('--numeric'); let cp = await opamSpawn(cmd, { cwd: Path.dirname(document.fileName) }); token.onCancellationRequested(() => { cp.disconnect(); }); cp.stdin.write(code); cp.stdin.end(); let output = await getStream(cp.stdout); cp.unref(); if (token.isCancellationRequested) return null; let newIndents = output.trim().split(/\n/g).map((n) => +n); let oldIndents = code.split(/\n/g).map((line) => /^\s*/.exec(line)[0]); let edits = []; let beginLine = range ? range.start.line : 0; newIndents.forEach((indent, index) => { let line = beginLine + index; let oldIndent = oldIndents[line]; let newIndent = ' '.repeat(indent); if (oldIndent !== newIndent) { edits.push(vscode.TextEdit.replace( new vscode.Range( new vscode.Position(line, 0), new vscode.Position(line, oldIndent.length) ), newIndent) ); } }); return edits; }; let ocamlKeywords = 'and|as|assert|begin|class|constraint|do|done|downto|else|end|exception|external|false|for|fun|function|functor|if|in|include|inherit|inherit!|initializer|lazy|let|match|method|method!|module|mutable|new|object|of|open|open!|or|private|rec|sig|struct|then|to|true|try|type|val|val!|virtual|when|while|with'.split('|'); export function activate(context: vscode.ExtensionContext) { let session = new OCamlMerlinSession(); let toVsPos = (pos) => { return new vscode.Position(pos.line - 1, pos.col); }; let fromVsPos = (pos: vscode.Position) => { return { line: pos.line + 1, col: pos.character }; }; let toVsRange = (start, end) => { return new vscode.Range(toVsPos(start), toVsPos(end)); }; context.subscriptions.push( vscode.languages.setLanguageConfiguration('ocaml', { indentationRules: { increaseIndentPattern: /^\s*(type|let)\s[^=]*=\s*$|\b(do|begin|struct|sig)\s*$/, decreaseIndentPattern: /\b(done|end)\s*$/, } }) ); context.subscriptions.push(session); context.subscriptions.push( vscode.languages.registerDocumentFormattingEditProvider(ocamlLang, { provideDocumentFormattingEdits(document, options, token) { return doOcpIndent(document, token); } }) ); context.subscriptions.push( vscode.languages.registerDocumentRangeFormattingEditProvider(ocamlLang, { provideDocumentRangeFormattingEdits(document, range, options, token) { return doOcpIndent(document, token, range); } }) ); context.subscriptions.push( vscode.languages.registerOnTypeFormattingEditProvider(ocamlLang, { async provideOnTypeFormattingEdits(document, position, ch, options, token) { let isEndAt = (word) => { let wordRange = document.getWordRangeAtPosition(position); return wordRange.end.isEqual(position) && document.getText(wordRange) === word; }; if ((ch === 'd' && !isEndAt('end')) || (ch === 'e' && !isEndAt('done'))) { return []; } return doOcpIndent(document, token); } }, ';', '|', ')', ']', '}', 'd', 'e') ); context.subscriptions.push( vscode.languages.registerCompletionItemProvider(ocamlLang, { async provideCompletionItems(document, position, token) { return new vscode.CompletionList(ocamlKeywords.map((keyword) => { let completionItem = new vscode.CompletionItem(keyword); completionItem.kind = vscode.CompletionItemKind.Keyword; return completionItem; })); } }) ); context.subscriptions.push( vscode.languages.registerCompletionItemProvider(ocamlLang, { async provideCompletionItems(document, position, token) { let line = document.getText(new vscode.Range( new vscode.Position(position.line, 0), position )); let match = /(?:[~?]?[A-Za-z_0-9'`.]+)$/.exec(line); let prefix = match && match[0] || ''; await session.syncBuffer(document.fileName, document.getText(), token); if (token.isCancellationRequested) return null; let [status, result] = await session.request(['complete', 'prefix', prefix, 'at', fromVsPos(position), 'with', 'doc']); if (token.isCancellationRequested) return null; if (status !== 'return') return; return new vscode.CompletionList(result.entries.map(({name, kind, desc, info}) => { let completionItem = new vscode.CompletionItem(name); let toVsKind = (kind) => { switch (kind.toLowerCase()) { case "value": return vscode.CompletionItemKind.Value; case "variant": return vscode.CompletionItemKind.Enum; case "constructor": return vscode.CompletionItemKind.Constructor; case "label": return vscode.CompletionItemKind.Field; case "module": return vscode.CompletionItemKind.Module; case "signature": return vscode.CompletionItemKind.Interface; case "type": return vscode.CompletionItemKind.Class; case "method": return vscode.CompletionItemKind.Function; case "#": return vscode.CompletionItemKind.Method; case "exn": return vscode.CompletionItemKind.Constructor; case "class": return vscode.CompletionItemKind.Class; } }; completionItem.kind = toVsKind(kind); completionItem.detail = desc; completionItem.documentation = info; if (prefix.startsWith('#') && name.startsWith(prefix)) { completionItem.textEdit = new vscode.TextEdit( new vscode.Range( new vscode.Position(position.line, position.character - prefix.length), position ), name ); } return completionItem; })); } }, '.', '#')); context.subscriptions.push( vscode.languages.registerDefinitionProvider(ocamlLang, { async provideDefinition(document, position, token) { await session.syncBuffer(document.fileName, document.getText(), token); if (token.isCancellationRequested) return null; let locate = async (kind: string): Promise<vscode.Location> => { let [status, result] = await session.request(['locate', null, kind, 'at', fromVsPos(position)]); if (token.isCancellationRequested) return null; if (status !== 'return' || typeof result === 'string') { return null; } let uri = document.uri; let {file, pos} = result; if (file) { uri = vscode.Uri.file(file); } return new vscode.Location(uri, toVsPos(pos)); }; let mlDef = await locate('ml'); let mliDef = await locate('mli'); let locs = []; if (mlDef && mliDef) { if (mlDef.uri.toString() === mliDef.uri.toString() && mlDef.range.isEqual(mliDef.range)) { locs = [mlDef]; } else { locs = [mliDef, mlDef]; } } else { if (mliDef) locs.push(mliDef); if (mlDef) locs.push(mlDef); } return locs; } }) ); context.subscriptions.push( vscode.languages.registerDocumentSymbolProvider(ocamlLang, { async provideDocumentSymbols(document, token) { await session.syncBuffer(document.fileName, document.getText(), token); if (token.isCancellationRequested) return null; let [status, result] = await session.request(['outline']); if (token.isCancellationRequested) return null; if (status !== 'return') return null; let symbols = []; let toVsKind = (kind) => { switch (kind.toLowerCase()) { case "value": return vscode.SymbolKind.Variable; case "variant": return vscode.SymbolKind.Enum; case "constructor": return vscode.SymbolKind.Constructor; case "label": return vscode.SymbolKind.Field; case "module": return vscode.SymbolKind.Module; case "signature": return vscode.SymbolKind.Interface; case "type": return vscode.SymbolKind.Class; case "method": return vscode.SymbolKind.Function; case "#": return vscode.SymbolKind.Method; case "exn": return vscode.SymbolKind.Constructor; case "class": return vscode.SymbolKind.Class; } }; let traverse = (nodes) => { for (let {name, kind, start, end, children} of nodes) { symbols.push(new vscode.SymbolInformation(name, toVsKind(kind), toVsRange(start, end))); if (Array.isArray(children)) { traverse(children); } } }; traverse(result); return symbols; } }) ); context.subscriptions.push( vscode.languages.registerHoverProvider(ocamlLang, { async provideHover(document, position, token) { await session.syncBuffer(document.fileName, document.getText(), token); if (token.isCancellationRequested) return null; let [status, result] = await session.request(['type', 'enclosing', 'at', fromVsPos(position)]); if (token.isCancellationRequested) return null; if (status !== 'return' || result.length <= 0) return; let {start, end, type} = result[0]; // Try expand type if (/^[A-Za-z_0-9']+$/.test(type)) { let [status, result] = await session.request(['type', 'enclosing', 'at', fromVsPos(position)]); if (token.isCancellationRequested) return null; if (!(status !== 'return' || result.length <= 0)) { start = result[0].start; end = result[0].end; type = result[0].type; } } // Since vscode shows scrollbar in hovertip. We don't need to truncate it ever. /* if (type.includes('\n')) { let lines = type.split(/\n/g); if (lines.length > 6) { let end = lines.pop(); lines = lines.slice(0, 5); lines.push(' (* ... *)'); lines.push(end); } type = lines.join('\n'); } */ if (/^sig\b/.test(type)) { type = `module type _ = ${type}`; } else if (!/^type\b/.test(type)) { type = `type _ = ${type}`; } return new vscode.Hover({ language: 'ocaml', value: type }, toVsRange(start, end)); } }) ); context.subscriptions.push( vscode.languages.registerDocumentHighlightProvider(ocamlLang, { async provideDocumentHighlights(document, position, token) { await session.syncBuffer(document.fileName, document.getText(), token); if (token.isCancellationRequested) return null; let [status, result] = await session.request(['occurrences', 'ident', 'at', fromVsPos(position)]); if (token.isCancellationRequested) return null; if (status !== 'return' || result.length <= 0) return; return result.map((item) => { return new vscode.DocumentHighlight(toVsRange(item.start, item.end)); }); } }) ); context.subscriptions.push( vscode.languages.registerRenameProvider(ocamlLang, { async provideRenameEdits(document, position, newName, token) { await session.syncBuffer(document.fileName, document.getText(), token); if (token.isCancellationRequested) return null; let [status, result] = await session.request(['occurrences', 'ident', 'at', fromVsPos(position)]); if (token.isCancellationRequested) return null; if (status !== 'return' || result.length <= 0) return; let edits = result.map((item) => { return new vscode.TextEdit(toVsRange(item.start, item.end), newName); }); let edit = new vscode.WorkspaceEdit(); edit.set(document.uri, edits); return edit; } }) ); context.subscriptions.push( vscode.languages.registerReferenceProvider(ocamlLang, { async provideReferences(document, position, context, token) { await session.syncBuffer(document.fileName, document.getText(), token); if (token.isCancellationRequested) return null; let [status, result] = await session.request(['occurrences', 'ident', 'at', fromVsPos(position)]); if (token.isCancellationRequested) return null; if (status !== 'return' || result.length <= 0) return; return result.map((item) => { return new vscode.Location(document.uri, toVsRange(item.start, item.end)); }); } }) ); context.subscriptions.push( vscode.commands.registerCommand('ocaml.switch_mli_ml', async () => { let editor = vscode.window.activeTextEditor; let doc = editor != null ? editor.document : null; let path = doc != null ? doc.fileName : null; let ext = Path.extname(path || ''); let newExt = { '.mli': '.ml', '.ml': '.mli' }[ext]; if (!newExt) { vscode.window.showInformationMessage('Target file must be an OCaml signature or implementation file'); return; } let newPath = path.substring(0, path.length - ext.length) + newExt; if (!(await fsExists(newPath))) { let name = { '.mli': 'Signature', '.ml': 'Implementation' }[newExt]; let result = await vscode.window.showInformationMessage(`${name} file doesn't exist.`, 'Create It'); if (result === 'Create It') { await fsWriteFile(newPath, ''); } else { return; } } await vscode.commands.executeCommand( 'vscode.open', vscode.Uri.file(newPath) ); }) ); let replTerm: vscode.Terminal; context.subscriptions.push( vscode.window.onDidCloseTerminal((term) => { if (term === replTerm) { replTerm = null; } }) ); context.subscriptions.push( vscode.commands.registerCommand('ocaml.repl', async () => { if (replTerm) { replTerm.dispose(); replTerm = null; } await checkREPL(); replTerm.show(); }) ); context.subscriptions.push( vscode.commands.registerCommand('ocaml.repl_send', async () => { await checkREPL(); replTerm.show(!configuration.get<boolean>('replFocus', false)); let editor = vscode.window.activeTextEditor; if (!editor) return; let selection = editor.document.getText(editor.selection); replTerm.sendText(selection, configuration.get<boolean>('replNewline', true)); }) ); context.subscriptions.push( vscode.commands.registerCommand('ocaml.repl_send_all', async () => { await checkREPL(); replTerm.show(!configuration.get<boolean>('replFocus', false)); let editor = vscode.window.activeTextEditor; if (!editor) return; let selection = editor.document.getText(); replTerm.sendText(selection, configuration.get<boolean>('replNewline', true)); }) ); function suffix() { if (/^win/.test(process.platform)) { return 'windows'; } return 'unix'; } async function checkREPL() { if (!replTerm) { let path = configuration.get<string>('replPath' + '.' + suffix(), 'ocaml'); replTerm = vscode.window.createTerminal('OCaml REPL', path); } } context.subscriptions.push( vscode.commands.registerCommand('ocaml.repl_send_stmt', async () => { await checkREPL(); replTerm.show(!configuration.get<boolean>('replFocus', false)); let editor = vscode.window.activeTextEditor; if (!editor) return; let selection = editor.document.getText(editor.selection); if (!/;;\s*$/.test(selection)) { selection += ';;'; } replTerm.sendText(selection, configuration.get<boolean>('replNewline', true)); }) ); context.subscriptions.push( vscode.commands.registerCommand('ocaml.restart_merlin', async () => { session.restart(); }) ); context.subscriptions.push( vscode.commands.registerCommand('ocaml.opam_switch', async () => { let opamPath = configuration.get<string>('opamPath'); let result: string = await new Promise<string>((resolve, reject) => { child_process.exec(`${opamPath} switch list --all`, (err, stdout) => { if (err) { reject(err); } else { resolve(stdout); } }); }); let lines = result.split(/\r?\n|\r/g); lines = lines.filter((line) => !!line); let items = lines.map((line) => { let match = /^(\S+)\s+(\S+)\s+(\S+)\s+(.*)$/.exec(line); return { A: match[1], B: match[2], C: match[3], D: match[4], }; }).filter((item) => { return item.A !== '--'; }).map((item) => { let desc = item.B === 'C' ? 'Current' : ''; return { label: item.A, description: desc, detail: item.D, }; }); let item = await vscode.window.showQuickPick(items, { placeHolder: 'Select Opam Switch' }); child_process.exec(`${opamPath} switch ${item.label}`, (err, stdout) => { if (err) { vscode.window.showErrorMessage(err.toString()); } else if (stdout) { vscode.window.showInformationMessage(stdout.replace(/\r?\n|\r/g, ' ')); } }); }) ); let provideLinter = async (document: vscode.TextDocument, token) => { await session.syncBuffer(document.fileName, document.getText(), token); if (token.isCancellationRequested) return null; let [status, result] = await session.request(['errors']); if (token.isCancellationRequested) return null; if (status !== 'return') return; let diagnostics = []; result.map(({type, start, end, message}) => { let fromType = (type) => { switch (type) { case 'type': case "parser": case "env": case "unknown": return vscode.DiagnosticSeverity.Error; case "warning": return vscode.DiagnosticSeverity.Warning; } }; if (type === 'type' && message.startsWith('Error: Signature mismatch:') && message.includes(': Actual declaration')) { let regex = /^\s*File ("[^"]+"), line (\d+), characters (\d+)-(\d+): Actual declaration$/mg; for (let match; (match = regex.exec(message)) !== null;) { let file = JSON.parse(match[1]); let line = JSON.parse(match[2]); let col1 = JSON.parse(match[3]); let col2 = JSON.parse(match[4]); if (Path.basename(file) === Path.basename(document.fileName)) { let diag = new vscode.Diagnostic( toVsRange({ line, col: col1 }, { line, col: col2 }), message, fromType(type.toLowerCase()) ); diag.source = 'merlin'; diagnostics.push(diag); } else { // Log here? } } return; } let diag = new vscode.Diagnostic( toVsRange(start || 0, end || 0), message, fromType(type.toLowerCase()) ); diag.source = 'merlin'; diagnostics.push(diag); }); return diagnostics; }; let LINTER_DEBOUNCE_TIMER = new WeakMap(); let LINTER_TOKEN_SOURCE = new WeakMap(); let LINTER_CLEAR_LISTENER = new WeakMap(); let diagnosticCollection = vscode.languages.createDiagnosticCollection('merlin'); let lintDocument = (document: vscode.TextDocument) => { if (document.languageId !== 'ocaml') return; clearTimeout(LINTER_DEBOUNCE_TIMER.get(document)); LINTER_DEBOUNCE_TIMER.set(document, setTimeout(async () => { if (LINTER_TOKEN_SOURCE.has(document)) { LINTER_TOKEN_SOURCE.get(document).cancel(); } LINTER_TOKEN_SOURCE.set(document, new vscode.CancellationTokenSource()); let diagnostics = await provideLinter(document, LINTER_TOKEN_SOURCE.get(document).token); diagnosticCollection.set(document.uri, diagnostics); }, configuration.get<number>('lintDelay'))); }; vscode.workspace.onDidSaveTextDocument(async (document) => { if (!configuration.get<boolean>('lintOnSave')) return; let diagnostics = await provideLinter(document, new vscode.CancellationTokenSource().token); diagnosticCollection.set(document.uri, diagnostics); }); vscode.workspace.onDidChangeTextDocument(({document}) => { if (!configuration.get<boolean>('lintOnChange')) return; if (document.languageId === 'ocaml') { lintDocument(document); return; } let relintOpenedDocuments = () => { diagnosticCollection.clear(); for (let document of vscode.workspace.textDocuments) { if (document.languageId === 'ocaml') { lintDocument(document); } } }; let path = Path.basename(document.fileName); if (path === '.merlin') { relintOpenedDocuments(); } }); vscode.workspace.onDidCloseTextDocument((document) => { if (document.languageId === 'ocaml') { diagnosticCollection.delete(document.uri); } }); } export function deactivate() { }
the_stack
interface HSLType { h: number; s: number; l: number; } interface RGBType { r: number; g: number; b: number; } interface ColorValueType { type: '%' | 'i' | 'f'; val: number; } /** * Converts an HSL color value to RGB. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes h, s, and l are contained in the set [0, 1] and * returns r, g, and b in the set [0, 255]. * * @param h The hue * @param s The saturation * @param l The lightness * @returns The RGB representation */ const HSL2RGB = (h: number, s: number, l: number): RGBType => { let r: number; let g: number; let b: number; if (h < 0) h = 0; if (h > 1) h = 1; if (s < 0) s = 0; if (s > 1) s = 1; if (l < 0) l = 0; if (l > 1) l = 1; if (s == 0) { r = g = b = l; // achromatic } else { const hue2rgb = (p: number, q: number, t: number): number => { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; }; const q = (l < 0.5) ? (l * (1 + s)) : (l + s - (l * s)); const p = (2 * l) - q; r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1 / 3); } return { r: r * 255, g: g * 255, b: b * 255 }; }; /** * Converts an RGB color value to HSL. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSL_color_space. * Assumes r, g, and b are contained in the set [0, 255] and * returns h, s, and l in the set [0, 1]. * * @param r The red color value * @param g The green color value * @param b The blue color value * @returns The HSL representation */ const RGB2HSL = (r: number, g: number, b: number): HSLType => { r /= 255; g /= 255; b /= 255; const max = Math.max(r, g, b); const min = Math.min(r, g, b); let h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { const d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h, s, l }; } /** * Converts a HEX color value to RGB by extracting R, G and B values from string using regex. * Returns r, g, and b values in range [0, 255]. Does not support RGBA colors just yet. * * @param hex The color value * @returns The RGB representation or {@code null} if the string value is invalid */ const HEX2RGB = (hex: string): RGBType => { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, (_match, r, g, b) => { return r + r + g + g + b + b; }); const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if (!result) { return null; } return { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) }; }; /** * Converts RGB values into HEX color string. Assumes all values are in range [0, 255]. * * @param r Red color value * @param g Green color value * @param b Blue color value * @returns HEX color string */ const RGB2HEX = (r: number, g: number, b: number): string => "#" + Math.floor((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); /** * Tries to match color' symbolic name into a triple of RGB color components. * * @param name Color name * @returns Color in RGB format or black color (default value) */ const NAME2RGB = (name: string): RGBType => { const COLORS = new Map([ ['aliceblue', [240, 248, 255]], ['antiquewhite', [250, 235, 215]], ['aqua', [0, 255, 255]], ['aquamarine', [127, 255, 212]], ['azure', [240, 255, 255]], ['beige', [245, 245, 220]], ['bisque', [255, 228, 196]], ['black', [0, 0, 0]], ['blanchedalmond', [255, 235, 205]], ['blue', [0, 0, 255]], ['blueviolet', [138, 43, 226]], ['brown', [165, 42, 42]], ['burlywood', [222, 184, 135]], ['cadetblue', [95, 158, 160]], ['chartreuse', [127, 255, 0]], ['chocolate', [210, 105, 30]], ['coral', [255, 127, 80]], ['cornflowerblue', [100, 149, 237]], ['cornsilk', [255, 248, 220]], ['crimson', [220, 20, 60]], ['cyan', [0, 255, 255]], ['darkblue', [0, 0, 139]], ['darkcyan', [0, 139, 139]], ['darkgoldenrod', [184, 132, 11]], ['darkgray', [169, 169, 169]], ['darkgreen', [0, 100, 0]], ['darkgrey', [169, 169, 169]], ['darkkhaki', [189, 183, 107]], ['darkmagenta', [139, 0, 139]], ['darkolivegreen', [85, 107, 47]], ['darkorange', [255, 140, 0]], ['darkorchid', [153, 50, 204]], ['darkred', [139, 0, 0]], ['darksalmon', [233, 150, 122]], ['darkseagreen', [143, 188, 143]], ['darkslateblue', [72, 61, 139]], ['darkslategray', [47, 79, 79]], ['darkslategrey', [47, 79, 79]], ['darkturquoise', [0, 206, 209]], ['darkviolet', [148, 0, 211]], ['deeppink', [255, 20, 147]], ['deepskyblue', [0, 191, 255]], ['dimgray', [105, 105, 105]], ['dimgrey', [105, 105, 105]], ['dodgerblue', [30, 144, 255]], ['firebrick', [178, 34, 34]], ['floralwhite', [255, 255, 240]], ['forestgreen', [34, 139, 34]], ['fuchsia', [255, 0, 255]], ['gainsboro', [220, 220, 220]], ['ghostwhite', [248, 248, 255]], ['gold', [255, 215, 0]], ['goldenrod', [218, 165, 32]], ['gray', [128, 128, 128]], ['green', [0, 128, 0]], ['greenyellow', [173, 255, 47]], ['grey', [128, 128, 128]], ['honeydew', [240, 255, 240]], ['hotpink', [255, 105, 180]], ['indianred', [205, 92, 92]], ['indigo', [75, 0, 130]], ['ivory', [255, 255, 240]], ['khaki', [240, 230, 140]], ['lavender', [230, 230, 250]], ['lavenderblush', [255, 240, 245]], ['lawngreen', [124, 252, 0]], ['lemonchiffon', [255, 250, 205]], ['lightblue', [173, 216, 230]], ['lightcoral', [240, 128, 128]], ['lightcyan', [224, 255, 255]], ['lightgoldenrodyellow', [250, 250, 210]], ['lightgray', [211, 211, 211]], ['lightgreen', [144, 238, 144]], ['lightgrey', [211, 211, 211]], ['lightpink', [255, 182, 193]], ['lightsalmon', [255, 160, 122]], ['lightseagreen', [32, 178, 170]], ['lightskyblue', [135, 206, 250]], ['lightslategray', [119, 136, 153]], ['lightslategrey', [119, 136, 153]], ['lightsteelblue', [176, 196, 222]], ['lightyellow', [255, 255, 224]], ['lime', [0, 255, 0]], ['limegreen', [50, 205, 50]], ['linen', [250, 240, 230]], ['magenta', [255, 0, 255]], ['maroon', [128, 0, 0]], ['mediumaquamarine', [102, 205, 170]], ['mediumblue', [0, 0, 205]], ['mediumorchid', [186, 85, 211]], ['mediumpurple', [147, 112, 219]], ['mediumseagreen', [60, 179, 113]], ['mediumslateblue', [123, 104, 238]], ['mediumspringgreen', [0, 250, 154]], ['mediumturquoise', [72, 209, 204]], ['mediumvioletred', [199, 21, 133]], ['midnightblue', [25, 25, 112]], ['mintcream', [245, 255, 250]], ['mistyrose', [255, 228, 225]], ['moccasin', [255, 228, 181]], ['navajowhite', [255, 222, 173]], ['navy', [0, 0, 128]], ['oldlace', [253, 245, 230]], ['olive', [128, 128, 0]], ['olivedrab', [107, 142, 35]], ['orange', [255, 165, 0]], ['orangered', [255, 69, 0]], ['orchid', [218, 112, 214]], ['palegoldenrod', [238, 232, 170]], ['palegreen', [152, 251, 152]], ['paleturquoise', [175, 238, 238]], ['palevioletred', [219, 112, 147]], ['papayawhip', [255, 239, 213]], ['peachpuff', [255, 218, 185]], ['peru', [205, 133, 63]], ['pink', [255, 192, 203]], ['plum', [221, 160, 203]], ['powderblue', [176, 224, 230]], ['purple', [128, 0, 128]], ['red', [255, 0, 0]], ['rosybrown', [188, 143, 143]], ['royalblue', [65, 105, 225]], ['saddlebrown', [139, 69, 19]], ['salmon', [250, 128, 114]], ['sandybrown', [244, 164, 96]], ['seagreen', [46, 139, 87]], ['seashell', [255, 245, 238]], ['sienna', [160, 82, 45]], ['silver', [192, 192, 192]], ['skyblue', [135, 206, 235]], ['slateblue', [106, 90, 205]], ['slategray', [119, 128, 144]], ['slategrey', [119, 128, 144]], ['snow', [255, 255, 250]], ['springgreen', [0, 255, 127]], ['steelblue', [70, 130, 180]], ['tan', [210, 180, 140]], ['teal', [0, 128, 128]], ['thistle', [216, 191, 216]], ['tomato', [255, 99, 71]], ['turquoise', [64, 224, 208]], ['violet', [238, 130, 238]], ['wheat', [245, 222, 179]], ['white', [255, 255, 255]], ['whitesmoke', [245, 245, 245]], ['yellow', [255, 255, 0]], ['yellowgreen', [154, 205, 5]], ]); const color: Array<number> = COLORS.get(name) || [0, 0, 0]; return { r: color[0], g: color[1], b: color[2] }; }; const parseColorRGB = (color: string): RGBType => { const HEX_NUMBER_REGEX = /^#/; if (HEX_NUMBER_REGEX.test(color)) { return HEX2RGB(color); } else { return NAME2RGB(color); } }; const parseAmount = (amount: string): ColorValueType => { const FLOAT_REGEX = /^-?\d+\.\d+$/; const INT_REGEX = /^-?\d+$/; const INT_PERCENT_REGEX = /^-?\d+%$/; if (INT_PERCENT_REGEX.test(amount)) { return { type: '%', val: parseFloat(amount.replace(/(%)$/, '')) }; } else if (FLOAT_REGEX.test(amount)) { return { type: 'f', val: parseFloat(amount) * 100.0 }; } else if (INT_REGEX.test(amount)) { return { type: 'i', val: parseInt(amount) }; } else { throw 'Unknown amount value ' + JSON.stringify(amount) + '. Expected percent string, float or integer number.'; } }; /** * Darkens the color by a given percentage amount. * The amount could be represented as a fraction of one (a number in range [0, 1]) or * an integer percent number (in range [0, 100]). * * It should be a string, either a float number or an integer number or an integer number and a percent sign. * * If the amount is negative - the function will lighten the color. * * @param color Color to darken, color name or color in HEX value * @param amount Darkening percentage. A string with either a float number, integer number or integer number and a percent sign ('%') * @returns Color in HEX value */ const darken = (color: string, amount: string): string => { let r_g_b = parseColorRGB(color); let h_s_l = RGB2HSL(r_g_b.r, r_g_b.g, r_g_b.b); let { type, val } = parseAmount(amount); val = val / -100; if ('%' === type) { if (val > 0) { val = (100 - h_s_l['l']) * val / 100; } else { val = h_s_l['l'] * (val / 100); } } h_s_l['l'] += val; r_g_b = HSL2RGB(h_s_l.h, h_s_l.s, h_s_l.l); return RGB2HEX(r_g_b.r, r_g_b.g, r_g_b.b); }; /** * Lightens the given color by a given percentage amount. Alias for {@code darken(color, '-' + amount)}. * * @param color Color to lighten, color name or color value in HEX format * @param amount The lightening percentage. A string with either a float number, integer number or integer number and a percent sign ('%') * @returns Lightened color in HEX format */ const lighten = (color: string, amount: string): string => darken(color, '-' + amount); export { darken, lighten, HSL2RGB, RGB2HEX, NAME2RGB };
the_stack
import { Component, OnDestroy } from '@angular/core'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { CoreSites } from '@services/sites'; import { AddonMessagesProvider, AddonMessagesConversationMember, AddonMessagesMessageAreaContact, AddonMessages, } from '../../services/messages'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreApp } from '@services/app'; import { CoreNavigator } from '@services/navigator'; import { Params } from '@angular/router'; import { CoreScreen } from '@services/screen'; /** * Page for searching users. */ @Component({ selector: 'page-addon-messages-search', templateUrl: 'search.html', }) export class AddonMessagesSearchPage implements OnDestroy { disableSearch = false; displaySearching = false; displayResults = false; query = ''; contacts: AddonMessagesSearchResults = { type: 'contacts', titleString: 'addon.messages.contacts', results: [], canLoadMore: false, loadingMore: false, }; nonContacts: AddonMessagesSearchResults = { type: 'noncontacts', titleString: 'addon.messages.noncontacts', results: [], canLoadMore: false, loadingMore: false, }; messages: AddonMessagesSearchMessageResults = { type: 'messages', titleString: 'addon.messages.messages', results: [], canLoadMore: false, loadingMore: false, loadMoreError: false, }; selectedResult?: AddonMessagesConversationMember | AddonMessagesMessageAreaContact; protected memberInfoObserver: CoreEventObserver; constructor() { // Update block status of a user. this.memberInfoObserver = CoreEvents.on( AddonMessagesProvider.MEMBER_INFO_CHANGED_EVENT, (data) => { if (!data.userBlocked && !data.userUnblocked) { // The block status has not changed, ignore. return; } const contact = this.contacts.results.find((user) => user.id == data.userId); if (contact) { contact.isblocked = !!data.userBlocked; } else { const nonContact = this.nonContacts.results.find((user) => user.id == data.userId); if (nonContact) { nonContact.isblocked = !!data.userBlocked; } } this.messages.results.forEach((message: AddonMessagesMessageAreaContact): void => { if (message.userid == data.userId) { message.isblocked = !!data.userBlocked; } }); }, CoreSites.getCurrentSiteId(), ); } /** * Clear search. */ clearSearch(): void { this.query = ''; this.displayResults = false; // Empty details. const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/messages/search/discussion'); if (splitViewLoaded) { CoreNavigator.navigate('../'); } } /** * Start a new search or load more results. * * @param query Text to search for. * @param loadMore Load more contacts, noncontacts or messages. If undefined, start a new search. * @param infiniteComplete Infinite scroll complete function. Only used from core-infinite-loading. * @return Resolved when done. */ async search(query: string, loadMore?: 'contacts' | 'noncontacts' | 'messages', infiniteComplete?: () => void): Promise<void> { CoreApp.closeKeyboard(); this.query = query; this.disableSearch = true; this.displaySearching = !loadMore; const promises: Promise<void>[] = []; let newContacts: AddonMessagesConversationMember[] = []; let newNonContacts: AddonMessagesConversationMember[] = []; let newMessages: AddonMessagesMessageAreaContact[] = []; let canLoadMoreContacts = false; let canLoadMoreNonContacts = false; let canLoadMoreMessages = false; if (!loadMore || loadMore == 'contacts' || loadMore == 'noncontacts') { const limitNum = loadMore ? AddonMessagesProvider.LIMIT_SEARCH : AddonMessagesProvider.LIMIT_INITIAL_USER_SEARCH; let limitFrom = 0; if (loadMore == 'contacts') { limitFrom = this.contacts.results.length; this.contacts.loadingMore = true; } else if (loadMore == 'noncontacts') { limitFrom = this.nonContacts.results.length; this.nonContacts.loadingMore = true; } promises.push( AddonMessages.searchUsers(query, limitFrom, limitNum).then((result) => { if (!loadMore || loadMore == 'contacts') { newContacts = result.contacts; canLoadMoreContacts = result.canLoadMoreContacts; } if (!loadMore || loadMore == 'noncontacts') { newNonContacts = result.nonContacts; canLoadMoreNonContacts = result.canLoadMoreNonContacts; } return; }), ); } if (!loadMore || loadMore == 'messages') { let limitFrom = 0; if (loadMore == 'messages') { limitFrom = this.messages.results.length; this.messages.loadingMore = true; } promises.push( AddonMessages.searchMessages(query, undefined, limitFrom).then((result) => { newMessages = result.messages; canLoadMoreMessages = result.canLoadMore; return; }), ); } try { await Promise.all(promises); if (!loadMore) { this.contacts.results = []; this.nonContacts.results = []; this.messages.results = []; } this.displayResults = true; if (!loadMore || loadMore == 'contacts') { this.contacts.results.push(...newContacts); this.contacts.canLoadMore = canLoadMoreContacts; this.setHighlight(newContacts, true); } if (!loadMore || loadMore == 'noncontacts') { this.nonContacts.results.push(...newNonContacts); this.nonContacts.canLoadMore = canLoadMoreNonContacts; this.setHighlight(newNonContacts, true); } if (!loadMore || loadMore == 'messages') { this.messages.results.push(...newMessages); this.messages.canLoadMore = canLoadMoreMessages; this.messages.loadMoreError = false; this.setHighlight(newMessages, false); } if (!loadMore) { if (this.contacts.results.length > 0) { this.openConversation(this.contacts.results[0], true); } else if (this.nonContacts.results.length > 0) { this.openConversation(this.nonContacts.results[0], true); } else if (this.messages.results.length > 0) { this.openConversation(this.messages.results[0], true); } } } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'addon.messages.errorwhileretrievingusers', true); if (loadMore == 'messages') { this.messages.loadMoreError = true; } } finally { this.disableSearch = false; this.displaySearching = false; if (loadMore == 'contacts') { this.contacts.loadingMore = false; } else if (loadMore == 'noncontacts') { this.nonContacts.loadingMore = false; } else if (loadMore == 'messages') { this.messages.loadingMore = false; } infiniteComplete && infiniteComplete(); } } /** * Open a conversation in the split view. * * @param result User or message. * @param onInit Whether the tser was selected on initial load. */ openConversation(result: AddonMessagesConversationMember | AddonMessagesMessageAreaContact, onInit: boolean = false): void { if (!onInit || CoreScreen.isTablet) { this.selectedResult = result; const params: Params = {}; if ('conversationid' in result) { params.conversationId = result.conversationid; } else { params.userId = result.id; } const splitViewLoaded = CoreNavigator.isCurrentPathInTablet('**/messages/search/discussion'); const path = (splitViewLoaded ? '../' : '') + 'discussion'; CoreNavigator.navigate(path, { params }); } } /** * Set the highlight values for each entry. * * @param results Results to highlight. * @param isUser Whether the results are from a user search or from a message search. */ setHighlight( results: (AddonMessagesConversationMemberWithHighlight | AddonMessagesMessageAreaContactWithHighlight)[], isUser = false, ): void { results.forEach((result) => { result.highlightName = isUser ? this.query : undefined; result.highlightMessage = !isUser ? this.query : undefined; }); } /** * Component destroyed. */ ngOnDestroy(): void { this.memberInfoObserver?.off(); } } type AddonMessagesSearchResults = { type: string; titleString: string; results: AddonMessagesConversationMemberWithHighlight[]; canLoadMore: boolean; loadingMore: boolean; }; type AddonMessagesSearchMessageResults = { type: string; titleString: string; results: AddonMessagesMessageAreaContactWithHighlight[]; canLoadMore: boolean; loadingMore: boolean; loadMoreError: boolean; }; type AddonMessagesSearchResultHighlight = { highlightName?: string; highlightMessage?: string; }; type AddonMessagesConversationMemberWithHighlight = AddonMessagesConversationMember & AddonMessagesSearchResultHighlight; type AddonMessagesMessageAreaContactWithHighlight = AddonMessagesMessageAreaContact & AddonMessagesSearchResultHighlight;
the_stack
/// <reference types="node" /> import { Vector } from "../vector"; import { DataType } from "../type"; import { MessageHeader } from "../enum"; import { Footer } from "./metadata/file"; import { Schema, Field } from "../schema"; import { Message } from "./metadata/message"; import * as metadata from "./metadata/message"; import { ArrayBufferViewInput } from "../util/buffer"; import { ByteStream, AsyncByteStream } from "../io/stream"; import { RandomAccessFile, AsyncRandomAccessFile } from "../io/file"; import { RecordBatch } from "../recordbatch"; import { FileHandle, ArrowJSONLike, ReadableInterop } from "../io/interfaces"; import { MessageReader, AsyncMessageReader } from "./message"; /** @ignore */ export declare type FromArg0 = ArrowJSONLike; /** @ignore */ export declare type FromArg1 = PromiseLike<ArrowJSONLike>; /** @ignore */ export declare type FromArg2 = | Iterable<ArrayBufferViewInput> | ArrayBufferViewInput; /** @ignore */ export declare type FromArg3 = PromiseLike< Iterable<ArrayBufferViewInput> | ArrayBufferViewInput >; /** @ignore */ export declare type FromArg4 = | Response | NodeJS.ReadableStream | ReadableStream<ArrayBufferViewInput> | AsyncIterable<ArrayBufferViewInput>; /** @ignore */ export declare type FromArg5 = | FileHandle | PromiseLike<FileHandle> | PromiseLike<FromArg4>; /** @ignore */ export declare type FromArgs = | FromArg0 | FromArg1 | FromArg2 | FromArg3 | FromArg4 | FromArg5; /** @ignore */ declare type OpenOptions = { autoDestroy?: boolean; }; /** @ignore */ declare type RecordBatchReaders< T extends { [key: string]: DataType; } = any > = RecordBatchFileReader<T> | RecordBatchStreamReader<T>; /** @ignore */ declare type AsyncRecordBatchReaders< T extends { [key: string]: DataType; } = any > = AsyncRecordBatchFileReader<T> | AsyncRecordBatchStreamReader<T>; /** @ignore */ declare type RecordBatchFileReaders< T extends { [key: string]: DataType; } = any > = RecordBatchFileReader<T> | AsyncRecordBatchFileReader<T>; /** @ignore */ declare type RecordBatchStreamReaders< T extends { [key: string]: DataType; } = any > = RecordBatchStreamReader<T> | AsyncRecordBatchStreamReader<T>; export declare class RecordBatchReader< T extends { [key: string]: DataType; } = any > extends ReadableInterop<RecordBatch<T>> { protected _impl: RecordBatchReaderImpls<T>; protected constructor(impl: RecordBatchReaderImpls<T>); readonly closed: boolean; readonly schema: Schema<T>; readonly autoDestroy: boolean; readonly dictionaries: Map<number, Vector<any>>; readonly numDictionaries: number; readonly numRecordBatches: number; readonly footer: Footer | null; isSync(): this is RecordBatchReaders<T>; isAsync(): this is AsyncRecordBatchReaders<T>; isFile(): this is RecordBatchFileReaders<T>; isStream(): this is RecordBatchStreamReaders<T>; next(): | IteratorResult<RecordBatch<T>> | Promise<IteratorResult<RecordBatch<T>>>; throw(value?: any): IteratorResult<any> | Promise<IteratorResult<any>>; return(value?: any): IteratorResult<any> | Promise<IteratorResult<any>>; cancel(): void | Promise<void>; reset(schema?: Schema<T> | null): this; open(options?: OpenOptions): this | Promise<this>; readRecordBatch( index: number ): RecordBatch<T> | null | Promise<RecordBatch<T> | null>; [Symbol.iterator](): IterableIterator<RecordBatch<T>>; [Symbol.asyncIterator](): AsyncIterableIterator<RecordBatch<T>>; toDOMStream(): ReadableStream<RecordBatch<T>>; toNodeStream(): import("stream").Readable; /** @nocollapse */ static throughNode( options?: import("stream").DuplexOptions & { autoDestroy: boolean; } ): import("stream").Duplex; /** @nocollapse */ static throughDOM< T extends { [key: string]: DataType; } >( writableStrategy?: ByteLengthQueuingStrategy, readableStrategy?: { autoDestroy: boolean; } ): { writable: WritableStream<Uint8Array>; readable: ReadableStream<RecordBatch<T>>; }; static from<T extends RecordBatchReader>(source: T): T; static from< T extends { [key: string]: DataType; } = any >(source: FromArg0): RecordBatchStreamReader<T>; static from< T extends { [key: string]: DataType; } = any >(source: FromArg1): Promise<RecordBatchStreamReader<T>>; static from< T extends { [key: string]: DataType; } = any >(source: FromArg2): RecordBatchFileReader<T> | RecordBatchStreamReader<T>; static from< T extends { [key: string]: DataType; } = any >( source: FromArg3 ): Promise<RecordBatchFileReader<T> | RecordBatchStreamReader<T>>; static from< T extends { [key: string]: DataType; } = any >( source: FromArg4 ): Promise<RecordBatchFileReader<T> | AsyncRecordBatchReaders<T>>; static from< T extends { [key: string]: DataType; } = any >( source: FromArg5 ): Promise<AsyncRecordBatchFileReader<T> | AsyncRecordBatchStreamReader<T>>; static readAll<T extends RecordBatchReader>( source: T ): T extends RecordBatchReaders ? IterableIterator<T> : AsyncIterableIterator<T>; static readAll< T extends { [key: string]: DataType; } = any >(source: FromArg0): IterableIterator<RecordBatchStreamReader<T>>; static readAll< T extends { [key: string]: DataType; } = any >(source: FromArg1): AsyncIterableIterator<RecordBatchStreamReader<T>>; static readAll< T extends { [key: string]: DataType; } = any >( source: FromArg2 ): IterableIterator<RecordBatchFileReader<T> | RecordBatchStreamReader<T>>; static readAll< T extends { [key: string]: DataType; } = any >( source: FromArg3 ): AsyncIterableIterator< RecordBatchFileReader<T> | RecordBatchStreamReader<T> >; static readAll< T extends { [key: string]: DataType; } = any >( source: FromArg4 ): AsyncIterableIterator< RecordBatchFileReader<T> | AsyncRecordBatchReaders<T> >; static readAll< T extends { [key: string]: DataType; } = any >( source: FromArg5 ): AsyncIterableIterator< AsyncRecordBatchFileReader<T> | AsyncRecordBatchStreamReader<T> >; } /** @ignore */ export declare class RecordBatchStreamReader< T extends { [key: string]: DataType; } = any > extends RecordBatchReader<T> { protected _impl: RecordBatchStreamReaderImpl<T>; constructor(_impl: RecordBatchStreamReaderImpl<T>); [Symbol.iterator](): IterableIterator<RecordBatch<T>>; [Symbol.asyncIterator](): AsyncIterableIterator<RecordBatch<T>>; } /** @ignore */ export declare class AsyncRecordBatchStreamReader< T extends { [key: string]: DataType; } = any > extends RecordBatchReader<T> { protected _impl: AsyncRecordBatchStreamReaderImpl<T>; constructor(_impl: AsyncRecordBatchStreamReaderImpl<T>); [Symbol.iterator](): IterableIterator<RecordBatch<T>>; [Symbol.asyncIterator](): AsyncIterableIterator<RecordBatch<T>>; } /** @ignore */ export declare class RecordBatchFileReader< T extends { [key: string]: DataType; } = any > extends RecordBatchStreamReader<T> { protected _impl: RecordBatchFileReaderImpl<T>; constructor(_impl: RecordBatchFileReaderImpl<T>); } /** @ignore */ export declare class AsyncRecordBatchFileReader< T extends { [key: string]: DataType; } = any > extends AsyncRecordBatchStreamReader<T> { protected _impl: AsyncRecordBatchFileReaderImpl<T>; constructor(_impl: AsyncRecordBatchFileReaderImpl<T>); } /** @ignore */ export interface RecordBatchStreamReader< T extends { [key: string]: DataType; } = any > extends RecordBatchReader<T> { open(options?: OpenOptions | undefined): this; cancel(): void; throw(value?: any): IteratorResult<any>; return(value?: any): IteratorResult<any>; next(value?: any): IteratorResult<RecordBatch<T>>; } /** @ignore */ export interface AsyncRecordBatchStreamReader< T extends { [key: string]: DataType; } = any > extends RecordBatchReader<T> { open(options?: OpenOptions | undefined): Promise<this>; cancel(): Promise<void>; throw(value?: any): Promise<IteratorResult<any>>; return(value?: any): Promise<IteratorResult<any>>; next(value?: any): Promise<IteratorResult<RecordBatch<T>>>; } /** @ignore */ export interface RecordBatchFileReader< T extends { [key: string]: DataType; } = any > extends RecordBatchStreamReader<T> { footer: Footer; readRecordBatch(index: number): RecordBatch<T> | null; } /** @ignore */ export interface AsyncRecordBatchFileReader< T extends { [key: string]: DataType; } = any > extends AsyncRecordBatchStreamReader<T> { footer: Footer; readRecordBatch(index: number): Promise<RecordBatch<T> | null>; } /** @ignore */ declare type RecordBatchReaderImpls< T extends { [key: string]: DataType; } = any > = | RecordBatchJSONReaderImpl<T> | RecordBatchFileReaderImpl<T> | RecordBatchStreamReaderImpl<T> | AsyncRecordBatchFileReaderImpl<T> | AsyncRecordBatchStreamReaderImpl<T>; /** @ignore */ interface RecordBatchReaderImpl< T extends { [key: string]: DataType; } = any > { closed: boolean; schema: Schema<T>; autoDestroy: boolean; dictionaries: Map<number, Vector>; isFile(): this is RecordBatchFileReaders<T>; isStream(): this is RecordBatchStreamReaders<T>; isSync(): this is RecordBatchReaders<T>; isAsync(): this is AsyncRecordBatchReaders<T>; reset(schema?: Schema<T> | null): this; } /** @ignore */ interface RecordBatchStreamReaderImpl< T extends { [key: string]: DataType; } = any > extends RecordBatchReaderImpl<T> { open(options?: OpenOptions): this; cancel(): void; throw(value?: any): IteratorResult<any>; return(value?: any): IteratorResult<any>; next(value?: any): IteratorResult<RecordBatch<T>>; [Symbol.iterator](): IterableIterator<RecordBatch<T>>; } /** @ignore */ interface AsyncRecordBatchStreamReaderImpl< T extends { [key: string]: DataType; } = any > extends RecordBatchReaderImpl<T> { open(options?: OpenOptions): Promise<this>; cancel(): Promise<void>; throw(value?: any): Promise<IteratorResult<any>>; return(value?: any): Promise<IteratorResult<any>>; next(value?: any): Promise<IteratorResult<RecordBatch<T>>>; [Symbol.asyncIterator](): AsyncIterableIterator<RecordBatch<T>>; } /** @ignore */ interface RecordBatchFileReaderImpl< T extends { [key: string]: DataType; } = any > extends RecordBatchStreamReaderImpl<T> { readRecordBatch(index: number): RecordBatch<T> | null; } /** @ignore */ interface AsyncRecordBatchFileReaderImpl< T extends { [key: string]: DataType; } = any > extends AsyncRecordBatchStreamReaderImpl<T> { readRecordBatch(index: number): Promise<RecordBatch<T> | null>; } /** @ignore */ declare abstract class RecordBatchReaderImpl< T extends { [key: string]: DataType; } = any > implements RecordBatchReaderImpl<T> { schema: Schema; closed: boolean; autoDestroy: boolean; dictionaries: Map<number, Vector>; protected _dictionaryIndex: number; protected _recordBatchIndex: number; readonly numDictionaries: number; readonly numRecordBatches: number; constructor(dictionaries?: Map<number, Vector<any>>); protected _loadRecordBatch( header: metadata.RecordBatch, body: any ): RecordBatch<T>; protected _loadDictionaryBatch( header: metadata.DictionaryBatch, body: any ): Vector<any>; protected _loadVectors( header: metadata.RecordBatch, body: any, types: (Field | DataType)[] ): import("../data").Data<any>[]; } /** @ignore */ declare class RecordBatchStreamReaderImpl< T extends { [key: string]: DataType; } = any > extends RecordBatchReaderImpl<T> implements IterableIterator<RecordBatch<T>> { protected _reader: MessageReader; protected _handle: ByteStream | ArrowJSONLike; constructor( source: ByteStream | ArrowJSONLike, dictionaries?: Map<number, Vector> ); isSync(): this is RecordBatchReaders<T>; isStream(): this is RecordBatchStreamReaders<T>; protected _readNextMessageAndValidate<T extends MessageHeader>( type?: T | null ): Message<T> | null; } /** @ignore */ declare class AsyncRecordBatchStreamReaderImpl< T extends { [key: string]: DataType; } = any > extends RecordBatchReaderImpl<T> implements AsyncIterableIterator<RecordBatch<T>> { protected _handle: AsyncByteStream; protected _reader: AsyncMessageReader; constructor(source: AsyncByteStream, dictionaries?: Map<number, Vector>); isAsync(): this is AsyncRecordBatchReaders<T>; isStream(): this is RecordBatchStreamReaders<T>; protected _readNextMessageAndValidate<T extends MessageHeader>( type?: T | null ): Promise<Message<T> | null>; } /** @ignore */ declare class RecordBatchFileReaderImpl< T extends { [key: string]: DataType; } = any > extends RecordBatchStreamReaderImpl<T> { protected _footer?: Footer; protected _handle: RandomAccessFile; readonly footer: Footer; readonly numDictionaries: number; readonly numRecordBatches: number; constructor( source: RandomAccessFile | ArrayBufferViewInput, dictionaries?: Map<number, Vector> ); isSync(): this is RecordBatchReaders<T>; isFile(): this is RecordBatchFileReaders<T>; open(options?: OpenOptions): this; protected _readDictionaryBatch(index: number): void; protected _readFooter(): Footer; protected _readNextMessageAndValidate<T extends MessageHeader>( type?: T | null ): Message<T> | null; } /** @ignore */ declare class AsyncRecordBatchFileReaderImpl< T extends { [key: string]: DataType; } = any > extends AsyncRecordBatchStreamReaderImpl<T> implements AsyncRecordBatchFileReaderImpl<T> { protected _footer?: Footer; protected _handle: AsyncRandomAccessFile; readonly footer: Footer; readonly numDictionaries: number; readonly numRecordBatches: number; constructor( source: FileHandle, byteLength?: number, dictionaries?: Map<number, Vector> ); constructor( source: FileHandle | AsyncRandomAccessFile, dictionaries?: Map<number, Vector> ); isFile(): this is RecordBatchFileReaders<T>; isAsync(): this is AsyncRecordBatchReaders<T>; open(options?: OpenOptions): Promise<this>; protected _readDictionaryBatch(index: number): Promise<void>; protected _readFooter(): Promise<Footer>; protected _readNextMessageAndValidate<T extends MessageHeader>( type?: T | null ): Promise<Message<T> | null>; } /** @ignore */ declare class RecordBatchJSONReaderImpl< T extends { [key: string]: DataType; } = any > extends RecordBatchStreamReaderImpl<T> { constructor(source: ArrowJSONLike, dictionaries?: Map<number, Vector>); protected _loadVectors( header: metadata.RecordBatch, body: any, types: (Field | DataType)[] ): import("../data").Data<any>[]; } export {};
the_stack
import { AssetProxy } from '../Engine/AssetProxy' import { PluginLoadFailException } from '../Exceptions' import defaults from '../helper/defaults' import { ColorRGB, ColorRGBA, Expression, Point2D, Point3D, Size2D, Size3D } from '../Values' export type ParameterType = // | 'POINT_2D' // | 'POINT_3D' // | 'SIZE_2D' // | 'SIZE_3D' | 'COLOR_RGB' | 'COLOR_RGBA' | 'BOOL' | 'STRING' | 'NUMBER' | 'FLOAT' | 'ENUM' // | 'CLIP' // | 'PULSE' | 'ASSET' | 'CODE' // | 'ARRAY' // | 'STRUCTURE' export interface ParameterTypeDescriptor<T extends ParameterType> { type: T paramName: string label: string enabled: boolean animatable: boolean } // export interface Point2DTypeDescripter extends ParameterTypeDescriptor<'POINT_2D'> { // defaultValue?: Point2D // } // export interface Point3DTypeDescripter extends ParameterTypeDescriptor<'POINT_3D'> { // defaultValue?: Point3D // } // export interface Size2DTypeDescripter extends ParameterTypeDescriptor<'SIZE_2D'> { // defaultValue?: Size2D // } // export interface Size3DTypeDescripter extends ParameterTypeDescriptor<'SIZE_3D'> { // defaultValue?: Size3D // } export interface ColorRGBTypeDescripter extends ParameterTypeDescriptor<'COLOR_RGB'> { defaultValue: () => ColorRGB } export interface ColorRGBATypeDescripter extends ParameterTypeDescriptor<'COLOR_RGBA'> { defaultValue: () => ColorRGBA } export interface BoolTypeDescripter extends ParameterTypeDescriptor<'BOOL'> { defaultValue: () => boolean } export interface StringTypeDescripter extends ParameterTypeDescriptor<'STRING'> { defaultValue: () => string } export interface NumberTypeDescripter extends ParameterTypeDescriptor<'NUMBER'> { defaultValue: () => number } export interface FloatTypeDescripter extends ParameterTypeDescriptor<'FLOAT'> { defaultValue: () => number } // export interface PulseTypeDescripter extends ParameterTypeDescriptor<'PULSE'> { // defaultValue: () => true, // } export interface EnumTypeDescripter extends ParameterTypeDescriptor<'ENUM'> { selection: string[] defaultValue: () => string | null } // export interface ClipTypeDescripter extends ParameterTypeDescriptor<'CLIP'> {} export interface AssetTypeDescripter extends ParameterTypeDescriptor<'ASSET'> { extensions: string[] defaultValue: () => null } export interface CodeTypeDescripter extends ParameterTypeDescriptor<'CODE'> { langType: string defaultValue: () => Expression } // export interface ArrayOfTypeDescripter extends ParameterTypeDescriptor<'ARRAY'> { // subType: TypeDescriptor // } // export interface StructureTypeDescripter extends ParameterTypeDescriptor<'STRUCTURE'> { // // TODO: implement structure type // subType: TypeDescriptor // } export type AnyParameterTypeDescriptor = // | Point2DTypeDescripter // | Point3DTypeDescripter // | Size2DTypeDescripter // | Size3DTypeDescripter // | Size3DTypeDescripter | ColorRGBTypeDescripter | ColorRGBATypeDescripter | BoolTypeDescripter | StringTypeDescripter | NumberTypeDescripter | FloatTypeDescripter // | PulseTypeDescripter | EnumTypeDescripter // | ClipTypeDescripter | AssetTypeDescripter | CodeTypeDescripter // | ArrayOfTypeDescripter // | StructureTypeDescripter export type ParameterValueTypes = // | Point2D // | Point3D // | Size2D // | Size3D ColorRGB | ColorRGBA | string | number | boolean | AssetProxy | null export const descriptorToValueType = (desc: AnyParameterTypeDescriptor) => { switch (desc.type) { // case 'POINT_2D': return Point2D // case 'POINT_3D': return Point3D // case 'SIZE_2D': return Size2D // case 'SIZE_3D': return Size3D default: throw new Error(`Unsupported parameter type ${desc.type}`) } } export class TypeDescriptor { public properties: AnyParameterTypeDescriptor[] = [] // public point2d(paramName: string, conf: {label: string, defaultValue?: Point2D, enabled?: boolean, animatable?: boolean}) // { // const {defaultValue, label, enabled, animatable} = defaults(conf, { // defaultValue: new Point2D(0, 0), // enabled: true, // animatable: true // }) // this.properties.push({type: 'POINT_2D', paramName, defaultValue, label, enabled, animatable}) // return this // } // public point3d(paramName: string, conf: {label: string, defaultValue?: Point3D, enabled?: boolean, animatable?: boolean}) // { // const {defaultValue, label, enabled, animatable} = defaults(conf, { // defaultValue: new Point3D(0, 0, 0), // enabled: true, // animatable: true, // }) // this.properties.push({type: 'POINT_3D', paramName, defaultValue, label, enabled, animatable}) // return this // } // public size2d(paramName: string, conf: {label: string, defaultValue?: Size2D, enabled?: boolean, animatable?: boolean}) // { // const {defaultValue, label, enabled, animatable} = defaults(conf, { // defaultValue: new Size2D(0, 0), // enabled: true, // animatable: true, // }) // this.properties.push({type: 'SIZE_2D', paramName, defaultValue, label, enabled, animatable}) // return this // } // public size3d(paramName: string, conf: {label: string, defaultValue?: Size3D, enabled?: boolean, animatable?: boolean}) // { // const {defaultValue, label, enabled, animatable} = defaults(conf, { // defaultValue: new Size3D(0, 0, 0), // enabled: true, // animatable: true, // }) // this.properties.push({type: 'SIZE_3D', paramName, defaultValue, label, enabled, animatable}) // return this // } public colorRgb( paramName: string, conf: { label: string defaultValue?: () => ColorRGB enabled?: boolean animatable?: boolean }, ) { const { defaultValue, label, enabled, animatable } = defaults(conf, { defaultValue: () => new ColorRGB(0, 0, 0), enabled: true, animatable: true, }) this.properties.push({ type: 'COLOR_RGB', paramName, defaultValue, label, enabled, animatable, }) return this } public colorRgba( paramName: string, conf: { label: string defaultValue?: () => ColorRGBA enabled?: boolean animatable?: boolean }, ) { const { defaultValue, label, enabled, animatable } = defaults(conf, { defaultValue: () => new ColorRGBA(0, 0, 0, 1), enabled: true, animatable: true, }) this.properties.push({ type: 'COLOR_RGBA', paramName, defaultValue, label, enabled, animatable, }) return this } public bool( paramName: string, conf: { label: string defaultValue?: () => boolean enabled?: boolean animatable?: boolean }, ) { const { defaultValue, label, enabled, animatable } = defaults(conf, { defaultValue: () => false, enabled: true, animatable: true, }) this.properties.push({ type: 'BOOL', paramName, defaultValue, label, enabled, animatable, }) return this } public string( paramName: string, conf: { label: string defaultValue?: () => string enabled?: boolean animatable?: boolean }, ) { const { defaultValue, label, enabled, animatable } = defaults(conf, { defaultValue: () => '', enabled: true, animatable: true, }) this.properties.push({ type: 'STRING', paramName, defaultValue, label, enabled, animatable, }) return this } public number( paramName: string, conf: { label: string defaultValue?: () => number enabled?: boolean animatable?: boolean }, ) { const { defaultValue, label, enabled, animatable } = defaults(conf, { defaultValue: () => 0, enabled: true, animatable: true, }) this.properties.push({ type: 'NUMBER', paramName, defaultValue, label, enabled, animatable, }) return this } public float( paramName: string, conf: { label: string defaultValue?: () => number enabled?: boolean animatable?: boolean }, ) { const { defaultValue, label, enabled, animatable } = defaults(conf, { defaultValue: () => 0, enabled: true, animatable: true, }) this.properties.push({ type: 'FLOAT', paramName, defaultValue, label, enabled, animatable, }) return this } // public pulse(paramName: string, conf: {label: string, enabled?: boolean}) // { // const {label, enabled} = defaults(conf, { // defaultValue: false, // enabled: true, // }) // this.properties.push({type: 'PULSE', paramName, label, enabled, animatable: true}) // return this // } public enum( paramName: string, conf: { label: string defaultValue?: () => string enabled?: boolean selection: string[] }, ) { const { defaultValue, label, enabled, selection } = defaults(conf, { enabled: true, defaultValue: () => null, selection: [], }) // Allow to empty selection. const validSelection = Array.isArray(selection) && selection.every(e => typeof e === 'string') if (!validSelection) { throw new PluginLoadFailException('`selection` must be an array of string') } const realDefaultValue = defaultValue() if (realDefaultValue != null && !selection.includes(realDefaultValue)) { throw new PluginLoadFailException('Default value not included in selection') } this.properties.push({ type: 'ENUM', paramName, defaultValue, label, enabled, selection, animatable: false, }) return this } // public clip(paramName: string, conf: {label: string, enabled?: boolean}) // { // const {label, enabled} = defaults(conf, { // enabled: true, // }) // this.properties.push({type: 'CLIP', paramName, label, enabled, animatable: false}) // return this // } public asset(paramName: string, conf: { label: string; enabled?: boolean; extensions: Array<string> }) { const { label, enabled, extensions } = defaults(conf, { enabled: true, extensions: [], }) const validextensions = Array.isArray(extensions) && extensions.length > 0 && extensions.every(e => typeof e === 'string') if (!validextensions) { throw new PluginLoadFailException('`extensions` must be an array of string and can not to be empty') } this.properties.push({ type: 'ASSET', paramName, label, enabled, animatable: false, defaultValue: () => null, extensions, }) return this } public code( paramName: string, conf: { label: string enabled?: boolean langType: string defaultValue?: () => Expression }, ) { const { defaultValue, label, enabled, langType } = defaults(conf, { defaultValue: () => new Expression(langType, ''), enabled: true, }) this.properties.push({ type: 'CODE', paramName, label, defaultValue, langType, enabled, animatable: false, }) return this } // public arrayOf(paramName: string, conf: {label: string, enabled?: boolean}, type: TypeDescriptor) // { // const {label, enabled} = defaults(conf, { // enabled: true, // }) // this.properties.push({type: 'ARRAY', paramName, subType: type, label, enabled, animatable: false}) // return this // } // public structure(paramName: string, conf: {label: string, enabled?: boolean}, type: TypeDescriptor) // { // const {label, enabled} = defaults(conf, { // enabled: true, // }) // this.properties.push({type: 'STRUCTURE', paramName, subType: type, label, enabled, animatable: false}) // return this // } } export default class Type { // public static point2d(paramName: string, option: {label: string, defaultValue?: Point2D, enabled?: boolean, animatable?: boolean}) // { // return (new TypeDescriptor()).point2d(paramName, option) // } // public static point3d(paramName: string, option: {label: string, defaultValue?: Point3D, enabled?: boolean, animatable?: boolean}) // { // return (new TypeDescriptor()).point3d(paramName, option) // } // public static size2d(paramName: string, option: {label: string, defaultValue?: Size2D, enabled?: boolean, animatable?: boolean}) // { // return (new TypeDescriptor()).size2d(paramName, option) // } // public static size3d(paramName: string, option: {label: string, defaultValue?: Size3D, enabled?: boolean, animatable?: boolean}) // { // return (new TypeDescriptor()).size3d(paramName, option) // } public static colorRgb( paramName: string, option: { label: string defaultValue?: () => ColorRGB enabled?: boolean animatable?: boolean }, ) { return new TypeDescriptor().colorRgb(paramName, option) } public static colorRgba( paramName: string, option: { label: string defaultValue?: () => ColorRGBA enabled?: boolean animatable?: boolean }, ) { return new TypeDescriptor().colorRgba(paramName, option) } public static bool( paramName: string, option: { label: string defaultValue?: () => boolean enabled?: boolean animatable?: boolean }, ) { return new TypeDescriptor().bool(paramName, option) } public static string( paramName: string, option: { label: string defaultValue?: () => string enabled?: boolean animatable?: boolean }, ) { return new TypeDescriptor().string(paramName, option) } public static number( paramName: string, option: { label: string defaultValue?: () => number enabled?: boolean animatable?: boolean }, ) { return new TypeDescriptor().number(paramName, option) } public static float( paramName: string, option: { label: string defaultValue?: () => number enabled?: boolean animatable?: boolean }, ) { return new TypeDescriptor().float(paramName, option) } // public static pulse(paramName: string, option: {label: string, enabled?: boolean}) // { // return (new TypeDescriptor()).pulse(paramName, option) // } // public static enum(paramName: string, option: {label: string, defaultValue?: string, enabled?: boolean, selection: string[]}) // { // return (new TypeDescriptor()).enum(paramName, option) // } // public static clip(paramName: string, option: {label: string, enabled?: boolean}) // { // return (new TypeDescriptor()).clip(paramName, option) // } public static asset(paramName: string, option: { label: string; enabled?: boolean; extensions: string[] }) { return new TypeDescriptor().asset(paramName, option) } public static code( paramName: string, option: { label: string defaultValue?: () => Expression enabled?: boolean langType: string }, ) { return new TypeDescriptor().code(paramName, option) } // public static arrayOf(paramName: string, option: {label: string, enabled?: boolean}, type: TypeDescriptor) // { // return (new TypeDescriptor()).arrayOf(paramName, option, type) // } public static none() { return new TypeDescriptor() } constructor() { throw new TypeError('Type is can not constructing') } } // export const POINT_2D = 'POINT_2D' // export const POINT_3D = 'POINT_3D' // export const SIZE_2D = 'SIZE_2D' // export const SIZE_3D = 'SIZE_3D' export const COLOR_RGB = 'COLOR_RGB' export const COLOR_RGBA = 'COLOR_RGBA' export const BOOL = 'BOOL' export const STRING = 'STRING' export const NUMBER = 'NUMBER' export const FLOAT = 'FLOAT' export const ENUM = 'ENUM' // export const CLIP = 'CLIP' export const ASSET = 'ASSET' // export const PULSE = 'PULSE' // export const ARRAY = 'ARRAY' // export const STRUCTURE = 'STRUCTURE'
the_stack
import React from 'react'; import { findDOMNode } from 'react-dom'; import assign from 'object-assign'; import DataGrid from '../'; import { render } from '../testUtils'; import '../../style/index.scss'; const fakeEvent = props => { return assign( { stopPropagation: () => {}, preventDefault: () => {}, }, props ); }; const dragSetup = (gridInstance, { index: colIndex, diff }, dropProps) => { const body = gridInstance.body; const header = body.columnLayout.headerLayout.header; const headerNode = findDOMNode(header); const headers = [...headerNode.children]; const firstFlexIndex = body.props.visibleColumns.reduce((index, col, i) => { if (col.flex != null && index == -1) { return i; } return index; }, -1); return { headers, headerNode, drag: () => { const colHeaderNode = headers[colIndex]; const currentTarget = colHeaderNode.querySelector( '.InovuaReactDataGrid__column-resize-handle' ); const shareSpace = dropProps && dropProps.shareSpace !== undefined ? dropProps.shareSpace : gridInstance.props.shareSpaceOnResize; const initialSize = parseInt(colHeaderNode.style.width, 10); const nextColumn = headers[colIndex + 1]; const nextColumnSize = nextColumn ? parseInt(nextColumn.style.width, 10) : null; body.columnLayout.onResizeMouseDown( { visibleIndex: colIndex, }, { colHeaderNode: headers[colIndex], event: fakeEvent({ currentTarget }), } ); body.columnLayout.onResizeDrop( assign( {}, { index: colIndex, offset: 0, diff, size: initialSize + diff, nextColumnSize: shareSpace ? nextColumnSize - diff : nextColumnSize, firstFlexIndex, shareSpace, }, dropProps ) ); }, }; }; describe('DataGrid Column resize (no groups)', () => { it('should correctly resize a flex column with keepFlex', done => { const columns = [ { name: 'firstName' }, { name: 'lastName' }, { name: 'age', flex: 1, keepFlex: true }, { name: 'email' }, ]; const dataSource = [{ firstName: 'john', email: 'john@gmail.com', id: 1 }]; let resizeColumn = []; let resizeSize = []; let resizeFlex = []; const onColumnResize = ({ column, size, flex }) => { resizeColumn.push(column); resizeSize.push(size); resizeFlex.push(flex); }; const gridInstance = render( <DataGrid onColumnResize={onColumnResize} dataSource={dataSource} idProperty="id" style={{ width: 900 }} columnDefaultWidth={100} columns={columns} /> ); setTimeout(() => { const { headers, drag } = dragSetup( gridInstance, { index: 2, diff: -98 }, { shareSpace: true, size: null } ); expect(headers.map(h => h.style.width)).to.eql([ '100px', '100px', '598px', // we have 900px available, 3x100px cols and left-right borders of 1px each // so 598 remaining space '100px', ]); drag(); expect(headers.map(h => h.style.width)).to.eql([ '100px', '100px', '500px', '198px', ]); expect(resizeColumn[0].name).to.equal('email'); expect(resizeSize[0]).to.equal(198); expect(resizeFlex[0]).to.equal(false); expect(resizeColumn[1].name).to.equal('age'); expect(resizeSize[1]).to.equal(500); expect(resizeFlex[1]).to.equal(true); expect(resizeFlex.length).to.equal(2); const g = gridInstance.rerender( <DataGrid dataSource={dataSource} idProperty="id" style={{ width: 1000 }} columnDefaultWidth={100} columns={columns} /> ); expect(g).to.equal(gridInstance); // the flex column should still take up the space, even if it was // resized, since it has keepFlex: true setTimeout(() => { expect(headers.map(h => h.style.width)).to.eql([ '100px', '100px', '600px', '198px', ]); gridInstance.unmount(); done(); }, 50); }, 20); }); it('should correctly resize a flex column without keepFlex', done => { const columns = [ { name: 'firstName' }, { name: 'lastName' }, { name: 'age', flex: 1 }, { name: 'email' }, ]; const dataSource = [{ firstName: 'john', email: 'john@gmail.com', id: 1 }]; let resizeColumn = []; let resizeSize = []; let resizeFlex = []; const onColumnResize = ({ column, size, flex }) => { resizeColumn.push(column); resizeSize.push(size); resizeFlex.push(flex); }; const gridInstance = render( <DataGrid onColumnResize={onColumnResize} dataSource={dataSource} idProperty="id" style={{ width: 900 }} columnDefaultWidth={100} columns={columns} /> ); setTimeout(() => { const { headers, drag } = dragSetup( gridInstance, { index: 2, diff: -98 }, { shareSpace: false, size: null } ); expect(headers.map(h => h.style.width)).to.eql([ '100px', '100px', '598px', // we have 900px available, 3x100px cols and left-right borders of 1px each // so 598 remaining space '100px', ]); drag(); expect(headers.map(h => h.style.width)).to.eql([ '100px', '100px', '500px', '100px', ]); expect(resizeColumn[0].name).to.equal('age'); expect(resizeSize[0]).to.equal(500); expect(resizeFlex[0]).to.equal(true); expect(resizeColumn.length).to.equal(1); gridInstance.unmount(); done(); }, 20); }); it('should correctly resize a flex column', done => { const columns = [ { name: 'firstName' }, { name: 'lastName' }, { name: 'age', flex: 1 }, { name: 'email' }, ]; const dataSource = [{ firstName: 'john', email: 'john@gmail.com', id: 1 }]; const gridInstance = render( <DataGrid dataSource={dataSource} idProperty="id" style={{ width: 1000 }} columnDefaultWidth={100} columns={columns} /> ); setTimeout(() => { const { headers, drag } = dragSetup(gridInstance, { index: 2, diff: -98, }); expect(headers.map(h => h.style.width)).to.eql([ '100px', '100px', '698px', // we have 1000px available, 3x100px cols and left-right borders of 1px each // so 698 remaining space '100px', ]); drag(); expect(headers.map(h => h.style.width)).to.eql([ '100px', '100px', '600px', '100px', ]); gridInstance.rerender( <DataGrid dataSource={dataSource} idProperty="id" style={{ width: 900 }} columnDefaultWidth={100} columns={columns} /> ); // the flex column should be 100px less when total available grid width is 900 instead of 1000px which was initial setTimeout(() => { expect(headers.map(h => h.style.width)).to.eql([ '100px', '100px', '500px', '100px', ]); gridInstance.unmount(); done(); }, 50); }, 20); }); it('should correctly resize a nonflex column, with a flex sibling and shareSpaceOnResize', done => { const columns = [ { name: 'firstName' }, { name: 'lastName' }, { name: 'age', flex: 1 }, { name: 'email' }, ]; const dataSource = [{ firstName: 'john', email: 'john@gmail.com', id: 1 }]; const gridInstance = render( <DataGrid dataSource={dataSource} idProperty="id" style={{ width: 900 }} columnDefaultWidth={100} columns={columns} shareSpaceOnResize /> ); setTimeout(() => { const { headers, drag } = dragSetup(gridInstance, { index: 1, diff: -30, }); expect(headers.map(h => h.style.width)).to.eql([ '100px', '100px', '598px', // we have 900px available, 3x100px cols and left-right borders of 1px each // so 598 remaining space '100px', ]); drag(); expect(headers.map(h => h.style.width)).to.eql([ '100px', '70px', '628px', '100px', ]); gridInstance.rerender( <DataGrid dataSource={dataSource} idProperty="id" style={{ width: 1000 }} columnDefaultWidth={100} shareSpaceOnResize columns={columns} /> ); // after the resize, the flex column should take all available space setTimeout(() => { expect(headers.map(h => h.style.width)).to.eql([ '100px', '70px', '728px', '100px', ]); gridInstance.unmount(); done(); }, 50); }, 20); }); it('should correctly resize columns in a simple case - all non-flex columns, shareSpaceOnResize=false', done => { const gridInstance = render( <DataGrid dataSource={[{ firstName: 'john', email: 'john@gmail.com', id: 1 }]} idProperty="id" columnDefaultWidth={100} columns={[ { name: 'firstName' }, { name: 'lastName' }, { name: 'age' }, { name: 'email' }, ]} /> ); setTimeout(() => { const { headers, drag } = dragSetup(gridInstance, { index: 1, diff: 69, }); expect(headers.map(h => h.style.width)).to.eql([ '100px', '100px', '100px', '100px', ]); drag(); expect(headers.map(h => h.style.width)).to.eql([ '100px', '169px', '100px', '100px', ]); const { drag: dragAgain } = dragSetup(gridInstance, { index: 1, diff: 31, }); dragAgain(); expect(headers.map(h => h.style.width)).to.eql([ '100px', '200px', '100px', '100px', ]); gridInstance.unmount(); done(); }, 20); }); it('should correctly resize columns with shareSpaceOnResize', done => { const gridInstance = render( <DataGrid shareSpaceOnResize dataSource={[{ firstName: 'john', email: 'john@gmail.com', id: 1 }]} idProperty="id" columnDefaultWidth={200} columns={[ { name: 'firstName' }, { name: 'lastName' }, { name: 'age' }, { name: 'email' }, ]} /> ); setTimeout(() => { const { headers, drag } = dragSetup(gridInstance, { index: 1, diff: 50, }); expect(headers.map(h => h.style.width)).to.eql([ '200px', '200px', '200px', '200px', ]); drag(); expect(headers.map(h => h.style.width)).to.eql([ '200px', '250px', '150px', '200px', ]); gridInstance.unmount(); done(); }, 20); }); });
the_stack
import { Component, Input, OnDestroy } from '@angular/core'; import { ScriptDataService } from '../../../../core/data/processes/script-data.service'; import { ContentSource } from '../../../../core/shared/content-source.model'; import { ProcessDataService } from '../../../../core/data/processes/process-data.service'; import { getAllCompletedRemoteData, getAllSucceededRemoteDataPayload, getFirstCompletedRemoteData, getFirstSucceededRemoteDataPayload } from '../../../../core/shared/operators'; import { filter, map, switchMap, tap } from 'rxjs/operators'; import { hasValue, hasValueOperator } from '../../../../shared/empty.util'; import { ProcessStatus } from '../../../../process-page/processes/process-status.model'; import { BehaviorSubject, Observable, Subscription } from 'rxjs'; import { RequestService } from '../../../../core/data/request.service'; import { NotificationsService } from '../../../../shared/notifications/notifications.service'; import { Collection } from '../../../../core/shared/collection.model'; import { CollectionDataService } from '../../../../core/data/collection-data.service'; import { Process } from '../../../../process-page/processes/process.model'; import { TranslateService } from '@ngx-translate/core'; import { HttpClient } from '@angular/common/http'; import { BitstreamDataService } from '../../../../core/data/bitstream-data.service'; import { ContentSourceSetSerializer } from '../../../../core/shared/content-source-set-serializer'; /** * Component that contains the controls to run, reset and test the harvest */ @Component({ selector: 'ds-collection-source-controls', styleUrls: ['./collection-source-controls.component.scss'], templateUrl: './collection-source-controls.component.html', }) export class CollectionSourceControlsComponent implements OnDestroy { /** * Should the controls be enabled. */ @Input() isEnabled: boolean; /** * The current collection */ @Input() collection: Collection; /** * Should the control section be shown */ @Input() shouldShow: boolean; contentSource$: Observable<ContentSource>; private subs: Subscription[] = []; testConfigRunning$ = new BehaviorSubject(false); importRunning$ = new BehaviorSubject(false); reImportRunning$ = new BehaviorSubject(false); constructor(private scriptDataService: ScriptDataService, private processDataService: ProcessDataService, private requestService: RequestService, private notificationsService: NotificationsService, private collectionService: CollectionDataService, private translateService: TranslateService, private httpClient: HttpClient, private bitstreamService: BitstreamDataService ) { } ngOnInit() { // ensure the contentSource gets updated after being set to stale this.contentSource$ = this.collectionService.findByHref(this.collection._links.self.href, false).pipe( getAllSucceededRemoteDataPayload(), switchMap((collection) => this.collectionService.getContentSource(collection.uuid, false)), getAllSucceededRemoteDataPayload() ); } /** * Tests the provided content source's configuration. * @param contentSource - The content source to be tested */ testConfiguration(contentSource) { this.testConfigRunning$.next(true); this.subs.push(this.scriptDataService.invoke('harvest', [ {name: '-g', value: null}, {name: '-a', value: contentSource.oaiSource}, {name: '-i', value: new ContentSourceSetSerializer().Serialize(contentSource.oaiSetId)}, ], []).pipe( getFirstCompletedRemoteData(), tap((rd) => { if (rd.hasFailed) { // show a notification when the script invocation fails this.notificationsService.error(this.translateService.get('collection.source.controls.test.submit.error')); this.testConfigRunning$.next(false); } }), // filter out responses that aren't successful since the pinging of the process only needs to happen when the invocation was successful. filter((rd) => rd.hasSucceeded && hasValue(rd.payload)), switchMap((rd) => this.processDataService.findById(rd.payload.processId, false)), getAllCompletedRemoteData(), filter((rd) => !rd.isStale && (rd.hasSucceeded || rd.hasFailed)), map((rd) => rd.payload), hasValueOperator(), ).subscribe((process: Process) => { if (process.processStatus.toString() !== ProcessStatus[ProcessStatus.COMPLETED].toString() && process.processStatus.toString() !== ProcessStatus[ProcessStatus.FAILED].toString()) { // Ping the current process state every 5s setTimeout(() => { this.requestService.setStaleByHrefSubstring(process._links.self.href); }, 5000); } if (process.processStatus.toString() === ProcessStatus[ProcessStatus.FAILED].toString()) { this.notificationsService.error(this.translateService.get('collection.source.controls.test.failed')); this.testConfigRunning$.next(false); } if (process.processStatus.toString() === ProcessStatus[ProcessStatus.COMPLETED].toString()) { this.bitstreamService.findByHref(process._links.output.href).pipe(getFirstSucceededRemoteDataPayload()).subscribe((bitstream) => { this.httpClient.get(bitstream._links.content.href, {responseType: 'text'}).subscribe((data: any) => { const output = data.replaceAll(new RegExp('.*\\@(.*)', 'g'), '$1') .replaceAll('The script has started', '') .replaceAll('The script has completed', ''); this.notificationsService.info(this.translateService.get('collection.source.controls.test.completed'), output); }); }); this.testConfigRunning$.next(false); } } )); } /** * Start the harvest for the current collection */ importNow() { this.importRunning$.next(true); this.subs.push(this.scriptDataService.invoke('harvest', [ {name: '-r', value: null}, {name: '-c', value: this.collection.uuid}, ], []) .pipe( getFirstCompletedRemoteData(), tap((rd) => { if (rd.hasFailed) { this.notificationsService.error(this.translateService.get('collection.source.controls.import.submit.error')); this.importRunning$.next(false); } else { this.notificationsService.success(this.translateService.get('collection.source.controls.import.submit.success')); } }), filter((rd) => rd.hasSucceeded && hasValue(rd.payload)), switchMap((rd) => this.processDataService.findById(rd.payload.processId, false)), getAllCompletedRemoteData(), filter((rd) => !rd.isStale && (rd.hasSucceeded || rd.hasFailed)), map((rd) => rd.payload), hasValueOperator(), ).subscribe((process) => { if (process.processStatus.toString() !== ProcessStatus[ProcessStatus.COMPLETED].toString() && process.processStatus.toString() !== ProcessStatus[ProcessStatus.FAILED].toString()) { // Ping the current process state every 5s setTimeout(() => { this.requestService.setStaleByHrefSubstring(process._links.self.href); this.requestService.setStaleByHrefSubstring(this.collection._links.self.href); }, 5000); } if (process.processStatus.toString() === ProcessStatus[ProcessStatus.FAILED].toString()) { this.notificationsService.error(this.translateService.get('collection.source.controls.import.failed')); this.importRunning$.next(false); } if (process.processStatus.toString() === ProcessStatus[ProcessStatus.COMPLETED].toString()) { this.notificationsService.success(this.translateService.get('collection.source.controls.import.completed')); this.requestService.setStaleByHrefSubstring(this.collection._links.self.href); this.importRunning$.next(false); } } )); } /** * Reset and reimport the current collection */ resetAndReimport() { this.reImportRunning$.next(true); this.subs.push(this.scriptDataService.invoke('harvest', [ {name: '-o', value: null}, {name: '-c', value: this.collection.uuid}, ], []) .pipe( getFirstCompletedRemoteData(), tap((rd) => { if (rd.hasFailed) { this.notificationsService.error(this.translateService.get('collection.source.controls.reset.submit.error')); this.reImportRunning$.next(false); } else { this.notificationsService.success(this.translateService.get('collection.source.controls.reset.submit.success')); } }), filter((rd) => rd.hasSucceeded && hasValue(rd.payload)), switchMap((rd) => this.processDataService.findById(rd.payload.processId, false)), getAllCompletedRemoteData(), filter((rd) => !rd.isStale && (rd.hasSucceeded || rd.hasFailed)), map((rd) => rd.payload), hasValueOperator(), ).subscribe((process) => { if (process.processStatus.toString() !== ProcessStatus[ProcessStatus.COMPLETED].toString() && process.processStatus.toString() !== ProcessStatus[ProcessStatus.FAILED].toString()) { // Ping the current process state every 5s setTimeout(() => { this.requestService.setStaleByHrefSubstring(process._links.self.href); this.requestService.setStaleByHrefSubstring(this.collection._links.self.href); }, 5000); } if (process.processStatus.toString() === ProcessStatus[ProcessStatus.FAILED].toString()) { this.notificationsService.error(this.translateService.get('collection.source.controls.reset.failed')); this.reImportRunning$.next(false); } if (process.processStatus.toString() === ProcessStatus[ProcessStatus.COMPLETED].toString()) { this.notificationsService.success(this.translateService.get('collection.source.controls.reset.completed')); this.requestService.setStaleByHrefSubstring(this.collection._links.self.href); this.reImportRunning$.next(false); } } )); } ngOnDestroy(): void { this.subs.forEach((sub) => { if (hasValue(sub)) { sub.unsubscribe(); } }); } }
the_stack
import { assert } from "chai"; import { Id64, Id64String } from "@itwin/core-bentley"; import { Box, LineString3d, Point3d, Range3d, Sphere } from "@itwin/core-geometry"; import { Code, ColorDef, DbResult, GeometryClass, GeometryParams, GeometryPartProps, GeometryStreamBuilder, IModel, PhysicalElementProps } from "@itwin/core-common"; import { ExportLinesInfo, ExportPartInfo, ExportPartInstanceInfo, ExportPartLinesInfo } from "../../ExportGraphics"; import { ExportGraphics, ExportGraphicsInfo, ExportGraphicsMeshVisitor, ExportGraphicsOptions, GeometricElement, PhysicalObject, SnapshotDb, } from "../../core-backend"; import { IModelTestUtils } from "../IModelTestUtils"; import { GeometryPart } from "../../Element"; function saveNewElementFromBuilder(builder: GeometryStreamBuilder, seedElement: GeometricElement, iModel: SnapshotDb): Id64String { const elementProps: PhysicalElementProps = { classFullName: PhysicalObject.classFullName, model: seedElement.model, category: seedElement.category, code: Code.createEmpty(), geom: builder.geometryStream, }; const newId = iModel.elements.insertElement(elementProps); iModel.saveChanges(); return newId; } describe("exportGraphics", () => { let iModel: SnapshotDb; before(() => { const seedFileName = IModelTestUtils.resolveAssetFile("CompatibilityTestSeed.bim"); const testFileName = IModelTestUtils.prepareOutputFile("GeometryStream", "GeometryStreamTest.bim"); iModel = IModelTestUtils.createSnapshotFromSeed(testFileName, seedFileName); }); after(() => { iModel.close(); }); it("handles single geometryClass in GeometryStream", async () => { // Get known model/category from seed element a la GeometryStream.test.ts const seedElement = iModel.elements.getElement<GeometricElement>("0x1d"); assert.exists(seedElement); assert.isTrue(seedElement.federationGuid === "18eb4650-b074-414f-b961-d9cfaa6c8746"); const builder = new GeometryStreamBuilder(); const geometryParams = new GeometryParams(seedElement.category); geometryParams.geometryClass = GeometryClass.Construction; builder.appendGeometryParamsChange(geometryParams); builder.appendGeometry(Sphere.createCenterRadius(Point3d.createZero(), 1)); const newId = saveNewElementFromBuilder(builder, seedElement, iModel); const infos: ExportGraphicsInfo[] = []; const exportGraphicsOptions: ExportGraphicsOptions = { elementIdArray: [newId], onGraphics: (info: ExportGraphicsInfo) => infos.push(info), }; const exportStatus = iModel.exportGraphics(exportGraphicsOptions); assert.strictEqual(exportStatus, DbResult.BE_SQLITE_OK); assert.strictEqual(infos.length, 1); assert.strictEqual(infos[0].geometryClass, GeometryClass.Construction); }); it("handles multiple geometryClass in GeometryStream", async () => { // Get known model/category from seed element a la GeometryStream.test.ts const seedElement = iModel.elements.getElement<GeometricElement>("0x1d"); assert.exists(seedElement); assert.isTrue(seedElement.federationGuid === "18eb4650-b074-414f-b961-d9cfaa6c8746"); const builder = new GeometryStreamBuilder(); const geometryParams = new GeometryParams(seedElement.category); geometryParams.geometryClass = GeometryClass.Construction; builder.appendGeometryParamsChange(geometryParams); builder.appendGeometry(Sphere.createCenterRadius(Point3d.createZero(), 1)); geometryParams.geometryClass = GeometryClass.Primary; builder.appendGeometryParamsChange(geometryParams); builder.appendGeometry(Box.createRange(Range3d.create(Point3d.createZero(), Point3d.create(1.0, 1.0, 1.0)), true)!); const newId = saveNewElementFromBuilder(builder, seedElement, iModel); const infos: ExportGraphicsInfo[] = []; const exportGraphicsOptions: ExportGraphicsOptions = { elementIdArray: [newId], onGraphics: (info: ExportGraphicsInfo) => infos.push(info), chordTol: 0.01, }; const exportStatus = iModel.exportGraphics(exportGraphicsOptions); assert.strictEqual(exportStatus, DbResult.BE_SQLITE_OK); assert.strictEqual(infos.length, 2); // Sphere is construction, box is primary. Output order is arbitrary, use mesh size to figure out which is which. if (infos[0].mesh.indices.length > 36) { assert.strictEqual(infos[0].geometryClass, GeometryClass.Construction); assert.strictEqual(infos[1].geometryClass, GeometryClass.Primary); } else { assert.strictEqual(infos[0].geometryClass, GeometryClass.Primary); assert.strictEqual(infos[1].geometryClass, GeometryClass.Construction); } }); it("handles geometryClass in lines", async () => { // Get known model/category from seed element a la GeometryStream.test.ts const seedElement = iModel.elements.getElement<GeometricElement>("0x1d"); assert.exists(seedElement); assert.isTrue(seedElement.federationGuid === "18eb4650-b074-414f-b961-d9cfaa6c8746"); const builder = new GeometryStreamBuilder(); const geometryParams = new GeometryParams(seedElement.category); geometryParams.geometryClass = GeometryClass.Construction; builder.appendGeometryParamsChange(geometryParams); builder.appendGeometry(LineString3d.createPoints([Point3d.createZero(), Point3d.create(1, 0, 0)])); const newId = saveNewElementFromBuilder(builder, seedElement, iModel); const infos: ExportGraphicsInfo[] = []; const lineInfos: ExportLinesInfo[] = []; const exportGraphicsOptions: ExportGraphicsOptions = { elementIdArray: [newId], onGraphics: (info: ExportGraphicsInfo) => infos.push(info), onLineGraphics: (lineInfo: ExportLinesInfo) => lineInfos.push(lineInfo), chordTol: 0.01, }; const exportStatus = iModel.exportGraphics(exportGraphicsOptions); assert.strictEqual(exportStatus, DbResult.BE_SQLITE_OK); assert.strictEqual(infos.length, 0); assert.strictEqual(lineInfos.length, 1); assert.strictEqual(lineInfos[0].geometryClass, GeometryClass.Construction); }); it("handles geometryClass defined in parts", async () => { // Get known model/category from seed element a la GeometryStream.test.ts const seedElement = iModel.elements.getElement<GeometricElement>("0x1d"); assert.exists(seedElement); assert.isTrue(seedElement.federationGuid === "18eb4650-b074-414f-b961-d9cfaa6c8746"); const partBuilder = new GeometryStreamBuilder(); const partGeometryParams = new GeometryParams(Id64.invalid); // category unused for GeometryPart partGeometryParams.geometryClass = GeometryClass.Construction; partBuilder.appendGeometryParamsChange(partGeometryParams); partBuilder.appendGeometry(Sphere.createCenterRadius(Point3d.createZero(), 1)); const partProps: GeometryPartProps = { classFullName: GeometryPart.classFullName, model: IModel.dictionaryId, code: Code.createEmpty(), geom: partBuilder.geometryStream, }; const partId = iModel.elements.insertElement(partProps); iModel.saveChanges(); const partInstanceBuilder = new GeometryStreamBuilder(); partInstanceBuilder.appendGeometryPart3d(partId); const partInstanceId = saveNewElementFromBuilder(partInstanceBuilder, seedElement, iModel); const infos: ExportGraphicsInfo[] = []; const partInstanceArray: ExportPartInstanceInfo[] = []; const exportGraphicsOptions: ExportGraphicsOptions = { elementIdArray: [partInstanceId], onGraphics: (info: ExportGraphicsInfo) => infos.push(info), partInstanceArray, }; const exportStatus = iModel.exportGraphics(exportGraphicsOptions); assert.strictEqual(exportStatus, DbResult.BE_SQLITE_OK); assert.strictEqual(infos.length, 0); assert.strictEqual(partInstanceArray.length, 1); const partInfos: ExportPartInfo[] = []; const exportPartStatus = iModel.exportPartGraphics({ elementId: partInstanceArray[0].partId, displayProps: partInstanceArray[0].displayProps, onPartGraphics: (info: ExportPartInfo) => partInfos.push(info), }); assert.strictEqual(exportPartStatus, DbResult.BE_SQLITE_OK); assert.strictEqual(partInfos.length, 1); assert.strictEqual(partInfos[0].geometryClass, GeometryClass.Construction); }); it("handles geometryClass defined outside parts", async () => { // Get known model/category from seed element a la GeometryStream.test.ts const seedElement = iModel.elements.getElement<GeometricElement>("0x1d"); assert.exists(seedElement); assert.isTrue(seedElement.federationGuid === "18eb4650-b074-414f-b961-d9cfaa6c8746"); const partBuilder = new GeometryStreamBuilder(); partBuilder.appendGeometry(Sphere.createCenterRadius(Point3d.createZero(), 1)); const partProps: GeometryPartProps = { classFullName: GeometryPart.classFullName, model: IModel.dictionaryId, code: Code.createEmpty(), geom: partBuilder.geometryStream, }; const partId = iModel.elements.insertElement(partProps); iModel.saveChanges(); const partInstanceBuilder = new GeometryStreamBuilder(); const partInstanceGeometryParams = new GeometryParams(seedElement.category); partInstanceGeometryParams.geometryClass = GeometryClass.Construction; partInstanceBuilder.appendGeometryParamsChange(partInstanceGeometryParams); partInstanceBuilder.appendGeometryPart3d(partId); const partInstanceId = saveNewElementFromBuilder(partInstanceBuilder, seedElement, iModel); const infos: ExportGraphicsInfo[] = []; const partInstanceArray: ExportPartInstanceInfo[] = []; const exportGraphicsOptions: ExportGraphicsOptions = { elementIdArray: [partInstanceId], onGraphics: (info: ExportGraphicsInfo) => infos.push(info), partInstanceArray, }; const exportStatus = iModel.exportGraphics(exportGraphicsOptions); assert.strictEqual(exportStatus, DbResult.BE_SQLITE_OK); assert.strictEqual(infos.length, 0); assert.strictEqual(partInstanceArray.length, 1); assert.strictEqual(partInstanceArray[0].displayProps.geometryClass, GeometryClass.Construction); const partInfos: ExportPartInfo[] = []; const exportPartStatus = iModel.exportPartGraphics({ elementId: partInstanceArray[0].partId, displayProps: partInstanceArray[0].displayProps, onPartGraphics: (info: ExportPartInfo) => partInfos.push(info), }); assert.strictEqual(exportPartStatus, DbResult.BE_SQLITE_OK); assert.strictEqual(partInfos.length, 1); assert.strictEqual(partInfos[0].geometryClass, GeometryClass.Construction); }); it("handles geometryClass for lines in parts", async () => { // Get known model/category from seed element a la GeometryStream.test.ts const seedElement = iModel.elements.getElement<GeometricElement>("0x1d"); assert.exists(seedElement); assert.isTrue(seedElement.federationGuid === "18eb4650-b074-414f-b961-d9cfaa6c8746"); const partBuilder = new GeometryStreamBuilder(); const partGeometryParams = new GeometryParams(Id64.invalid); // category unused for GeometryPart partGeometryParams.geometryClass = GeometryClass.Construction; partBuilder.appendGeometryParamsChange(partGeometryParams); partBuilder.appendGeometry(LineString3d.createPoints([Point3d.createZero(), Point3d.create(1, 0, 0)])); const partProps: GeometryPartProps = { classFullName: GeometryPart.classFullName, model: IModel.dictionaryId, code: Code.createEmpty(), geom: partBuilder.geometryStream, }; const partId = iModel.elements.insertElement(partProps); iModel.saveChanges(); const partInstanceBuilder = new GeometryStreamBuilder(); partInstanceBuilder.appendGeometryPart3d(partId); const partInstanceId = saveNewElementFromBuilder(partInstanceBuilder, seedElement, iModel); const infos: ExportGraphicsInfo[] = []; const partInstanceArray: ExportPartInstanceInfo[] = []; const exportGraphicsOptions: ExportGraphicsOptions = { elementIdArray: [partInstanceId], onGraphics: (info: ExportGraphicsInfo) => infos.push(info), partInstanceArray, }; const exportStatus = iModel.exportGraphics(exportGraphicsOptions); assert.strictEqual(exportStatus, DbResult.BE_SQLITE_OK); assert.strictEqual(infos.length, 0); assert.strictEqual(partInstanceArray.length, 1); const partInfos: ExportPartInfo[] = []; const partLineInfos: ExportPartLinesInfo[] = []; const exportPartStatus = iModel.exportPartGraphics({ elementId: partInstanceArray[0].partId, displayProps: partInstanceArray[0].displayProps, onPartGraphics: (info: ExportPartInfo) => partInfos.push(info), onPartLineGraphics: (info: ExportPartLinesInfo) => partLineInfos.push(info), }); assert.strictEqual(exportPartStatus, DbResult.BE_SQLITE_OK); assert.strictEqual(partInfos.length, 0); assert.strictEqual(partLineInfos.length, 1); assert.strictEqual(partLineInfos[0].geometryClass, GeometryClass.Construction); }); it("converts to IndexedPolyface", async () => { // Get known model/category from seed element a la GeometryStream.test.ts const seedElement = iModel.elements.getElement<GeometricElement>("0x1d"); assert.exists(seedElement); assert.isTrue(seedElement.federationGuid === "18eb4650-b074-414f-b961-d9cfaa6c8746"); const box = Box.createRange(Range3d.create(Point3d.createZero(), Point3d.create(1.0, 1.0, 1.0)), true); assert.isFalse(undefined === box); const builder = new GeometryStreamBuilder(); builder.appendGeometry(box!); const newId = saveNewElementFromBuilder(builder, seedElement, iModel); const infos: ExportGraphicsInfo[] = []; const onGraphics = (info: ExportGraphicsInfo) => { infos.push(info); }; const exportGraphicsOptions: ExportGraphicsOptions = { elementIdArray: [newId], onGraphics, }; const exportStatus = iModel.exportGraphics(exportGraphicsOptions); assert.strictEqual(exportStatus, DbResult.BE_SQLITE_OK); assert.strictEqual(infos.length, 1); assert.strictEqual(infos[0].color, ColorDef.white.tbgr); assert.strictEqual(infos[0].mesh.indices.length, 36); assert.strictEqual(infos[0].elementId, newId); assert.strictEqual(infos[0].geometryClass, GeometryClass.Primary); const polyface = ExportGraphics.convertToIndexedPolyface(infos[0].mesh); assert.strictEqual(polyface.facetCount, 12); assert.strictEqual(polyface.data.pointCount, 24); assert.strictEqual(polyface.data.normalCount, 24); assert.strictEqual(polyface.data.paramCount, 24); }); // // // 2---3 6 // | \ | | \ // 0---1 4---5 // it("ExportMeshGraphicsVisitor", async () => { const numPoints = 7; const numFacets = 3; const pointData = [0, 0, 0, 1, 0, 0, 0, 2, 0, 1, 2, 0, 2, 0, 0, 4, 0, 0, 3, 2, 0]; const paramData = [0, 0, 1, 0, 0, 2, 1, 2, 2, 0, 4, 0, 3, 2]; const normalData = new Float32Array(pointData.length); const a0 = 2.0; const a1 = 3.0; const b0 = -2.0; const b1 = 5.0; // make normals functionally related to point coordinates . . . not good normals, but good for tests let paramCursor = 0; for (let i = 0; i < pointData.length; i++) { normalData[i] = a1 * pointData[i] + a0; if ((i + 1) % 3 !== 0) paramData[paramCursor++] = b0 + b1 * pointData[i]; } const smallMesh = { points: new Float64Array(pointData), params: new Float32Array(paramData), // normals have one-based index as z .. normals: new Float32Array(normalData), indices: new Int32Array([0, 1, 2, 2, 1, 3, 4, 5, 6]), isTwoSided: true, }; const knownArea = 4.0; assert.isTrue(smallMesh.points.length === 3 * numPoints); assert.isTrue(smallMesh.normals.length === 3 * numPoints); assert.isTrue(smallMesh.params.length === 2 * numPoints); assert.isTrue(smallMesh.indices.length === 3 * numFacets); const visitor = ExportGraphicsMeshVisitor.create(smallMesh, 0); assert.isDefined(visitor.paramIndex, "paramIndex defined"); assert.isDefined(visitor.paramIndex, "paramIndex defined"); let numFacetsA = 0; let indexCursor = 0; let areaSum = 0.0; while (visitor.moveToNextFacet()) { numFacetsA++; assert.isTrue(visitor.point.length === 3); assert.isTrue(smallMesh.indices[indexCursor] === visitor.pointIndex[0]); assert.isTrue(smallMesh.indices[indexCursor + 1] === visitor.pointIndex[1]); assert.isTrue(smallMesh.indices[indexCursor + 2] === visitor.pointIndex[2]); const areaVector = visitor.point.crossProductIndexIndexIndex(0, 1, 2)!; areaSum += areaVector.magnitude() * 0.5; assert.isTrue(smallMesh.indices[indexCursor] === visitor.paramIndex![0]); assert.isTrue(smallMesh.indices[indexCursor + 1] === visitor.paramIndex![1]); assert.isTrue(smallMesh.indices[indexCursor + 2] === visitor.paramIndex![2]); assert.isTrue(smallMesh.indices[indexCursor] === visitor.normalIndex![0]); assert.isTrue(smallMesh.indices[indexCursor + 1] === visitor.normalIndex![1]); assert.isTrue(smallMesh.indices[indexCursor + 2] === visitor.normalIndex![2]); for (let k = 0; k < 3; k++) { const point = visitor.point.getPoint3dAtUncheckedPointIndex(k); const normal = visitor.normal!.getPoint3dAtUncheckedPointIndex(k); const param = visitor.param!.getPoint2dAtUncheckedPointIndex(k); for (let j = 0; j < 3; j++) { assert.isTrue(a0 + a1 * point.at(j) === normal.at(j)); } for (let j = 0; j < 2; j++) { assert.isTrue(b0 + b1 * point.at(j) === (j === 0 ? param.x : param.y)); } } indexCursor += 3; } assert.isTrue(Math.abs(knownArea - areaSum) < 1.0e-13); assert.isTrue(numFacetsA === numFacets, "facet count"); }); });
the_stack
import test from 'tape' import { RepoBackend, RepoFrontend } from '../src' import { expect, expectDocs, generateServerPath, testRepo } from './misc' import { validateDocURL } from '../src/Metadata' import { INFINITY_SEQ } from '../src/CursorStore' import * as Stream from '../src/StreamLogic' import * as Crypto from '../src/Crypto' test('Simple create doc and make a change', (t) => { const repo = testRepo() const url = repo.create() repo.watch<any>( url, expectDocs(t, [ [{}, 'blank started doc'], [{ foo: 'bar' }, 'change preview'], [{ foo: 'bar' }, 'change final'], ]) ) repo.change<any>(url, (state: any) => { state.foo = 'bar' }) test.onFinish(() => repo.close()) }) test('Create a doc backend - then wire it up to a frontend - make a change', (t) => { const back = new RepoBackend({ memory: true }) const front = new RepoFrontend() back.subscribe(front.receive) front.subscribe(back.receive) const url = front.create() front.watch<any>( url, expectDocs(t, [ [{}, 'blank started doc'], [{ foo: 'bar' }, 'change preview'], [{ foo: 'bar' }, 'change final'], ]) ) front.change<any>(url, (state) => { state.foo = 'bar' }) test.onFinish(() => front.close()) }) test('Test document merging', (t) => { t.plan(5) const repo = testRepo() const url1 = repo.create({ foo: 'bar' }) const url2 = repo.create({ baz: 'bah' }) const id = validateDocURL(url1) const id2 = validateDocURL(url2) repo.watch<any>( url1, expectDocs(t, [ [ { foo: 'bar' }, 'initial value', () => { const clock = repo.back.cursors.get(repo.back.id, id) t.deepEqual(clock, { [id]: INFINITY_SEQ }) }, ], [ { foo: 'bar', baz: 'bah' }, 'merged value', () => { const clock = repo.back.cursors.get(repo.back.id, id) const clock2 = repo.back.cursors.get(repo.back.id, id2) t.deepEqual(clock, { [id]: INFINITY_SEQ, [id2]: 1 }) t.deepEqual(clock2, { [id2]: INFINITY_SEQ }) }, ], ]) ) repo.watch( url2, expectDocs(t, [ [{ baz: 'bah' }, 'initial value'], [{ baz: 'boo' }, 'change value'], [ { baz: 'boo' }, 'change value echo', () => { const clock1 = repo.back.cursors.get(repo.back.id, id) const clock2 = repo.back.cursors.get(repo.back.id, id2) t.deepEqual(clock1, { [id]: INFINITY_SEQ, [id2]: 1 }) t.deepEqual(clock2, { [id2]: INFINITY_SEQ }) }, ], ]) ) repo.merge(url1, url2) repo.change(url2, (doc: any) => { doc.baz = 'boo' }) }) test('Test document forking...', (t) => { t.plan(0) const repo = testRepo() const id = repo.create({ foo: 'bar' }) repo.watch<any>(id, expectDocs(t, [[{ foo: 'bar' }, 'init val']])) const id2 = repo.fork(id) repo.watch<any>( id2, expectDocs(t, [ [{}, 'hmm'], [ { foo: 'bar' }, 'init val', () => { repo.change<any>(id2, (state: any) => { state.bar = 'foo' }) }, ], [{ foo: 'bar', bar: 'foo' }, 'changed val'], [{ foo: 'bar', bar: 'foo' }, 'changed val echo'], ]) ) test.onFinish(() => repo.close()) }) test('Test materialize...', (t) => { t.plan(1) const repo = testRepo() const url = repo.create({ foo: 'bar0' }) repo.watch<any>( url, expectDocs(t, [ [{ foo: 'bar0' }, 'init val'], [{ foo: 'bar1' }, 'changed val'], [{ foo: 'bar1' }, 'changed val echo'], [{ foo: 'bar2' }, 'changed val'], [{ foo: 'bar2' }, 'changed val echo'], [{ foo: 'bar3' }, 'changed val'], [ { foo: 'bar3' }, 'changed val echo', () => { repo.materialize<any>(url, 2, (state) => { t.equal(state.foo, 'bar1') }) }, ], ]) ) repo.change<any>(url, (state: any) => { state.foo = 'bar1' }) repo.change<any>(url, (state: any) => { state.foo = 'bar2' }) repo.change<any>(url, (state: any) => { state.foo = 'bar3' }) test.onFinish(() => repo.close()) }) test('Test signing and verifying', async (t) => { t.plan(1) const repo = testRepo() const url = repo.create({ foo: 'bar0' }) const message = 'test message' const signedMessage = await repo.crypto.sign(url, message) const success = await repo.crypto.verify(url, signedMessage) t.true(success) test.onFinish(() => repo.close()) }) test("Test verifying garbage returns false and doesn't throw", async (t) => { t.plan(1) const repo = testRepo() const url = repo.create({ foo: 'bar0' }) const message = 'test message' await repo.crypto.sign(url, message) const success = await repo.crypto.verify(url, { message, signature: 'thisisnotasignature' as Crypto.EncodedSignature, }) t.false(success) test.onFinish(() => repo.close()) }) test('Test verifying with wrong signature fails', async (t) => { t.plan(1) const repo = testRepo() const url1 = repo.create({ foo: 'bar0' }) const url2 = repo.create({ foo2: 'bar1' }) const message = 'test message' const signedMessage2 = await repo.crypto.sign(url2, message) const success = await repo.crypto.verify(url1, { message, signature: signedMessage2.signature }) t.false(success) test.onFinish(() => repo.close()) }) test('Test signing as document from another repo', async (t) => { t.plan(1) const repo = testRepo() const repo2 = testRepo() const url = repo.create({ foo: 'bar0' }) const message = 'test message' repo2.crypto.sign(url, message).then( () => t.fail('sign() promise should reject'), () => t.pass('Should reject') ) test.onFinish(() => { repo.close() repo2.close() }) }) test('Test verifying a signature from another repo succeeds', async (t) => { t.plan(1) const repo = testRepo() const repo2 = testRepo() const url = repo.create({ foo: 'bar0' }) const message = 'test message' const signedMessage = await repo.crypto.sign(url, message) const success = await repo2.crypto.verify(url, signedMessage) t.true(success) test.onFinish(() => { repo.close() repo2.close() }) }) test('Test sealedBox and openSealedBox', async (t) => { t.plan(1) const repo = testRepo() const keyPair = Crypto.encodedEncryptionKeyPair() const message = 'test message' const sealedBox = await repo.crypto.sealedBox(keyPair.publicKey, message) const openedMessage = await repo.crypto.openSealedBox(keyPair, sealedBox) t.equal(openedMessage, message) test.onFinish(() => { repo.close() }) }) test('Test open sealed box in another repo', async (t) => { t.plan(1) const repo = testRepo() const repo2 = testRepo() const keyPair = Crypto.encodedEncryptionKeyPair() const message = 'test message' const sealedBox = await repo.crypto.sealedBox(keyPair.publicKey, message) const openedMessage = await repo2.crypto.openSealedBox(keyPair, sealedBox) t.equal(openedMessage, message) test.onFinish(() => { repo.close() repo2.close() }) }) test('Test fails with wrong keypair', async (t) => { t.plan(1) const repo = testRepo() const keyPair = Crypto.encodedEncryptionKeyPair() const keyPair2 = Crypto.encodedEncryptionKeyPair() const message = 'test message' const sealedBox = await repo.crypto.sealedBox(keyPair.publicKey, message) repo.crypto.openSealedBox(keyPair2, sealedBox).then( () => t.fail('openSealedBox should reject'), () => t.pass('Should reject') ) test.onFinish(() => { repo.close() }) }) test('Test encryption key pair', async (t) => { t.plan(1) const repo = testRepo() const keyPair = await repo.crypto.encryptionKeyPair() const message = 'test message' const sealedBox = await repo.crypto.sealedBox(keyPair.publicKey, message) const openedMessage = await repo.crypto.openSealedBox(keyPair, sealedBox) t.equal(openedMessage, message) test.onFinish(() => { repo.close() }) }) test('Test meta...', (t) => { t.plan(2) const repo = testRepo() const id = repo.create({ foo: 'bar0' }) repo.watch<any>(id, (_state, _clock, index) => { repo.meta(id, (meta) => { if (meta && meta.type === 'Document') { if (index === 1) { const actor = meta.actor! const seq = meta.clock[actor] t.equal(seq, 3) } if (index === 3) { const actor = meta.actor! const seq = meta.clock[actor] t.equal(seq, 3) t.end() } } }) }) repo.change<any>(id, (state: any) => { state.foo = 'bar1' }) repo.change<any>(id, (state: any) => { state.foo = 'bar2' }) test.onFinish(() => repo.close()) }) test('Writing and reading files works', async (t) => { t.plan(1) const repo = testRepo() repo.startFileServer(generateServerPath()) const pseudoFile = Buffer.alloc(1024 * 1024, 1) const { url } = await repo.files.write(Stream.fromBuffer(pseudoFile), 'application/octet-stream') const [, readable] = await repo.files.read(url) const buffer = await Stream.toBuffer(readable) t.deepEqual(pseudoFile, buffer) repo.close() }) test('Changing a document updates the clock store', async (t) => { t.plan(1) const repo = testRepo() const url = repo.create() const docId = validateDocURL(url) // We'll make one change const expectedClock = { [docId]: 1 } // Clock passed to `watch` matches expected clock. repo.watch<any>( url, expect(t, arg2, [ [{}, 'empty state'], [expectedClock, 'change preview'], [expectedClock, 'change final'], ]) ) repo.change<any>(url, (state: any) => { state.foo = 'bar' }) // Note: the interface of repo.change doesn't guarantee this // won't race - but it doesn't. We should change this test such // that a race can't be introduced. t.deepEqual(expectedClock, repo.back.clocks.get(repo.id, docId)) // Clock is stored in ClockStore and matches expected value // NOTE: this will fire twice because we have a bug which // applies change twice. // repo.back.clocks.updateLog.subscribe(([docId, clock]) => { // t.deepEqual(expectedClock, clock) // }) }) function arg2<T>(_arg1: unknown, arg2: T): T { return arg2 }
the_stack
import { AssetBalance, AssetBalanceWithPrice, Balance, BigNumber, HasBalance } from '@rotki/common'; import { GeneralAccount } from '@rotki/common/lib/account'; import { Blockchain } from '@rotki/common/lib/blockchain'; import { get } from '@vueuse/core'; import isEmpty from 'lodash/isEmpty'; import map from 'lodash/map'; import { TRADE_LOCATION_BLOCKCHAIN } from '@/data/defaults'; import { BlockchainAssetBalances } from '@/services/balances/types'; import { GeneralAccountData } from '@/services/types-api'; import { useAssetInfoRetrieval, useIgnoredAssetsStore } from '@/store/assets'; import { AccountAssetBalances, AssetBreakdown, BalanceByLocation, BalanceState, BlockchainAccountWithBalance, BlockchainTotal, ExchangeRateGetter, L2Totals, LocationBalance, NonFungibleBalance } from '@/store/balances/types'; import { Section, Status } from '@/store/const'; import { RotkehlchenState } from '@/store/types'; import { Getters } from '@/store/typing'; import { getStatus } from '@/store/utils'; import { Writeable } from '@/types'; import { ExchangeInfo, SupportedExchange } from '@/types/exchanges'; import { L2_LOOPRING } from '@/types/protocols'; import { ReadOnlyTag } from '@/types/user'; import { assert } from '@/utils/assertions'; import { Zero } from '@/utils/bignumbers'; import { assetSum, balanceSum } from '@/utils/calculation'; import { uniqueStrings } from '@/utils/data'; export interface BalanceGetters { ethAccounts: BlockchainAccountWithBalance[]; eth2Balances: BlockchainAccountWithBalance[]; ethAddresses: string[]; btcAccounts: BlockchainAccountWithBalance[]; kusamaBalances: BlockchainAccountWithBalance[]; avaxAccounts: BlockchainAccountWithBalance[]; polkadotBalances: BlockchainAccountWithBalance[]; loopringAccounts: BlockchainAccountWithBalance[]; totals: AssetBalance[]; exchangeRate: ExchangeRateGetter; exchanges: ExchangeInfo[]; exchangeBalances: (exchange: string) => AssetBalance[]; aggregatedBalances: AssetBalanceWithPrice[]; aggregatedAssets: string[]; liabilities: AssetBalanceWithPrice[]; manualBalanceByLocation: LocationBalance[]; blockchainTotal: BigNumber; blockchainTotals: BlockchainTotal[]; accountAssets: (account: string) => AssetBalance[]; accountLiabilities: (account: string) => AssetBalance[]; hasDetails: (account: string) => boolean; manualLabels: string[]; accounts: GeneralAccount[]; account: (address: string) => GeneralAccount | undefined; isEthereumToken: (asset: string) => boolean; assetBreakdown: (asset: string) => AssetBreakdown[]; loopringBalances: (address: string) => AssetBalance[]; blockchainAssets: AssetBalanceWithPrice[]; locationBreakdown: (location: string) => AssetBalanceWithPrice[]; byLocation: BalanceByLocation; exchangeNonce: (exchange: SupportedExchange) => number; nfTotalValue: BigNumber; nfBalances: NonFungibleBalance[]; } function balances( accounts: GeneralAccountData[], balances: BlockchainAssetBalances, blockchain: Exclude<Blockchain, 'BTC'> ): BlockchainAccountWithBalance[] { const data: BlockchainAccountWithBalance[] = []; for (const account of accounts) { const accountAssets = balances[account.address]; const balance: Balance = accountAssets ? { amount: accountAssets.assets[blockchain].amount, usdValue: assetSum(accountAssets.assets) } : { amount: Zero, usdValue: Zero }; data.push({ address: account.address, label: account.label ?? '', tags: account.tags ?? [], chain: blockchain, balance }); } return data; } export const getters: Getters< BalanceState, BalanceGetters, RotkehlchenState, any > = { ethAccounts({ eth, ethAccounts, loopringBalances }: BalanceState): BlockchainAccountWithBalance[] { const accounts = balances(ethAccounts, eth, Blockchain.ETH); // check if account is loopring account return accounts.map(ethAccount => { const address = ethAccount.address; const balances = loopringBalances[address]; const tags = ethAccount.tags || []; if (balances) { tags.push(ReadOnlyTag.LOOPRING); } return { ...ethAccount, tags: tags.filter(uniqueStrings) }; }); }, eth2Balances({ eth2, eth2Validators }: BalanceState): BlockchainAccountWithBalance[] { const balances: BlockchainAccountWithBalance[] = []; for (const { publicKey, validatorIndex, ownershipPercentage } of eth2Validators.entries) { const validatorBalances = eth2[publicKey]; let balance: Balance = { amount: Zero, usdValue: Zero }; if (validatorBalances && validatorBalances.assets) { const assets = validatorBalances.assets; balance = { amount: assets[Blockchain.ETH2].amount, usdValue: assetSum(assets) }; } balances.push({ address: publicKey, chain: Blockchain.ETH2, balance, label: validatorIndex.toString() ?? '', tags: [], ownershipPercentage }); } return balances; }, ethAddresses: ({ ethAccounts }) => { return ethAccounts.map(({ address }) => address); }, kusamaBalances: ({ ksmAccounts, ksm }) => { return balances(ksmAccounts, ksm, Blockchain.KSM); }, avaxAccounts: ({ avaxAccounts, avax }: BalanceState): BlockchainAccountWithBalance[] => { return balances(avaxAccounts, avax, Blockchain.AVAX); }, polkadotBalances: ({ dotAccounts, dot }) => { return balances(dotAccounts, dot, Blockchain.DOT); }, btcAccounts({ btc, btcAccounts }: BalanceState): BlockchainAccountWithBalance[] { const accounts: BlockchainAccountWithBalance[] = []; const { standalone, xpubs } = btcAccounts; const zeroBalance = () => ({ amount: Zero, usdValue: Zero }); for (const { address, label, tags } of standalone) { const balance = btc.standalone?.[address] ?? zeroBalance(); accounts.push({ address, label: label ?? '', tags: tags ?? [], chain: Blockchain.BTC, balance }); } for (const { addresses, derivationPath, label, tags, xpub } of xpubs) { accounts.push({ chain: Blockchain.BTC, xpub, derivationPath: derivationPath ?? '', address: '', label: label ?? '', tags: tags ?? [], balance: zeroBalance() }); if (!addresses) { continue; } for (const { address, label, tags } of addresses) { const { xpubs } = btc; if (!xpubs) { continue; } const index = xpubs.findIndex(xpub => xpub.addresses[address]) ?? -1; const balance = index >= 0 ? xpubs[index].addresses[address] : zeroBalance(); accounts.push({ chain: Blockchain.BTC, xpub: xpub, derivationPath: derivationPath ?? '', address: address, label: label ?? '', tags: tags ?? [], balance: balance }); } } return accounts; }, loopringAccounts({ loopringBalances, ethAccounts }): BlockchainAccountWithBalance[] { const accounts: BlockchainAccountWithBalance[] = []; for (const address in loopringBalances) { const assets = loopringBalances[address]; const tags = ethAccounts.find(account => account.address === address)?.tags || []; const balance = { amount: Zero, usdValue: Zero }; for (const asset in assets) { const assetBalance = assets[asset]; balance.amount = balance.amount.plus(assetBalance.amount); balance.usdValue = balance.usdValue.plus(assetBalance.usdValue); } accounts.push({ address, balance, chain: Blockchain.ETH, label: '', tags: [...tags, ReadOnlyTag.LOOPRING].filter(uniqueStrings) }); } return accounts; }, totals(state: BalanceState): AssetBalance[] { const { isAssetIgnored } = useIgnoredAssetsStore(); return map(state.totals, (value: Balance, asset: string) => { const assetBalance: AssetBalance = { asset, ...value }; return assetBalance; }).filter(balance => !get(isAssetIgnored(balance.asset))); }, exchangeRate: (state: BalanceState) => (currency: string) => { return state.usdToFiatExchangeRates[currency]; }, exchanges: (state: BalanceState): ExchangeInfo[] => { const balances = state.exchangeBalances; return Object.keys(balances) .map(value => ({ location: value, balances: balances[value], total: assetSum(balances[value]) })) .sort((a, b) => b.total.minus(a.total).toNumber()); }, exchangeBalances: (state: BalanceState) => (exchange: string): AssetBalanceWithPrice[] => { const { isAssetIgnored } = useIgnoredAssetsStore(); const exchangeBalances = state.exchangeBalances[exchange]; const noPrice = new BigNumber(-1); return exchangeBalances ? Object.keys(exchangeBalances) .filter(asset => !get(isAssetIgnored(asset))) .map( asset => ({ asset, amount: exchangeBalances[asset].amount, usdValue: exchangeBalances[asset].usdValue, usdPrice: state.prices[asset] ?? noPrice } as AssetBalanceWithPrice) ) : []; }, aggregatedBalances: ( { connectedExchanges, manualBalances, loopringBalances, prices }: BalanceState, { exchangeBalances, totals } ): AssetBalanceWithPrice[] => { const { isAssetIgnored } = useIgnoredAssetsStore(); const ownedAssets: { [asset: string]: AssetBalanceWithPrice } = {}; const addToOwned = (value: AssetBalance) => { const asset = ownedAssets[value.asset]; if (get(isAssetIgnored(value.asset))) { return; } ownedAssets[value.asset] = !asset ? { ...value, usdPrice: prices[value.asset] ?? new BigNumber(-1) } : { asset: asset.asset, amount: asset.amount.plus(value.amount), usdValue: asset.usdValue.plus(value.usdValue), usdPrice: prices[asset.asset] ?? new BigNumber(-1) }; }; const exchanges = connectedExchanges .map(({ location }) => location) .filter(uniqueStrings); for (const exchange of exchanges) { const balances = exchangeBalances(exchange); balances.forEach((value: AssetBalance) => addToOwned(value)); } totals.forEach((value: AssetBalance) => addToOwned(value)); manualBalances.forEach(value => addToOwned(value)); for (const address in loopringBalances) { const balances = loopringBalances[address]; for (const asset in balances) { addToOwned({ ...balances[asset], asset }); } } return Object.values(ownedAssets).sort((a, b) => b.usdValue.minus(a.usdValue).toNumber() ); }, liabilities: ({ liabilities, manualLiabilities, prices }) => { const noPrice = new BigNumber(-1); const liabilitiesMerged: Record<string, Balance> = { ...liabilities }; for (const { amount, asset, usdValue } of manualLiabilities) { const liability = liabilitiesMerged[asset]; if (liability) { liabilitiesMerged[asset] = { amount: liability.amount.plus(amount), usdValue: liability.usdValue.plus(usdValue) }; } else { liabilitiesMerged[asset] = { amount: amount, usdValue: usdValue }; } } return Object.keys(liabilitiesMerged).map(asset => ({ asset, amount: liabilitiesMerged[asset].amount, usdValue: liabilitiesMerged[asset].usdValue, usdPrice: prices[asset] ?? noPrice })); }, // simplify the manual balances object so that we can easily reduce it manualBalanceByLocation: ( state: BalanceState, { exchangeRate }, { session } ): LocationBalance[] => { const mainCurrency = session?.generalSettings.mainCurrency.tickerSymbol; assert(mainCurrency, 'main currency was not properly set'); const manualBalances = state.manualBalances; const currentExchangeRate = exchangeRate(mainCurrency); if (currentExchangeRate === undefined) { return []; } const simplifyManualBalances = manualBalances.map(perLocationBalance => { // because we mix different assets we need to convert them before they are aggregated // thus in amount display we always pass the manualBalanceByLocation in the user's main currency let convertedValue: BigNumber; if (mainCurrency === perLocationBalance.asset) { convertedValue = perLocationBalance.amount; } else { convertedValue = perLocationBalance.usdValue.multipliedBy(currentExchangeRate); } // to avoid double-conversion, we take as usdValue the amount property when the original asset type and // user's main currency coincide const { location, usdValue }: LocationBalance = { location: perLocationBalance.location, usdValue: convertedValue }; return { location, usdValue }; }); // Aggregate all balances per location const aggregateManualBalancesByLocation: BalanceByLocation = simplifyManualBalances.reduce( (result: BalanceByLocation, manualBalance: LocationBalance) => { if (result[manualBalance.location]) { // if the location exists on the reduced object, add the usdValue of the current item to the previous total result[manualBalance.location] = result[ manualBalance.location ].plus(manualBalance.usdValue); } else { // otherwise create the location and initiate its value result[manualBalance.location] = manualBalance.usdValue; } return result; }, {} ); return Object.keys(aggregateManualBalancesByLocation) .map(location => ({ location, usdValue: aggregateManualBalancesByLocation[location] })) .sort((a, b) => b.usdValue.minus(a.usdValue).toNumber()); }, blockchainTotal: (_, getters) => { return getters.totals.reduce((sum: BigNumber, asset: AssetBalance) => { return sum.plus(asset.usdValue); }, Zero); }, blockchainTotals: (state, getters, _rootState): BlockchainTotal[] => { const sum = (accounts: HasBalance[]): BigNumber => { return accounts.reduce((sum: BigNumber, { balance }: HasBalance) => { return sum.plus(balance.usdValue); }, Zero); }; const totals: BlockchainTotal[] = []; const ethAccounts: BlockchainAccountWithBalance[] = getters.ethAccounts; const btcAccounts: BlockchainAccountWithBalance[] = getters.btcAccounts; const kusamaBalances: BlockchainAccountWithBalance[] = getters.kusamaBalances; const polkadotBalances: BlockchainAccountWithBalance[] = getters.polkadotBalances; const avaxAccounts: BlockchainAccountWithBalance[] = getters.avaxAccounts; const eth2Balances: BlockchainAccountWithBalance[] = getters.eth2Balances; const loopring: AccountAssetBalances = state.loopringBalances; if (ethAccounts.length > 0) { const ethStatus = getStatus(Section.BLOCKCHAIN_ETH); const l2Totals: L2Totals[] = []; if (Object.keys(loopring).length > 0) { const balances: { [asset: string]: HasBalance } = {}; for (const address in loopring) { for (const asset in loopring[address]) { if (!balances[asset]) { balances[asset] = { balance: loopring[address][asset] }; } else { balances[asset] = { balance: balanceSum( loopring[address][asset], balances[asset].balance ) }; } } } const loopringStatus = getStatus(Section.L2_LOOPRING_BALANCES); l2Totals.push({ protocol: L2_LOOPRING, usdValue: sum(Object.values(balances)), loading: loopringStatus === Status.NONE || loopringStatus === Status.LOADING }); } totals.push({ chain: Blockchain.ETH, l2: l2Totals.sort((a, b) => b.usdValue.minus(a.usdValue).toNumber()), usdValue: sum(ethAccounts), loading: ethStatus === Status.NONE || ethStatus === Status.LOADING }); } if (btcAccounts.length > 0) { const btcStatus = getStatus(Section.BLOCKCHAIN_BTC); totals.push({ chain: Blockchain.BTC, l2: [], usdValue: sum(btcAccounts), loading: btcStatus === Status.NONE || btcStatus === Status.LOADING }); } if (kusamaBalances.length > 0) { const ksmStatus = getStatus(Section.BLOCKCHAIN_KSM); totals.push({ chain: Blockchain.KSM, l2: [], usdValue: sum(kusamaBalances), loading: ksmStatus === Status.NONE || ksmStatus === Status.LOADING }); } if (avaxAccounts.length > 0) { const avaxStatus = getStatus(Section.BLOCKCHAIN_AVAX); totals.push({ chain: Blockchain.AVAX, l2: [], usdValue: sum(avaxAccounts), loading: avaxStatus === Status.NONE || avaxStatus === Status.LOADING }); } if (polkadotBalances.length > 0) { const dotStatus = getStatus(Section.BLOCKCHAIN_DOT); totals.push({ chain: Blockchain.DOT, l2: [], usdValue: sum(polkadotBalances), loading: dotStatus === Status.NONE || dotStatus === Status.LOADING }); } if (eth2Balances.length > 0) { const eth2Status = getStatus(Section.BLOCKCHAIN_ETH2); totals.push({ chain: Blockchain.ETH2, l2: [], usdValue: sum(eth2Balances), loading: eth2Status === Status.NONE || eth2Status === Status.LOADING }); } return totals.sort((a, b) => b.usdValue.minus(a.usdValue).toNumber()); }, accountAssets: (state: BalanceState) => (account: string) => { const { isAssetIgnored } = useIgnoredAssetsStore(); const ethAccount = state.eth[account]; if (!ethAccount || isEmpty(ethAccount)) { return []; } return Object.entries(ethAccount.assets) .filter(([asset]) => !get(isAssetIgnored(asset))) .map( ([key, { amount, usdValue }]) => ({ asset: key, amount: amount, usdValue: usdValue } as AssetBalance) ); }, accountLiabilities: (state: BalanceState) => (account: string) => { const { isAssetIgnored } = useIgnoredAssetsStore(); const ethAccount = state.eth[account]; if (!ethAccount || isEmpty(ethAccount)) { return []; } return Object.entries(ethAccount.liabilities) .filter(([asset]) => !get(isAssetIgnored(asset))) .map( ([key, { amount, usdValue }]) => ({ asset: key, amount: amount, usdValue: usdValue } as AssetBalance) ); }, hasDetails: (state: BalanceState) => (account: string) => { const ethAccount = state.eth[account]; const loopringBalance = state.loopringBalances[account] || {}; if (!ethAccount || isEmpty(ethAccount)) { return false; } const assetsCount = Object.entries(ethAccount.assets).length; const liabilitiesCount = Object.entries(ethAccount.liabilities).length; const loopringsCount = Object.entries(loopringBalance).length; return assetsCount + liabilitiesCount + loopringsCount > 1; }, manualLabels: ({ manualBalances, manualLiabilities }: BalanceState) => { const balances = manualLiabilities.concat(manualBalances); return balances.map(value => value.label); }, accounts: ( _, { ethAccounts, btcAccounts, kusamaBalances, polkadotBalances, avaxAccounts } ): GeneralAccount[] => { return ethAccounts .concat(btcAccounts) .concat(kusamaBalances) .concat(polkadotBalances) .concat(avaxAccounts) .filter((account: BlockchainAccountWithBalance) => !!account.address) .map((account: BlockchainAccountWithBalance) => ({ chain: account.chain, address: account.address, label: account.label, tags: account.tags })); }, account: (_, getters) => (address: string) => { const accounts = getters.accounts as GeneralAccount[]; return accounts.find(acc => acc.address === address); }, isEthereumToken: () => (asset: string) => { const { assetInfo } = useAssetInfoRetrieval(); const match = get(assetInfo(asset)); if (match) { return match.assetType === 'ethereum token'; } return false; }, aggregatedAssets: (_, getters) => { const liabilities = getters.liabilities.map(({ asset }) => asset); const assets = getters.aggregatedBalances.map(({ asset }) => asset); assets.push(...liabilities); return assets.filter(uniqueStrings); }, assetBreakdown: ({ btc: { standalone, xpubs }, btcAccounts, ksmAccounts, dotAccounts, avaxAccounts, eth, ethAccounts, exchangeBalances, ksm, dot, avax, manualBalances, loopringBalances }) => asset => { const breakdown: AssetBreakdown[] = []; for (const exchange in exchangeBalances) { const exchangeData = exchangeBalances[exchange]; if (!exchangeData[asset]) { continue; } breakdown.push({ address: '', location: exchange, balance: exchangeData[asset], tags: [] }); } for (let i = 0; i < manualBalances.length; i++) { const manualBalance = manualBalances[i]; if (manualBalance.asset !== asset) { continue; } breakdown.push({ address: '', location: manualBalance.location, balance: { amount: manualBalance.amount, usdValue: manualBalance.usdValue }, tags: manualBalance.tags }); } for (const address in eth) { const ethBalances = eth[address]; const assetBalance = ethBalances.assets[asset]; if (!assetBalance) { continue; } const tags = ethAccounts.find(ethAccount => ethAccount.address === address) ?.tags || []; breakdown.push({ address, location: Blockchain.ETH, balance: assetBalance, tags }); } for (const address in loopringBalances) { const existing: Writeable<AssetBreakdown> | undefined = breakdown.find( value => value.address === address ); const balanceElement = loopringBalances[address][asset]; if (!balanceElement) { continue; } if (existing) { existing.balance = balanceSum(existing.balance, balanceElement); } else { breakdown.push({ address, location: Blockchain.ETH, balance: loopringBalances[address][asset], tags: [ReadOnlyTag.LOOPRING] }); } } if (asset === Blockchain.BTC) { if (standalone) { for (const address in standalone) { const btcBalance = standalone[address]; const tags = btcAccounts?.standalone.find( btcAccount => btcAccount.address === address )?.tags || []; breakdown.push({ address, location: Blockchain.BTC, balance: btcBalance, tags }); } } if (xpubs) { for (let i = 0; i < xpubs.length; i++) { const xpub = xpubs[i]; const addresses = xpub.addresses; const tags = btcAccounts?.xpubs[i].tags; for (const address in addresses) { const btcBalance = addresses[address]; breakdown.push({ address, location: Blockchain.BTC, balance: btcBalance, tags }); } } } } for (const address in ksm) { const balances = ksm[address]; const assetBalance = balances.assets[asset]; if (!assetBalance) { continue; } const tags = ksmAccounts.find(ksmAccount => ksmAccount.address === address) ?.tags || []; breakdown.push({ address, location: Blockchain.KSM, balance: assetBalance, tags }); } for (const address in dot) { const balances = dot[address]; const assetBalance = balances.assets[asset]; if (!assetBalance) { continue; } const tags = dotAccounts.find(dotAccount => dotAccount.address === address) ?.tags || []; breakdown.push({ address, location: Blockchain.DOT, balance: assetBalance, tags }); } for (const address in avax) { const balances = avax[address]; const assetBalance = balances.assets[asset]; if (!assetBalance) { continue; } const tags = avaxAccounts.find(avaxAccount => avaxAccount.address === address) ?.tags || []; breakdown.push({ address, location: Blockchain.AVAX, balance: assetBalance, tags }); } return breakdown; }, loopringBalances: state => address => { const balances: AssetBalance[] = []; const loopringBalance = state.loopringBalances[address]; if (loopringBalance) { for (const asset in loopringBalance) { balances.push({ ...loopringBalance[asset], asset }); } } return balances; }, blockchainAssets: (state, { totals }) => { const noPrice = new BigNumber(-1); const blockchainTotal = [ ...totals.map(value => ({ ...value, usdPrice: state.prices[value.asset] ?? noPrice })) ]; const { isAssetIgnored } = useIgnoredAssetsStore(); const loopringBalances = state.loopringBalances; for (const address in loopringBalances) { const accountBalances = loopringBalances[address]; for (const asset in accountBalances) { if (get(isAssetIgnored(asset))) { continue; } const existing: Writeable<AssetBalance> | undefined = blockchainTotal.find(value => value.asset === asset); if (!existing) { blockchainTotal.push({ asset, ...accountBalances[asset], usdPrice: state.prices[asset] ?? noPrice }); } else { const sum = balanceSum(existing, accountBalances[asset]); existing.usdValue = sum.usdValue; existing.amount = sum.amount; } } } return blockchainTotal; }, locationBreakdown: ( { connectedExchanges, manualBalances, loopringBalances, prices }: BalanceState, { exchangeBalances, totals } ) => identifier => { const { isAssetIgnored } = useIgnoredAssetsStore(); const ownedAssets: { [asset: string]: AssetBalanceWithPrice } = {}; const addToOwned = (value: AssetBalance) => { const asset = ownedAssets[value.asset]; if (get(isAssetIgnored(value.asset))) { return; } ownedAssets[value.asset] = !asset ? { ...value, usdPrice: prices[value.asset] ?? new BigNumber(-1) } : { asset: asset.asset, amount: asset.amount.plus(value.amount), usdValue: asset.usdValue.plus(value.usdValue), usdPrice: prices[asset.asset] ?? new BigNumber(-1) }; }; const exchange = connectedExchanges.find( ({ location }) => identifier === location ); if (exchange) { const balances = exchangeBalances(identifier); balances.forEach((value: AssetBalance) => addToOwned(value)); } if (identifier === TRADE_LOCATION_BLOCKCHAIN) { totals.forEach((value: AssetBalance) => addToOwned(value)); for (const address in loopringBalances) { const balances = loopringBalances[address]; for (const asset in balances) { addToOwned({ ...balances[asset], asset }); } } } manualBalances.forEach(value => { if (value.location === identifier) { addToOwned(value); } }); return Object.values(ownedAssets).sort((a, b) => b.usdValue.minus(a.usdValue).toNumber() ); }, byLocation: ( state, { blockchainTotal, exchangeRate, exchanges, manualBalanceByLocation: manual }, { session } ) => { const byLocation: BalanceByLocation = {}; for (const { location, usdValue } of manual) { byLocation[location] = usdValue; } const mainCurrency = session?.generalSettings.mainCurrency.tickerSymbol; assert(mainCurrency, 'main currency was not properly set'); const currentExchangeRate = exchangeRate(mainCurrency); const blockchainTotalConverted = currentExchangeRate ? blockchainTotal.multipliedBy(currentExchangeRate) : blockchainTotal; const blockchain = byLocation[TRADE_LOCATION_BLOCKCHAIN]; if (blockchain) { byLocation[TRADE_LOCATION_BLOCKCHAIN] = blockchain.plus( blockchainTotalConverted ); } else { byLocation[TRADE_LOCATION_BLOCKCHAIN] = blockchainTotalConverted; } for (const { location, total } of exchanges) { const locationElement = byLocation[location]; const exchangeBalanceConverted = currentExchangeRate ? total.multipliedBy(currentExchangeRate) : total; if (locationElement) { byLocation[location] = locationElement.plus(exchangeBalanceConverted); } else { byLocation[location] = exchangeBalanceConverted; } } return byLocation; }, exchangeNonce: ({ connectedExchanges: exchanges }) => exchange => { return ( exchanges.filter(({ location }) => location === exchange).length + 1 ); }, nfTotalValue: ({ nonFungibleBalances }) => { let sum = Zero; for (const address in nonFungibleBalances) { const addressNfts = nonFungibleBalances[address]; for (const nft of addressNfts) { sum = sum.plus(nft.usdPrice); } } return sum; }, nfBalances: ({ nonFungibleBalances }) => { const nfBalances: NonFungibleBalance[] = []; for (const address in nonFungibleBalances) { const addressNfBalance = nonFungibleBalances[address]; nfBalances.push(...addressNfBalance); } return nfBalances; } };
the_stack
import {useCallback, useEffect, useRef, useState} from "react"; import {Conversation, ConversationItem, LinkedConversation, MessageItem, MessageModifier} from "shared/data/blocks"; import {ConversationItemType, ParticipantActionType} from "shared/data/stateCodes"; import {getPlatformUtils} from "shared/util/platformUtils"; import {isModifierTapback, messageItemToConversationPreview} from "shared/util/conversationUtils"; import * as ConnectionManager from "shared/connection/connectionManager"; import {modifierUpdateEmitter} from "shared/connection/connectionManager"; import {getNotificationUtils} from "shared/util/notificationUtils"; import {useUnmountedPromiseWrapper} from "shared/util/hookUtils"; import {playSoundMessageIn, playSoundNotification, playSoundTapback} from "shared/util/soundUtils"; import {normalizeAddress} from "shared/util/addressHelper"; import {arrayContainsAll} from "shared/util/arrayUtils"; import localMessageCache from "shared/util/localMessageCacheUtils"; interface ConversationsState { conversations: Conversation[] | undefined, loadConversations(): Promise<Conversation[]>, addConversation(newConversation: Conversation): void, markConversationRead(conversationID: number): void } type ChatID = string | number; //A chat's GUID or local ID export default function useConversationState(activeConversationID: number | undefined, interactive: boolean = false): ConversationsState { const [conversations, setConversations] = useState<Conversation[] | undefined>(undefined); const pendingConversationDataMap = useRef(new Map<string, ConversationItem[]>()).current; const wrapPromiseUnmount = useUnmountedPromiseWrapper(); const applyUpdateMessages = useCallback(async (newItems: ConversationItem[]) => { //Sort new items into their conversations const sortedConversationItems = newItems.reduce((accumulator: Map<ChatID, ConversationItem[]>, item: ConversationItem) => { //Get this item's ID const chatID = getItemChatID(item); if(chatID === undefined) return accumulator; //Get the message array for the message's conversation let array: ConversationItem[] | undefined = accumulator.get(chatID); if(array === undefined) { array = []; accumulator.set(chatID, array); } //Add the item to the array array.push(item); return accumulator; }, new Map()); //Find all chats (and their messages) from the server that we don't have saved locally const unlinkedSortedConversationItems: Map<string, ConversationItem[]> = conversations === undefined ? new Map() : new Map( Array.from(sortedConversationItems.entries()) .filter((entry): entry is [string, ConversationItem[]] => typeof entry[0] === "string" && !conversations.some((conversation) => !conversation.localOnly && conversation.guid === entry[0])) ); if(unlinkedSortedConversationItems.size > 0) { //Saving the items for later reference when we have conversation information for(const [chatGUID, conversationItems] of unlinkedSortedConversationItems.entries()) { let pendingConversationItems = pendingConversationDataMap.get(chatGUID); if(pendingConversationItems === undefined) { pendingConversationItems = []; pendingConversationDataMap.set(chatGUID, pendingConversationItems); } pendingConversationItems.push(...conversationItems); } //Requesting information for new chats wrapPromiseUnmount( ConnectionManager.fetchConversationInfo(Array.from(unlinkedSortedConversationItems.keys())) ).then((result) => { type LinkedGroupedConversationItems = [LinkedConversation, ConversationItem[]]; const linkedSortedConversationItems = result.map(([chatGUID, conversation]): LinkedGroupedConversationItems | undefined => { //Remove the pending conversation if the conversation request failed if(conversation === undefined) { pendingConversationDataMap.delete(chatGUID); return undefined; } //Get the pending messages const pendingMessages = pendingConversationDataMap.get(chatGUID); //Remove the pending conversation pendingConversationDataMap.delete(chatGUID); return [conversation, pendingMessages ?? []]; }).filter((entry): entry is LinkedGroupedConversationItems => entry !== undefined); if(linkedSortedConversationItems.length > 0) { //Ignore if we haven't loaded conversations yet if(conversations !== undefined) { //Clone the conversation array const pendingConversationArray = [...conversations]; for(const [newConversation, conversationItems] of linkedSortedConversationItems) { //Skip conversations that already exist if(pendingConversationArray.find((conversation) => !conversation.localOnly && conversation.guid === newConversation.guid)) continue; //Check if there are any local conversations with matching members const matchingLocalConversationIndex = conversations.findIndex((conversation) => { return conversation.localOnly && conversation.service === newConversation.service && arrayContainsAll(conversation.members, newConversation.members, normalizeAddress); }); if(matchingLocalConversationIndex !== -1) { //Copy and update the local conversation const matchingLocalConversation: Conversation = {...conversations[matchingLocalConversationIndex]}; matchingLocalConversation.localOnly = false; //Change to linked conversation (matchingLocalConversation as LinkedConversation).guid = newConversation.guid; matchingLocalConversation.members = newConversation.members; matchingLocalConversation.name = newConversation.name; //Remove local cached messages (this conversation will fetch messages from the server from now on) localMessageCache.delete(matchingLocalConversation.localID); //Update the conversation pendingConversationArray[matchingLocalConversationIndex] = matchingLocalConversation; } else { //Add the conversation sortInsertConversation(pendingConversationArray, newConversation); } //Simulate the arrival of this conversations's pending messages //to have the target conversation update properly setTimeout(() => { ConnectionManager.messageUpdateEmitter.notify(conversationItems); }); } //Update the conversations setConversations(pendingConversationArray); } } }); } //Updating conversations setConversations((conversations) => { //Ignore if we haven't loaded conversations yet if(conversations === undefined) return undefined; //Cloning the conversation array const pendingConversationArray = [...conversations]; for(const [chatID, conversationItems] of sortedConversationItems.entries()) { //Match the conversation to a local conversation const matchedConversationIndex = getConversationIndex(pendingConversationArray, chatID); if(matchedConversationIndex === -1) continue; //Filter out non-message items const conversationMessages = conversationItems.filter((item): item is MessageItem => item.itemType === ConversationItemType.Message); //Ignore if there are no message items if(conversationMessages.length === 0) continue; //Get the latest message const latestMessage = conversationMessages.reduce((lastMessage, message) => message.date > lastMessage.date ? message : lastMessage); //Create the updated conversation const updatedConversation: Conversation = { ...pendingConversationArray[matchedConversationIndex], preview: messageItemToConversationPreview(latestMessage) }; if(activeConversationID !== updatedConversation.localID && latestMessage.sender !== undefined) { updatedConversation.unreadMessages = true; } //Re-sort the conversation into the list sortInsertConversation(pendingConversationArray, updatedConversation, matchedConversationIndex); } //Applying side effects for(const conversationItem of newItems) { if(conversationItem.itemType === ConversationItemType.ParticipantAction) { //Get the targeted conversation const matchedConversationIndex = getConversationIndex(pendingConversationArray, getItemChatID(conversationItem)); if(matchedConversationIndex === -1) continue; //If we're the target, we can ignore this as we don't show up in our own copy of the member list if(conversationItem.target === undefined) continue; //Update the conversation members if(conversationItem.type === ParticipantActionType.Join) { pendingConversationArray[matchedConversationIndex] = { ...pendingConversationArray[matchedConversationIndex], members: pendingConversationArray[matchedConversationIndex].members.concat(conversationItem.target) }; } else if(conversationItem.type === ParticipantActionType.Leave) { pendingConversationArray[matchedConversationIndex] = { ...pendingConversationArray[matchedConversationIndex], members: pendingConversationArray[matchedConversationIndex].members.filter((member) => member !== conversationItem.target) }; } } else if(conversationItem.itemType === ConversationItemType.ChatRenameAction) { //Get the targeted conversation const matchedConversationIndex = getConversationIndex(pendingConversationArray, getItemChatID(conversationItem)); if(matchedConversationIndex === -1) continue; //Rename the conversation pendingConversationArray[matchedConversationIndex] = { ...pendingConversationArray[matchedConversationIndex], name: conversationItem.chatName }; } } return pendingConversationArray; }); if(interactive) { //Map the active conversation ID to a server GUID const activeConversation = conversations?.find((conversation) => conversation.localID === activeConversationID); const activeConversationGUID: string | undefined = activeConversation !== undefined && !activeConversation.localOnly ? activeConversation.guid : undefined; //Get if the window is focused const hasFocus = await wrapPromiseUnmount(getPlatformUtils().hasFocus()); //Get whether a message is received in the currently selected conversation const activeConversationUpdated = hasFocus && newItems.some((item) => { //If the new item isn't an incoming message, ignore it if(item.itemType !== ConversationItemType.Message || item.sender === undefined) { return false; } return item.chatGuid === activeConversationGUID; }); //Collect messages that should cause a notification to be displayed const notificationMessages = new Map( Array.from(sortedConversationItems.entries()).map(([chatID, messages]): [string, MessageItem[]] | undefined => { if(typeof chatID !== "string") return undefined; //Make sure this conversation is available and linked if(conversations === undefined || !conversations.some((conversation) => !conversation.localOnly && conversation.guid === chatID)) { return undefined; } //Make sure we're not displaying messages for the currently focused conversation. //in this case, we should play a sound instead if(hasFocus && chatID === activeConversationGUID) { return undefined; } //Collect outgoing messages const notificationMessages = messages.filter((message): message is MessageItem => { return message.itemType === ConversationItemType.Message && message.sender !== undefined; }); //If we have no messages, skip creating an entry if(notificationMessages.length === 0) { return undefined; } //Add the entry to the map return [ chatID, notificationMessages ]; }).filter((entry): entry is [string, MessageItem[]] => entry !== undefined) ); if(notificationMessages.size > 0) { if(hasFocus) { //If we have focus, play a notification sound playSoundNotification(); } else { //Otherwise show notifications for(const [chatGUID, messages] of notificationMessages.entries()) { //Finding the conversation const conversation = conversations?.find((conversation): conversation is LinkedConversation => !conversation.localOnly && conversation.guid === chatGUID); if(conversation === undefined) continue; //Sending a notification getNotificationUtils().showNotifications(conversation, messages); } } } else { if(activeConversationUpdated) { playSoundMessageIn(); } } } }, [wrapPromiseUnmount, activeConversationID, conversations, setConversations, pendingConversationDataMap, interactive]); //Subscribe to message updates useEffect(() => { ConnectionManager.messageUpdateEmitter.registerListener(applyUpdateMessages); return () => ConnectionManager.messageUpdateEmitter.unregisterListener(applyUpdateMessages); }, [applyUpdateMessages]); //Subscribe to modifier updates useEffect(() => { if(!interactive) return; const listener = (modifierArray: MessageModifier[]) => { //Play a tapback sound if(modifierArray.some((modifier) => isModifierTapback(modifier) && modifier.isAddition)) { playSoundTapback(); } }; modifierUpdateEmitter.registerListener(listener); return () => modifierUpdateEmitter.unregisterListener(listener); }, [interactive]); const loadConversations = useCallback((): Promise<Conversation[]> => { return wrapPromiseUnmount(ConnectionManager.fetchConversations().then((conversations) => { setConversations(conversations); return conversations; })); }, [wrapPromiseUnmount, setConversations]); //Adds a new conversation at the top of the list const addConversation = useCallback((newConversation: Conversation) => { setConversations((conversations) => { //Ignore if the conversations are still loading if(conversations === undefined) return conversations; return [newConversation].concat(conversations); }); }, [setConversations]); //Marks the conversation with the specified GUID as read const markConversationRead = useCallback((conversationID: number) => { setConversations((conversations) => { if(conversations === undefined) return conversations; //Copy the conversations array const pendingConversations = [...conversations]; //Find the conversation const conversationIndex = pendingConversations.findIndex((conversation) => !conversation.localOnly && conversation.localID === conversationID); if(conversationIndex === -1) return conversations; //Update the conversation pendingConversations[conversationIndex] = { ...pendingConversations[conversationIndex], unreadMessages: false }; return pendingConversations; }); }, [setConversations]); return { conversations, loadConversations, addConversation, markConversationRead }; } /** * Sorts a conversation into a conversation list * @param array The array of conversations to insert to * @param conversation The conversation to insert * @param existingIndex The existing index of the conversation, which if provided, * will cause the conversation at this index to be removed from the list */ function sortInsertConversation(array: Conversation[], conversation: Conversation, existingIndex?: number) { //Remove the conversation from the list if(existingIndex !== undefined) { array.splice(existingIndex, 1); } //Re-insert the conversation into the list let olderConversationIndex = array.findIndex((existingConversation) => existingConversation.preview.date < conversation.preview.date); if(olderConversationIndex === -1) olderConversationIndex = array.length; array.splice(olderConversationIndex, 0, conversation); } /** * Gets the chat ID of a conversation item, or undefined if the item has none */ function getItemChatID(conversationItem: ConversationItem): ChatID | undefined { return conversationItem.chatGuid ?? conversationItem.chatLocalID; } /** * Gets the index of the conversation with the specified ID from the conversation array */ function getConversationIndex(conversations: Conversation[], chatID: ChatID | undefined): number { if(typeof chatID === "string") { //Match GUID return conversations.findIndex((conversation) => !conversation.localOnly && conversation.guid === chatID); } else if(typeof chatID === "number") { //Match local ID return conversations.findIndex((conversation) => conversation.localID === chatID); } else { return -1; } }
the_stack
import * as chai from "chai"; import * as types from "../../src/constants/ActionTypes"; import { IDiagnostic, IInstrumentation, IVariableLocation } from "../../src/IState"; import getStore, { IObservableAppStore } from "../observableAppStore"; import IMlsClient, { IRunRequest, ICompileResponse } from "../../src/IMlsClient"; import actions from "../../src/actionCreators/actions"; import { cloneWorkspace } from "../../src/workspaces"; import { defaultWorkspace } from "../testResources"; import ServiceError from "../../src/ServiceError"; import { setWorkspace, updateWorkspaceBuffer } from "../../src/actionCreators/workspaceActionCreators"; import { getNetworkFailureClient } from "../mlsClient/getNetworkFailureClient"; import chaiExclude = require("chai-exclude"); import { IApplicationInsightsClient, NullAIClient } from "../../src/ApplicationInsights"; import { WasmCodeRunnerResponse, WasmCodeRunnerRequest } from "../../src/actionCreators/runActionCreators"; chai.use(require("deep-equal")); chai.use(chaiExclude); class ObservableAIClient implements IApplicationInsightsClient { public events: Array<{ name: string, properties?: { [key: string]: string; }, measurements?: { [key: string]: number; } }>; public dependencies: Array<{ method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, operationId?: string }>; public exceptions: Array<{ exception: Error, handledAt?: string, properties?: { [key: string]: string; }, measurements?: { [key: string]: number; }, severityLevel?: AI.SeverityLevel }>; constructor() { this.events = []; this.dependencies = []; this.exceptions = []; } public trackEvent(name: string, properties?: { [key: string]: string; }, measurements?: { [key: string]: number; }): void { this.events.push({ name, properties, measurements }); } public trackDependency(method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, operationId?: string): void { this.dependencies.push({ method, absoluteUrl, pathName, totalTime, success, resultCode, operationId }); } public trackException(exception: Error, handledAt?: string, properties?: { [key: string]: string; }, measurements?: { [key: string]: number; }, severityLevel?: AI.SeverityLevel): void { this.exceptions.push({ exception, handledAt, properties, measurements, severityLevel }); } } describe("RUN Action Creators", () => { var store: IObservableAppStore; beforeEach(() => { store = getStore(); }); it("should create an action to run", () => { const expectedAction = { type: types.RUN_CODE_REQUEST, requestId: "identifier" }; actions.runRequest("identifier").should.deep.equal(expectedAction); }); it("should create an action to process run success", () => { const expectedAction = { type: types.RUN_CODE_SUCCESS, exception: "some exception", executionStrategy: "Agent", output: ["some", "output"], succeeded: false, diagnostics: [] as IDiagnostic[], instrumentation: [] as IInstrumentation[], variableLocations: [] as IVariableLocation[] }; actions .runSuccess({ exception: "some exception", output: ["some", "output"], succeeded: false, diagnostics: [] as IDiagnostic[], instrumentation: [] as IInstrumentation[], variableLocations: [] as IVariableLocation[] }) .should.deep.equal(expectedAction); }); it("should create an action to process run success with requestId", () => { const expectedAction = { type: types.RUN_CODE_SUCCESS, exception: "some exception", executionStrategy: "Agent", output: ["some", "output"], succeeded: false, diagnostics: [] as IDiagnostic[], instrumentation: [] as IInstrumentation[], variableLocations: [] as IVariableLocation[], requestId: "TestRun" }; actions .runSuccess({ exception: "some exception", output: ["some", "output"], succeeded: false, diagnostics: [] as IDiagnostic[], instrumentation: [] as IInstrumentation[], variableLocations: [] as IVariableLocation[], requestId: "TestRun" }) .should.deep.equal(expectedAction); }); it("should create an action to process run failure", () => { var ex = new ServiceError(404, "Not Found"); const expectedAction = { type: types.RUN_CODE_FAILURE, error: { statusCode: 404, message: "Not Found", requestId: "" } }; actions.runFailure(ex).should.deep.equal(expectedAction); }); it("should create an action to record a button click", () => { const expectedAction = { type: types.RUN_CLICKED }; actions.runClicked().should.deep.equal(expectedAction); }); it("creates RUN_CODE_REQUEST and RUN_CODE_SUCCESS", async () => { const workspace = cloneWorkspace(defaultWorkspace); var sourceCode = "Console.WriteLine(\"Hello, World\");"; workspace.buffers = [{ id: "Program.cs", content: sourceCode, position: 0 }]; workspace.files = [{ name: "Program.cs", text: sourceCode }]; const expectedActions = [ actions.setWorkspace(workspace), actions.runRequest("trydotnet.client_TestRun"), actions.runSuccess({ output: ["Hello, World"], succeeded: true, }) ]; store.withDefaultClient(); store.withAiClient(new NullAIClient()); store.dispatch(actions.setWorkspace(workspace)); await store.dispatch(actions.run("trydotnet.client_TestRun")); store.getActions().should.deep.equal(expectedActions); }); it("creates RUN_CODE_REQUEST and RUN_CODE_FAILURE when fetching sourceCode from Uri fails", async () => { const expectedActions = [ actions.runRequest("trydotnet.client_TestRun"), actions.runFailure(new Error("ECONNREFUSED"), "trydotnet.client_TestRun") ]; let mockAiClient = new ObservableAIClient(); store.withClient(getNetworkFailureClient()); store.withAiClient(mockAiClient); store.configure([actions.setWorkspace(defaultWorkspace)]); await store.dispatch(actions.run("trydotnet.client_TestRun")); chai.expect(store.getActions()).excludingEvery("ex").to.deep.equal(expectedActions); chai.expect(mockAiClient.dependencies.length).to.eq(0); chai.expect(mockAiClient.events.length).to.eq(0); chai.expect(mockAiClient.exceptions.length).to.eq(1); }); it("passes activeBufferId in the RunRequest", async () => { let actualRunRequest: any = { activeBufferId: undefined }; const stubClient = { run: (args: IRunRequest): any => { actualRunRequest = args; return null; } }; let mockAiClient = new ObservableAIClient(); store.withClient(stubClient as IMlsClient); store.withAiClient(mockAiClient); store.configure([ actions.setActiveBuffer("expected"), setWorkspace(defaultWorkspace) ]); await store.dispatch(actions.run()); actualRunRequest.activeBufferId.should.deep.equal("expected"); }); it("passes additional parameters in the RunRequest", async () => { let actualRunRequest: any = { activeBufferId: undefined }; let expectedRunRequest: any = { activeBufferId: "expected", workspace: { ...defaultWorkspace }, requestId: "testRun", runArgs: "done!" }; const stubClient = { run: (args: IRunRequest): any => { actualRunRequest = args; return null; } }; let mockAiClient = new ObservableAIClient(); store.withClient(stubClient as IMlsClient); store.withAiClient(mockAiClient); store.configure([ actions.setActiveBuffer("expected"), setWorkspace(defaultWorkspace) ]); await store.dispatch(actions.run("testRun", { runArgs: "done!" })); actualRunRequest.should.deep.equal(expectedRunRequest); }); it("should create an action to compile", () => { const expectedAction = { type: types.COMPILE_CODE_REQUEST, requestId: "trydotnet.client_TestRun", workspaceVersion: 1 }; actions.compileRequest("trydotnet.client_TestRun", 1).should.deep.equal(expectedAction); }); it("should include diagnostics in compile failure", () => { const response: ICompileResponse = { base64assembly: null, diagnostics: [{ end: 0, start: 0, message: "stuff", severity: 1 }], succeeded: false }; const expectedAction = { type: types.COMPILE_CODE_FAILURE, diagnostics: response.diagnostics, workspaceVersion: 1 }; actions.compileFailure(response, 1).should.deep.equal(expectedAction); }); it("should include diagnostics and requestId in compile failure", () => { const response: ICompileResponse = { base64assembly: null, diagnostics: [{ end: 0, start: 0, message: "stuff", severity: 1 }], succeeded: false, requestId: "trydotnet.client_TestRun", }; const expectedAction = { type: types.COMPILE_CODE_FAILURE, diagnostics: response.diagnostics, requestId: "trydotnet.client_TestRun", workspaceVersion: 1 }; actions.compileFailure(response, 1).should.deep.equal(expectedAction); }); it("should include assembly in compile success", () => { const response: ICompileResponse = { base64assembly: "foo", diagnostics: [], succeeded: true }; const expectedAction = { type: types.COMPILE_CODE_SUCCESS, base64assembly: response.base64assembly, workspaceVersion: 1 }; actions.compileSuccess(response, 1).should.deep.equal(expectedAction); }); it("sends telemetry if blazor fails", async () => { const stubClient = { compile: (_args: IRunRequest): any => { return { succeeded: true }; } }; store.withClient(stubClient as IMlsClient); store.configure([ setWorkspace(defaultWorkspace), actions.setWorkspaceType("blazor-console"), actions.configureWasmRunner(), ]); let mockAiClient = new ObservableAIClient(); store.withAiClient(mockAiClient); await store.dispatch(actions.run()); let response: WasmCodeRunnerResponse = { runnerException: "bad", codeRunnerVersion: "1.0.0" }; let blazorResult = { codeRunnerVersion: "something", data: response }; store.getState().wasmRunner.callback(blazorResult); chai.expect(mockAiClient.dependencies.length).to.eq(0); chai.expect(mockAiClient.events.length).to.eq(1); chai.expect(mockAiClient.exceptions.length).to.eq(0); }); it("dispatches RUN_CODE_FAILURE if blazor compile fails", async () => { const stubClient = { compile: (_args: IRunRequest): any => { throw new Error("compiler failure!!!"); } }; store.withClient(stubClient as IMlsClient); store.configure([ setWorkspace(defaultWorkspace), actions.setWorkspaceType("blazor-console"), actions.configureWasmRunner(), ]); await store.dispatch(actions.run()); let runFailure = store.getActions().find(a => a.type === types.RUN_CODE_FAILURE); // tslint:disable-next-line:no-unused-expression-chai runFailure.should.not.be.null; }); it("dispatches RUN_CODE_SUCCESS if blazor compile fails and contains diagnostics in output", async () => { const stubClient = { compile: (_args: IRunRequest): any => { return { succeeded: false, diagnostics: [{ message: "not compiling code with typos" }] }; } }; store.withClient(stubClient as IMlsClient); store.configure([ setWorkspace(defaultWorkspace), actions.setWorkspaceType("blazor-console"), actions.configureWasmRunner(), ]); await store.dispatch(actions.run()); let runSuccess = store.getActions().find(a => a.type === types.RUN_CODE_SUCCESS); // tslint:disable-next-line:no-unused-expression-chai runSuccess.should.not.be.null; (<any>runSuccess).output.should.deep.equal(["not compiling code with typos"]); }); it("sends telemetry if blazor succeeds", async () => { const stubClient = { compile: (_args: IRunRequest): any => { return { succeeded: true }; } }; store.withClient(stubClient as IMlsClient); store.configure([ setWorkspace(defaultWorkspace), actions.setWorkspaceType("blazor-console"), actions.configureWasmRunner(), ]); let mockAiClient = new ObservableAIClient(); store.withAiClient(mockAiClient); await store.dispatch(actions.run()); let response: WasmCodeRunnerResponse = { succeeded: true, output: ["good"], codeRunnerVersion: "1.0.0" }; let blazorResult = { codeRunnerVersion: "something", data: response }; store.getState().wasmRunner.callback(blazorResult); chai.expect(mockAiClient.dependencies.length).to.eq(0); let event = mockAiClient.events.find(e => e.name === "Blazor.Success"); // tslint:disable-next-line:no-unused-expression-chai chai.expect(event).not.to.be.undefined; chai.expect(mockAiClient.exceptions.length).to.eq(0); }); it("runWithWasmRunner does not compile if the workspace hasn't changed", async () => { let compileCount = 0; const stubClient = { compile: (_args: IRunRequest): any => { compileCount += 1; return { succeeded: true }; } }; store.withClient(stubClient as IMlsClient); store.configure([ setWorkspace(defaultWorkspace), actions.setWorkspaceType("blazor-console"), actions.configureWasmRunner(), ]); chai.expect(compileCount).to.eq(0); await store.dispatch(actions.run()); chai.expect(compileCount).to.eq(1); await store.dispatch(actions.run()); chai.expect(compileCount).to.eq(1); }); it("runWithWasmRunner compiles if the workspace has changed", async () => { let compileCount = 0; const stubClient = { compile: (_args: IRunRequest): any => { compileCount += 1; return { succeeded: true }; } }; store.withClient(stubClient as IMlsClient); store.configure([ setWorkspace(defaultWorkspace), actions.setWorkspaceType("blazor-console"), actions.configureWasmRunner(), ]); chai.expect(compileCount).to.eq(0); await store.dispatch(actions.run()); chai.expect(compileCount).to.eq(1); store.dispatch(updateWorkspaceBuffer("foo", "Program.cs")); await store.dispatch(actions.run()); chai.expect(compileCount).to.eq(2); }); it("runWithWasmRunner passes additional parameters in the RunRequest", async () => { const stubClient = { compile: (args: IRunRequest): any => { return { requestId: args.requestId, succeeded: true }; } }; store.withClient(stubClient as IMlsClient); store.configure([ setWorkspace(defaultWorkspace), actions.setWorkspaceType("blazor-console"), actions.configureWasmRunner(), ]); let mockAiClient = new ObservableAIClient(); store.withAiClient(mockAiClient); await store.dispatch(actions.run("testRun", { runArgs: "done!" })); let response: WasmCodeRunnerResponse = { succeeded: true, output: ["good"], codeRunnerVersion: "1.0.0" }; let blazorResult = { codeRunnerVersion: "something", data: response }; store.getState().wasmRunner.callback(blazorResult); chai.expect(mockAiClient.dependencies.length).to.eq(0); let event = mockAiClient.events.find(e => e.name === "Blazor.Success"); let wasmRunRequestAction = store.getActions().find(a => a.type === types.SEND_WASMRUNNER_MESSAGE); // tslint:disable-next-line:no-unused-expression-chai chai.expect(wasmRunRequestAction).not.to.be.undefined; // tslint:disable-next-line:no-unused-expression-chai chai.expect(event).not.to.be.undefined; chai.expect(mockAiClient.exceptions.length).to.eq(0); let request: WasmCodeRunnerRequest = <WasmCodeRunnerRequest>((<any>wasmRunRequestAction).payload); request["runArgs"].should.be.equal("done!"); }); });
the_stack
import i18next from 'i18next'; import _ from 'lodash'; import { ControlResponseBuilder } from '../..'; import { ControlInput } from '../../controls/ControlInput'; import { assert } from '../../utils/AssertionUtils'; import { AplContent, MultiValueListAPLComponentProps, MultiValueListControl } from './MultiValueListControl'; /* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ export namespace MultiValueListControlAPLPropsBuiltIns { export interface DefaultSelectValueAPLProps { /** * Default: 'Create your list' */ title?: string; /** * Default (en-*): 'Done;' */ submitButtonText?: string; /** * Default: 'Say an item or touch it to add it your list' */ subtitle?: string; /** * Default: 'YOUR SELECTIONS' */ selectionListTitle?: string; /** * Default: 'Swipe left to remove items' */ selectionListSubtitle?: string; /** * Whether debug information is displayed * * Default: false */ debug?: boolean; /** * Function that maps the MultiValueListControlState.value to rendered value that * will be presented to the user as a list. * * Default: returns the value unchanged. */ valueRenderer: (choice: string, input: ControlInput) => string; } export function defaultSelectValueAPLContent( props: DefaultSelectValueAPLProps, ): (control: MultiValueListControl, input: ControlInput) => AplContent { return (control: MultiValueListControl, input: ControlInput) => { return { document: multiValueListDocumentGenerator(control, input), dataSource: multiValueListDataSourceGenerator(control, input, props), }; }; } /** * The APL dataSource to use when requesting a value * * Default: A TextListLayout data source to bind to an APL document. * See * https://developer.amazon.com/en-US/docs/alexa/alexa-presentation-language/apl-data-source.html */ export function multiValueListDataSourceGenerator( control: MultiValueListControl, input: ControlInput, contentProps: DefaultSelectValueAPLProps, ) { const listOfChoices = []; const selectedChoices = []; const choices = control.getChoicesList(input); for (const item of choices) { listOfChoices.push({ primaryText: contentProps.valueRenderer(item, input), }); } const selections = control.getSlotIds(); for (const item of selections) { selectedChoices.push({ primaryText: contentProps.valueRenderer(item, input), }); } return { general: { headerTitle: contentProps.title ?? i18next.t('MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_HEADER_TITLE'), headerSubtitle: contentProps.subtitle ?? i18next.t('MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_HEADER_SUBTITLE'), selectionListTitle: contentProps.selectionListTitle ?? i18next.t('MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_SELECTION_TITLE'), selectionListSubtitle: contentProps.selectionListSubtitle ?? i18next.t('MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_SELECTION_SUBTITLE'), controlId: control.id, }, choices: { listItems: listOfChoices, }, selections: { listItems: selectedChoices, }, }; } /** * The APL document to use when selecting a value * * Default: A dual-TextListLayout document one with scrollable and clickable list and another with swipeAction to remove items from list. * See * https://developer.amazon.com/en-US/docs/alexa/alexa-presentation-language/apl-alexa-text-list-layout.html */ export function multiValueListDocumentGenerator(control: MultiValueListControl, input: ControlInput) { return { type: 'APL', version: '1.5', import: [ { name: 'alexa-layouts', version: '1.2.0', }, ], layouts: {}, mainTemplate: { parameters: ['payload'], items: [ { type: 'Container', width: '100%', id: 'root', bind: [ { name: 'debugText', type: 'string', value: 'debugValue', }, { name: 'disableScreen', type: 'boolean', value: false, }, { name: 'showDebug', type: 'boolean', value: false, }, ], items: [ { type: 'AlexaBackground', }, { type: 'AlexaHeader', headerDivider: true, headerTitle: '${payload.general.headerTitle}', headerSubtitle: '${payload.general.headerSubtitle}', height: '20vh', }, { type: 'AlexaButton', buttonText: 'Done', id: 'actionComplete', primaryAction: { type: 'Sequential', commands: [ { type: 'SendEvent', arguments: ['${payload.general.controlId}', 'Complete'], }, { type: 'SetValue', componentId: 'root', property: 'disableScreen', value: true, }, { type: 'SetValue', componentId: 'root', property: 'debugText', value: 'Done Selected', }, ], }, right: '@marginHorizontal', top: "${@viewportProfile == @hubLandscapeSmall ? '1vw' : '2vw'}", position: 'absolute', }, { type: 'Text', id: 'DebugText', text: '${debugText}', display: "${showDebug ? 'normal' : 'invisible'}", position: 'absolute', right: '0vw', }, { type: 'Container', paddingRight: '@marginHorizontal', paddingTop: '@spacingSmall', direction: 'row', width: '100%', shrink: 1, items: [ { type: 'Container', width: '55%', height: '80vh', items: [ { type: 'Sequence', scrollDirection: 'vertical', data: '${payload.choices.listItems}', width: '100%', paddingLeft: '0', numbered: true, grow: 1, items: [ { type: 'Container', items: [ { type: 'AlexaTextListItem', touchForward: true, disabled: '${disableScreen}', primaryText: '${data.primaryText}', primaryAction: { type: 'Sequential', commands: [ { type: 'SendEvent', arguments: [ '${payload.general.controlId}', 'Select', '${ordinal}', ], }, { type: 'SetValue', componentId: 'root', property: 'disableScreen', value: true, }, { type: 'SetValue', componentId: 'root', property: 'debugText', value: 'selected ${ordinal}', }, ], }, }, ], }, ], }, ], }, { type: 'Container', width: '55%', height: '80vh', items: [ { type: 'AlexaBackground', backgroundColor: 'white', }, { type: 'Text', style: 'textStyleMetadata', color: 'black', textAlign: 'center', textAlignVertical: 'center', maxLines: 1, paddingTop: '@spacingXSmall', text: '${payload.general.selectionListTitle}', }, { type: 'Text', style: 'textStyleMetadataAlt', color: 'black', textAlign: 'center', textAlignVertical: 'center', maxLines: 1, text: '${payload.general.selectionListSubtitle}', }, { type: 'Sequence', scrollDirection: 'vertical', data: '${payload.selections.listItems}', width: '100%', paddingLeft: '0', numbered: true, grow: 1, items: [ { type: 'Container', items: [ { type: 'AlexaSwipeToAction', touchForward: true, hideOrdinal: true, theme: 'light', actionIconType: 'AVG', actionIcon: 'cancel', actionIconBackground: 'red', disabled: '${disableScreen}', primaryText: '${data.primaryText}', onSwipeDone: { type: 'Sequential', commands: [ { type: 'SendEvent', arguments: [ '${payload.general.controlId}', 'Remove', '${ordinal}', ], }, { type: 'SetValue', componentId: 'root', property: 'disableScreen', value: true, }, { type: 'SetValue', componentId: 'root', property: 'debugText', value: 'removed ${ordinal}', }, ], }, }, ], }, ], }, ], }, ], }, ], }, ], }, graphics: { cancel: { type: 'AVG', version: '1.0', width: 24, height: 24, parameters: ['fillColor'], items: [ { type: 'path', fill: '${fillColor}', pathData: 'M19.07 17.66L13.41 12l5.66-5.66C19.41 5.94 19.39 5.35 19.02 4.98 18.65 4.61 18.06 4.59 17.66 4.93L12 10.59 6.34 4.93C5.94 4.59 5.35 4.61 4.98 4.98 4.61 5.35 4.59 5.94 4.93 6.34L10.59 12l-5.66 5.66C4.64 17.9 4.52 18.29 4.61 18.65 4.7 19.02 4.98 19.3 5.35 19.39 5.71 19.48 6.1 19.36 6.34 19.07L12 13.41l5.66 5.66C18.06 19.41 18.65 19.39 19.02 19.02 19.39 18.65 19.41 18.06 19.07 17.66z', }, ], }, }, }; } } /** * Namespace which define built-in renderers for APL Component Mode. */ export namespace MultiValueListControlComponentAPLBuiltIns { /** * Function which returns an APL component using AlexaCheckbox Layout. * * @param control - MultiValueListControl * @param props - Control context props e.g valueRenderer * @param input - Input * @param resultBuilder - Result builder */ export function renderCheckBoxComponent( control: MultiValueListControl, props: MultiValueListAPLComponentProps, input: ControlInput, resultBuilder: ControlResponseBuilder, ) { assert(props.valueRenderer !== undefined); resultBuilder.addAPLDocumentLayout('MultiValueListSelector', { parameters: [ { name: 'controlId', type: 'string', }, { name: 'listItems', type: 'object', }, ], items: [ { type: 'Sequence', scrollDirection: 'vertical', data: '${listItems}', width: '100%', height: '100%', paddingLeft: '0', numbered: true, items: [ { type: 'Container', items: [ { type: 'TouchWrapper', disabled: '${disabled}', item: { type: 'Container', direction: 'row', items: [ { type: 'Text', paddingLeft: '32px', style: 'textStyleBody', text: '${data.primaryText}', textAlignVertical: 'center', grow: 1, }, { type: 'AlexaCheckbox', id: '${checkboxId}', checkboxHeight: '64px', checkboxWidth: '64px', selectedColor: '${selectedColor}', checked: '${data.checked}', disabled: '${disabled}', onPress: [ { type: 'Sequential', commands: [ { type: 'SendEvent', arguments: [ '${controlId}', 'Toggle', '${ordinal}', ], }, { type: 'SetValue', componentId: 'root', property: 'disableScreen', value: true, }, { type: 'SetValue', componentId: 'root', property: 'debugText', value: 'Selected ${ordinal}', }, ], }, ], }, ], }, onPress: [ { type: 'Sequential', commands: [ { type: 'SendEvent', arguments: ['${controlId}', 'Toggle', '${ordinal}'], }, { type: 'SetValue', componentId: 'root', property: 'disableScreen', value: true, }, { type: 'SetValue', componentId: 'root', property: 'debugText', value: 'Selected ${ordinal}', }, ], }, ], }, ], }, ], }, ], }); const listItems: Array<{ primaryText: string; checked: boolean; }> = []; const choices = control.getChoicesList(input); for (const item of choices) { listItems.push({ primaryText: props.valueRenderer([item], input)[0], checked: control.getSlotIds().includes(item), }); } return { type: 'MultiValueListSelector', controlId: control.id, listItems, }; } /** * Function which returns an APL component using dualTextList Layout. * * @param control - MultiValueListControl * @param props - Control context props e.g valueRenderer * @param input - Input * @param resultBuilder - Result builder */ export function dualTextListComponent( control: MultiValueListControl, props: MultiValueListAPLComponentProps, input: ControlInput, resultBuilder: ControlResponseBuilder, ) { assert(props.valueRenderer !== undefined); resultBuilder.addAPLDocumentLayout('MultiValueListSelector', { parameters: [ { name: 'controlId', type: 'string', }, { name: 'payload', type: 'object', }, ], items: [ { type: 'Container', direction: 'row', width: '100%', height: '100%', items: [ { type: 'Container', width: '50%', items: [ { type: 'Sequence', data: '${payload.choices.listItems}', numbered: true, grow: 1, paddingLeft: '10px', items: [ { type: 'AlexaTextListItem', hideHorizontalMargin: true, primaryText: '${data.primaryText}', primaryAction: { type: 'Sequential', commands: [ { type: 'SetValue', componentId: 'root', property: 'debugText', value: '${ordinal}', }, { type: 'SendEvent', arguments: [ '${payload.general.controlId}', 'Select', '${ordinal}', ], }, ], }, touchForward: true, }, ], }, ], }, { type: 'Container', width: '50%', items: [ { type: 'AlexaBackground', backgroundColor: 'white', }, { type: 'Text', style: 'textStyleMetadata', color: 'black', textAlign: 'center', textAlignVertical: 'center', maxLines: 1, paddingTop: '@spacingXSmall', text: '${payload.general.selectionListTitle}', }, { type: 'Text', style: 'textStyleMetadataAlt', color: 'black', textAlign: 'center', textAlignVertical: 'center', maxLines: 1, text: '${payload.general.selectionListSubtitle}', }, { type: 'Sequence', scrollDirection: 'vertical', data: '${payload.selections.listItems}', numbered: true, grow: 1, items: [ { type: 'Container', items: [ { type: 'AlexaSwipeToAction', touchForward: true, hideOrdinal: true, theme: 'light', actionIconType: 'AVG', actionIcon: 'cancel', actionIconBackground: 'red', primaryText: '${data.primaryText}', onSwipeDone: { type: 'Sequential', commands: [ { type: 'SetValue', componentId: 'root', property: 'debugText', value: '${ordinal}', }, { type: 'SendEvent', arguments: [ '${payload.general.controlId}', 'Remove', '${ordinal}', ], }, ], }, }, ], }, ], }, ], }, ], }, ], }); const listOfChoices = []; const selectedChoices = []; const choices = control.getChoicesList(input); for (const item of choices) { listOfChoices.push({ primaryText: props.valueRenderer([item], input)[0], }); } const selections = control.getSlotIds(); for (const item of selections) { selectedChoices.push({ primaryText: props.valueRenderer([item], input)[0], }); } const payload = { general: { headerTitle: i18next.t('MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_HEADER_TITLE'), headerSubtitle: i18next.t('MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_HEADER_SUBTITLE'), selectionListTitle: i18next.t('MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_SELECTION_TITLE'), selectionListSubtitle: i18next.t('MULTI_VALUE_LIST_CONTROL_DEFAULT_APL_SELECTION_SUBTITLE'), controlId: control.id, }, choices: { listItems: listOfChoices, }, selections: { listItems: selectedChoices, }, }; return { type: 'MultiValueListSelector', controlId: control.id, payload, }; } /** * Function which returns an APL component using AlexaIconButton Layout * providing increment/decrement buttons for listItems. * * @param control - MultiValueListControl * @param props - Control context props e.g valueRenderer * @param input - Input * @param resultBuilder - Result builder */ export function aggregateDuplicatesComponent( control: MultiValueListControl, props: MultiValueListAPLComponentProps, input: ControlInput, resultBuilder: ControlResponseBuilder, ) { assert(props.valueRenderer !== undefined); resultBuilder.addAPLDocumentLayout('MultiValueListSelector', { parameters: [ { name: 'controlId', type: 'string', }, { name: 'listItems', type: 'object', }, ], items: [ { type: 'Sequence', id: 'root', scrollDirection: 'vertical', data: '${listItems}', width: '100%', height: '100%', paddingLeft: '0', numbered: true, bind: [ { name: 'disableContent', value: false, type: 'boolean', }, ], items: [ { type: 'Container', items: [ { type: 'TouchWrapper', disabled: '${disabled}', item: { type: 'Container', direction: 'row', items: [ { type: 'Text', paddingLeft: '32px', style: 'textStyleBody', text: '${data.primaryText}', textAlignVertical: 'center', grow: 1, }, { type: 'Text', paddingTop: '12px', id: 'counter-${ordinal}', textAlign: 'center', text: '${data.value}', }, { type: 'AlexaIconButton', buttonSize: '72dp', disabled: '${disableContent}', vectorSource: 'M21 11h-8V3C13 2.45 12.55 2 12 2 11.45 2 11 2.45 11 3v8H3C2.45 11 2 11.45 2 12 2 12.55 2.45 13 3 13h8v8C11 21.55 11.45 22 12 22 12.55 22 13 21.55 13 21v-8h8C21.55 13 22 12.55 22 12 22 11.45 21.55 11 21 11z', primaryAction: { type: 'Sequential', commands: [ { type: 'SetValue', property: 'disableContent', value: true, }, { type: 'SendEvent', arguments: [ '${controlId}', 'Select', '${ordinal}', ], }, ], }, }, { type: 'AlexaIconButton', buttonSize: '72dp', disabled: '${data.value <=0 || disableContent}', vectorSource: 'M21 13H3C2.45 13 2 12.55 2 12 2 11.45 2.45 11 3 11h18C21.55 11 22 11.45 22 12 22 12.55 21.55 13 21 13z', primaryAction: { type: 'Sequential', commands: [ { type: 'SetValue', property: 'disableContent', value: true, }, { type: 'SendEvent', arguments: [ '${controlId}', 'Reduce', '${ordinal}', ], }, ], }, }, ], }, onPress: [ { type: 'Sequential', commands: [ { type: 'SetValue', property: 'disableContent', value: true, }, { type: 'SendEvent', arguments: ['${controlId}', 'Select', '${ordinal}'], }, ], }, ], }, ], }, ], }, ], }); const listItems: Array<{ primaryText: string; value: number; }> = []; const aggregateValues: { [key: string]: any } = {}; const selections = control.getSlotIds(); selections.forEach((x) => { aggregateValues[x] = (aggregateValues[x] ?? 0) + 1; }); const choices = control.getChoicesList(input); for (const item of choices) { listItems.push({ primaryText: props.valueRenderer([item], input)[0], value: aggregateValues[item] ?? 0, }); } return { type: 'MultiValueListSelector', controlId: control.id, listItems, }; } /** * Defines DualTextListRenderer for APLComponentMode. */ export class DualTextListRender { /** * Provides a default implementation of dualTextList with default props. * * @param control - ListControl * @param defaultProps - props * @param input - Input * @param resultBuilder - Result builder */ static default = ( control: MultiValueListControl, defaultProps: MultiValueListAPLComponentProps, input: ControlInput, resultBuilder: ControlResponseBuilder, ) => dualTextListComponent(control, defaultProps, input, resultBuilder); /** * Provides customization over `dualTextListComponent()` arguments where the input * props overrides the defaults. * * @param props - props */ static of(props: MultiValueListAPLComponentProps) { return ( control: MultiValueListControl, defaultProps: MultiValueListAPLComponentProps, input: ControlInput, resultBuilder: ControlResponseBuilder, ) => { // Merges the user-provided props with the default props. // Any property defined by the user-provided data overrides the defaults. const mergedProps = _.merge(defaultProps, props); return dualTextListComponent(control, mergedProps, input, resultBuilder); }; } } /** * Defines CheckBoxRenderer for APLComponentMode. * * Provides methods to render APL components using AlexaCheckbox layouts. */ export class CheckBoxRenderer { /** * Provides a default implementation of CheckBox-textList with default props. * * @param control - ListControl * @param defaultProps - props * @param input - Input * @param resultBuilder - Result builder */ static default = ( control: MultiValueListControl, defaultProps: MultiValueListAPLComponentProps, input: ControlInput, resultBuilder: ControlResponseBuilder, ) => renderCheckBoxComponent(control, defaultProps, input, resultBuilder); /** * Provides customization over `renderCheckBoxComponent()` arguments where the input * props overrides the defaults. * * @param props - props */ static of(props: MultiValueListAPLComponentProps) { return ( control: MultiValueListControl, defaultProps: MultiValueListAPLComponentProps, input: ControlInput, resultBuilder: ControlResponseBuilder, ) => { // Merges the user-provided props with the default props. // Any property defined by the user-provided data overrides the defaults. const mergedProps = _.merge(defaultProps, props); return renderCheckBoxComponent(control, mergedProps, input, resultBuilder); }; } } /** * Defines AggregateDuplicatesRenderer for APLComponentMode. * * Provides methods to render APL components using AlexaIconButton layouts. */ export class AggregateDuplicatesRenderer { /** * Provides a default implementation of aggregateDuplicates-textList with default props. * * Usage: * - This is used to render list items where duplicates counts of item selections * are allowed. * - Returns a textList layout with increment and decrement alexaIcons on each listItem. * * @param control - ListControl * @param defaultProps - props * @param input - Input * @param resultBuilder - Result builder */ static default = ( control: MultiValueListControl, defaultProps: MultiValueListAPLComponentProps, input: ControlInput, resultBuilder: ControlResponseBuilder, ) => aggregateDuplicatesComponent(control, defaultProps, input, resultBuilder); /** * Provides customization over `aggregateDuplicatesComponent()` arguments where the input * props overrides the defaults. * * @param props - props */ static of(props: MultiValueListAPLComponentProps) { return ( control: MultiValueListControl, defaultProps: MultiValueListAPLComponentProps, input: ControlInput, resultBuilder: ControlResponseBuilder, ) => { // Merges the user-provided props with the default props. // Any property defined by the user-provided data overrides the defaults. const mergedProps = _.merge(defaultProps, props); return aggregateDuplicatesComponent(control, mergedProps, input, resultBuilder); }; } } }
the_stack
import { Component, OnInit } from '@angular/core'; import * as $ from 'jquery'; import * as Raphael from 'raphael'; import 'jqueryui'; import { RecordingService } from '../message/recording/recording.service'; import { Recording } from '../message/recording/recording'; import { Extension } from '../extension/extension'; import { ExtensionService } from '../extension/extension.service'; import { IVRService } from './ivr.service'; import { start_app } from './start'; import { answer_app } from './answer'; import { hangup_app } from './hangup'; import { input_app } from './input'; import { voicePlay_app } from './voice_play'; import { transfer_app } from './transfer'; import { record_app } from './record'; import { play_menu_app } from './play_menu'; import { amd_app } from './amd'; import { dnc_app } from './dnc'; import { tts_app } from './tts'; import { say_alpha_app } from './say_alpha'; import { say_digit_app } from './say_digit'; import { say_number_app } from './say_number'; import { say_date_app } from './say_date'; import { say_time_app } from './say_time'; import { callerid_set_app } from './callerid_set'; import { IVR } from './ivr'; import { ActivatedRoute, Router } from '@angular/router'; export let total_apps = {}; @Component({ selector: 'ngx-add-ivr-component', styleUrls: ['./ivr-form-component.scss'], templateUrl: './ivr-form-component.html', }) export class AddIVRComponent implements OnInit { public static canvasWidth= 9000; public static canvasHeight= 360; public static r: any; public static currEditInd: any; //Define Div public static voice_play_form: any; public static call_transfer_form: any; public static record_form: any; public static play_ivr_menu_form: any; public static tts_form: any; public static say_alpha_form: any; public static say_digit_form: any; public static say_number_form: any; public static say_date_form: any; public static say_time_form: any; public static caller_id_form: any; //Define Forms all_apps = []; //Define edit form data recording: Recording[] = []; public selectedRec: Recording; extension: Extension[] = []; SelectedExt: Extension; program_id: any = null; ivr: IVR = new IVR(); classesMapping = { 'start': start_app, 'answer': answer_app, 'hangup': hangup_app, 'disconnect': hangup_app, 'input': input_app, 'voice_play': voicePlay_app, 'transfer': transfer_app, 'record': record_app, 'play_menu': play_menu_app, 'amd': amd_app, 'dnc': dnc_app, 'tts': tts_app, 'say_alpha': say_alpha_app, 'say_digit': say_digit_app, 'say_number': say_number_app, 'say_date': say_date_app, 'say_time': say_time_app, 'callerid_set': callerid_set_app, }; menu = [{name : 'Enter Manually'}, {name: '[contact:first_name]' , value: '[contact:first_name]'}, {name: '[contact:last_name]' , value: '[contact:last_name]'}, {name: '[contact:phone]' , value: '[contact:phone]'}, { name: '[contact:email]', value: '[contact:email]'}, { name: '[contact:address]', value: '[contact:address]'}, { name: '[contact:custom1]', value: '[contact:custom1]'}, { name: '[contact:custom2]', value: '[contact:custom2]'}, { name: '[contact:custom3]', value: '[contact:custom3]'}, { name: '[contact:description]', value: '[contact:description]'}]; constructor(private recording_service: RecordingService , private extension_service: ExtensionService, private ivr_service: IVRService , private route: ActivatedRoute, private router: Router) { } ngOnInit() { AddIVRComponent.r = Raphael('holder', AddIVRComponent.canvasWidth, AddIVRComponent.canvasHeight); this.route.params.subscribe(params => { this.program_id = +params['id']; const test_url = this.router.url.split('/'); const lastsegment = test_url[test_url.length - 1]; if (lastsegment === 'new') { this.createStartApplication(); return null; } else { return this.ivr_service.get_ivrData(this.program_id).then(data => { this.ivr = data; const ivr_scheme = JSON.parse(this.ivr.ivr_scheme); this.load_ivr_data(ivr_scheme); }); } }); this.getRecordinglist(); this.getExtlist(); } ngAfterContentInit() { // Initialize all Divs AddIVRComponent.voice_play_form = $('#voice_play_form'); AddIVRComponent.call_transfer_form = $('#call_transfer_form'); AddIVRComponent.record_form = $('#record_form'); AddIVRComponent.play_ivr_menu_form = $('#play_ivr_menu_form'); AddIVRComponent.tts_form = $('#tts_form'); AddIVRComponent.say_alpha_form = $('#say_alpha_form'); AddIVRComponent.say_digit_form = $('#say_digit_form'); AddIVRComponent.say_number_form = $('#say_number_form'); AddIVRComponent.say_date_form = $('#say_date_form'); AddIVRComponent.say_time_form = $('#say_time_form'); AddIVRComponent.caller_id_form = $('#caller_id_form'); // Hide all Divs AddIVRComponent.voice_play_form.hide(); AddIVRComponent.call_transfer_form.hide(); AddIVRComponent.record_form.hide(); AddIVRComponent.play_ivr_menu_form.hide(); AddIVRComponent.tts_form.hide(); AddIVRComponent.say_alpha_form.hide(); AddIVRComponent.say_digit_form.hide(); AddIVRComponent.say_number_form.hide(); AddIVRComponent.say_date_form.hide(); AddIVRComponent.say_time_form.hide(); AddIVRComponent.caller_id_form.hide(); // Dragging on icon $('#answer-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'answer'); }, }, ); $('#hangup-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'hangup'); }, }, ); $('#input-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'input'); }, }, ); $('#voice_play-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'voice_play'); }, }, ); $('#transfer-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'transfer'); }, }, ); $('#record-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'record'); }, }, ); $('#play_menu-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'play_menu'); }, }, ); $('#amd-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'amd'); }, }, ); $('#dnc-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'dnc'); }, }, ); $('#tts-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'tts'); }, }, ); $('#say_alpha-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'say_alpha'); }, }, ); $('#say_digit-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'say_digit'); }, }, ); $('#say_number-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'say_number'); }, }, ); $('#say_date-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'say_date'); }, }, ); $('#say_time-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'say_time'); }, }, ); $('#callerid_set-icon').draggable( { opacity: 0.5, helper: 'clone', stop: (event, ui) => { this.onDraggableStop(event, ui, 'callerid_set'); }, }, ); } createStartApplication() { this.createApplication('start', 20, 20); } onDraggableStop(event, ui, action) { const screenX = parseInt( ui.offset.left ); const screenY = parseInt( ui.offset.top ); let left = 0; let top = 0; left = screenX - $('#holder').offset().left + $('#holder').scrollLeft(); top = screenY - $('#holder').offset().top + $('#holder').scrollTop(); if (left > 0 && top > 0 && left < AddIVRComponent.canvasWidth && top < AddIVRComponent.canvasHeight) { this.createApplication(action, left, top); } } createApplication(action, left, top) { const new_index = 'app_' + this.all_apps.length; const newApp = this.loadClass(new_index, action, left, top); this.all_apps.push(newApp); total_apps[new_index] = newApp; } // GET all recordings getRecordinglist() { this.recording_service.get_RecordingList().then(data => { this.recording = data; }); } getExtlist() { this.extension_service.get_ExtensionList().then(data => { this.extension = data; }); } loadClass(new_index, action, left, top) { const app = new this.classesMapping[action](new_index, left, top); app.setup(); return app; } saveIVRData() { const serApps = {}; for (const i in total_apps) { serApps[i] = {}; serApps[i]['app_index'] = total_apps[i].app_index; serApps[i]['type'] = total_apps[i].type; serApps[i]['data'] = total_apps[i].data; serApps[i]['resources'] = total_apps[i].resources; if (total_apps[i].type === 'say_time' || total_apps[i].type === 'say_alpha' || total_apps[i].type === 'say_digit' || total_apps[i].type === 'say_number' || total_apps[i].type === 'say_date' || total_apps[i].type === 'say_time' || total_apps[i].type === 'callerid_set' ) { if (total_apps[i].type.includes('say_')) { // Found world var trim_type = total_apps[i].type.replace(/say_/g,''); } else if (total_apps[i].type.includes('_set')) { // Found world var trim_type = total_apps[i].type.replace(/_set/g,''); } const prop_name = trim_type; const prop_name_variable = total_apps[i].type + '_variable'; if (total_apps[i]['data'][prop_name] === 'undefined' || total_apps[i]['data'][prop_name] === undefined) { serApps[i]['data'][prop_name] = serApps[i]['data'][prop_name_variable]; delete serApps[i]['data'][prop_name_variable]; } else { delete serApps[i]['data'][prop_name_variable]; } } // serialize image // NOTE: While unserializing, add imageHandler events for this image const node = total_apps[i].app_img; if (node && node.type == 'image') { var object_1 = { type: node.type, width: node.attrs['width'], height: node.attrs['height'], x: node.attrs['x'], y: node.attrs['y'], src: node.attrs['src'], title: node.attrs['title'], cursor: node.attrs['cursor'], transform: node.transformations ? node.transformations.join(' ') : '', }; } serApps[i]['x'] = object_1.x; serApps[i]['y'] = object_1.y; serApps[i]['img_title'] = object_1.title; ////////////////////////////////////////////////////////////// //serialize nodeIn const in_nod = []; for (let j = 0; j < total_apps[i].in_nod.length; j++) { in_nod[j] = {}; in_nod[j]['node_type'] = 'input'; in_nod[j]['app_index'] = total_apps[i].app_index; const pointers = []; if (total_apps[i].in_nod[j].pointers.length > 0) { for (let k = 0; k < total_apps[i].in_nod[j].pointers.length; k++ ) { pointers[k] = {}; pointers[k]['parent_app_index'] = total_apps[i].in_nod[j].pointers[k].parent_app_index; pointers[k]['pointer_index'] = total_apps[i].in_nod[j].pointers[k].pointer_index; pointers[k]['linked_app_index'] = total_apps[i].in_nod[j].pointers[k].linked_app_index; pointers[k]['data'] = total_apps[i].in_nod[j].pointers[k].data; } in_nod[j].pointers = pointers; } } serApps[i].in_nod = in_nod; //end nodeIn ////////////////////////////////////////////////////////////// //serialize nodeOut //NOTE: while unserializing, add appConnections with outPointer const out_nod = []; for (let n = 0; n < total_apps[i].out_nod.length; n++) { out_nod[n] = {}; // nodeOut properties out_nod[n]['node_type'] = total_apps[i].out_nod[n].node_type; const object_10 = { 'parent_app_index': total_apps[i].out_nod[n].pointer.parent_app_index, 'linked_app_index': total_apps[i].out_nod[n].pointer.linked_app_index, }; out_nod[n].pointer = object_10; } serApps[i].out_nod = out_nod; //end nodeOut } const json = JSON.stringify(serApps); this.ivr.ivr_scheme = json; } postIVRData() { this.saveIVRData(); this.ivr_service.add_IVR(this.ivr).then(response => { this.router.navigate(['../../ivr'], {relativeTo: this.route}); }); } updateIVRData() { this.saveIVRData(); this.ivr_service.update_ivrData(this.ivr).then(response => { this.router.navigate(['../../ivr'], {relativeTo: this.route}); }); } load_ivr_data(ivr_data) { const re_app = ivr_data; if (re_app != null) { for (const k in re_app) { const newApp = this.loadClass(re_app[k].app_index, re_app[k].type, re_app[k].x, re_app[k].y); this.all_apps.push(newApp); total_apps[k] = newApp; } for (const k in re_app) { //Restore data for apps if (re_app[k].type == 'say_time' || re_app[k].type == 'callerid_set' || re_app[k].type == 'say_alpha' || re_app[k].type == 'say_date' || re_app[k].type == 'say_digit' || re_app[k].type == 'say_number') { if (re_app[k].type.includes('say_')) { // Found world var trim_type = re_app[k].type.replace(/say_/g,''); } else if (re_app[k].type.includes('_set')) { // Found world var trim_type = re_app[k].type.replace(/_set/g,''); } const prop_name = trim_type; const prop_name_variable = re_app[k].type + '_variable'; if (re_app[k]['data'][prop_name] != '[contact:first_name]' && re_app[k]['data'][prop_name] != '[contact:last_name]' && re_app[k]['data'][prop_name] != '[contact:phone]' && re_app[k]['data'][prop_name] != '[contact:email]' && re_app[k]['data'][prop_name] != '[contact:address]' && re_app[k]['data'][prop_name] != '[contact:description]' && re_app[k]['data'][prop_name] != '[contact:custom1]' && re_app[k]['data'][prop_name] != '[contact:custom2]' && re_app[k]['data'][prop_name] != '[contact:custom3]') { re_app[k]['data'][prop_name_variable] = re_app[k]['data'][prop_name]; re_app[k]['data'][prop_name] = 'undefined'; } else { re_app[k]['data'][prop_name_variable] = ''; } } // Restore data total_apps[k].restoreData(re_app[k].data); total_apps[k].restoreTooltip(re_app[k].img_title); //Restore Resources if (re_app[k].type == 'voice_play' || re_app[k].type == 'play_menu' || re_app[k].type == 'transfer') { total_apps[k].restoreResources(re_app[k].resources); } // Restore Pointers for (let i = 0; i < total_apps[k].out_nod.length; i++) { total_apps[k].out_nod[i].pointer.restorePointer(re_app[k].out_nod[i]); } //Hide all forms AddIVRComponent.voice_play_form.hide(); AddIVRComponent.call_transfer_form.hide(); AddIVRComponent.record_form.hide(); AddIVRComponent.play_ivr_menu_form.hide(); AddIVRComponent.tts_form.hide(); AddIVRComponent.say_alpha_form.hide(); AddIVRComponent.say_digit_form.hide(); AddIVRComponent.say_number_form.hide(); AddIVRComponent.say_date_form.hide(); AddIVRComponent.say_time_form.hide(); AddIVRComponent.caller_id_form.hide(); for (const k in total_apps) { total_apps[k].image_border.attr({'opacity': 0}); total_apps[k].removeBtnBack.attr({'fill-opacity': 100, 'fill': 'white', 'opacity': 0}); total_apps[k].removeBtnText.attr({font: '11px Arial', 'text-anchor': 'start', 'fill': 'black', 'cursor': 'pointer', 'opacity': 0}); } } } } }
the_stack
import {Test, T, A} from '../sources' const {checks, check} = Test // /////////////////////////////////////////////////////////////////////////////////////// // LIST ///////////////////////////////////////////////////////////////////////////////// type T = [ 1, 2, '3' | undefined, 'xxxx', {a: 'a'} & {b: 'b'}, string | number, number, object, readonly [0, 1, 2?], 'xxxx'? ]; type T1 = [ 1, 2, '3', 'xxxx', string, number, number & {}, object, readonly [0, 1, 2?, 3?], {a: never}, 'xxxx'? ]; // --------------------------------------------------------------------------------------- // APPEND checks([ check<T.Append<[0, 1, 2, 3], 4>, [0, 1, 2, 3, 4], Test.Pass>(), check<T.Append<[0, 1, 2, 3], [4, 5]>, [0, 1, 2, 3, [4, 5]], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // ASSIGN checks([ check<T.Assign<[1], [[2, 1], [3, 2?]]>, [3, 2 | 1], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // ATLEAST type T_ATLEAST = [ 0, 1, 2 ] | [ 3, 4, 5, 6 ]; type ATLEAST_T_013 = | [0, 1, 2] | [0, 1 | undefined, 2 | undefined] | [0 | undefined, 1, 2 | undefined] | [3, 4 | undefined, 5 | undefined, 6 | undefined] | [3 | undefined, 4, 5 | undefined, 6 | undefined] | [3 | undefined, 4 | undefined, 5 | undefined, 6]; checks([ check<T.AtLeast<T_ATLEAST, '0' | '1' | '3'>, ATLEAST_T_013, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // COMPULSORY // No test needed (same as O.Compulsory) // --------------------------------------------------------------------------------------- // COMPULSORYKEYS // No test needed (same as O.CompulsoryKeys) // --------------------------------------------------------------------------------------- // CONCAT checks([ check<T.Concat<[1, 2, 3], [4, 5, 6]>, [1, 2, 3, 4, 5, 6], Test.Pass>(), check<T.Concat<['1', '2', '3'], ['4']>, ['1', '2', '3', '4'], Test.Pass>(), check<T.Concat<[1], number[]>, [1, ...number[]], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // DIFF checks([ check<T.Diff<[1, 2, 3], [4, 5, 6], 'default'>, [], Test.Pass>(), check<T.Diff<[1, 2, 3], [4, number, 6], 'extends->'>, [1, number, 3], Test.Pass>(), check<T.Diff<[1, 2, 3], [4, 5, 6, 7], 'equals'>, [1, 2, 3, 7], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // DROP checks([ check<T.Drop<[1, 2, 3, 4], 10, '->'>, [], Test.Pass>(), check<T.Drop<[1, 2, 3, 4], 2, '->'>, [3, 4], Test.Pass>(), check<T.Drop<[1, 2, 3, 4], 2, '<-'>, [1, 2], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // EITHER type T_EITHER = [ 0, 1, 2 ]; type EITHER_T_01 = [0, undefined, 2] | [undefined, 1, 2]; checks([ check<T.Either<T_EITHER, '0' | '1'>, EITHER_T_01, Test.Pass>(), ]) // ------------------------------------------------------------------------------------- // EXCLUDE checks([ check<T.Exclude<[1, 2, 3, 4], [0, 0, 0], 'default'>, [4], Test.Pass>(), check<T.Exclude<[1, 2, 3, 4], [1, 0, 0], 'equals'>, [2, 3, 4], Test.Pass>(), check<T.Exclude<[1, 2, 3, 4], [1, string, 3], 'extends->'>, [2, 4], Test.Pass>(), check<T.Exclude<[1, number, 3, 4], [1, 2, 3], 'extends->'>, [number, 4], Test.Pass>(), ]) // ------------------------------------------------------------------------------------- // EXCLUDEKEYS checks([ check<T.ExcludeKeys<[1, 2, 3, 4], [0, 0, 0], 'default'>, '3', Test.Pass>(), check<T.ExcludeKeys<[1, 2, 3, 4], [1, 0, 0], 'equals'>, '1' | '2' | '3', Test.Pass>(), check<T.ExcludeKeys<[1, 2, 3, 4], [1, string, 3], 'extends->'>, '1' | '3', Test.Pass>(), check<T.ExcludeKeys<[1, number, 3, 4], [1, 2, 3], 'extends->'>, '1' | '3', Test.Pass>(), ]) // ------------------------------------------------------------------------------------- // EXTRACT checks([ check<T.Extract<[1, 2, 3, 4, 5], 1, 3>, [2, 3, 4], Test.Pass>(), check<T.Extract<[1, 2, 3, 4, 5], -1, 13>, [1, 2, 3, 4, 5], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // FILTER type FILTER_T_NUMBER_EXTENDS = [ '3' | undefined, 'xxxx', {a: 'a'} & {b: 'b'}, string | number, object, readonly [ 0, 1, 2?, ], 'xxxx' | undefined ]; type FILTER_T_NUMBER_EQUALS = [ 1, 2, '3' | undefined, 'xxxx', {a: 'a'} & {b: 'b'}, string | number, object, readonly [0, 1, 2?], 'xxxx' | undefined ]; checks([ check<T.Filter<T, number, 'default'>, FILTER_T_NUMBER_EXTENDS, Test.Pass>(), check<T.Filter<T, number, 'extends->'>, FILTER_T_NUMBER_EXTENDS, Test.Pass>(), check<T.Filter<T, number, 'equals'>, FILTER_T_NUMBER_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // FILTERKEYS // No test needed (same as O.FilterKeys) // --------------------------------------------------------------------------------------- // FLATTEN type T_FLATTEN = [1, 12, [2, [3, [4, [5, [6, [7, [8, [9, 92?]]]]]]]]]; type FLATTEN_T = [1, 12, 2, 3, 4, 5, 6, 7, 8, 9, 92] | [1, 12, 2, 3, 4, 5, 6, 7, 8, 9, undefined]; checks([ check<T.Flatten<any>, any[], Test.Pass>(), check<T.Flatten<any[]>, any[], Test.Pass>(), check<T.Flatten<T_FLATTEN>, FLATTEN_T, Test.Pass>(), check<T.Flatten<[1, 2, 42]>, [1, 2, 42], Test.Pass>(), check<T.Flatten<[1, 2?]>, [1, undefined] | [1, 2], Test.Pass>(), check<T.Flatten<readonly [1, 2, 42]>, [1, 2, 42], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // GROUP type T_GROUP = [1, 2, 3, 4, 5, 6, 7, 8]; type GROUP_T_1 = [[1], [2], [3], [4], [5], [6], [7], [8]]; type GROUP_T_2 = [[1, 2], [3, 4], [5, 6], [7, 8]]; type GROUP_T_3 = [[1, 2, 3], [4, 5, 6], [7, 8, undefined]]; checks([ check<T.Group<T_GROUP, 1>, GROUP_T_1, Test.Pass>(), check<T.Group<T_GROUP, 2>, GROUP_T_2, Test.Pass>(), check<T.Group<T_GROUP, 3>, GROUP_T_3, Test.Pass>(), check<T.Group<[], 3>, [], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // HAS // No test needed (same as O.Has) // --------------------------------------------------------------------------------------- // HASPATH // No test needed (same as O.HasPath) // --------------------------------------------------------------------------------------- // HEAD checks([ check<T.Head<T>, 1, Test.Pass>(), // check<T.Head<any>, never, Test.Pass>(), check<T.Head<never>, never, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // INCLUDES // No test needed (same as O.Includes) // --------------------------------------------------------------------------------------- // INTERSECT type t = T.Intersect<T, T1, 'default'> type INTERSECT_T_T1_NUMBER_DEFAULT = [ 1, 2, '3' | undefined, 'xxxx', {a: 'a'} & {b: 'b'}, string | number, number, object, readonly [0, 1, 2?], 'xxxx' | undefined ]; type INTERSECT_T_T1_NUMBER_EXTENDS = [ 1, 2, '3' | undefined, 'xxxx', number | string, number, object, readonly [0, 1, 2?] ]; type INTERSECT_T_T1_NUMBER_EQUALS = [ 1, 2, 'xxxx', object, ]; checks([ check<T.Intersect<T, T1, 'default'>, INTERSECT_T_T1_NUMBER_DEFAULT, Test.Pass>(), check<T.Intersect<T, T1, 'extends->'>, INTERSECT_T_T1_NUMBER_EXTENDS, Test.Pass>(), check<T.Intersect<T, T1, 'equals'>, INTERSECT_T_T1_NUMBER_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // INTERSECTKEYS // No test needed (same as O.IntersectKeys) // --------------------------------------------------------------------------------------- // KEYSET checks([ check<T.KeySet<1, 6>, 1 | 2 | 3 | 4 | 5 | 6, Test.Pass>(), check<T.KeySet<-5, -2>, -5 | -4 | -3 | -2, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // LAST checks([ check<T.Last<T>, 'xxxx' | readonly [0, 1, 2?] | undefined, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // LASTINDEX checks([ check<T.LastKey<[0, 1, 2?]>, 1 | 2, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // LENGTH checks([ check<T.Length<[0, 1, 2?]>, 2 | 3, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // LONGEST checks([ check<T.Longest<T, T1>, T1, Test.Pass>(), check<T.Longest<T1, T>, T1, Test.Pass>(), check<T.Longest<[0], [1]>, [0], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // MERGE checks([ // eslint-disable-next-line func-call-spacing check<T.Merge<[0, 0, 0?], [1, 2, 3?]>, [0, 0, (0 | 3)?], Test.Pass>(), check<T.Merge<[0, 0, 0?], [1, 2, 3]>, [0, 0, 0 | 3], Test.Pass>(), check<T.Merge<[0?], [1, 2, 3]>, [0 | 1, 2, 3], Test.Pass>(), check<T.Merge<[0?], [1, 2, 3]>, [2, 3?], Test.Fail>(), check<T.Merge<[1, 2, 3?], [0, 0, 0]>, [1, 2, 3 | 0], Test.Pass>(), check<T.Merge<[0, [1]], [1, [2, 3], 4], 'deep'>, [0, [1, 3], 4], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // MERGEALL checks([ check<T.MergeAll<[0], [[1, 2, 3?]]>, [0, 2, 3?], Test.Pass>(), check<T.MergeAll<[0], [[1, 2, 3]]>, [0, 2, 3], Test.Pass>(), check<T.MergeAll<[0?], [[1, 2, 3]]>, [2, 3?], Test.Fail>(), check<T.MergeAll<[1, 2, 3?], [[0, 0, 0]]>, [1, 2, 3 | 0], Test.Pass>(), check<T.MergeAll<[0, [1]], [[1, [2, 3], 4]], 'deep'>, [0, [1, 3], 4], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // MERGEKEYS // No test needed (same as O.MergeKeys) // --------------------------------------------------------------------------------------- // MODIFY checks([ check<T.Modify<[9, string], [9, A.x?]>, [9, string?], Test.Pass>(), check<T.Modify<[], [9, A.x]>, [9, never], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // NONNULLABLE checks([ check<T.NonNullable<[0 | undefined, 1, 2 | undefined]>, [0, 1, 2], Test.Pass>(), check<T.NonNullable<[0 | undefined, 1, 2 | undefined], '2'>, [0 | undefined, 1, 2], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // NONNULLABLEKEYS // No test needed (same as O.NonNullableKeys) // --------------------------------------------------------------------------------------- // NULLABLE checks([ check<T.Nullable<[0, 1, 2]>, [0 | undefined | null, 1 | undefined | null, 2 | undefined | null], Test.Pass>(), check<T.Nullable<[0, 1, 2], '2'>, [0, 1, 2 | undefined | null], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // NULLABLEKEYS // No test needed (same as O.NonNullableKeys) // --------------------------------------------------------------------------------------- // OBJECTOF checks([ check<T.ObjectOf<readonly [0]>, {readonly 0: 0}, Test.Pass>(), check<T.ObjectOf<[0, 1, 2]>, {0: 0, 1: 1, 2: 2}, Test.Pass>(), check<T.ObjectOf<[0, 1, 2?]>, {0: 0, 1: 1, 2?: 2}, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // OMIT checks([ check<T.Omit<[0, 1, 2?], '0'>, [1, 2 | undefined], Test.Pass>(), check<T.Omit<[0, 1, 2?], '1' | '2'>, [0], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // OPTIONAL checks([ check<T.Optional<[0, 1, 2]>, [0?, 1?, 2?], Test.Pass>(), check<T.Optional<[0, 1, 2?]>, [0?, 1?, 2?], Test.Pass>(), check<T.Optional<never>, never, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // OPTIONALKEYS // No test needed (same as O.OptionalKeys) // --------------------------------------------------------------------------------------- // OVERWRITE // No test needed (same as O.Overwrite) // --------------------------------------------------------------------------------------- // OPTIONAL checks([ check<T.Partial<[0, 1, 2]>, [0?, 1?, 2?], Test.Pass>(), check<T.Partial<[0, 1, 2?]>, [0?, 1?, 2?], Test.Pass>(), check<T.Partial<never>, never, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // PATCH checks([ check<T.Patch<[0], [1, 2, 3?]>, [0, 2, 3?], Test.Pass>(), check<T.Patch<[0], [1, 2, 3]>, [0, 2, 3], Test.Pass>(), check<T.Patch<[0?], [1, 2, 3]>, [2, 3?], Test.Fail>(), check<T.Patch<[1, 2, 3?], [0, 0, 0]>, [1, 2, 3?], Test.Pass>(), check<T.Patch<[0, [1]], [1, [2, 3], 4], 'deep'>, [0, [1, 3], 4], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // PATCHALL checks([ check<T.PatchAll<[0], [[1, 2, 3?]]>, [0, 2, 3?], Test.Pass>(), check<T.PatchAll<[0], [[1, 2, 3]]>, [0, 2, 3], Test.Pass>(), check<T.PatchAll<[0?], [[1, 2, 3]]>, [2, 3?], Test.Fail>(), check<T.PatchAll<[1, 2, 3?], [[0, 0, 0]]>, [1, 2, 3?], Test.Pass>(), check<T.PatchAll<[0, [1]], [[1, [2, 3], 4]], 'deep'>, [0, [1, 3], 4], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // PATH // No test needed (same as O.Path) // --------------------------------------------------------------------------------------- // PATHS // No test needed (same as O.Paths) // --------------------------------------------------------------------------------------- // PATHUP // No test needed (same as O.PathUp) // --------------------------------------------------------------------------------------- // PICK checks([ check<T.Pick<[0, 1, 2], '0'>, [0], Test.Pass>(), check<T.Pick<[0, 1, 2?], '1' | '2'>, [1, 2 | undefined], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // POP checks([ check<T.Pop<[1, 2, 3]>, [1, 2], Test.Pass>(), check<T.Pop<[1, 2?, 3?]>, [1, 2?], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // PREPEND checks([ check<T.Prepend<[0, 1, 2, 3?], 4>, [4, 0, 1, 2, 3?], Test.Pass>(), check<T.Prepend<[0, 1, 2, 3], [4, 5?]>, [[4, 5?], 0, 1, 2, 3], Test.Pass>(), check<T.Prepend<never, [4, 5]>, never, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // READONLY checks([ check<T.Readonly<[0, 1, 2]>, readonly [0, 1, 2], Test.Pass>(), check<T.Readonly<[0, 1, 2?]>, readonly [0, 1, 2?], Test.Pass>(), check<T.Readonly<never>, never, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // READONLYKEYS // No test needed (same as O.ReadonlyKeys) // --------------------------------------------------------------------------------------- // REMOVE checks([ check<T.Remove<[0, 1, 2], 1, 1>, [0, 2], Test.Pass>(), check<T.Remove<[0, 1, 2?], 1, 1>, [0, 2 | undefined], Test.Pass>(), check<T.Remove<[0, 1, 2], 0, 2>, [], Test.Pass>(), check<T.Remove<[0, 1, 2?], -1, 10>, [], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // REPEAT checks([ check<T.Repeat<1, 3>, [1, 1, 1], Test.Pass>(), check<T.Repeat<1, never>, never, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // REPLACE // No test needed (same as O.Replace) // --------------------------------------------------------------------------------------- // REQUIRED checks([ check<T.Required<[0, 1, 2?]>, [0, 1, 2], Test.Pass>(), check<T.Required<[0, 1?, 2?]>, [0, 1, 2], Test.Pass>(), check<T.Required<[0, 1, 2]>, [0, 1, 2], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // REVERSE checks([ check<T.Reverse<[1, 2, 3]>, [3, 2, 1], Test.Pass>(), check<T.Reverse<[1, 2, 3?]>, [3 | undefined, 2, 1], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // SELECT type SELECT_T_NUMBER_EXTENDS = [ 1, 2, string | number, number ]; type SELECT_T_NUMBER_EQUALS = [ number ]; checks([ check<T.Select<T, number, 'default'>, SELECT_T_NUMBER_EXTENDS, Test.Pass>(), check<T.Select<T, number, 'extends->'>, SELECT_T_NUMBER_EXTENDS, Test.Pass>(), check<T.Select<T, number, 'equals'>, SELECT_T_NUMBER_EQUALS, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // SELECTKEYS // No test needed (same as O.SelectKeys) // --------------------------------------------------------------------------------------- // SHORTEST checks([ check<T.Shortest<T, T1>, T, Test.Pass>(), check<T.Shortest<T1, T>, T, Test.Pass>(), check<T.Shortest<[0], [1]>, [0], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // TAIL checks([ check<T.Tail<[1, 2, 3?, 4?]>, [2, 3?, 4?], Test.Pass>(), check<T.Tail<[]>, [], Test.Pass>(), check<T.Tail<never>, never, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // TAKE checks([ check<T.Take<[1, 2, 3?, 4?], 2, '->'>, [1, 2], Test.Pass>(), check<T.Take<[1, 2, 3?, 4?], 2, '<-'>, [3?, 4?], Test.Pass>(), // nothing happens check<T.Take<[1, 2, 3, 4], 2, '<-'>, [3, 4], Test.Pass>(), // nothing happens ]) // --------------------------------------------------------------------------------------- // TUPLE // Cannot be tested // --------------------------------------------------------------------------------------- // UNDEFINABLE checks([ check<T.Undefinable<[0, 1, 2]>, [0 | undefined, 1 | undefined, 2 | undefined], Test.Pass>(), check<T.Undefinable<[0, 1, 2], '2'>, [0, 1, 2 | undefined], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // UNDEFINABLEKEYS // No test needed (same as O.UndefinableKeys) // --------------------------------------------------------------------------------------- // LIST checks([ check<T.List<string>, readonly string[], Test.Pass>(), check<T.List<never>, readonly never[], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // UNIONIZE checks([ check<T.Unionize<[2], string[]>, [2 | string | undefined], Test.Pass>(), check<T.Unionize<string[], [2]>, Array<string | 2>, Test.Pass>(), check<T.Unionize<[1], [2, 3]>, [1 | 2], Test.Pass>(), ]) // --------------------------------------------------------------------------------?------- // UNIONOF checks([ check<T.UnionOf<[1, 2, 3?]>, 1 | 2 | 3 | undefined, Test.Pass>(), check<T.UnionOf<[]>, never, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // UNNEST checks([ check<T.UnNest<[[1], [2], [3, [4]]]>, [1, 2, 3, [4]], Test.Pass>(), check<T.UnNest<number[][][] | number[]>, number[][] | number[], Test.Pass>(), check<T.UnNest<any>, any[], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // UPDATE checks([ check<T.Update<string[], number, A.x | 2>, Array<(string | 2)>, Test.Pass>(), check<T.Update<[1], 0, 2>, [2], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // WRITABLE type WRITABLE_W_T_ARR = ['a', 'b']; type WRITABLE_R_T_ARR = readonly ['a', 'b']; checks([ check<T.Writable<WRITABLE_W_T_ARR>, WRITABLE_W_T_ARR, Test.Pass>(), check<T.Writable<WRITABLE_R_T_ARR>, WRITABLE_W_T_ARR, Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // WRITABLEKEYS // No test needed (same as O.WritableKeys) // --------------------------------------------------------------------------------------- // ZIP checks([ check<T.Zip<['a', 'b', 'c'], [1, 2, 3, 4]>, [['a', 1], ['b', 2], ['c', 3]], Test.Pass>(), check<T.Zip<['a', 'b'], []>, [['a', undefined], ['b', undefined]], Test.Pass>(), ]) // --------------------------------------------------------------------------------------- // ZIPOBJ checks([ check<T.ZipObj<['a', 'b', 'c'], [1, 2, 3, 4]>, {a: 1, b: 2, c: 3}, Test.Pass>(), check<T.ZipObj<['a', 'b'], []>, {a: undefined, b: undefined}, Test.Pass>(), ])
the_stack
import { EventEmitter, Inject, Injectable, NgModuleRef } from '@angular/core'; import { getPolygonByPointAndRadius, getPolygonByBufferRadius, ImageryCommunicatorService, IImageryMapPosition, IMapSettings } from '@ansyn/imagery'; import { ICoordinatesSystem, LayoutKey, MapActionTypes, ProjectionConverterService, selectActiveMapId, selectMaps, selectMapsList, SetLayoutAction, SetMapPositionByRadiusAction, SetMapPositionByRectAction, SetMinimalistViewModeAction, ShadowMouseProducer, ToggleFooter } from '@ansyn/map-facade'; import { Actions, ofType } from '@ngrx/effects'; import { Dictionary } from '@ngrx/entity'; import { select, Store } from '@ngrx/store'; import { feature, featureCollection } from '@turf/turf'; import { AutoSubscription, AutoSubscriptions } from 'auto-subscriptions'; import { Feature, FeatureCollection, Point, Polygon } from 'geojson'; import { cloneDeep } from 'lodash'; import { combineLatest, Observable } from 'rxjs'; import { map, take, tap, withLatestFrom } from 'rxjs/operators'; import { AddLayer, RemoveLayer, SetLayerSelection, UpdateLayer } from '../modules/menu-items/layers-manager/actions/layers.actions'; import { ILayer } from '../modules/menu-items/layers-manager/models/layers.model'; import { selectActiveAnnotationLayer, selectLayersEntities } from '../modules/menu-items/layers-manager/reducers/layers.reducer'; import { GoToAction, SetActiveCenter, ToolsActionsTypes } from '../modules/status-bar/components/tools/actions/tools.actions'; import { DisplayOverlayAction, DisplayOverlaySuccessAction, LoadOverlaysSuccessAction, OverlaysActionTypes, SetOverlaysCriteriaAction } from '../modules/overlays/actions/overlays.actions'; import { IOverlay, IOverlaysCriteria } from '../modules/overlays/models/overlay.model'; import { ANSYN_ID } from './ansyn-id.provider'; import { selectFilteredOverlays, selectOverlaysArray, selectOverlaysCriteria } from '../modules/overlays/reducers/overlays.reducer'; import { ToggleMenuCollapse } from '@ansyn/menu'; import { UUID } from 'angular2-uuid'; import { DataLayersService } from '../modules/menu-items/layers-manager/services/data-layers.service'; import { AnnotationsVisualizer } from '@ansyn/ol'; import NoSuchMapError from './NoSuchMapError'; import { UpdateGeoFilterStatus } from '../modules/status-bar/actions/status-bar.actions'; import { OverlaysService } from '../modules/overlays/services/overlays.service'; export type mapIdOrNumber = string | number | undefined; @Injectable({ providedIn: 'root' }) @AutoSubscriptions({ init: 'init', destroy: 'destroy' }) /** * a api for manipulating on the ansyn app. */ export class AnsynApi { /** * the id of the active map. * @var */ activeMapId; /** * key-value from the map id to the map itself. * @var {Dictionary<IMapSettings>} */ mapsEntities; /** * the active annotation layer * @var {ILayer} */ activeAnnotationLayer; /** * the id of the default layer. * @var {string} */ defaultLayerId: string; events = { /** * fire when the app is ready(map was loaded) */ onReady: new EventEmitter<boolean>(), /** * fire when the timeline was load with overlays. * @property overlays - array of the loaded overlays or false if there was error. */ overlaysLoadedSuccess: new EventEmitter<IOverlay[] | false>(), /** * fire when an overlay was loaded to the map * @property the loaded overlay or false if there was error on open the overlay. * @property mapId - the id of the map. */ displayOverlaySuccess: new EventEmitter<{ overlay: IOverlay | false, mapId: string }>() }; /** @deprecated onReady as own event was deprecated use events.onReady instead */ onReady = new EventEmitter<boolean>(true); /** * @return An observable that emits the maps in array. */ getMaps$: Observable<IMapSettings[]> = this.store.pipe( select(selectMapsList), take(1) ); /** * @return an observable that emit the current mouse position on the map. */ onShadowMouseProduce$: Observable<any> = this.actions$.pipe( ofType(MapActionTypes.SHADOW_MOUSE_PRODUCER), map(({ payload }: ShadowMouseProducer) => { return payload.point.coordinates; }) ); /** * @return An observable that emit when the map layout is change */ onSetLayoutSuccess$: Observable<any> = this.actions$.pipe( ofType(MapActionTypes.SET_LAYOUT_SUCCESS) ); /** * @return An observable that emit when the center of the map is change * from the search box or the go-to tool */ getActiveCenter$: Observable<any> = this.actions$.pipe( ofType(ToolsActionsTypes.SET_ACTIVE_CENTER), map(({ payload }: SetActiveCenter) => { return payload; }) ); private mapList; private features = []; @AutoSubscription private activateMap$: Observable<string> = this.store.select(selectActiveMapId).pipe( tap((activeMapId) => this.activeMapId = activeMapId) ); @AutoSubscription private mapsEntities$: Observable<Dictionary<IMapSettings>> = this.store.pipe( select(selectMaps), tap((mapsEntities) => this.mapsEntities = mapsEntities) ); @AutoSubscription private mapList$ = this.store.pipe( select(selectMapsList), tap((mapList) => this.mapList = mapList) ); @AutoSubscription private activeAnnotationLayer$: Observable<ILayer> = this.store .pipe( select(selectActiveAnnotationLayer), withLatestFrom(this.store.select(selectLayersEntities)), map(([activeAnnotationLayerId, entities]) => entities[activeAnnotationLayerId]), tap((activeAnnotationLayer) => { this.activeAnnotationLayer = activeAnnotationLayer; this.defaultLayerId = this.activeAnnotationLayer ? this.activeAnnotationLayer.id : undefined; }) ); /** Events **/ @AutoSubscription private ready$ = this.imageryCommunicatorService.instanceCreated.pipe( take(1), tap((map) => { this.onReady.emit(true); // tslint:disable-line this.events.onReady.emit(true); }) ); /** Events end **/ @AutoSubscription private overlaysSearchEnd$ = this.actions$.pipe( ofType<LoadOverlaysSuccessAction>(OverlaysActionTypes.LOAD_OVERLAYS_SUCCESS), tap(({ payload }) => { this.events.overlaysLoadedSuccess.emit(payload.length > 0 ? payload : false); }) ); @AutoSubscription private displayOverlaySuccess$ = this.actions$.pipe( ofType<DisplayOverlaySuccessAction>(OverlaysActionTypes.DISPLAY_OVERLAY_SUCCESS), tap(({ payload }) => this.events.displayOverlaySuccess.emit({ overlay: payload.overlay, mapId: payload.mapId })) ); @AutoSubscription private displayOverlayFailed$ = this.actions$.pipe( ofType<DisplayOverlaySuccessAction>(OverlaysActionTypes.DISPLAY_OVERLAY_FAILED), tap(({ payload }) => this.events.displayOverlaySuccess.emit({ overlay: false, mapId: payload.mapId })) ); constructor(protected store: Store<any>, protected actions$: Actions, protected projectionConverterService: ProjectionConverterService, protected imageryCommunicatorService: ImageryCommunicatorService, protected overlaysService: OverlaysService, protected moduleRef: NgModuleRef<any>, private dataLayersService: DataLayersService, @Inject(ANSYN_ID) public id: string) { this.init(); } /** * draw the shadow mouse visualizer in the specific point * @param geoPoint The point where we will draw the visualizer. */ setOutSourceMouseShadow(geoPoint: Point): void { if (!Boolean(geoPoint)) { console.error('can\'t set undefined point to shadow mouse'); return null; } this.store.dispatch(new ShadowMouseProducer({ point: { coordinates: geoPoint.coordinates, type: 'point' }, outsideSource: true })); } /** * open an overlay on the map * @param overlay the overlay will be display * @param mapId the map number or id. default the active map id. */ displayOverLay(overlay: IOverlay, mapId?: mapIdOrNumber): void { if (!Boolean(overlay)) { console.error('can\'t display undefined overlay'); return null; } this.store.dispatch(new DisplayOverlayAction({ overlay, mapId: this.getMapIdFromMapNumber(mapId), forceFirstDisplay: true })); } /** * draw the feature collection on the map. * @param featureCollection the features to draw on the map. */ setAnnotations(featureCollection: FeatureCollection<any>): void { if (!Boolean(featureCollection)) { console.error('can\'t set undefined annotations'); return null; } if (featureCollection.type !== 'FeatureCollection') { console.error('feature collection must have FeatureCollection type'); return null; } this.store.dispatch(new UpdateLayer(<ILayer>{ ...this.activeAnnotationLayer, data: cloneDeep(featureCollection) })); this.features = featureCollection.features; } /** * delete all the features in the map */ deleteAllAnnotations(): void { const plugin: AnnotationsVisualizer = this.imageryCommunicatorService.communicatorsAsArray()[0].getPlugin(AnnotationsVisualizer); this.features.forEach(feature => plugin.setEditAnnotationMode(<string>feature.properties.id, false)); this.setAnnotations(<FeatureCollection>(featureCollection([]))); } /** * feed the timeline with the given overlays * @param overlays array of IOverlay to be load into the timeline */ setOverlays(overlays: IOverlay[]): void { if (!Boolean(overlays)) { console.error('can\'t set undefined overlays'); return null; } this.store.dispatch(new LoadOverlaysSuccessAction(overlays, true)); } /** * change the application layout * @param layout the new layout key. * @return Observable that emit once the layout successfully change. */ changeMapLayout(layout: LayoutKey): Observable<any> { if (!Boolean(layout)) { console.error('can\'t change layout to undefined'); return null; } this.store.dispatch(new SetLayoutAction(layout)); return this.onSetLayoutSuccess$.pipe(take(1)); } /** * convert coordinate from one coordinate system to another * @param position the position in the old coordinate system * @param convertFrom the current coordinate system of the position * @param convertTo the new coordinate system to the position * @return the position in the new coordinate system. */ transfromHelper(position: number[], convertFrom: ICoordinatesSystem, convertTo: ICoordinatesSystem): void { const conversionValid = this.projectionConverterService.isValidConversion(position, convertFrom); if (conversionValid) { this.projectionConverterService.convertByProjectionDatum(position, convertFrom, convertTo); } } /** * @param mapId the map id or number, default the active map id. * @return the position of the map. */ getMapPosition(mapId: mapIdOrNumber): IImageryMapPosition { return this.mapsEntities[this.getMapIdFromMapNumber(mapId)].data.position; } /** * set the center of the map to the given point * @param geoPoint the new center for the map. * @param mapId the map id or number, default the active map id. */ goToPosition(geoPoint: Point, mapId?: mapIdOrNumber): void { if (!Boolean(geoPoint)) { console.error('can\'t go to undefined point'); return null; } this.store.dispatch(new GoToAction(geoPoint.coordinates, this.getMapIdFromMapNumber(mapId))); } /** * set the map extent to the given polygon * @param rect a rectangle polygon * @param mapId the id of the map to be set. default the active map id. */ setMapPositionByRect(rect: Polygon, mapId?: mapIdOrNumber) { if (!Boolean(rect)) { console.error('can\'t set position to undefined rect'); return null; } this.store.dispatch(new SetMapPositionByRectAction({ id: this.getMapIdFromMapNumber(mapId), rect })); } /** * @return all the overlays in the timeline. */ getOverlays(): Observable<IOverlay[]> { return combineLatest([this.store.select(selectOverlaysArray), this.store.select(selectFilteredOverlays)]).pipe( take(1), map(([overlays, filteredOverlays]: [IOverlay[], string[]]) => { return overlays.filter((overlay) => { return filteredOverlays.includes(overlay.id); }); }) ); } /** * rotate the map by degree. if it is not geo registered image rotate the image. * @param radian The rotation of the map in radians. * @param mapId the id of the map. default to the active map. */ setRotation(radian: number, mapId?: mapIdOrNumber) { if (radian === undefined) { console.error('can\'t rotate to undefined degree'); return null; } this.imageryCommunicatorService.provide(this.getMapIdFromMapNumber(mapId)).setRotation(radian); } /** * get the current rotation of the map. * @param mapId the id of the map. default to the active map. * @return the map rotation in radians. */ getRotation(mapId?: mapIdOrNumber): number { return this.imageryCommunicatorService.provide(this.getMapIdFromMapNumber(mapId)).getRotation(); } /** * set the map center to the specific point and scale the map to the radius * @param center GeoJSON point to be set the map to. * @param radiusInMeters set the map scale to radiusInMeters / 10 * @param mapId the id of the map to be set. default the active map id. * @param search does make new search in the new position or not. */ setMapPositionByRadius(center: Point, radiusInMeters: number, mapId: mapIdOrNumber, search: boolean = false): void { if (!Boolean(center)) { console.error('can\'t set position to undefined point'); return null; } this.store.dispatch(new SetMapPositionByRadiusAction({ id: this.getMapIdFromMapNumber(mapId), center, radiusInMeters })); if (search) { const criteria: IOverlaysCriteria = { region: feature(center) }; this.store.dispatch(new SetOverlaysCriteriaAction(criteria)); } } /** * make a new search with the specific criteria * @param criteria of the search. you can pass only one criterion. * @param [radiusInMetersBuffer] if the region criterion is provide, bump the region by the radius. */ setOverlaysCriteria(criteria: IOverlaysCriteria, radiusInMetersBuffer?: number) { if (!Boolean(criteria)) { console.error('failed to set overlays criteria to undefined'); return null; } if (Boolean(criteria.region)) { if ((radiusInMetersBuffer !== undefined && radiusInMetersBuffer !== 0)) { let featureRegion: Feature<Polygon>; const notFeatureRegion: Point | Polygon = criteria.region.type !== 'Feature' ? criteria.region : criteria.region.geometry; switch (notFeatureRegion.type.toLowerCase()) { case 'point': featureRegion = getPolygonByPointAndRadius((notFeatureRegion as Point).coordinates, radiusInMetersBuffer / 1000); break; case 'polygon': featureRegion = getPolygonByBufferRadius(notFeatureRegion as Polygon, radiusInMetersBuffer); break; default: console.error('not supported type: ' + notFeatureRegion.type); return null; } criteria.region = {...featureRegion, properties: {...featureRegion.properties, searchMode: 'Polygon'}}; } criteria.region = criteria.region.type !== 'Feature' ? feature(criteria.region) : criteria.region; } this.store.dispatch(new SetOverlaysCriteriaAction(criteria)); this.store.dispatch(new UpdateGeoFilterStatus({type: criteria.region.geometry.type})); } /** * @return An Observable that emits when the search criteria was change. */ getOverlaysCriteria(): Observable<IOverlaysCriteria> { return this.store.select(selectOverlaysCriteria); } /** * @return the overlay that display on the map, or undefined if no overlay was display * @param mapId the id of the map. */ getOverlayData(mapId?: mapIdOrNumber): IOverlay { return this.mapsEntities[this.getMapIdFromMapNumber(mapId)].data.overlay; } /** * display the overlay with the id `overlayId` in the active map. * if `addToTimeline` is true, the overlay was add to the timeline. * @param overlayId the id of the overlay we want to display * @param mapId the id of the map to add the overlay * @param addToTimeline if load the overlay to timeline. */ displayOverlayById(overlayId: string, mapId?: mapIdOrNumber, addToTimeline?: boolean) { this.overlaysService.getOverlaysById([{ id: overlayId, sourceType: undefined}]).pipe( map(overlays => overlays.find(overlay => Boolean(overlay.sourceType))), tap( overlay => { if (overlay) { this.displayOverLay(overlay, mapId); if (addToTimeline) { this.store.dispatch(new LoadOverlaysSuccessAction([overlay], false)); } } }) ).subscribe() } /** * set if the footer(the timeline container) is minimize or maximize. * @param collapse true for minimize the footer, or false to maximize. */ collapseFooter(collapse: boolean) { this.store.dispatch(new ToggleFooter(collapse)); } /** * set if the menu is minimize or maximize. * @param collapse true for minimize the menu, or false to maximize. */ collapseMenu(collapse: boolean) { this.store.dispatch(new ToggleMenuCollapse(collapse)); } /** * set the app to minimalist view. * minimalist view show only the map the compass and the name of the overlay(or Base map, if there is no overlay display)/ * @param collapse true to set the app to minimalist view, false to set the app to normal view. */ setMinimalistViewMode(collapse: boolean) { this.collapseFooter(collapse); this.collapseMenu(collapse); this.store.dispatch(new SetMinimalistViewModeAction(collapse)); } /** * add new layer to the Data Layer * @param layerName the layer name. * @param layerData the features to be add into the layer. * @param isEditable set if this layer was editable or not. default true * @return the layer id. for future deletion of the layer. */ insertLayer(layerName: string, layerData: FeatureCollection<any>, isEditable: boolean = true): string { if (!(layerName && layerName.length)) { console.error('failed to add layer without a name', layerName); return null; } if (!Boolean(layerData)) { console.error('failed to add layer ', layerName, ' feature collection is undefined'); return null; } layerData.features.forEach((feature) => { feature.properties.isNonEditable = !isEditable; const { label } = feature.properties; feature.properties.label = label && typeof label === 'object' ? label : { text: label, geometry: null }; }); this.generateFeaturesIds(layerData); const layer = this.dataLayersService.generateLayer({name: layerName, data: layerData, isNonEditable: !isEditable}); this.store.dispatch(new AddLayer(layer)); return layer.id; } /** * remove the specific layer from the Data layer. * @param layerId the id of the layer who return from */ removeLayer(layerId: string): void { if (!(layerId && layerId.length)) { console.error('failed to remove layer - invalid layerId ', layerId); return; } this.store.dispatch(new RemoveLayer(layerId)); } /** * set if the specific layer is show or hide. * @param layerId the id of the layer who return from * @param show true to show the layer, false to hide. */ showLayer(layerId: string, show: boolean): void { if (!(layerId && layerId.length)) { console.error('failed to show layer - invalid layerId ', layerId); return; } this.store.dispatch(new SetLayerSelection({ id: layerId, value: show })); } init(): void { } destroy(): void { this.moduleRef.destroy(); this.removeElement(this.id); } private getMapIdFromMapNumber(mapId: mapIdOrNumber): string { if (typeof mapId !== 'number' && !Boolean(mapId)) { return this.activeMapId; } if ((typeof mapId === 'string' && Boolean(this.mapsEntities[mapId])) || (typeof mapId === 'number' && mapId > 0 && mapId <= 4 && Boolean(this.mapList[mapId - 1]))) { return typeof mapId === 'string' ? mapId : this.mapList[mapId - 1].id; } else { throw new NoSuchMapError(mapId); } } private removeElement(id): void { const elem: HTMLElement = <any>document.getElementById(id); if (elem) { elem.innerHTML = ''; } } private generateFeaturesIds(annotationsLayer): void { /* reference */ annotationsLayer.features.forEach((feature) => { feature.properties = { ...feature.properties, id: feature.id ? feature.id : UUID.UUID() }; }); } }
the_stack
import * as path from 'path'; import { AutoScalingGroup, BlockDevice, CfnAutoScalingGroup, DefaultResult, LifecycleTransition, } from '@aws-cdk/aws-autoscaling'; import { CfnNetworkInterface, Connections, IConnectable, IMachineImage, InstanceType, ISecurityGroup, IVpc, OperatingSystemType, SubnetSelection, UserData, } from '@aws-cdk/aws-ec2'; import { Effect, IGrantable, IPrincipal, IRole, PolicyStatement, Role, ServicePrincipal, } from '@aws-cdk/aws-iam'; import { Code, Function as LambdaFunction, Runtime, } from '@aws-cdk/aws-lambda'; import { RetentionDays, } from '@aws-cdk/aws-logs'; import { Topic, } from '@aws-cdk/aws-sns'; import { LambdaSubscription, } from '@aws-cdk/aws-sns-subscriptions'; import { CfnResource, Construct, Duration, Lazy, Names, Stack, Tags, } from '@aws-cdk/core'; /** * Required and optional properties that define the construction of a {@link StaticPrivateIpServer} */ export interface StaticPrivateIpServerProps { /** * VPC in which to launch the instance. */ readonly vpc: IVpc; /** * The type of instance to launch */ readonly instanceType: InstanceType; /** * The AMI to launch the instance with. */ readonly machineImage: IMachineImage; /** * Specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes. * * Each instance that is launched has an associated root device volume, either an Amazon EBS volume or an instance store volume. * You can use block device mappings to specify additional EBS volumes or instance store volumes to attach to an instance when it is launched. * * @default Uses the block device mapping of the AMI. */ readonly blockDevices?: BlockDevice[]; /** * Name of the EC2 SSH keypair to grant access to the instance. * * @default No SSH access will be possible. */ readonly keyName?: string; /** * The specific private IP address to assign to the Elastic Network Interface of this instance. * * @default An IP address is randomly assigned from the subnet. */ readonly privateIpAddress?: string; /** * The length of time to wait for the instance to signal successful deployment * during the initial deployment, or update, of your stack. * * The maximum value is 12 hours. * * @default The deployment does not require a success signal from the instance. */ readonly resourceSignalTimeout?: Duration; /** * An IAM role to associate with the instance profile that is assigned to this instance. * The role must be assumable by the service principal `ec2.amazonaws.com` * * @default A role will automatically be created, it can be accessed via the `role` property. */ readonly role?: IRole; /** * The security group to assign to this instance. * * @default A new security group is created for this instance. */ readonly securityGroup?: ISecurityGroup; /** * Specific UserData to use. UserData is a script that is run automatically by the instance the very first time that a new instance is started. * * The UserData may be mutated after creation. * * @default A UserData that is appropriate to the {@link machineImage}'s operating system is created. */ readonly userData?: UserData; /** * Where to place the instance within the VPC. * * @default The instance is placed within a Private subnet. */ readonly vpcSubnets?: SubnetSelection; } /** * This construct provides a single instance, provided by an Auto Scaling Group (ASG), that * has an attached Elastic Network Interface (ENI) that is providing a private ip address. * This ENI is automatically re-attached to the instance if the instance is replaced * by the ASG. * * The ENI provides an unchanging private IP address that can always be used to connect * to the instance regardless of how many times the instance has been replaced. Furthermore, * the ENI has a MAC address that remains unchanged unless the ENI is destroyed. * * Essentially, this provides an instance with an unchanging private IP address that will * automatically recover from termination. This instance is suitable for use as an application server, * such as a license server, that must always be reachable by the same IP address. * * Resources Deployed * ------------------------ * - Auto Scaling Group (ASG) with min & max capacity of 1 instance. * - Elastic Network Interface (ENI). * - Security Group for the ASG. * - Instance Role and corresponding IAM Policy. * - SNS Topic & Role for instance-launch lifecycle events -- max one of each per stack. * - Lambda function, with role, to attach the ENI in response to instance-launch lifecycle events -- max one per stack. * * Security Considerations * ------------------------ * - The AWS Lambda that is deployed through this construct will be created from a deployment package * that is uploaded to your CDK bootstrap bucket during deployment. You must limit write access to * your CDK bootstrap bucket to prevent an attacker from modifying the actions performed by this Lambda. * We strongly recommend that you either enable Amazon S3 server access logging on your CDK bootstrap bucket, * or enable AWS CloudTrail on your account to assist in post-incident analysis of compromised production * environments. * - The AWS Lambda that is deployed through this construct has broad IAM permissions to attach any Elastic * Network Interface (ENI) to any instance. You should not grant any additional actors/principals the ability * to modify or execute this Lambda. * - The SNS Topic that is deployed through this construct controls the execution of the Lambda discussed above. * Principals that can publish messages to this SNS Topic will be able to trigger the Lambda to run. You should * not allow any additional principals to publish messages to this SNS Topic. */ export class StaticPrivateIpServer extends Construct implements IConnectable, IGrantable { /** * The Auto Scaling Group that contains the instance this construct creates. */ public readonly autoscalingGroup: AutoScalingGroup; /** * Allows for providing security group connections to/from this instance. */ public readonly connections: Connections; /** * The principal to grant permission to. Granting permissions to this principal will grant * those permissions to the instance role. */ public readonly grantPrincipal: IPrincipal; /** * The type of operating system that the instance is running. */ public readonly osType: OperatingSystemType; /** * The Private IP address that has been assigned to the ENI. */ public readonly privateIpAddress: string; /** * The IAM role that is assumed by the instance. */ public readonly role: IRole; /** * The UserData for this instance. * UserData is a script that is run automatically by the instance the very first time that a new instance is started. */ public readonly userData: UserData; constructor(scope: Construct, id: string, props: StaticPrivateIpServerProps) { super(scope, id); const { subnets } = props.vpc.selectSubnets(props.vpcSubnets); if (subnets.length === 0) { throw new Error(`Did not find any subnets matching ${JSON.stringify(props.vpcSubnets)}. Please use a different selection.`); } const subnet = subnets[0]; if (props.resourceSignalTimeout && props.resourceSignalTimeout.toSeconds() > (12 * 60 * 60)) { throw new Error('Resource signal timeout cannot exceed 12 hours.'); } this.autoscalingGroup = new AutoScalingGroup(this, 'Asg', { minCapacity: 1, maxCapacity: 1, vpc: props.vpc, instanceType: props.instanceType, machineImage: props.machineImage, vpcSubnets: { subnets: [subnet] }, blockDevices: props.blockDevices, keyName: props.keyName, resourceSignalCount: props.resourceSignalTimeout ? 1 : undefined, resourceSignalTimeout: props.resourceSignalTimeout, role: props.role, securityGroup: props.securityGroup, userData: props.userData, }); this.connections = this.autoscalingGroup.connections; this.grantPrincipal = this.autoscalingGroup.grantPrincipal; this.osType = this.autoscalingGroup.osType; this.role = this.autoscalingGroup.role; this.userData = this.autoscalingGroup.userData; const scopePath = this.node.scopes.map(construct => construct.node.id).slice(1); // Slice to remove the unnamed <root> scope. const eni = new CfnNetworkInterface(this, 'Eni', { subnetId: subnet.subnetId, description: `Static ENI for ${scopePath.join('/')}`, groupSet: Lazy.list({ produce: () => this.connections.securityGroups.map(sg => sg.securityGroupId) }), privateIpAddress: props.privateIpAddress, }); this.privateIpAddress = eni.attrPrimaryPrivateIpAddress; // We need to be sure that the ENI is created before the instance would be brought up; otherwise, we cannot attach it. (this.autoscalingGroup.node.defaultChild as CfnResource).addDependsOn(eni); this.attachEniLifecyleTarget(eni); this.node.defaultChild = this.autoscalingGroup.node.defaultChild; } /** * Set up an instance launch lifecycle action that will attach the eni to the single instance * in this construct's AutoScalingGroup when a new instance is launched. */ protected attachEniLifecyleTarget(eni: CfnNetworkInterface) { // Note: The design of AutoScalingGroup life cycle notifications in CDK v1.49.1 is such that // using the provided AutoScalingGroup.addLifecycleHook() will result in a setup that misses // launch notifications for instances created when the ASG is created. This is because // it uses the separate CfnLifecycleHook resource to do it, and that resource references the // ASG ARN; i.e. it must be created after the ASG has an ARN... thus it can miss instance launches // when the ASG is first created. // // We work around this by using an escape-hatch to the L1 ASG to create our own notification from scratch. const eventHandler = this.setupLifecycleEventHandlerFunction(); const { topic, role } = this.setupLifecycleNotificationTopic(eventHandler); // Ensure no race conditions that might prevent the lambda from being able to perform its required functions by making // the ASG depend on the creation of the SNS Subscription. // Note: The topic subscriptions are children of the lambda, and are given an id equal to the Topic's id. this.autoscalingGroup.node.defaultChild!.node.addDependency(eventHandler.node.findChild(topic.node.id)); (this.autoscalingGroup.node.defaultChild as CfnAutoScalingGroup).lifecycleHookSpecificationList = [ { defaultResult: DefaultResult.ABANDON, heartbeatTimeout: 120, lifecycleHookName: 'NewStaticPrivateIpServer', lifecycleTransition: LifecycleTransition.INSTANCE_LAUNCHING, notificationTargetArn: topic.topicArn, roleArn: role.roleArn, notificationMetadata: JSON.stringify({ eniId: eni.ref }), }, ]; } /** * Create, or fetch, the lambda function that will process instance-start lifecycle events from this construct. */ protected setupLifecycleEventHandlerFunction(): LambdaFunction { const stack = Stack.of(this); // The SingletonFunction does not tell us when it's newly created vs. finding a pre-existing // one. So, we do our own singleton Function so that we know when it's the first creation, and, thus, // we must attach one-time permissions. const functionUniqueId = 'AttachEniToInstance' + this.removeHyphens('83a5dca5-db54-4aa4-85d2-8d419cdf85ce'); let singletonPreExists: boolean = true; let eventHandler = stack.node.tryFindChild(functionUniqueId) as LambdaFunction; if (!eventHandler) { const handlerCode = Code.fromAsset(path.join(__dirname, '..', '..', 'lambdas', 'nodejs', 'asg-attach-eni'), { exclude: ['**/*', '!index*'], }); eventHandler = new LambdaFunction(stack, functionUniqueId, { code: handlerCode, handler: 'index.handler', runtime: Runtime.NODEJS_12_X, description: `Created by RFDK StaticPrivateIpServer to process instance launch lifecycle events in stack '${stack.stackName}'. This lambda attaches an ENI to newly launched instances.`, logRetention: RetentionDays.THREE_DAYS, }); singletonPreExists = false; } // Note: We **cannot** reference the ASG's ARN in the lambda's policy. It would create a deadlock at deployment: // Lambda policy waiting on ASG completion to get ARN // -> lambda waiting on policy to be created // -> ASG waiting on lambda to signal lifecycle continue for instance start // -> back to the start of the cycle. // Instead we use resourcetags condition to limit the scope of the lambda. const tagKey = 'RfdkStaticPrivateIpServerGrantConditionKey'; const tagValue = Names.uniqueId(eventHandler); const grantCondition: { [key: string]: string } = {}; grantCondition[`autoscaling:ResourceTag/${tagKey}`] = tagValue; Tags.of(this.autoscalingGroup).add(tagKey, tagValue); // Allow the lambda to complete the lifecycle action for only tagged ASGs. const iamCompleteLifecycle = new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'autoscaling:CompleteLifecycleAction', ], resources: [ `arn:${stack.partition}:autoscaling:${stack.region}:${stack.account}:autoScalingGroup:*:autoScalingGroupName/*`, ], conditions: { 'ForAnyValue:StringEquals': grantCondition, }, }); eventHandler.role!.addToPrincipalPolicy(iamCompleteLifecycle); if (!singletonPreExists) { // Allow the lambda to attach the ENI to the instance that was created. // Referencing: https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html // Last-Accessed: July 2020 // The ec2:DescribeNetworkInterfaces, and ec2:AttachNetworkInterface operations // do not support conditions, and do not support resource restriction. // So, we only attach the policy to the lambda function once; when we first create it. const iamEniAttach = new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'ec2:DescribeNetworkInterfaces', 'ec2:AttachNetworkInterface', ], resources: ['*'], }); eventHandler.role!.addToPrincipalPolicy(iamEniAttach); } return eventHandler; } /** * Create, or fetch, an SNS Topic to which we'll direct the ASG's instance-start lifecycle hook events. Also creates, or fetches, * the accompanying role that allows the lifecycle events to be published to the SNS Topic. * @param lambdaHandler The lambda singleton that will be processing the lifecycle events. * @returns { topic: Topic, role: Role } */ protected setupLifecycleNotificationTopic(lambdaHandler: LambdaFunction): { [key: string]: any } { const stack = Stack.of(this); // We only need to have a single SNS topic & subscription set up to handle lifecycle events for *all* instances of this class. // We have to be careful, however, to ensure that our initial setup only happens once when we first add the topic and such // to this stack; otherwise, we will not be able to deploy more than one of these constructs in a stack. const notificationRoleUniqueId = 'AttachEniNotificationRole' + this.removeHyphens('a0376ff8-248e-4534-bf42-58c6ffa4d5b4'); const notificationTopicUniqueId = 'AttachEniNotificationTopic' + this.removeHyphens('c8b1e9a6-783c-4954-b191-204dd5e3b9e0'); let notificationTopic: Topic = (stack.node.tryFindChild(notificationTopicUniqueId) as Topic); let notificationRole: Role; if (!notificationTopic) { // First time creating the singleton Topic in this stack. Set it all up... notificationRole = new Role(stack, notificationRoleUniqueId, { assumedBy: new ServicePrincipal('autoscaling.amazonaws.com'), }); notificationTopic = new Topic(stack, notificationTopicUniqueId, { displayName: `For RFDK instance-launch notifications for stack '${stack.stackName}'`, }); notificationTopic.addSubscription(new LambdaSubscription(lambdaHandler)); notificationTopic.grantPublish(notificationRole); } else { notificationRole = stack.node.findChild(notificationRoleUniqueId) as Role; } return { topic: notificationTopic, role: notificationRole, }; } /** * Convert a UUID into a string that's usable in a construct id. */ private removeHyphens(x: string): string { return x.replace(/[-]/g, ''); } }
the_stack
import sade from 'sade'; import glob from 'tiny-glob/sync'; import { rollup, watch, RollupOptions, OutputOptions, RollupWatchOptions, WatcherOptions, } from 'rollup'; import asyncro from 'asyncro'; import chalk from 'chalk'; import * as fs from 'fs-extra'; import * as jest from 'jest'; import { CLIEngine } from 'eslint'; import logError from './logError'; import path from 'path'; import execa from 'execa'; import shell from 'shelljs'; import ora from 'ora'; import semver from 'semver'; import { paths } from './constants'; import * as Messages from './messages'; import { createBuildConfigs } from './createBuildConfigs'; import { createJestConfig, JestConfigOptions } from './createJestConfig'; import { createEslintConfig } from './createEslintConfig'; import { resolveApp, safePackageName, clearConsole, getNodeEngineRequirement, } from './utils'; import { concatAllArray } from 'jpjs'; import getInstallCmd from './getInstallCmd'; import getInstallArgs from './getInstallArgs'; import { Input, Select } from 'enquirer'; import { PackageJson, WatchOpts, BuildOpts, ModuleFormat, NormalizedOpts, } from './types'; import { createProgressEstimator } from './createProgressEstimator'; import { templates } from './templates'; import { composePackageJson } from './templates/utils'; import * as deprecated from './deprecated'; const pkg = require('../package.json'); const prog = sade('tsdx'); let appPackageJson: PackageJson; try { appPackageJson = fs.readJSONSync(paths.appPackageJson); } catch (e) { } export const isDir = (name: string) => fs .stat(name) .then(stats => stats.isDirectory()) .catch(() => false); export const isFile = (name: string) => fs .stat(name) .then(stats => stats.isFile()) .catch(() => false); async function jsOrTs(filename: string) { const extension = (await isFile(resolveApp(filename + '.ts'))) ? '.ts' : (await isFile(resolveApp(filename + '.tsx'))) ? '.tsx' : (await isFile(resolveApp(filename + '.jsx'))) ? '.jsx' : '.js'; return resolveApp(`${filename}${extension}`); } async function getInputs( entries?: string | string[], source?: string ): Promise<string[]> { return concatAllArray( ([] as any[]) .concat( entries && entries.length ? entries : (source && resolveApp(source)) || ((await isDir(resolveApp('src'))) && (await jsOrTs('src/index'))) ) .map(file => glob(file)) ); } prog .version(pkg.version) .command('create <pkg>') .describe('Create a new package with TSDX') .example('create mypackage') .option( '--template', `Specify a template. Allowed choices: [${Object.keys(templates).join( ', ' )}]` ) .example('create --template react mypackage') .action(async (pkg: string, opts: any) => { console.log( chalk.blue(` ::::::::::: :::::::: ::::::::: ::: ::: :+: :+: :+: :+: :+: :+: :+: +:+ +:+ +:+ +:+ +:+ +:+ +#+ +#++:++#++ +#+ +:+ +#++:+ +#+ +#+ +#+ +#+ +#+ +#+ #+# #+# #+# #+# #+# #+# #+# ### ######## ######### ### ### `) ); const bootSpinner = ora(`Creating ${chalk.bold.green(pkg)}...`); let template; // Helper fn to prompt the user for a different // folder name if one already exists async function getProjectPath(projectPath: string): Promise<string> { const exists = await fs.pathExists(projectPath); if (!exists) { return projectPath; } bootSpinner.fail(`Failed to create ${chalk.bold.red(pkg)}`); const prompt = new Input({ message: `A folder named ${chalk.bold.red( pkg )} already exists! ${chalk.bold('Choose a different name')}`, initial: pkg + '-1', result: (v: string) => v.trim(), }); pkg = await prompt.run(); projectPath = (await fs.realpath(process.cwd())) + '/' + pkg; bootSpinner.start(`Creating ${chalk.bold.green(pkg)}...`); return await getProjectPath(projectPath); // recursion! } try { // get the project path const realPath = await fs.realpath(process.cwd()); let projectPath = await getProjectPath(realPath + '/' + pkg); const prompt = new Select({ message: 'Choose a template', choices: Object.keys(templates), }); if (opts.template) { template = opts.template.trim(); if (!prompt.choices.includes(template)) { bootSpinner.fail(`Invalid template ${chalk.bold.red(template)}`); template = await prompt.run(); } } else { template = await prompt.run(); } bootSpinner.start(); // copy the template await fs.copy( path.resolve(__dirname, `../templates/${template}`), projectPath, { overwrite: true, } ); // fix gitignore await fs.move( path.resolve(projectPath, './gitignore'), path.resolve(projectPath, './.gitignore') ); // update license year and author let license: string = await fs.readFile( path.resolve(projectPath, 'LICENSE'), { encoding: 'utf-8' } ); license = license.replace(/<year>/, `${new Date().getFullYear()}`); // attempt to automatically derive author name let author = getAuthorName(); if (!author) { bootSpinner.stop(); const licenseInput = new Input({ name: 'author', message: 'Who is the package author?', }); author = await licenseInput.run(); setAuthorName(author); bootSpinner.start(); } license = license.replace(/<author>/, author.trim()); await fs.writeFile(path.resolve(projectPath, 'LICENSE'), license, { encoding: 'utf-8', }); const templateConfig = templates[template as keyof typeof templates]; const generatePackageJson = composePackageJson(templateConfig); // Install deps process.chdir(projectPath); const safeName = safePackageName(pkg); const pkgJson = generatePackageJson({ name: safeName, author }); const nodeVersionReq = getNodeEngineRequirement(pkgJson); if ( nodeVersionReq && !semver.satisfies(process.version, nodeVersionReq) ) { bootSpinner.fail(Messages.incorrectNodeVersion(nodeVersionReq)); process.exit(1); } await fs.outputJSON(path.resolve(projectPath, 'package.json'), pkgJson); bootSpinner.succeed(`Created ${chalk.bold.green(pkg)}`); await Messages.start(pkg); } catch (error) { bootSpinner.fail(`Failed to create ${chalk.bold.red(pkg)}`); logError(error); process.exit(1); } const templateConfig = templates[template as keyof typeof templates]; const { dependencies: deps } = templateConfig; const installSpinner = ora(Messages.installing(deps.sort())).start(); try { const cmd = await getInstallCmd(); await execa(cmd, getInstallArgs(cmd, deps)); installSpinner.succeed('Installed dependencies'); console.log(await Messages.start(pkg)); } catch (error) { installSpinner.fail('Failed to install dependencies'); logError(error); process.exit(1); } }); prog .command('watch') .describe('Rebuilds on any change') .option('--entry, -i', 'Entry module') .example('watch --entry src/foo.tsx') .option('--target', 'Specify your target environment', 'browser') .example('watch --target node') .option('--name', 'Specify name exposed in UMD builds') .example('watch --name Foo') .option('--format', 'Specify module format(s)', 'cjs,esm') .example('watch --format cjs,esm') .option( '--verbose', 'Keep outdated console output in watch mode instead of clearing the screen' ) .example('watch --verbose') .option('--noClean', "Don't clean the dist folder") .example('watch --noClean') .option('--tsconfig', 'Specify custom tsconfig path') .example('watch --tsconfig ./tsconfig.foo.json') .option('--onFirstSuccess', 'Run a command on the first successful build') .example('watch --onFirstSuccess "echo The first successful build!"') .option('--onSuccess', 'Run a command on a successful build') .example('watch --onSuccess "echo Successful build!"') .option('--onFailure', 'Run a command on a failed build') .example('watch --onFailure "The build failed!"') .option('--transpileOnly', 'Skip type checking') .example('watch --transpileOnly') .option('--extractErrors', 'Extract invariant errors to ./errors/codes.json.') .example('watch --extractErrors') .action(async (dirtyOpts: WatchOpts) => { const opts = await normalizeOpts(dirtyOpts); const buildConfigs = await createBuildConfigs(opts); if (!opts.noClean) { await cleanDistFolder(); } if (opts.format.includes('cjs')) { await writeCjsEntryFile(opts.name); } if (opts.format.includes('esm')) { await writeMjsEntryFile(opts.name); } type Killer = execa.ExecaChildProcess | null; let firstTime = true; let successKiller: Killer = null; let failureKiller: Killer = null; function run(command?: string) { if (!command) { return null; } const [exec, ...args] = command.split(' '); return execa(exec, args, { stdio: 'inherit', }); } function killHooks() { return Promise.all([ successKiller ? successKiller.kill('SIGTERM') : null, failureKiller ? failureKiller.kill('SIGTERM') : null, ]); } const spinner = ora().start(); watch( (buildConfigs as RollupWatchOptions[]).map(inputOptions => ({ watch: { silent: true, include: ['src/**'], exclude: ['node_modules/**'], } as WatcherOptions, ...inputOptions, })) ).on('event', async event => { // clear previous onSuccess/onFailure hook processes so they don't pile up await killHooks(); if (event.code === 'START') { if (!opts.verbose) { clearConsole(); } spinner.start(chalk.bold.cyan('Compiling modules...')); } if (event.code === 'ERROR') { spinner.fail(chalk.bold.red('Failed to compile')); logError(event.error); failureKiller = run(opts.onFailure); } if (event.code === 'END') { spinner.succeed(chalk.bold.green('Compiled successfully')); console.log(` ${chalk.dim('Watching for changes')} `); try { await deprecated.moveTypes(); if (firstTime && opts.onFirstSuccess) { firstTime = false; run(opts.onFirstSuccess); } else { successKiller = run(opts.onSuccess); } } catch (_error) { } } }); }); prog .command('build') .describe('Build your project once and exit') .option('--entry, -i', 'Entry module') .example('build --entry src/foo.tsx') .option('--target', 'Specify your target environment', 'browser') .example('build --target node') .option('--name', 'Specify name exposed in UMD builds') .example('build --name Foo') .option('--format', 'Specify module format(s)', 'cjs,esm') .example('build --format cjs,esm') .option('--legacy', 'Babel transpile and emit ES5.') .example('build --legacy') .option('--tsconfig', 'Specify custom tsconfig path') .example('build --tsconfig ./tsconfig.foo.json') .option('--transpileOnly', 'Skip type checking') .example('build --transpileOnly') .option( '--extractErrors', 'Extract errors to ./errors/codes.json and provide a url for decoding.' ) .example( 'build --extractErrors=https://reactjs.org/docs/error-decoder.html?invariant=' ) .action(async (dirtyOpts: BuildOpts) => { const opts = await normalizeOpts(dirtyOpts); const buildConfigs = await createBuildConfigs(opts); await cleanDistFolder(); const logger = await createProgressEstimator(); if (opts.format.includes('cjs')) { const promise = writeCjsEntryFile(opts.name).catch(logError); logger(promise, 'Creating CJS entry file'); } if (opts.format.includes('esm')) { const promise = writeMjsEntryFile(opts.name).catch(logError); logger(promise, 'Creating MJS entry file'); } try { const promise = asyncro .map( buildConfigs, async (inputOptions: RollupOptions & { output: OutputOptions }) => { let bundle = await rollup(inputOptions); await bundle.write(inputOptions.output); } ) .catch((e: any) => { throw e; }) .then(async () => { await deprecated.moveTypes(); }); logger(promise, 'Building modules'); await promise; } catch (error) { logError(error); process.exit(1); } }); async function normalizeOpts(opts: WatchOpts): Promise<NormalizedOpts> { return { ...opts, name: opts.name || appPackageJson.name, input: await getInputs(opts.entry, appPackageJson.source), format: opts.format.split(',').map((format: string) => { if (format === 'es') { return 'esm'; } return format; }) as [ModuleFormat, ...ModuleFormat[]], }; } async function cleanDistFolder() { await fs.remove(paths.appDist); } function writeCjsEntryFile(name: string) { const baseLine = `module.exports = require('./${safePackageName(name)}`; const contents = ` 'use strict' if (process.env.NODE_ENV === 'production') { ${baseLine}.production.min.cjs') } else { ${baseLine}.development.cjs') } `; return fs.outputFile(path.join(paths.appDist, 'index.cjs'), contents); } function writeMjsEntryFile(name: string) { const contents = ` export { default } from './${name}.min.mjs'; export * from './${name}.min.mjs'; `; return fs.outputFile(path.join(paths.appDist, 'index.mjs'), contents); } function getAuthorName() { let author = ''; author = shell .exec('npm config get init-author-name', { silent: true }) .stdout.trim(); if (author) return author; author = shell .exec('git config --global user.name', { silent: true }) .stdout.trim(); if (author) { setAuthorName(author); return author; } author = shell .exec('npm config get init-author-email', { silent: true }) .stdout.trim(); if (author) return author; author = shell .exec('git config --global user.email', { silent: true }) .stdout.trim(); if (author) return author; return author; } function setAuthorName(author: string) { shell.exec(`npm config set init-author-name "${author}"`, { silent: true }); } prog .command('test') .describe('Run jest test runner. Passes through all flags directly to Jest') .action(async (opts: { config?: string }) => { // Do this as the first thing so that any code reading it knows the right env. process.env.BABEL_ENV = 'test'; process.env.NODE_ENV = 'test'; // Makes the script crash on unhandled rejections instead of silently // ignoring them. In the future, promise rejections that are not handled will // terminate the Node.js process with a non-zero exit code. process.on('unhandledRejection', err => { throw err; }); const argv = process.argv.slice(2); let jestConfig: JestConfigOptions = { ...createJestConfig( relativePath => path.resolve(__dirname, '..', relativePath), opts.config ? path.dirname(opts.config) : paths.appRoot ), ...appPackageJson.jest, passWithNoTests: true, }; // Allow overriding with jest.config const defaultPathExists = await fs.pathExists(paths.jestConfig); if (opts.config || defaultPathExists) { const jestConfigPath = resolveApp(opts.config || paths.jestConfig); const jestConfigContents: JestConfigOptions = require(jestConfigPath); jestConfig = { ...jestConfig, ...jestConfigContents }; } // if custom path, delete the arg as it's already been merged if (opts.config) { let configIndex = argv.indexOf('--config'); if (configIndex !== -1) { // case of "--config path", delete both args argv.splice(configIndex, 2); } else { // case of "--config=path", only one arg to delete const configRegex = /--config=.+/; configIndex = argv.findIndex(arg => arg.match(configRegex)); if (configIndex !== -1) { argv.splice(configIndex, 1); } } } argv.push( '--config', JSON.stringify({ ...jestConfig, }) ); const [, ...argsToPassToJestCli] = argv; jest.run(argsToPassToJestCli); }); prog .command('lint') .describe('Run eslint with Prettier') .example('lint src test') .option('--fix', 'Fixes fixable errors and warnings') .example('lint src test --fix') .option('--ignore-pattern', 'Ignore a pattern') .example('lint src test --ignore-pattern test/foobar.ts') .option( '--max-warnings', 'Exits with non-zero error code if number of warnings exceed this number', Infinity ) .example('lint src test --max-warnings 10') .option('--write-file', 'Write the config file locally') .example('lint --write-file') .option('--report-file', 'Write JSON report to file locally') .example('lint --report-file eslint-report.json') .action( async (opts: { fix: boolean; 'ignore-pattern': string; 'write-file': boolean; 'report-file': string; 'max-warnings': number; _: string[]; }) => { if (opts['_'].length === 0 && !opts['write-file']) { const defaultInputs = ['src', 'test'].filter(fs.existsSync); opts['_'] = defaultInputs; console.log( chalk.yellow( `Defaulting to "tsdx lint ${defaultInputs.join(' ')}"`, '\nYou can override this in the package.json scripts, like "lint": "tsdx lint src otherDir"' ) ); } const config = await createEslintConfig({ pkg: appPackageJson, rootDir: paths.appRoot, writeFile: opts['write-file'], }); const cli = new CLIEngine({ baseConfig: { ...config, ...appPackageJson.eslint, }, extensions: ['.ts', '.tsx', '.js', '.jsx'], fix: opts.fix, ignorePattern: opts['ignore-pattern'], }); const report = cli.executeOnFiles(opts['_']); if (opts.fix) { CLIEngine.outputFixes(report); } console.log(cli.getFormatter()(report.results)); if (opts['report-file']) { await fs.outputFile( opts['report-file'], cli.getFormatter('json')(report.results) ); } if (report.errorCount) { process.exit(1); } if (report.warningCount > opts['max-warnings']) { process.exit(1); } } ); prog.parse(process.argv);
the_stack
import { watch, watchEffect, computed, reactive, ref, set, shallowReactive, nextTick, } from '../../../src' import Vue from 'vue' // reference: https://vue-composition-api-rfc.netlify.com/api.html#watch describe('api: watch', () => { // const warnSpy = jest.spyOn(console, 'warn'); const warnSpy = jest.spyOn((Vue as any).util, 'warn') beforeEach(() => { warnSpy.mockReset() }) it('effect', async () => { const state = reactive({ count: 0 }) let dummy watchEffect(() => { dummy = state.count }) expect(dummy).toBe(0) state.count++ await nextTick() expect(dummy).toBe(1) }) it('watching single source: getter', async () => { const state = reactive({ count: 0 }) let dummy watch( () => state.count, (count, prevCount) => { dummy = [count, prevCount] // assert types count + 1 if (prevCount) { prevCount + 1 } } ) state.count++ await nextTick() expect(dummy).toMatchObject([1, 0]) }) it('watching single source: ref', async () => { const count = ref(0) let dummy watch(count, (count, prevCount) => { dummy = [count, prevCount] // assert types count + 1 if (prevCount) { prevCount + 1 } }) count.value++ await nextTick() expect(dummy).toMatchObject([1, 0]) }) it('watching single source: computed ref', async () => { const count = ref(0) const plus = computed(() => count.value + 1) let dummy watch(plus, (count, prevCount) => { dummy = [count, prevCount] // assert types count + 1 if (prevCount) { prevCount + 1 } }) count.value++ await nextTick() expect(dummy).toMatchObject([2, 1]) }) it('watching primitive with deep: true', async () => { const count = ref(0) let dummy watch( count, (c, prevCount) => { dummy = [c, prevCount] }, { deep: true, } ) count.value++ await nextTick() expect(dummy).toMatchObject([1, 0]) }) it('directly watching reactive object (with automatic deep: true)', async () => { const src = reactive({ count: 0, }) let dummy watch(src, ({ count }) => { dummy = count }) src.count++ await nextTick() expect(dummy).toBe(1) }) it('watching multiple sources', async () => { const state = reactive({ count: 1 }) const count = ref(1) const plus = computed(() => count.value + 1) let dummy watch([() => state.count, count, plus], (vals, oldVals) => { dummy = [vals, oldVals] // assert types vals.concat(1) oldVals.concat(1) }) state.count++ count.value++ await nextTick() expect(dummy).toMatchObject([ [2, 2, 3], [1, 1, 2], ]) }) it('watching multiple sources: readonly array', async () => { const state = reactive({ count: 1 }) const status = ref(false) let dummy watch([() => state.count, status] as const, (vals, oldVals) => { dummy = [vals, oldVals] const [count] = vals const [, oldStatus] = oldVals // assert types count + 1 oldStatus === true }) state.count++ status.value = true await nextTick() expect(dummy).toMatchObject([ [2, true], [1, false], ]) }) it('warn invalid watch source', () => { // @ts-ignore watch(1, () => {}) expect(warnSpy).toHaveBeenCalledWith( expect.stringContaining('Invalid watch source'), expect.anything() ) }) it('stopping the watcher (effect)', async () => { const state = reactive({ count: 0 }) let dummy const stop = watchEffect(() => { dummy = state.count }) expect(dummy).toBe(0) stop() state.count++ await nextTick() // should not update expect(dummy).toBe(0) }) it('stopping the watcher (with source)', async () => { const state = reactive({ count: 0 }) let dummy const stop = watch( () => state.count, (count) => { dummy = count } ) state.count++ await nextTick() expect(dummy).toBe(1) stop() state.count++ await nextTick() // should not update expect(dummy).toBe(1) }) it('cleanup registration (effect)', async () => { const state = reactive({ count: 0 }) const cleanup = jest.fn() let dummy const stop = watchEffect((onCleanup) => { onCleanup(cleanup) dummy = state.count }) expect(dummy).toBe(0) state.count++ await nextTick() expect(cleanup).toHaveBeenCalledTimes(1) expect(dummy).toBe(1) stop() expect(cleanup).toHaveBeenCalledTimes(2) }) it('cleanup registration (with source)', async () => { const count = ref(0) const cleanup = jest.fn() let dummy const stop = watch(count, (count, prevCount, onCleanup) => { onCleanup(cleanup) dummy = count }) count.value++ await nextTick() expect(cleanup).toHaveBeenCalledTimes(0) expect(dummy).toBe(1) count.value++ await nextTick() expect(cleanup).toHaveBeenCalledTimes(1) expect(dummy).toBe(2) stop() expect(cleanup).toHaveBeenCalledTimes(2) }) // it('flush timing: post (default)', async () => { // const count = ref(0); // let callCount = 0; // const assertion = jest.fn(count => { // callCount++; // // on mount, the watcher callback should be called before DOM render // // on update, should be called after the count is updated // const expectedDOM = callCount === 1 ? `` : `${count}`; // expect(serializeInner(root)).toBe(expectedDOM); // }); // const Comp = { // setup() { // watchEffect(() => { // assertion(count.value); // }); // return () => count.value; // }, // }; // const root = nodeOps.createElement('div'); // render(h(Comp), root); // expect(assertion).toHaveBeenCalledTimes(1); // count.value++; // await nextTick(); // expect(assertion).toHaveBeenCalledTimes(2); // }); // it('flush timing: pre', async () => { // const count = ref(0); // const count2 = ref(0); // let callCount = 0; // const assertion = jest.fn((count, count2Value) => { // callCount++; // // on mount, the watcher callback should be called before DOM render // // on update, should be called before the count is updated // const expectedDOM = callCount === 1 ? `` : `${count - 1}`; // expect(serializeInner(root)).toBe(expectedDOM); // // in a pre-flush callback, all state should have been updated // const expectedState = callCount === 1 ? 0 : 1; // expect(count2Value).toBe(expectedState); // }); // const Comp = { // setup() { // watchEffect( // () => { // assertion(count.value, count2.value); // }, // { // flush: 'pre', // } // ); // return () => count.value; // }, // }; // const root = nodeOps.createElement('div'); // render(h(Comp), root); // expect(assertion).toHaveBeenCalledTimes(1); // count.value++; // count2.value++; // await nextTick(); // // two mutations should result in 1 callback execution // expect(assertion).toHaveBeenCalledTimes(2); // }); // it('flush timing: sync', async () => { // const count = ref(0); // const count2 = ref(0); // let callCount = 0; // const assertion = jest.fn(count => { // callCount++; // // on mount, the watcher callback should be called before DOM render // // on update, should be called before the count is updated // const expectedDOM = callCount === 1 ? `` : `${count - 1}`; // expect(serializeInner(root)).toBe(expectedDOM); // // in a sync callback, state mutation on the next line should not have // // executed yet on the 2nd call, but will be on the 3rd call. // const expectedState = callCount < 3 ? 0 : 1; // expect(count2.value).toBe(expectedState); // }); // const Comp = { // setup() { // watchEffect( // () => { // assertion(count.value); // }, // { // flush: 'sync', // } // ); // return () => count.value; // }, // }; // const root = nodeOps.createElement('div'); // render(h(Comp), root); // expect(assertion).toHaveBeenCalledTimes(1); // count.value++; // count2.value++; // await nextTick(); // expect(assertion).toHaveBeenCalledTimes(3); // }); it('deep', async () => { const state = reactive({ nested: { count: ref(0), }, array: [1, 2, 3], map: new Map([ ['a', 1], ['b', 2], ]), set: new Set([1, 2, 3]), }) let dummy watch( () => state, (state) => { dummy = [ state.nested.count, state.array[0], state.map.get('a'), state.set.has(1), ] }, { deep: true } ) state.nested.count++ await nextTick() expect(dummy).toEqual([1, 1, 1, true]) // nested array mutation set(state.array, '0', 2) await nextTick() expect(dummy).toEqual([1, 2, 1, true]) // NOT supported by Vue.observe :( // // nested map mutation // state.map.set('a', 2); // await nextTick(); // expect(dummy).toEqual([1, 2, 2, true]); // // nested set mutation // state.set.delete(1); // await nextTick(); // expect(dummy).toEqual([1, 2, 2, false]); }) it('immediate', async () => { const count = ref(0) const cb = jest.fn() watch(count, cb, { immediate: true }) expect(cb).toHaveBeenCalledTimes(1) count.value++ await nextTick() expect(cb).toHaveBeenCalledTimes(2) }) it('immediate: triggers when initial value is null', async () => { const state = ref(null) const spy = jest.fn() watch(() => state.value, spy, { immediate: true }) expect(spy).toHaveBeenCalled() }) it('immediate: triggers when initial value is undefined', async () => { const state = ref() const spy = jest.fn() watch(() => state.value, spy, { immediate: true }) expect(spy).toHaveBeenCalled() state.value = 3 await nextTick() expect(spy).toHaveBeenCalledTimes(2) // testing if undefined can trigger the watcher state.value = undefined await nextTick() expect(spy).toHaveBeenCalledTimes(3) // it shouldn't trigger if the same value is set state.value = undefined await nextTick() expect(spy).toHaveBeenCalledTimes(3) }) it('shallow reactive effect', async () => { const state = shallowReactive({ count: 0 }) let dummy watch( () => state.count, () => { dummy = state.count }, { immediate: true } ) expect(dummy).toBe(0) state.count++ await nextTick() expect(dummy).toBe(1) }) it('shallow reactive object', async () => { const state = shallowReactive({ a: { count: 0 } }) let dummy watch( () => state.a, () => { dummy = state.a.count }, { immediate: true } ) expect(dummy).toBe(0) state.a.count++ await nextTick() expect(dummy).toBe(0) state.a = { count: 5 } await nextTick() expect(dummy).toBe(5) }) // it('warn immediate option when using effect', async () => { // const count = ref(0); // let dummy; // watchEffect( // () => { // dummy = count.value; // }, // // @ts-ignore // { immediate: false } // ); // expect(dummy).toBe(0); // expect(warnSpy).toHaveBeenCalledWith(`"immediate" option is only respected`); // count.value++; // await nextTick(); // expect(dummy).toBe(1); // }); // it('warn and not respect deep option when using effect', async () => { // const arr = ref([1, [2]]); // const spy = jest.fn(); // watchEffect( // () => { // spy(); // return arr; // }, // // @ts-ignore // { deep: true } // ); // expect(spy).toHaveBeenCalledTimes(1); // (arr.value[1] as Array<number>)[0] = 3; // await nextTick(); // expect(spy).toHaveBeenCalledTimes(1); // expect(warnSpy).toHaveBeenCalledWith(`"deep" option is only respected`); // }); // #388 it('should not call the callback multiple times', () => { const data = ref([1, 1, 1, 1, 1]) const data2 = ref<number[]>([]) watchEffect( () => { data2.value = data.value.slice(1, 2) }, { flush: 'sync', } ) expect(data2.value).toMatchObject([1]) }) // #498 it('watchEffect should not lead to infinite loop when accessing', async () => { let dummy = 0 const state = reactive({ data: [], watchVar: 123, }) watchEffect(() => { // accessing state.watchVar // setting state.data = [] dummy += 1 }) expect(dummy).toBe(1) await nextTick() expect(dummy).toBe(1) }) it('watching deep ref', async () => { const count = ref(0) const double = computed(() => count.value * 2) const state = reactive([count, double]) let dummy watch( () => state, (state) => { dummy = [state[0].value, state[1].value] }, { deep: true } ) count.value++ await nextTick() expect(dummy).toEqual([1, 2]) }) // #805 #807 it('watching sources: [ref<[]>] w/ deep', async () => { const foo = ref([1]) const cb = jest.fn() watch([foo], cb, { deep: true }) foo.value.push(2) await nextTick() expect(cb).toBeCalledTimes(1) }) })
the_stack
import { strict as assert } from "assert"; import { MockFluidDataStoreRuntime, MockContainerRuntimeFactory, MockStorage, } from "@fluidframework/test-runtime-utils"; import { ReferenceType } from "@fluidframework/merge-tree"; import { IChannelServices } from "@fluidframework/datastore-definitions"; import { ISummaryTree } from "@fluidframework/protocol-definitions"; import { SharedStringFactory, SharedString } from ".."; function applyOperations(sharedString: SharedString, content = sharedString.getLength().toString()) { const lenMod = sharedString.getLength() % 4; switch (lenMod) { case 0: sharedString.insertText(0, content); break; case 1: { const pos = Math.floor(sharedString.getLength() / lenMod); sharedString.insertMarker(pos, ReferenceType.Simple); break; } case 2: { sharedString.insertText(sharedString.getLength(), content); const pos = Math.floor(sharedString.getLength() / lenMod); sharedString.removeText( pos, pos + 1); // fall through to insert after remove } default: sharedString.insertText(sharedString.getLength(), content); } } const mergeTreeSnapshotChunkSize = 5; function generateSummaryTree( containerRuntimeFactory: MockContainerRuntimeFactory, options: any = {}, ): [SharedString, ISummaryTree] { const dataStoreRuntime1 = new MockFluidDataStoreRuntime(); dataStoreRuntime1.options = options; // Connect the first SharedString. const containerRuntime1 = containerRuntimeFactory.createContainerRuntime(dataStoreRuntime1); const services1: IChannelServices = { deltaConnection: containerRuntime1.createDeltaConnection(), objectStorage: new MockStorage(), }; const sharedString = new SharedString(dataStoreRuntime1, "shared-string", SharedStringFactory.Attributes); sharedString.initializeLocal(); sharedString.connect(services1); // Create and connect a second SharedString. const dataStoreRuntime2 = new MockFluidDataStoreRuntime(); dataStoreRuntime2.options = options; const containerRuntime2 = containerRuntimeFactory.createContainerRuntime(dataStoreRuntime2); const sharedString2 = new SharedString(dataStoreRuntime2, "shared-string", SharedStringFactory.Attributes); const services2: IChannelServices = { deltaConnection: containerRuntime2.createDeltaConnection(), objectStorage: new MockStorage(), }; sharedString2.initializeLocal(); sharedString2.connect(services2); while (sharedString.getLength() < mergeTreeSnapshotChunkSize * 3) { applyOperations(sharedString); containerRuntimeFactory.processAllMessages(); } assert.equal(sharedString2.getText(), sharedString.getText()); const summaryTree = sharedString2.summarize().summary; assert(summaryTree); return [sharedString2, summaryTree]; } describe("SharedString Partial Load", () => { it("Validate Full Load", async () => { const containerRuntimeFactory = new MockContainerRuntimeFactory(); const options = { mergeTreeSnapshotChunkSize }; const [remoteSharedString, summaryTree] = generateSummaryTree(containerRuntimeFactory, options); const localDataStoreRuntime = new MockFluidDataStoreRuntime(); localDataStoreRuntime.options = options; const localContainerRuntime = containerRuntimeFactory.createContainerRuntime(localDataStoreRuntime); const localServices = { deltaConnection: localContainerRuntime.createDeltaConnection(), objectStorage: MockStorage.createFromSummary(summaryTree), }; const localSharedString = new SharedString(localDataStoreRuntime, "shared-string", SharedStringFactory.Attributes); await localSharedString.load(localServices); assert.equal(localSharedString.getText(), remoteSharedString.getText()); }); it("Validate New Format Load", async () => { const containerRuntimeFactory = new MockContainerRuntimeFactory(); const options = { newMergeTreeSnapshotFormat: true, mergeTreeSnapshotChunkSize }; const [remoteSharedString, summaryTree] = generateSummaryTree(containerRuntimeFactory, options); const localDataStoreRuntime = new MockFluidDataStoreRuntime(); localDataStoreRuntime.options = options; const localContainerRuntime = containerRuntimeFactory.createContainerRuntime(localDataStoreRuntime); const localServices = { deltaConnection: localContainerRuntime.createDeltaConnection(), objectStorage: MockStorage.createFromSummary(summaryTree), }; const localSharedString = new SharedString(localDataStoreRuntime, "shared-string", SharedStringFactory.Attributes); await localSharedString.load(localServices); assert.equal(localSharedString.getText(), remoteSharedString.getText()); }); it("Validate Partial load", async () => { const containerRuntimeFactory = new MockContainerRuntimeFactory(); const options = { newMergeTreeSnapshotFormat: true, sequenceInitializeFromHeaderOnly: true, mergeTreeSnapshotChunkSize, }; const [remoteSharedString, summaryTree] = generateSummaryTree(containerRuntimeFactory, options); const localDataStoreRuntime = new MockFluidDataStoreRuntime(); localDataStoreRuntime.options = options; const localContainerRuntime = containerRuntimeFactory.createContainerRuntime(localDataStoreRuntime); const localServices = { deltaConnection: localContainerRuntime.createDeltaConnection(), objectStorage: MockStorage.createFromSummary(summaryTree), }; const localSharedString = new SharedString(localDataStoreRuntime, "shared-string", SharedStringFactory.Attributes); await localSharedString.load(localServices); assert.notEqual(localSharedString.getText(), remoteSharedString.getText()); await localSharedString.loaded; localDataStoreRuntime.deltaManager.lastSequenceNumber = localSharedString.getCurrentSeq(); assert.equal(localSharedString.getText(), remoteSharedString.getText()); }); it("Validate Partial load with local ops", async () => { const containerRuntimeFactory = new MockContainerRuntimeFactory(); const options = { sequenceInitializeFromHeaderOnly: true, mergeTreeSnapshotChunkSize, }; const [remoteSharedString, summaryTree] = generateSummaryTree(containerRuntimeFactory, options); const localDataStoreRuntime = new MockFluidDataStoreRuntime(); localDataStoreRuntime.options = options; const localContainerRuntime = containerRuntimeFactory.createContainerRuntime(localDataStoreRuntime); const localServices = { deltaConnection: localContainerRuntime.createDeltaConnection(), objectStorage: MockStorage.createFromSummary(summaryTree), }; const localSharedString = new SharedString(localDataStoreRuntime, "shared-string", SharedStringFactory.Attributes); await localSharedString.load(localServices); localDataStoreRuntime.deltaManager.lastSequenceNumber = containerRuntimeFactory.sequenceNumber; localDataStoreRuntime.deltaManager.minimumSequenceNumber = containerRuntimeFactory.getMinSeq(); assert.notEqual(localSharedString.getText(), remoteSharedString.getText()); for (let i = 0; i < 10; i++) { applyOperations(localSharedString, "L"); } assert.equal(containerRuntimeFactory.outstandingMessageCount, 0); await localSharedString.loaded; assert.notEqual(localSharedString.getText(), remoteSharedString.getText()); assert.notEqual(containerRuntimeFactory.outstandingMessageCount, 0); containerRuntimeFactory.processAllMessages(); assert.equal(localSharedString.getText(), remoteSharedString.getText()); }); it("Validate Partial load with remote ops", async () => { const containerRuntimeFactory = new MockContainerRuntimeFactory(); const options = { sequenceInitializeFromHeaderOnly: true, mergeTreeSnapshotChunkSize, }; const [remoteSharedString, summaryTree] = generateSummaryTree(containerRuntimeFactory, options); const localDataStoreRuntime = new MockFluidDataStoreRuntime(); localDataStoreRuntime.options = options; const localContainerRuntime = containerRuntimeFactory.createContainerRuntime(localDataStoreRuntime); const localServices = { deltaConnection: localContainerRuntime.createDeltaConnection(), objectStorage: MockStorage.createFromSummary(summaryTree), }; const localSharedString = new SharedString(localDataStoreRuntime, "shared-string", SharedStringFactory.Attributes); await localSharedString.load(localServices); localDataStoreRuntime.deltaManager.lastSequenceNumber = containerRuntimeFactory.sequenceNumber; localDataStoreRuntime.deltaManager.minimumSequenceNumber = containerRuntimeFactory.getMinSeq(); assert.notEqual(localSharedString.getText(), remoteSharedString.getText()); for (let i = 0; i < 10; i++) { applyOperations(remoteSharedString, "R"); } containerRuntimeFactory.processAllMessages(); assert.notEqual(localSharedString.getText(), remoteSharedString.getText()); await localSharedString.loaded; assert.equal(localSharedString.getText(), remoteSharedString.getText()); }); it("Validate Partial load with local and remote ops", async () => { const containerRuntimeFactory = new MockContainerRuntimeFactory(); const options = { sequenceInitializeFromHeaderOnly: true, mergeTreeSnapshotChunkSize, }; const [remoteSharedString, summaryTree] = generateSummaryTree(containerRuntimeFactory, options); const localDataStoreRuntime = new MockFluidDataStoreRuntime(); localDataStoreRuntime.options = options; const localContainerRuntime = containerRuntimeFactory.createContainerRuntime(localDataStoreRuntime); const localServices = { deltaConnection: localContainerRuntime.createDeltaConnection(), objectStorage: MockStorage.createFromSummary(summaryTree), }; const localSharedString = new SharedString(localDataStoreRuntime, "shared-string", SharedStringFactory.Attributes); await localSharedString.load(localServices); localDataStoreRuntime.deltaManager.lastSequenceNumber = containerRuntimeFactory.sequenceNumber; localDataStoreRuntime.deltaManager.minimumSequenceNumber = containerRuntimeFactory.getMinSeq(); assert.notEqual(localSharedString.getText(), remoteSharedString.getText()); for (let i = 0; i < 10; i++) { applyOperations(remoteSharedString, "R"); } for (let i = 0; i < 10; i++) { applyOperations(localSharedString, "L"); } containerRuntimeFactory.processAllMessages(); assert.notEqual(localSharedString.getText(), remoteSharedString.getText()); await localSharedString.loaded; assert.notEqual(localSharedString.getText(), remoteSharedString.getText()); containerRuntimeFactory.processAllMessages(); assert.equal(localSharedString.getText(), remoteSharedString.getText()); }); });
the_stack
import HttpPollingDatafileManager from '../src/httpPollingDatafileManager'; import { Headers, AbortableRequest, Response } from '../src/http'; import { DatafileManagerConfig } from '../src/datafileManager'; import { advanceTimersByTime, getTimerCount } from './testUtils'; import PersistentKeyValueCache from '../src/persistentKeyValueCache'; jest.mock('../src/backoffController', () => { return jest.fn().mockImplementation(() => { const getDelayMock = jest.fn().mockImplementation(() => 0); return { getDelay: getDelayMock, countError: jest.fn(), reset: jest.fn(), }; }); }); import BackoffController from '../src/backoffController'; // Test implementation: // - Does not make any real requests: just resolves with queued responses (tests push onto queuedResponses) class TestDatafileManager extends HttpPollingDatafileManager { queuedResponses: (Response | Error)[] = []; responsePromises: Promise<Response>[] = []; simulateResponseDelay = false; // Need these unsued vars for the mock call types to work (being able to check calls) // eslint-disable-next-line @typescript-eslint/no-unused-vars makeGetRequest(url: string, headers: Headers): AbortableRequest { const nextResponse: Error | Response | undefined = this.queuedResponses.pop(); let responsePromise: Promise<Response>; if (nextResponse === undefined) { responsePromise = Promise.reject('No responses queued'); } else if (nextResponse instanceof Error) { responsePromise = Promise.reject(nextResponse); } else { if (this.simulateResponseDelay) { // Actual response will have some delay. This is required to get expected behavior for caching. responsePromise = new Promise(resolve => setTimeout(() => resolve(nextResponse), 50)); } else { responsePromise = Promise.resolve(nextResponse); } } this.responsePromises.push(responsePromise); return { responsePromise, abort: jest.fn() }; } getConfigDefaults(): Partial<DatafileManagerConfig> { return {}; } } const testCache: PersistentKeyValueCache = { get(key: string): Promise<string> { let val = ''; switch (key) { case 'opt-datafile-keyThatExists': val = JSON.stringify({ name: 'keyThatExists' }); break; } return Promise.resolve(val); }, set(): Promise<void> { return Promise.resolve(); }, contains(): Promise<boolean> { return Promise.resolve(false); }, remove(): Promise<void> { return Promise.resolve(); }, }; describe('httpPollingDatafileManager', () => { beforeEach(() => { jest.useFakeTimers(); }); let manager: TestDatafileManager; afterEach(async () => { if (manager) { manager.stop(); } jest.clearAllMocks(); jest.restoreAllMocks(); jest.clearAllTimers(); }); describe('when constructed with sdkKey and datafile and autoUpdate: true,', () => { beforeEach(() => { manager = new TestDatafileManager({ datafile: JSON.stringify({ foo: 'abcd' }), sdkKey: '123', autoUpdate: true }); }); it('returns the passed datafile from get', () => { expect(JSON.parse(manager.get())).toEqual({ foo: 'abcd' }); }); it('after being started, fetches the datafile, updates itself, and updates itself again after a timeout', async () => { manager.queuedResponses.push( { statusCode: 200, body: '{"fooz": "barz"}', headers: {}, }, { statusCode: 200, body: '{"foo": "bar"}', headers: {}, } ); const updateFn = jest.fn(); manager.on('update', updateFn); manager.start(); expect(manager.responsePromises.length).toBe(1); await manager.responsePromises[0]; expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); updateFn.mockReset(); await advanceTimersByTime(300000); expect(manager.responsePromises.length).toBe(2); await manager.responsePromises[1]; expect(updateFn).toBeCalledTimes(1); expect(updateFn.mock.calls[0][0]).toEqual({ datafile: '{"fooz": "barz"}' }); expect(JSON.parse(manager.get())).toEqual({ fooz: 'barz' }); }); }); describe('when constructed with sdkKey and datafile and autoUpdate: false,', () => { beforeEach(() => { manager = new TestDatafileManager({ datafile: JSON.stringify({ foo: 'abcd' }), sdkKey: '123', autoUpdate: false, }); }); it('returns the passed datafile from get', () => { expect(JSON.parse(manager.get())).toEqual({ foo: 'abcd' }); }); it('after being started, fetches the datafile, updates itself once, but does not schedule a future update', async () => { manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); manager.start(); expect(manager.responsePromises.length).toBe(1); await manager.responsePromises[0]; expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); expect(getTimerCount()).toBe(0); }); }); describe('when constructed with sdkKey and autoUpdate: true', () => { beforeEach(() => { manager = new TestDatafileManager({ sdkKey: '123', updateInterval: 1000, autoUpdate: true }); }); describe('initial state', () => { it('returns null from get before becoming ready', () => { expect(manager.get()).toEqual(''); }); }); describe('started state', () => { it('passes the default datafile URL to the makeGetRequest method', async () => { const makeGetRequestSpy = jest.spyOn(manager, 'makeGetRequest'); manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); manager.start(); expect(makeGetRequestSpy).toBeCalledTimes(1); expect(makeGetRequestSpy.mock.calls[0][0]).toBe('https://cdn.optimizely.com/datafiles/123.json'); await manager.onReady(); }); it('after being started, fetches the datafile and resolves onReady', async () => { manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); manager.start(); await manager.onReady(); expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); }); describe('live updates', () => { it('sets a timeout to update again after the update interval', async () => { manager.queuedResponses.push( { statusCode: 200, body: '{"foo3": "bar3"}', headers: {}, }, { statusCode: 200, body: '{"foo4": "bar4"}', headers: {}, } ); const makeGetRequestSpy = jest.spyOn(manager, 'makeGetRequest'); manager.start(); expect(makeGetRequestSpy).toBeCalledTimes(1); await manager.responsePromises[0]; await advanceTimersByTime(1000); expect(makeGetRequestSpy).toBeCalledTimes(2); }); it('emits update events after live updates', async () => { manager.queuedResponses.push( { statusCode: 200, body: '{"foo3": "bar3"}', headers: {}, }, { statusCode: 200, body: '{"foo2": "bar2"}', headers: {}, }, { statusCode: 200, body: '{"foo": "bar"}', headers: {}, } ); const updateFn = jest.fn(); manager.on('update', updateFn); manager.start(); await manager.onReady(); expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); expect(updateFn).toBeCalledTimes(0); await advanceTimersByTime(1000); await manager.responsePromises[1]; expect(updateFn).toBeCalledTimes(1); expect(updateFn.mock.calls[0][0]).toEqual({ datafile: '{"foo2": "bar2"}' }); expect(JSON.parse(manager.get())).toEqual({ foo2: 'bar2' }); updateFn.mockReset(); await advanceTimersByTime(1000); await manager.responsePromises[2]; expect(updateFn).toBeCalledTimes(1); expect(updateFn.mock.calls[0][0]).toEqual({ datafile: '{"foo3": "bar3"}' }); expect(JSON.parse(manager.get())).toEqual({ foo3: 'bar3' }); }); describe('when the update interval time fires before the request is complete', () => { it('waits until the request is complete before making the next request', async () => { let resolveResponsePromise: (resp: Response) => void; const responsePromise: Promise<Response> = new Promise(res => { resolveResponsePromise = res; }); const makeGetRequestSpy = jest.spyOn(manager, 'makeGetRequest').mockReturnValueOnce({ abort() {}, responsePromise, }); manager.start(); expect(makeGetRequestSpy).toBeCalledTimes(1); await advanceTimersByTime(1000); expect(makeGetRequestSpy).toBeCalledTimes(1); resolveResponsePromise!({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); await responsePromise; await advanceTimersByTime(0); expect(makeGetRequestSpy).toBeCalledTimes(2); }); }); it('cancels a pending timeout when stop is called', async () => { manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); manager.start(); await manager.onReady(); expect(getTimerCount()).toBe(1); manager.stop(); expect(getTimerCount()).toBe(0); }); it('cancels reactions to a pending fetch when stop is called', async () => { manager.queuedResponses.push( { statusCode: 200, body: '{"foo2": "bar2"}', headers: {}, }, { statusCode: 200, body: '{"foo": "bar"}', headers: {}, } ); manager.start(); await manager.onReady(); expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); await advanceTimersByTime(1000); expect(manager.responsePromises.length).toBe(2); manager.stop(); await manager.responsePromises[1]; // Should not have updated datafile since manager was stopped expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); }); it('calls abort on the current request if there is a current request when stop is called', async () => { manager.queuedResponses.push({ statusCode: 200, body: '{"foo2": "bar2"}', headers: {}, }); const makeGetRequestSpy = jest.spyOn(manager, 'makeGetRequest'); manager.start(); const currentRequest = makeGetRequestSpy.mock.results[0]; expect(currentRequest.type).toBe('return'); expect(currentRequest.value.abort).toBeCalledTimes(0); manager.stop(); expect(currentRequest.value.abort).toBeCalledTimes(1); }); it('can fail to become ready on the initial request, but succeed after a later polling update', async () => { manager.queuedResponses.push( { statusCode: 200, body: '{"foo": "bar"}', headers: {}, }, { statusCode: 404, body: '', headers: {}, } ); manager.start(); expect(manager.responsePromises.length).toBe(1); await manager.responsePromises[0]; // Not ready yet due to first request failed, but should have queued a live update expect(getTimerCount()).toBe(1); // Trigger the update, should fetch the next response which should succeed, then we get ready advanceTimersByTime(1000); await manager.onReady(); expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); }); describe('newness checking', () => { it('does not update if the response status is 304', async () => { manager.queuedResponses.push( { statusCode: 304, body: '', headers: {}, }, { statusCode: 200, body: '{"foo": "bar"}', headers: { 'Last-Modified': 'Fri, 08 Mar 2019 18:57:17 GMT', }, } ); const updateFn = jest.fn(); manager.on('update', updateFn); manager.start(); await manager.onReady(); expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); // First response promise was for the initial 200 response expect(manager.responsePromises.length).toBe(1); // Trigger the queued update await advanceTimersByTime(1000); // Second response promise is for the 304 response expect(manager.responsePromises.length).toBe(2); await manager.responsePromises[1]; // Since the response was 304, updateFn should not have been called expect(updateFn).toBeCalledTimes(0); expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); }); it('sends if-modified-since using the last observed response last-modified', async () => { manager.queuedResponses.push( { statusCode: 304, body: '', headers: {}, }, { statusCode: 200, body: '{"foo": "bar"}', headers: { 'Last-Modified': 'Fri, 08 Mar 2019 18:57:17 GMT', }, } ); manager.start(); await manager.onReady(); const makeGetRequestSpy = jest.spyOn(manager, 'makeGetRequest'); await advanceTimersByTime(1000); expect(makeGetRequestSpy).toBeCalledTimes(1); const firstCall = makeGetRequestSpy.mock.calls[0]; const headers = firstCall[1]; expect(headers).toEqual({ 'if-modified-since': 'Fri, 08 Mar 2019 18:57:17 GMT', }); }); }); describe('backoff', () => { it('uses the delay from the backoff controller getDelay method when greater than updateInterval', async () => { const BackoffControllerMock = (BackoffController as unknown) as jest.Mock<BackoffController, []>; const getDelayMock = BackoffControllerMock.mock.results[0].value.getDelay; getDelayMock.mockImplementationOnce(() => 5432); const makeGetRequestSpy = jest.spyOn(manager, 'makeGetRequest'); manager.queuedResponses.push({ statusCode: 404, body: '', headers: {}, }); manager.start(); await manager.responsePromises[0]; expect(makeGetRequestSpy).toBeCalledTimes(1); // Should not make another request after 1 second because the error should have triggered backoff advanceTimersByTime(1000); expect(makeGetRequestSpy).toBeCalledTimes(1); // But after another 5 seconds, another request should be made await advanceTimersByTime(5000); expect(makeGetRequestSpy).toBeCalledTimes(2); }); it('calls countError on the backoff controller when a non-success status code response is received', async () => { manager.queuedResponses.push({ statusCode: 404, body: '', headers: {}, }); manager.start(); await manager.responsePromises[0]; const BackoffControllerMock = (BackoffController as unknown) as jest.Mock<BackoffController, []>; expect(BackoffControllerMock.mock.results[0].value.countError).toBeCalledTimes(1); }); it('calls countError on the backoff controller when the response promise rejects', async () => { manager.queuedResponses.push(new Error('Connection failed')); manager.start(); try { await manager.responsePromises[0]; } catch (e) { //empty } const BackoffControllerMock = (BackoffController as unknown) as jest.Mock<BackoffController, []>; expect(BackoffControllerMock.mock.results[0].value.countError).toBeCalledTimes(1); }); it('calls reset on the backoff controller when a success status code response is received', async () => { manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: { 'Last-Modified': 'Fri, 08 Mar 2019 18:57:17 GMT', }, }); manager.start(); const BackoffControllerMock = (BackoffController as unknown) as jest.Mock<BackoffController, []>; // Reset is called in start - we want to check that it is also called after the response, so reset the mock here BackoffControllerMock.mock.results[0].value.reset.mockReset(); await manager.onReady(); expect(BackoffControllerMock.mock.results[0].value.reset).toBeCalledTimes(1); }); it('resets the backoff controller when start is called', async () => { const BackoffControllerMock = (BackoffController as unknown) as jest.Mock<BackoffController, []>; manager.start(); expect(BackoffControllerMock.mock.results[0].value.reset).toBeCalledTimes(1); try { await manager.responsePromises[0]; } catch (e) { // empty } }); }); }); }); }); describe('when constructed with sdkKey and autoUpdate: false', () => { beforeEach(() => { manager = new TestDatafileManager({ sdkKey: '123', autoUpdate: false }); }); it('after being started, fetches the datafile and resolves onReady', async () => { manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); manager.start(); await manager.onReady(); expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); }); it('does not schedule a live update after ready', async () => { manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); const updateFn = jest.fn(); manager.on('update', updateFn); manager.start(); await manager.onReady(); expect(getTimerCount()).toBe(0); }); // TODO: figure out what's wrong with this test it.skip('rejects the onReady promise if the initial request promise rejects', async () => { manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); manager.makeGetRequest = (): AbortableRequest => ({ abort(): void {}, responsePromise: Promise.reject(new Error('Could not connect')), }); manager.start(); let didReject = false; try { await manager.onReady(); } catch (e) { didReject = true; } expect(didReject).toBe(true); }); }); describe('when constructed with sdkKey and a valid urlTemplate', () => { beforeEach(() => { manager = new TestDatafileManager({ sdkKey: '456', updateInterval: 1000, urlTemplate: 'https://localhost:5556/datafiles/%s', }); }); it('uses the urlTemplate to create the url passed to the makeGetRequest method', async () => { const makeGetRequestSpy = jest.spyOn(manager, 'makeGetRequest'); manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); manager.start(); expect(makeGetRequestSpy).toBeCalledTimes(1); expect(makeGetRequestSpy.mock.calls[0][0]).toBe('https://localhost:5556/datafiles/456'); await manager.onReady(); }); }); describe('when constructed with an update interval below the minimum', () => { beforeEach(() => { manager = new TestDatafileManager({ sdkKey: '123', updateInterval: 500, autoUpdate: true }); }); it('uses the default update interval', async () => { const makeGetRequestSpy = jest.spyOn(manager, 'makeGetRequest'); manager.queuedResponses.push({ statusCode: 200, body: '{"foo3": "bar3"}', headers: {}, }); manager.start(); await manager.onReady(); expect(makeGetRequestSpy).toBeCalledTimes(1); await advanceTimersByTime(300000); expect(makeGetRequestSpy).toBeCalledTimes(2); }); }); describe('when constructed with a cache implementation having an already cached datafile', () => { beforeEach(() => { manager = new TestDatafileManager({ sdkKey: 'keyThatExists', updateInterval: 500, autoUpdate: true, cache: testCache, }); manager.simulateResponseDelay = true; }); it('uses cached version of datafile first and resolves the promise while network throws error and no update event is triggered', async () => { manager.queuedResponses.push(new Error('Connection Error')); const updateFn = jest.fn(); manager.on('update', updateFn); manager.start(); await manager.onReady(); expect(JSON.parse(manager.get())).toEqual({ name: 'keyThatExists' }); await advanceTimersByTime(50); expect(JSON.parse(manager.get())).toEqual({ name: 'keyThatExists' }); expect(updateFn).toBeCalledTimes(0); }); it('uses cached datafile, resolves ready promise, fetches new datafile from network and triggers update event', async () => { manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); const updateFn = jest.fn(); manager.on('update', updateFn); manager.start(); await manager.onReady(); expect(JSON.parse(manager.get())).toEqual({ name: 'keyThatExists' }); expect(updateFn).toBeCalledTimes(0); await advanceTimersByTime(50); expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); expect(updateFn).toBeCalledTimes(1); }); it('sets newly recieved datafile in to cache', async () => { const cacheSetSpy = jest.spyOn(testCache, 'set'); manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); manager.start(); await manager.onReady(); await advanceTimersByTime(50); expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); expect(cacheSetSpy.mock.calls[0][0]).toEqual('opt-datafile-keyThatExists'); expect(JSON.parse(cacheSetSpy.mock.calls[0][1])).toEqual({ foo: 'bar' }); }); }); describe('when constructed with a cache implementation without an already cached datafile', () => { beforeEach(() => { manager = new TestDatafileManager({ sdkKey: 'keyThatDoesExists', updateInterval: 500, autoUpdate: true, cache: testCache, }); manager.simulateResponseDelay = true; }); it('does not find cached datafile, fetches new datafile from network, resolves promise and does not trigger update event', async () => { manager.queuedResponses.push({ statusCode: 200, body: '{"foo": "bar"}', headers: {}, }); const updateFn = jest.fn(); manager.on('update', updateFn); manager.start(); await advanceTimersByTime(50); await manager.onReady(); expect(JSON.parse(manager.get())).toEqual({ foo: 'bar' }); expect(updateFn).toBeCalledTimes(0); }); }); });
the_stack
import * as assert from 'assert'; import {after, afterEach, before, beforeEach, describe, it} from 'mocha'; import * as fs from 'fs'; import * as gcpMetadata from 'gcp-metadata'; import * as path from 'path'; import * as proxyquire from 'proxyquire'; import {DebugAgentConfig, ResolvedDebugAgentConfig} from '../src/agent/config'; import {defaultConfig as DEFAULT_CONFIG} from '../src/agent/config'; import {Debuggee} from '../src/debuggee'; import * as stackdriver from '../src/types/stackdriver'; DEFAULT_CONFIG.allowExpressions = true; DEFAULT_CONFIG.workingDirectory = path.join(__dirname, '..', '..'); import { Debuglet, CachedPromise, FindFilesResult, Platforms, } from '../src/agent/debuglet'; import {ScanResults} from '../src/agent/io/scanner'; import * as extend from 'extend'; import {Debug} from '../src/client/stackdriver/debug'; const DEBUGGEE_ID = 'bar'; const REGISTER_PATH = '/v2/controller/debuggees/register'; const BPS_PATH = '/v2/controller/debuggees/' + DEBUGGEE_ID + '/breakpoints'; const EXPRESSIONS_REGEX = /Expressions and conditions are not allowed.*https:\/\/goo\.gl\/ShSm6r/; // eslint-disable-next-line @typescript-eslint/no-var-requires const fakeCredentials = require('./fixtures/gcloud-credentials.json'); const packageInfo = { name: 'Some name', version: 'Some version', }; import * as nock from 'nock'; import * as nocks from './nocks'; nock.disableNetConnect(); const defaultConfig = extend(true, {}, DEFAULT_CONFIG, {logLevel: 0}); let oldGP: string | undefined; // TODO: Have this actually implement Breakpoint. const bp: stackdriver.Breakpoint = { id: 'test', action: 'CAPTURE', location: {path: 'build/test/fixtures/foo.js', line: 2}, } as stackdriver.Breakpoint; // TODO: Have this actually implement Breakpoint. const errorBp: stackdriver.Breakpoint = { id: 'testLog', action: 'FOO', location: {path: 'build/test/fixtures/foo.js', line: 2}, } as {} as stackdriver.Breakpoint; function verifyBreakpointRejection( re: RegExp, body: {breakpoint: stackdriver.Breakpoint} ) { const status = body.breakpoint.status; const hasCorrectDescription = !!status!.description.format.match(re); return status!.isError && hasCorrectDescription; } describe('CachedPromise', () => { it('CachedPromise.get() will resolve after CachedPromise.resolve()', function (done) { this.timeout(2000); const cachedPromise = new CachedPromise(); cachedPromise.get().then(() => { done(); }); cachedPromise.resolve(); }); }); describe('Debuglet', () => { describe('findFiles', () => { const SOURCEMAP_DIR = path.join(__dirname, 'fixtures', 'sourcemaps'); it('throws an error for an invalid directory', async () => { const config = extend({}, defaultConfig, { workingDirectory: path.join(SOURCEMAP_DIR, '!INVALID'), }); let err: Error | null = null; try { await Debuglet.findFiles(config, 'fake-id'); } catch (e) { err = e as Error; } assert.ok(err); }); it('finds the correct sourcemaps files', async () => { const config = extend({}, defaultConfig, { workingDirectory: SOURCEMAP_DIR, }); const searchResults = await Debuglet.findFiles(config, 'fake-id'); assert(searchResults.jsStats); assert.strictEqual(Object.keys(searchResults.jsStats).length, 1); assert(searchResults.jsStats[path.join(SOURCEMAP_DIR, 'js-file.js')]); assert.strictEqual(searchResults.mapFiles.length, 2); const mapFiles = searchResults.mapFiles.sort(); assert(mapFiles[0].endsWith('empty-source-map.js.map')); assert(mapFiles[1].endsWith('js-map-file.js.map')); }); }); describe('setup', () => { before(() => { oldGP = process.env.GCLOUD_PROJECT; }); after(() => { process.env.GCLOUD_PROJECT = oldGP; }); beforeEach(() => { delete process.env.GCLOUD_PROJECT; nocks.oauth2(); }); afterEach(() => { nock.cleanAll(); }); it('should merge config correctly', () => { const testValue = 2 * defaultConfig.capture.maxExpandFrames; const config = {capture: {maxExpandFrames: testValue}}; // TODO: Fix this so that config does not have to be cast as // DebugAgentConfig. const mergedConfig = Debuglet.normalizeConfig_( config as DebugAgentConfig ); // TODO: Debuglet.normalizeConfig_() expects 1 parameter but the original // test code had zero arguments here. Determine which is correct. const compareConfig = Debuglet.normalizeConfig_(null!); // The actual config should be exactly defaultConfig with only // maxExpandFrames adjusted. compareConfig.capture.maxExpandFrames = testValue; assert.deepStrictEqual(mergedConfig, compareConfig); }); it('should not start when projectId is not available', done => { const debug = new Debug({}, packageInfo); const savedGetProjectId = debug.authClient.getProjectId; debug.authClient.getProjectId = () => { return Promise.reject(new Error('no project id')); }; const debuglet = new Debuglet(debug, defaultConfig); debuglet.once('initError', (err: Error) => { assert.ok(err); // no need to stop the debuggee. debug.authClient.getProjectId = savedGetProjectId; done(); }); debuglet.once('started', () => { assert.fail('The debuglet should not have started'); }); debuglet.start(); }); it('should give a useful error message when projectId is not available', done => { const debug = new Debug({}, packageInfo); const savedGetProjectId = debug.authClient.getProjectId; debug.authClient.getProjectId = () => { return Promise.reject(new Error('no project id')); }; const debuglet = new Debuglet(debug, defaultConfig); let message = ''; const savedLoggerError = debuglet.logger.error; debuglet.logger.error = (text: string) => { message += text; }; debuglet.once('initError', err => { debug.authClient.getProjectId = savedGetProjectId; debuglet.logger.error = savedLoggerError; assert.ok(err); assert(message.startsWith('The project ID could not be determined:')); done(); }); debuglet.once('started', () => { assert.fail('The debuglet should fail to start without a projectId'); }); debuglet.start(); }); it('should not crash without project num', done => { const debug = new Debug({}, packageInfo); const savedGetProjectId = debug.authClient.getProjectId; debug.authClient.getProjectId = () => { return Promise.reject(new Error('no project id')); }; const debuglet = new Debuglet(debug, defaultConfig); debuglet.once('started', () => { assert.fail('The debuglet should not have started'); }); debuglet.once('initError', () => { debug.authClient.getProjectId = savedGetProjectId; done(); }); debuglet.start(); }); it('should use config.projectId', done => { const projectId = '11020304f2934-a'; const debug = new Debug( {projectId, credentials: fakeCredentials}, packageInfo ); nocks.projectId('project-via-metadata'); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, { debuggee: {id: DEBUGGEE_ID}, }); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); // TODO: Handle the case where debuglet.debuggee is undefined assert.strictEqual((debuglet.debuggee as Debuggee).project, projectId); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should enable breakpoint canary when enableCanary is set', done => { const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); nocks.oauth2(); const config = debugletConfig(); config.serviceContext.enableCanary = true; const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, { debuggee: {id: DEBUGGEE_ID}, }); debuglet.once('registered', () => { assert.strictEqual( (debuglet.debuggee as Debuggee).canaryMode, 'CANARY_MODE_ALWAYS_ENABLED' ); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should have default resetV8DebuggerThreshold value', done => { const debuglet = new Debuglet(new Debug({}, packageInfo), {}); assert.strictEqual(debuglet.config.resetV8DebuggerThreshold, 30); done(); }); it('should overwrite resetV8DebuggerThreshold when available', done => { const debuglet = new Debuglet(new Debug({}, packageInfo), { resetV8DebuggerThreshold: 123, }); assert.strictEqual(debuglet.config.resetV8DebuggerThreshold, 123); done(); }); it('should not fail if files cannot be read', done => { const MOCKED_DIRECTORY = process.cwd(); const errors: Array<{filename: string; error: string}> = []; for (let i = 1; i <= 2; i++) { const filename = `cannot-read-${i}.js`; const error = `EACCES: permission denied, open '${filename}'`; errors.push({filename, error}); } const mockedDebuglet = proxyquire('../src/agent/debuglet', { './io/scanner': { scan: (baseDir: string, regex: RegExp, precomputedHash?: string) => { assert.strictEqual(baseDir, MOCKED_DIRECTORY); const results: ScanResults = { errors: () => { const map = new Map<string, Error>(); for (const item of errors) { map.set(item.filename, new Error(item.error)); } return map; }, all: () => { return {}; }, selectStats: () => { return {}; }, selectFiles: () => { return []; }, hash: precomputedHash || 'fake-hash', }; return results; }, }, }); const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = extend({}, defaultConfig, { workingDirectory: MOCKED_DIRECTORY, }); const debuglet = new mockedDebuglet.Debuglet(debug, config); let text = ''; debuglet.logger.warn = (s: string) => { text += s; }; debuglet.on('initError', () => { assert.fail('It should not fail for files it cannot read'); }); debuglet.once('started', () => { for (const item of errors) { const regex = new RegExp(item.error); assert( regex.test(text), `Should warn that file '${item.filename}' cannot be read` ); } debuglet.stop(); done(); }); debuglet.start(); }); describe('environment variables', () => { let env: NodeJS.ProcessEnv; beforeEach(() => { env = extend({}, process.env); }); afterEach(() => { process.env = extend({}, env); }); it('should use GCLOUD_PROJECT in lieu of config.projectId', done => { process.env.GCLOUD_PROJECT = '11020304f2934-b'; const debug = new Debug({credentials: fakeCredentials}, packageInfo); nocks.projectId('project-via-metadata'); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, { debuggee: {id: DEBUGGEE_ID}, }); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); assert.strictEqual( debuglet.debuggee!.project, process.env.GCLOUD_PROJECT ); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should use options.projectId in preference to the environment variable', done => { process.env.GCLOUD_PROJECT = 'should-not-be-used'; const debug = new Debug( {projectId: 'project-via-options', credentials: fakeCredentials}, packageInfo ); nocks.projectId('project-via-metadata'); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, { debuggee: {id: DEBUGGEE_ID}, }); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); assert.strictEqual(debuglet.debuggee!.project, 'project-via-options'); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should respect GCLOUD_DEBUG_LOGLEVEL', done => { process.env.GCLOUD_PROJECT = '11020304f2934'; process.env.GCLOUD_DEBUG_LOGLEVEL = '3'; const debug = new Debug({credentials: fakeCredentials}, packageInfo); nocks.projectId('project-via-metadata'); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, { debuggee: {id: DEBUGGEE_ID}, }); let buffer = ''; const oldConsoleError = console.error; console.error = (str: string) => { buffer += str; }; debuglet.once('registered', () => { const logger = debuglet.logger; const STRING1 = 'jjjjjjjjjjjjjjjjjfjfjfjf'; const STRING2 = 'kkkkkkkfkfkfkfkfkkffkkkk'; logger.info(STRING1); logger.debug(STRING2); console.error = oldConsoleError; assert(buffer.indexOf(STRING1) !== -1); assert(buffer.indexOf(STRING2) === -1); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should respect GAE_SERVICE and GAE_VERSION env. vars.', () => { process.env.GAE_SERVICE = 'fake-gae-service'; process.env.GAE_VERSION = 'fake-gae-version'; const debug = new Debug({}, packageInfo); const debuglet = new Debuglet(debug, defaultConfig); assert.ok(debuglet.config); assert.ok(debuglet.config.serviceContext); assert.strictEqual( debuglet.config.serviceContext.service, 'fake-gae-service' ); assert.strictEqual( debuglet.config.serviceContext.version, 'fake-gae-version' ); }); it('should respect GAE_MODULE_NAME and GAE_MODULE_VERSION env. vars.', () => { process.env.GAE_MODULE_NAME = 'fake-gae-service'; process.env.GAE_MODULE_VERSION = 'fake-gae-version'; const debug = new Debug({}, packageInfo); const debuglet = new Debuglet(debug, defaultConfig); assert.ok(debuglet.config); assert.ok(debuglet.config.serviceContext); assert.strictEqual( debuglet.config.serviceContext.service, 'fake-gae-service' ); assert.strictEqual( debuglet.config.serviceContext.version, 'fake-gae-version' ); }); it('should respect K_SERVICE and K_REVISION env. vars.', () => { process.env.K_SERVICE = 'fake-cloudrun-service'; process.env.K_REVISION = 'fake-cloudrun-version'; const debug = new Debug({}, packageInfo); const debuglet = new Debuglet(debug, defaultConfig); assert.ok(debuglet.config); assert.ok(debuglet.config.serviceContext); assert.strictEqual( debuglet.config.serviceContext.service, 'fake-cloudrun-service' ); assert.strictEqual( debuglet.config.serviceContext.version, 'fake-cloudrun-version' ); }); it('should respect FUNCTION_NAME env. var.', () => { process.env.FUNCTION_NAME = 'fake-fn-name'; const debug = new Debug({}, packageInfo); const debuglet = new Debuglet(debug, defaultConfig); assert.ok(debuglet.config); assert.ok(debuglet.config.serviceContext); assert.strictEqual( debuglet.config.serviceContext.service, 'fake-fn-name' ); assert.strictEqual( debuglet.config.serviceContext.version, 'unversioned' ); }); it('should prefer new flex vars over GAE_MODULE_*', () => { process.env.GAE_MODULE_NAME = 'fake-gae-module'; process.env.GAE_MODULE_VERSION = 'fake-gae-module-version'; process.env.GAE_SERVICE = 'fake-gae-service'; process.env.GAE_VERSION = 'fake-gae-version'; const debug = new Debug({}, packageInfo); const debuglet = new Debuglet(debug, defaultConfig); assert.ok(debuglet.config); assert.ok(debuglet.config.serviceContext); assert.strictEqual( debuglet.config.serviceContext.service, 'fake-gae-service' ); assert.strictEqual( debuglet.config.serviceContext.version, 'fake-gae-version' ); }); it('should respect GAE_DEPLOYMENT_ID env. var. when available', () => { process.env.GAE_DEPLOYMENT_ID = 'some deployment id'; delete process.env.GAE_MINOR_VERSION; const debug = new Debug({}, packageInfo); const debuglet = new Debuglet(debug, defaultConfig); assert.ok(debuglet.config); assert.ok(debuglet.config.serviceContext); assert.strictEqual( debuglet.config.serviceContext.minorVersion_, 'some deployment id' ); }); it('should respect GAE_MINOR_VERSION env. var. when available', () => { delete process.env.GAE_DEPLOYMENT_ID; process.env.GAE_MINOR_VERSION = 'some minor version'; const debug = new Debug({}, packageInfo); const debuglet = new Debuglet(debug, defaultConfig); assert.ok(debuglet.config); assert.ok(debuglet.config.serviceContext); assert.strictEqual( debuglet.config.serviceContext.minorVersion_, 'some minor version' ); }); it('should prefer GAE_DEPLOYMENT_ID over GAE_MINOR_VERSION', () => { process.env.GAE_DEPLOYMENT_ID = 'some deployment id'; process.env.GAE_MINOR_VERSION = 'some minor version'; const debug = new Debug({}, packageInfo); const debuglet = new Debuglet(debug, defaultConfig); assert.ok(debuglet.config); assert.ok(debuglet.config.serviceContext); assert.strictEqual( debuglet.config.serviceContext.minorVersion_, 'some deployment id' ); }); it('should not have minorVersion unless enviroment provides it', () => { const debug = new Debug({}, packageInfo); const debuglet = new Debuglet(debug, defaultConfig); assert.ok(debuglet.config); assert.ok(debuglet.config.serviceContext); // TODO: IMPORTANT: It appears that this test is incorrect as it // is. That is, if minorVersion is replaced with the // correctly named minorVersion_, then the test fails. // Resolve this. assert.strictEqual( undefined, ( debuglet.config.serviceContext as { minorVersion: {}; } ).minorVersion ); }); it('should not provide minorversion upon registration on non flex', done => { const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH, (body: {debuggee: Debuggee}) => { assert.strictEqual(undefined, body.debuggee.labels!.minorversion); return true; }) .once() .reply(200, {debuggee: {id: DEBUGGEE_ID}}); // TODO: Determine if the id parameter should be used. debuglet.once('registered', () => { debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); }); it('should retry on failed registration', function (done) { this.timeout(10000); const debug = new Debug( {projectId: '11020304f2934', credentials: fakeCredentials}, packageInfo ); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(404) .post(REGISTER_PATH) .reply(509) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it("should error if a package.json doesn't exist", done => { const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = extend({}, defaultConfig, { workingDirectory: __dirname, forceNewAgent_: true, }); const debuglet = new Debuglet(debug, config); debuglet.once('initError', (err: Error) => { assert(err); done(); }); debuglet.start(); }); it('should by default error when workingDirectory is a root directory with a package.json', done => { const debug = new Debug({}, packageInfo); /* * `path.sep` represents a root directory on both Windows and Unix. * On Windows, `path.sep` resolves to the current drive. * * That is, after opening a command prompt in Windows, relative to the * drive C: and starting the Node REPL, the value of `path.sep` * represents `C:\\'. * * If `D:` is entered at the prompt to switch to the D: drive before * starting the Node REPL, `path.sep` represents `D:\\`. */ const root = path.sep; const mockedDebuglet = proxyquire('../src/agent/debuglet', { /* * Mock the 'fs' module to verify that if the root directory is used, * and the root directory is reported to contain a `package.json` * file, then the agent still produces an `initError` when the * working directory is the root directory. */ fs: { stat: ( filepath: string | Buffer, cb: (err: Error | null, stats: {}) => void ) => { if (filepath === path.join(root, 'package.json')) { // The key point is that looking for `package.json` in the // root directory does not cause an error. return cb(null, {}); } fs.stat(filepath, cb); }, }, }); const config = extend({}, defaultConfig, {workingDirectory: root}); const debuglet = new mockedDebuglet.Debuglet(debug, config); let text = ''; debuglet.logger.error = (str: string) => { text += str; }; debuglet.on('initError', (err: Error) => { const errorMessage = 'The working directory is a root ' + 'directory. Disabling to avoid a scan of the entire filesystem ' + 'for JavaScript files. Use config `allowRootAsWorkingDirectory` ' + 'if you really want to do this.'; assert.ok(err); assert.strictEqual(err.message, errorMessage); assert.ok(text.includes(errorMessage)); done(); }); debuglet.once('started', () => { assert.fail('Should not start if workingDirectory is a root directory'); }); debuglet.start(); }); it('should be able to force the workingDirectory to be a root directory', done => { const root = path.sep; // Act like the root directory contains a `package.json` file const mockedDebuglet = proxyquire('../src/agent/debuglet', { fs: { stat: ( filepath: string | Buffer, cb: (err: Error | null, stats: {}) => void ) => { if (filepath === path.join(root, 'package.json')) { return cb(null, {}); } fs.stat(filepath, cb); }, }, }); // Don't actually scan the entire filesystem. Act like the filesystem // is empty. mockedDebuglet.Debuglet.findFiles = ( config: ResolvedDebugAgentConfig ): Promise<FindFilesResult> => { const baseDir = config.workingDirectory; assert.strictEqual(baseDir, root); return Promise.resolve({ jsStats: {}, mapFiles: [], errors: new Map<string, Error>(), hash: 'fake-hash', }); }; // No need to restore `findFiles` because we are modifying a // mocked version of `Debuglet` not `Debuglet` itself. const config = extend({}, defaultConfig, { workingDirectory: root, allowRootAsWorkingDirectory: true, }); const debug = new Debug({}, packageInfo); // Act like the debuglet can get a project id debug.authClient.getProjectId = async () => 'some-project-id'; const debuglet = new mockedDebuglet.Debuglet(debug, config); debuglet.on('initError', (err: Error) => { assert.ifError(err); done(); }); debuglet.once('started', () => { debuglet.stop(); done(); }); debuglet.start(); }); it('should register successfully otherwise', done => { const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); nocks.oauth2(); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, { debuggee: {id: DEBUGGEE_ID}, }); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should attempt to retrieve cluster name if needed', done => { const savedRunningOnGCP = Debuglet.runningOnGCP; Debuglet.runningOnGCP = () => { return Promise.resolve(true); }; const clusterScope = nock(gcpMetadata.HOST_ADDRESS) .get('/computeMetadata/v1/instance/attributes/cluster-name') .once() .reply(200, 'cluster-name-from-metadata'); const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); nocks.oauth2(); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, { debuggee: {id: DEBUGGEE_ID}, }); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); debuglet.stop(); clusterScope.done(); scope.done(); Debuglet.runningOnGCP = savedRunningOnGCP; done(); }); debuglet.start(); }); it('should attempt to retreive region correctly if needed', done => { const savedGetPlatform = Debuglet.getPlatform; Debuglet.getPlatform = () => Platforms.CLOUD_FUNCTION; const clusterScope = nock(gcpMetadata.HOST_ADDRESS) .get('/computeMetadata/v1/instance/region') .once() .reply(200, '123/456/region_name', gcpMetadata.HEADERS); const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); nocks.oauth2(); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, { debuggee: {id: DEBUGGEE_ID}, }); debuglet.once('registered', () => { Debuglet.getPlatform = savedGetPlatform; assert.strictEqual( (debuglet.debuggee as Debuggee).labels?.region, 'region_name' ); debuglet.stop(); clusterScope.done(); scope.done(); done(); }); debuglet.start(); }); it('should continue to register when could not get region', done => { const savedGetPlatform = Debuglet.getPlatform; Debuglet.getPlatform = () => Platforms.CLOUD_FUNCTION; const clusterScope = nock(gcpMetadata.HOST_ADDRESS) .get('/computeMetadata/v1/instance/region') .once() .reply(400); const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); nocks.oauth2(); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, { debuggee: {id: DEBUGGEE_ID}, }); debuglet.once('registered', () => { Debuglet.getPlatform = savedGetPlatform; debuglet.stop(); clusterScope.done(); scope.done(); done(); }); debuglet.start(); }); it('should pass config source context to api', done => { const REPO_URL = 'https://github.com/non-existent-users/non-existend-repo'; const REVISION_ID = '5'; const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = debugletConfig({ sourceContext: {url: REPO_URL, revisionId: REVISION_ID}, }); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH, (body: {debuggee: Debuggee}) => { const context = body.debuggee.sourceContexts![0]; return ( context && context.url === REPO_URL && context.revisionId === REVISION_ID ); }) .reply(200, {debuggee: {id: DEBUGGEE_ID}}); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should pass source context to api if present', done => { const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const old = Debuglet.getSourceContextFromFile; Debuglet.getSourceContextFromFile = async () => { return {a: 5 as {} as string}; }; const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH, (body: {debuggee: Debuggee}) => { const context = body.debuggee.sourceContexts![0]; return context && context.a === 5; }) .reply(200, {debuggee: {id: DEBUGGEE_ID}}); debuglet.once('registered', (id: string) => { Debuglet.getSourceContextFromFile = old; assert.strictEqual(id, DEBUGGEE_ID); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should prefer config source context to file', done => { const REPO_URL = 'https://github.com/non-existent-users/non-existend-repo'; const REVISION_ID = '5'; const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const old = Debuglet.getSourceContextFromFile; Debuglet.getSourceContextFromFile = async () => { return {a: 5 as {} as string}; }; const config = debugletConfig({ sourceContext: {url: REPO_URL, revisionId: REVISION_ID}, }); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH, (body: {debuggee: Debuggee}) => { const context = body.debuggee.sourceContexts![0]; return ( context && context.url === REPO_URL && context.revisionId === REVISION_ID ); }) .reply(200, {debuggee: {id: DEBUGGEE_ID}}); debuglet.once('registered', (id: string) => { Debuglet.getSourceContextFromFile = old; assert.strictEqual(id, DEBUGGEE_ID); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should de-activate when the server responds with isDisabled', function (done) { this.timeout(4000); const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, { debuggee: {id: DEBUGGEE_ID, isDisabled: true}, }); debuglet.once('remotelyDisabled', () => { assert.ok(!debuglet.fetcherActive); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should retry after a isDisabled request', function (done) { this.timeout(4000); const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID, isDisabled: true}}) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}); let gotDisabled = false; debuglet.once('remotelyDisabled', () => { assert.ok(!debuglet.fetcherActive); gotDisabled = true; }); debuglet.once('registered', (id: string) => { assert.ok(gotDisabled); assert.strictEqual(id, DEBUGGEE_ID); debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should re-register when registration expires', done => { const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}) .get(BPS_PATH + '?successOnTimeout=true') .reply(404) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}); debuglet.once('registered', (id1: string) => { assert.strictEqual(id1, DEBUGGEE_ID); debuglet.once('registered', (id2: string) => { assert.strictEqual(id2, DEBUGGEE_ID); debuglet.stop(); scope.done(); done(); }); }); debuglet.start(); }); it('should fetch and add breakpoints', function (done) { this.timeout(2000); const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}) .get(BPS_PATH + '?successOnTimeout=true') .reply(200, {breakpoints: [bp]}); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); setTimeout(() => { assert.deepStrictEqual(debuglet.activeBreakpointMap.test, bp); debuglet.stop(); scope.done(); done(); }, 1000); }); debuglet.start(); }); it('should have breakpoints fetched when promise is resolved', function (done) { this.timeout(2000); const breakpoint: stackdriver.Breakpoint = { id: 'test1', action: 'CAPTURE', location: {path: 'build/test/fixtures/foo.js', line: 2}, } as stackdriver.Breakpoint; const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}) .get(BPS_PATH + '?successOnTimeout=true') .reply(200, {breakpoints: [breakpoint]}); const debugPromise = debuglet.isReadyManager.isReady(); debuglet.once('registered', () => { debugPromise.then(() => { // Once debugPromise is resolved, debuggee must be registered. assert(debuglet.debuggee); setTimeout(() => { assert.deepStrictEqual( debuglet.activeBreakpointMap.test1, breakpoint ); debuglet.activeBreakpointMap = {}; debuglet.stop(); scope.done(); done(); }, 1000); }); }); debuglet.start(); }); it('should resolve breakpointFetched promise when registration expires', function (done) { this.timeout(2000); const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); // const debuglet = new Debuglet(debug, defaultConfig); // const scope = nock(API) /// this change to a unique scope per test causes const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}) .get(BPS_PATH + '?successOnTimeout=true') .reply(404); // signal re-registration. const debugPromise = debuglet.isReadyManager.isReady(); debugPromise.then(() => { debuglet.stop(); scope.done(); done(); }); debuglet.start(); }); it('should reject breakpoints with conditions when allowExpressions=false', function (done) { this.timeout(2000); const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = debugletConfig({allowExpressions: false}); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}) .get(BPS_PATH + '?successOnTimeout=true') .reply(200, { breakpoints: [ { id: 'test', action: 'CAPTURE', condition: 'x === 5', location: {path: 'fixtures/foo.js', line: 2}, }, ], }) .put( BPS_PATH + '/test', verifyBreakpointRejection.bind(null, EXPRESSIONS_REGEX) ) .reply(200); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); setTimeout(() => { assert.ok(!debuglet.activeBreakpointMap.test); debuglet.stop(); debuglet.config.allowExpressions = true; scope.done(); done(); }, 1000); }); debuglet.start(); }); it('should reject breakpoints with expressions when allowExpressions=false', function (done) { this.timeout(2000); const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = debugletConfig({allowExpressions: false}); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}) .get(BPS_PATH + '?successOnTimeout=true') .reply(200, { breakpoints: [ { id: 'test', action: 'CAPTURE', expressions: ['x'], location: {path: 'fixtures/foo.js', line: 2}, }, ], }) .put( BPS_PATH + '/test', verifyBreakpointRejection.bind(null, EXPRESSIONS_REGEX) ) .reply(200); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); setTimeout(() => { assert.ok(!debuglet.activeBreakpointMap.test); debuglet.stop(); debuglet.config.allowExpressions = true; scope.done(); done(); }, 1000); }); debuglet.start(); }); it('should re-fetch breakpoints on error', function (done) { this.timeout(6000); const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); const config = debugletConfig(); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}) .get(BPS_PATH + '?successOnTimeout=true') .reply(404) .get(BPS_PATH + '?successOnTimeout=true') .reply(200, {waitExpired: true}) .get(BPS_PATH + '?successOnTimeout=true') .reply(200, {breakpoints: [bp, errorBp]}) .put( BPS_PATH + '/' + errorBp.id, (body: {breakpoint: stackdriver.Breakpoint}) => { const status = body.breakpoint.status; return ( status!.isError && status!.description.format.indexOf('actions are CAPTURE') !== -1 ); } ) .reply(200); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); setTimeout(() => { assert.deepStrictEqual(debuglet.activeBreakpointMap.test, bp); assert(!debuglet.activeBreakpointMap.testLog); debuglet.stop(); scope.done(); done(); }, 1000); }); debuglet.start(); }); it('should expire stale breakpoints', function (done) { const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); this.timeout(6000); const config = debugletConfig({ breakpointExpirationSec: 1, forceNewAgent_: true, }); const debuglet = new Debuglet(debug, config); const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}) .get(BPS_PATH + '?successOnTimeout=true') .reply(200, {breakpoints: [bp]}) .put( BPS_PATH + '/test', (body: {breakpoint: stackdriver.Breakpoint}) => { const status = body.breakpoint.status; return ( status!.description.format === 'The snapshot has expired' && status!.refersTo === 'BREAKPOINT_AGE' ); } ) .reply(200); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); setTimeout(() => { assert.deepStrictEqual(debuglet.activeBreakpointMap.test, bp); setTimeout(() => { assert(!debuglet.activeBreakpointMap.test); debuglet.stop(); scope.done(); done(); }, 1100); }, 500); }); debuglet.start(); }); // This test catches regressions in a bug where the agent would // re-schedule an already expired breakpoint to expire if the // server listed the breakpoint as active (which it may do depending // on how quickly the expiry is processed). // The test expires a breakpoint and then has the api respond with // the breakpoint listed as active. It validates that the breakpoint // is only expired with the server once. it('should not update expired breakpoints', function (done) { const debug = new Debug( {projectId: 'fake-project', credentials: fakeCredentials}, packageInfo ); this.timeout(6000); const config = debugletConfig({ breakpointExpirationSec: 1, breakpointUpdateIntervalSec: 1, forceNewAgent_: true, }); const debuglet = new Debuglet(debug, config); let unexpectedUpdate = false; const scope = nock(config.apiUrl) .post(REGISTER_PATH) .reply(200, {debuggee: {id: DEBUGGEE_ID}}) .get(BPS_PATH + '?successOnTimeout=true') .reply(200, {breakpoints: [bp]}) .put( BPS_PATH + '/test', (body: {breakpoint: stackdriver.Breakpoint}) => { return ( body.breakpoint.status!.description.format === 'The snapshot has expired' ); } ) .reply(200) .get(BPS_PATH + '?successOnTimeout=true') .times(4) .reply(200, {breakpoints: [bp]}); // Get ready to fail the test if any additional updates come through. nock.emitter.on('no match', req => { if (req.path.startsWith(BPS_PATH) && req.method === 'PUT') { unexpectedUpdate = true; } }); debuglet.once('registered', (id: string) => { assert.strictEqual(id, DEBUGGEE_ID); setTimeout(() => { assert.deepStrictEqual(debuglet.activeBreakpointMap.test, bp); setTimeout(() => { assert(!debuglet.activeBreakpointMap.test); assert(!unexpectedUpdate, 'unexpected update request'); debuglet.stop(); scope.done(); done(); }, 4500); }, 500); }); debuglet.start(); }); }); describe('map subtract', () => { it('should be correct', () => { const a = {a: 1, b: 2}; const b = {a: 1}; assert.deepStrictEqual(Debuglet.mapSubtract(a, b), [2]); assert.deepStrictEqual(Debuglet.mapSubtract(b, a), []); assert.deepStrictEqual(Debuglet.mapSubtract(a, {}), [1, 2]); assert.deepStrictEqual(Debuglet.mapSubtract({}, b), []); }); }); describe('format', () => { it('should be correct', () => { // TODO: Determine if Debuglet.format() should allow a number[] // or if only string[] should be allowed. assert.deepStrictEqual( Debuglet.format('hi', [5] as {} as string[]), 'hi' ); assert.deepStrictEqual( Debuglet.format('hi $0', [5] as {} as string[]), 'hi 5' ); assert.deepStrictEqual( Debuglet.format('hi $0 $1', [5, 'there'] as {} as string[]), 'hi 5 there' ); assert.deepStrictEqual( Debuglet.format('hi $0 $1', [5] as {} as string[]), 'hi 5 $1' ); assert.deepStrictEqual( Debuglet.format('hi $0 $1 $0', [5] as {} as string[]), 'hi 5 $1 5' ); assert.deepStrictEqual( Debuglet.format('hi $$', [5] as {} as string[]), 'hi $' ); assert.deepStrictEqual( Debuglet.format('hi $$0', [5] as {} as string[]), 'hi $0' ); assert.deepStrictEqual( Debuglet.format('hi $00', [5] as {} as string[]), 'hi 50' ); assert.deepStrictEqual( Debuglet.format('hi $0', ['$1', 5] as {} as string[]), 'hi $1' ); assert.deepStrictEqual( Debuglet.format('hi $11', [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', ] as {} as string[]), 'hi b' ); }); }); describe('createDebuggee', () => { it('should have sensible labels', () => { const debuggee = Debuglet.createDebuggee( 'some project', 'id', {service: 'some-service', version: 'production'}, {}, false, packageInfo, Platforms.DEFAULT ); assert.ok(debuggee); assert.ok(debuggee.labels); assert.strictEqual(debuggee.labels!.module, 'some-service'); assert.strictEqual(debuggee.labels!.version, 'production'); }); it('should not add a module label when service is default', () => { const debuggee = Debuglet.createDebuggee( 'fancy-project', 'very-unique', {service: 'default', version: 'yellow.5'}, {}, false, packageInfo, Platforms.DEFAULT ); assert.ok(debuggee); assert.ok(debuggee.labels); assert.strictEqual(debuggee.labels!.module, undefined); assert.strictEqual(debuggee.labels!.version, 'yellow.5'); }); it('should have an error statusMessage with the appropriate arg', () => { const debuggee = Debuglet.createDebuggee( 'a', 'b', {}, {}, false, packageInfo, Platforms.DEFAULT, undefined, 'Some Error Message' ); assert.ok(debuggee); assert.ok(debuggee.statusMessage); }); it('should be in CANARY_MODE_DEFAULT_ENABLED canaryMode', () => { const debuggee = Debuglet.createDebuggee( 'some project', 'id', {enableCanary: true, allowCanaryOverride: true}, {}, false, packageInfo, Platforms.DEFAULT ); assert.strictEqual(debuggee.canaryMode, 'CANARY_MODE_DEFAULT_ENABLED'); }); it('should be in CANARY_MODE_ALWAYS_ENABLED canaryMode', () => { const debuggee = Debuglet.createDebuggee( 'some project', 'id', {enableCanary: true, allowCanaryOverride: false}, {}, false, packageInfo, Platforms.DEFAULT ); assert.strictEqual(debuggee.canaryMode, 'CANARY_MODE_ALWAYS_ENABLED'); }); it('should be in CANARY_MODE_DEFAULT_DISABLED canaryMode', () => { const debuggee = Debuglet.createDebuggee( 'some project', 'id', {enableCanary: false, allowCanaryOverride: true}, {}, false, packageInfo, Platforms.DEFAULT ); assert.strictEqual(debuggee.canaryMode, 'CANARY_MODE_DEFAULT_DISABLED'); }); it('should be in CANARY_MODE_ALWAYS_DISABLED canaryMode', () => { const debuggee = Debuglet.createDebuggee( 'some project', 'id', {enableCanary: false, allowCanaryOverride: false}, {}, false, packageInfo, Platforms.DEFAULT ); assert.strictEqual(debuggee.canaryMode, 'CANARY_MODE_ALWAYS_DISABLED'); }); }); describe('getPlatform', () => { it('should correctly identify default platform.', () => { assert.ok(Debuglet.getPlatform() === Platforms.DEFAULT); }); it('should correctly identify GCF (legacy) platform.', () => { // GCF sets this env var on older runtimes. process.env.FUNCTION_NAME = 'mock'; assert.ok(Debuglet.getPlatform() === Platforms.CLOUD_FUNCTION); delete process.env.FUNCTION_NAME; // Don't contaminate test environment. }); it('should correctly identify GCF (modern) platform.', () => { // GCF sets this env var on modern runtimes. process.env.FUNCTION_TARGET = 'mock'; assert.ok(Debuglet.getPlatform() === Platforms.CLOUD_FUNCTION); delete process.env.FUNCTION_TARGET; // Don't contaminate test environment. }); }); describe('getRegion', () => { it('should return function region for older GCF runtime', async () => { process.env.FUNCTION_REGION = 'mock'; assert.ok((await Debuglet.getRegion()) === 'mock'); delete process.env.FUNCTION_REGION; }); it('should return region for newer GCF runtime', async () => { const clusterScope = nock(gcpMetadata.HOST_ADDRESS) .get('/computeMetadata/v1/instance/region') .once() .reply(200, '123/456/region_name', gcpMetadata.HEADERS); assert.ok((await Debuglet.getRegion()) === 'region_name'); clusterScope.done(); }); it('should return undefined when cannot get region metadata', async () => { const clusterScope = nock(gcpMetadata.HOST_ADDRESS) .get('/computeMetadata/v1/instance/region') .once() .reply(400); assert.ok((await Debuglet.getRegion()) === undefined); clusterScope.done(); }); }); describe('_createUniquifier', () => { it('should create a unique string', () => { const fn = Debuglet._createUniquifier; const desc = 'description'; const version = 'version'; const uid = 'uid'; const sourceContext = {git: 'something'}; const labels = {key: 'value'}; const u1 = fn(desc, version, uid, sourceContext, labels); assert.strictEqual(fn(desc, version, uid, sourceContext, labels), u1); assert.notStrictEqual( fn('foo', version, uid, sourceContext, labels), u1, 'changing the description should change the result' ); assert.notStrictEqual( fn(desc, '1.2', uid, sourceContext, labels), u1, 'changing the version should change the result' ); assert.notStrictEqual( fn(desc, version, '5', sourceContext, labels), u1, 'changing the description should change the result' ); assert.notStrictEqual( fn(desc, version, uid, {git: 'blah'}, labels), u1, 'changing the sourceContext should change the result' ); assert.notStrictEqual( fn(desc, version, uid, sourceContext, {key1: 'value2'}), u1, 'changing the labels should change the result' ); }); }); }); // a counter for unique test urls. let apiUrlInc = 0; /** * returns a new config object to be passed to debuglet. always has apiUrl * @param conf custom config values */ function debugletConfig(conf?: {}): ResolvedDebugAgentConfig & { apiUrl: string; } { const apiUrl = 'https://clouddebugger.googleapis.com' + ++apiUrlInc; const c = Object.assign( {}, DEFAULT_CONFIG, conf ) as ResolvedDebugAgentConfig & {apiUrl: string}; c.apiUrl = apiUrl; return c; }
the_stack
* 视频超分 */ export interface VideoSuperResolution { /** * 超分视频类型:可选值:lq,hq lq: 针对低清晰度有较多噪声视频的超分; hq: 针对高清晰度视频超分; 默认取值:lq。 */ Type?: string /** * 超分倍数,可选值:2。 注意:当前只支持两倍超分。 */ Size?: number } /** * 编辑处理/拼接任务/处理结果 */ export interface MediaJoiningTaskResult { /** * 拼接结果文件。 注意:此字段可能返回 null,表示取不到有效值。 */ File: TaskResultFile } /** * 音频降噪 */ export interface Denoise { /** * 音频降噪强度,可选项: 1. weak 2.normal, 3.strong 默认为weak */ Type?: string } /** * 智能拆条结果项 */ export interface StripTaskResultItem { /** * 视频拆条片段地址。 */ SegmentUrl: string /** * 拆条封面图片地址。 */ CovImgUrl: string /** * 置信度,取值范围是 0 到 100。 */ Confidence: number /** * 拆条片段起始的偏移时间,单位:秒。 */ StartTimeOffset: number /** * 拆条片段终止的偏移时间,单位:秒。 */ EndTimeOffset: number } /** * 任务视频cos授权信息 */ export interface CosAuthMode { /** * 授权类型,可选值: 0:bucket授权,需要将对应bucket授权给本服务帐号(3020447271),否则会读写cos失败; 1:key托管,把cos的账号id和key托管于本服务,本服务会提供一个托管id; 3:临时key授权。 注意:目前智能编辑还不支持临时key授权;画质重生目前只支持bucket授权 */ Type: number /** * cos账号托管id,Type等于1时必选。 */ HostedId?: string /** * cos身份识别id,Type等于3时必选。 */ SecretId?: string /** * cos身份秘钥,Type等于3时必选。 */ SecretKey?: string /** * 临时授权 token,Type等于3时必选。 */ Token?: string } /** * 片头片尾识别结果项 */ export interface OpeningEndingTaskResultItem { /** * 视频片头的结束时间点,单位:秒。 */ OpeningTimeOffset: number /** * 片头识别置信度,取值范围是 0 到 100。 */ OpeningConfidence: number /** * 视频片尾的开始时间点,单位:秒。 */ EndingTimeOffset: number /** * 片尾识别置信度,取值范围是 0 到 100。 */ EndingConfidence: number } /** * 编辑处理/剪切任务/处理结果 */ export interface MediaCuttingTaskResult { /** * 如果ResultListType不为NoListFile时,结果(TaskResultFile)列表文件的存储位置。 注意:此字段可能返回 null,表示取不到有效值。 */ ListFile: TaskResultFile /** * 结果个数。 注意:此字段可能返回 null,表示取不到有效值。 */ ResultCount: number /** * 第一个结果文件。 注意:此字段可能返回 null,表示取不到有效值。 */ FirstFile: TaskResultFile /** * 最后一个结果文件。 注意:此字段可能返回 null,表示取不到有效值。 */ LastFile: TaskResultFile } /** * 智能封面结果项 */ export interface CoverTaskResultItem { /** * 智能封面地址。 */ CoverUrl: string /** * 置信度,取值范围是 0 到 100。 */ Confidence: number } /** * 编辑处理/剪切任务信息 */ export interface MediaCuttingInfo { /** * 截取时间信息。 */ TimeInfo: MediaCuttingTimeInfo /** * 输出结果信息。 */ TargetInfo: MediaTargetInfo /** * 截取结果形式信息。 */ OutForm: MediaCuttingOutForm /** * 列表文件形式,存储到用户存储服务中,可选值: UseSaveInfo:默认,结果列表和结果存储同一位置; NoListFile:不存储结果列表。 */ ResultListSaveType?: string } /** * 周期时间点信息。 */ export interface IntervalTime { /** * 间隔周期,单位ms */ Interval: number /** * 开始时间点,单位ms */ StartTime?: number } /** * 低光照增强参数 */ export interface LowLightEnhance { /** * 低光照增强类型,可选项:normal。 */ Type: string } /** * 流封装信息 */ export interface MuxInfo { /** * 删除流,可选项:video,audio。 */ DeleteStream?: string /** * Flv 参数,目前支持add_keyframe_index */ FlvFlags?: string } /** * 目标视频信息。 */ export interface TargetVideoInfo { /** * 视频宽度,单位像素 */ Width?: number /** * 视频高度,单位像素 */ Height?: number /** * 视频帧率,范围在1到120之间 */ FrameRate?: number } /** * 视频转码信息 */ export interface VideoInfo { /** * 视频帧率,取值范围:[0, 60],单位:Hz。 注意:当取值为 0,表示帧率和原始视频保持一致。 */ Fps?: number /** * 宽度,取值范围:0 和 [128, 4096] 注意: 当 Width、Height 均为 0,则分辨率同源; 当 Width 为 0,Height 非 0,则 Width 按比例缩放; 当 Width 非 0,Height 为 0,则 Height 按比例缩放; 当 Width、Height 均非 0,则分辨率按用户指定。 */ Width?: number /** * 高度,取值范围:0 和 [128, 4096] 注意: 当 Width、Height 均为 0,则分辨率同源; 当 Width 为 0,Height 非 0,则 Width 按比例缩放; 当 Width 非 0,Height 为 0,则 Height 按比例缩放; 当 Width、Height 均非 0,则分辨率按用户指定。 */ Height?: number /** * 长边分辨率,取值范围:0 和 [128, 4096] 注意: 当 LongSide、ShortSide 均为 0,则分辨率按照Width,Height; 当 LongSide 为 0,ShortSide 非 0,则 LongSide 按比例缩放; 当 LongSide非 0,ShortSide为 0,则 ShortSide 按比例缩放; 当 LongSide、ShortSide 均非 0,则分辨率按用户指定。 长短边优先级高于Weight,Height,设置长短边则忽略宽高。 */ LongSide?: number /** * 短边分辨率,取值范围:0 和 [128, 4096] 注意: 当 LongSide、ShortSide 均为 0,则分辨率按照Width,Height; 当 LongSide 为 0,ShortSide 非 0,则 LongSide 按比例缩放; 当 LongSide非 0,ShortSide为 0,则 ShortSide 按比例缩放; 当 LongSide、ShortSide 均非 0,则分辨率按用户指定。 长短边优先级高于Weight,Height,设置长短边则忽略宽高。 */ ShortSide?: number /** * 视频流的码率,取值范围:0 和 [128, 35000],单位:kbps。当取值为 0,表示视频码率和原始视频保持一致。 */ Bitrate?: number /** * 固定I帧之间,视频帧数量,取值范围: [25, 2500],如果不填,使用编码默认最优序列。 */ Gop?: number /** * 编码器支持选项,可选值: h264, h265, av1。 不填默认h264。 */ VideoCodec?: string /** * 图片水印。 */ PicMarkInfo?: Array<PicMarkInfoItem> /** * 填充方式,当视频流配置宽高参数与原始视频的宽高比不一致时,对转码的处理方式,即为“填充”。 */ DarInfo?: DarInfo /** * 支持hdr,可选项: hdr10, hlg。 此时,VideoCodec会强制设置为h265, 编码位深为10 */ Hdr?: string /** * 画质增强参数信息。 */ VideoEnhance?: VideoEnhance /** * 数字水印参数信息。 */ HiddenMarkInfo?: HiddenMarkInfo /** * 文本水印参数信息。 */ TextMarkInfo?: Array<TextMarkInfoItem> } /** * DescribeQualityControlTaskResult请求参数结构体 */ export interface DescribeQualityControlTaskResultRequest { /** * 质检任务 ID */ TaskId: string } /** * DescribeMediaQualityRestorationTaskRusult返回参数结构体 */ export interface DescribeMediaQualityRestorationTaskRusultResponse { /** * 画质重生任务结果信息 */ TaskResult?: MediaQualityRestorationTaskResult /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 视频Dar信息 */ export interface DarInfo { /** * 填充模式,可选值: 1:留黑,保持视频宽高比不变,边缘剩余部分使用黑色填充。 2:拉伸,对每一帧进行拉伸,填满整个画面,可能导致转码后的视频被“压扁“或者“拉长“。 默认为2。 */ FillMode?: number } /** * CreateQualityControlTask返回参数结构体 */ export interface CreateQualityControlTaskResponse { /** * 质检任务 ID 注意:此字段可能返回 null,表示取不到有效值。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 音频响度信息 */ export interface LoudnessInfo { /** * 音频整体响度 */ Loudness?: number /** * 音频响度范围 */ LoudnessRange?: number } /** * 画质重生子任务参数信息 */ export interface SubTaskTranscodeInfo { /** * 子任务名称。 */ TaskName: string /** * 目标文件信息。 */ TargetInfo: TargetInfo /** * 视频剪辑信息。注意:如果填写了EditInfo,则VideoInfo和AudioInfo必填 */ EditInfo?: EditInfo /** * 视频转码信息,不填保持和源文件一致。 */ VideoInfo?: VideoInfo /** * 音频转码信息,不填保持和源文件一致。 */ AudioInfo?: AudioInfo /** * 指定封装信息。 */ MuxInfo?: MuxInfo } /** * CreateQualityControlTask请求参数结构体 */ export interface CreateQualityControlTaskRequest { /** * 质检任务参数 */ QualityControlInfo: QualityControlInfo /** * 视频源信息 */ DownInfo: DownInfo /** * 任务结果回调地址信息 */ CallbackInfo?: CallbackInfo } /** * 帧标签任务参数 */ export interface FrameTagRec { /** * 标签类型: "Common": 通用类型 "Game":游戏类型 */ TagType: string /** * 游戏具体类型: "HonorOfKings_AnchorViews":王者荣耀主播视角 "HonorOfKings_GameViews":王者荣耀比赛视角 "LOL_AnchorViews":英雄联盟主播视角 "LOL_GameViews":英雄联盟比赛视角 "PUBG_AnchorViews":和平精英主播视角 "PUBG_GameViews":和平精英比赛视角 */ GameExtendType?: string } /** * 智能集锦结果项 */ export interface HighlightsTaskResultItem { /** * 智能集锦地址。 */ HighlightUrl: string /** * 智能集锦封面地址。 */ CovImgUrl: string /** * 置信度,取值范围是 0 到 100。 */ Confidence: number /** * 智能集锦持续时间,单位:秒。 */ Duration: number /** * 智能集锦子片段结果集,集锦片段由这些子片段拼接生成。 */ SegmentSet: Array<HighlightsTaskResultItemSegment> } /** * CreateMediaQualityRestorationTask返回参数结构体 */ export interface CreateMediaQualityRestorationTaskResponse { /** * 画质重生任务ID,可以通过该ID查询任务状态。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 细节增强参数 */ export interface Sharp { /** * 细节增强方式,取值:normal。 */ Type?: string /** * 细节增强强度,可选项:0.0-1.0。小于0.0的默认为0.0,大于1.0的默认为1.0。 */ Ratio?: number } /** * 媒体识别任务处理结果 */ export interface MediaRecognitionTaskResult { /** * 帧标签识别结果 注意:此字段可能返回 null,表示取不到有效值。 */ FrameTagResults: FrameTagResult /** * 语音字幕识别结果 注意:此字段可能返回 null,表示取不到有效值。 */ SubtitleResults: SubtitleResult } /** * 媒体识别任务参数 */ export interface MediaRecognitionInfo { /** * 帧标签识别 */ FrameTagRec?: FrameTagRec /** * 语音字幕识别 */ SubtitleRec?: SubtitleRec } /** * 任务存储信息 */ export interface SaveInfo { /** * 存储类型,可选值: 1:CosInfo。 */ Type: number /** * Cos形式存储信息,当Type等于1时必选。 */ CosInfo?: CosInfo } /** * 去划痕参数 */ export interface ScratchRepair { /** * 去划痕方式,取值:normal。 */ Type?: string /** * 去划痕强度, 可选项:0.0-1.0。小于0.0的默认为0.0,大于1.0的默认为1.0。 */ Ratio?: number } /** * 去编码毛刺、伪影参数 */ export interface ArtifactReduction { /** * 去毛刺方式:weak,,strong */ Type?: string /** * 去毛刺算法,可选项: edaf, wdaf, 默认edaf。 注意:此参数已经弃用 */ Algorithm?: string } /** * 视频标签识别任务参数信息 */ export interface TagEditingInfo { /** * 是否开启视频标签识别。0为关闭,1为开启。其他非0非1值默认为0。 */ Switch: number /** * 额外定制化服务参数。参数为序列化的Json字符串,例如:{"k1":"v1"}。 */ CustomInfo?: string } /** * StopMediaQualityRestorationTask返回参数结构体 */ export interface StopMediaQualityRestorationTaskResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 智能拆条任务参数信息 */ export interface StripEditingInfo { /** * 是否开启智能拆条。0为关闭,1为开启。其他非0非1值默认为0。 */ Switch: number /** * 额外定制化服务参数。参数为序列化的Json字符串,例如:{"k1":"v1"}。 */ CustomInfo?: string } /** * 智能编辑任务参数信息 */ export interface EditingInfo { /** * 视频标签识别任务参数,不填则不开启。 */ TagEditingInfo?: TagEditingInfo /** * 视频分类识别任务参数,不填则不开启。 */ ClassificationEditingInfo?: ClassificationEditingInfo /** * 智能拆条任务参数,不填则不开启。 */ StripEditingInfo?: StripEditingInfo /** * 智能集锦任务参数,不填则不开启。 */ HighlightsEditingInfo?: HighlightsEditingInfo /** * 智能封面任务参数,不填则不开启。 */ CoverEditingInfo?: CoverEditingInfo /** * 片头片尾识别任务参数,不填则不开启。 */ OpeningEndingEditingInfo?: OpeningEndingEditingInfo } /** * CreateMediaProcessTask请求参数结构体 */ export interface CreateMediaProcessTaskRequest { /** * 编辑处理任务参数。 */ MediaProcessInfo: MediaProcessInfo /** * 编辑处理任务输入源列表。 */ SourceInfoSet?: Array<MediaSourceInfo> /** * 结果存储信息,对于涉及存储的请求必选。部子任务支持数组备份写,具体以对应任务文档为准。 */ SaveInfoSet?: Array<SaveInfo> /** * 任务结果回调地址信息。部子任务支持数组备份回调,具体以对应任务文档为准。 */ CallbackInfoSet?: Array<CallbackInfo> } /** * 语音字幕识别结果 */ export interface SubtitleResult { /** * 语音字幕数组 */ SubtitleItems: Array<SubtitleItem> } /** * CreateMediaProcessTask返回参数结构体 */ export interface CreateMediaProcessTaskResponse { /** * 编辑任务 ID,可以通过该 ID 查询任务状态和结果。 注意:此字段可能返回 null,表示取不到有效值。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 任务结果文件信息 */ export interface TaskResultFile { /** * 文件链接。 注意:此字段可能返回 null,表示取不到有效值。 */ Url: string /** * 文件大小,部分任务支持,单位:字节 注意:此字段可能返回 null,表示取不到有效值。 */ FileSize: number /** * 媒体信息,对于媒体文件,部分任务支持返回 注意:此字段可能返回 null,表示取不到有效值。 */ MediaInfo: MediaResultInfo } /** * CreateEditingTask返回参数结构体 */ export interface CreateEditingTaskResponse { /** * 编辑任务 ID,可以通过该 ID 查询任务状态。 */ TaskId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 任务视频Url形式下载信息。 */ export interface UrlInfo { /** * 视频 URL。 注意:编辑理解仅支持mp4、flv等格式的点播文件,不支持hls; */ Url: string /** * 视频地址格式,可选值: 0:音视频 ; 1:直播流。 默认为0。其他非0非1值默认为0。画质重生任务只支持0。 */ Format?: number /** * 【不再支持】指定请求资源时,HTTP头部host的值。 */ Host?: string } /** * 编辑处理的媒体源 */ export interface MediaSourceInfo { /** * 媒体源资源下载信息。 */ DownInfo: DownInfo /** * 媒体源ID标记,用于多个输入源时,请内媒体源的定位,对于多输入的任务,一般要求必选。 ID只能包含字母、数字、下划线、中划线,长读不能超过128。 */ Id?: string /** * 媒体源类型,具体类型如下: Video:视频 Image:图片 Audio:音频 */ Type?: string } /** * 任务结果回调地址信息 */ export interface CallbackInfo { /** * 回调URL。 */ Url: string } /** * 时间区间。 */ export interface SectionTime { /** * 开始时间点,单位ms */ StartTime: number /** * 时间区间时长,单位ms */ Duration: number } /** * 语音字幕任务参数 */ export interface SubtitleRec { /** * 语音识别: zh:中文 en:英文 */ AsrDst?: string /** * 翻译识别: zh:中文 en:英文 */ TransDst?: string } /** * 结果媒体文件的视频流信息 */ export interface ResultVideoInfo { /** * 流在媒体文件中的流ID 注意:此字段可能返回 null,表示取不到有效值。 */ StreamId: number /** * 流的时长,单位:毫秒 注意:此字段可能返回 null,表示取不到有效值。 */ Duration: number /** * 画面宽度 注意:此字段可能返回 null,表示取不到有效值。 */ Width: number /** * 画面高度 注意:此字段可能返回 null,表示取不到有效值。 */ Height: number /** * 视频帧率 注意:此字段可能返回 null,表示取不到有效值。 */ Fps: number } /** * 图片水印信息 */ export interface PicMarkInfoItem { /** * 图片水印的X坐标。 */ PosX: number /** * 图片水印的Y坐标 。 */ PosY: number /** * 图片水印路径,,如果不从Cos拉取水印,则必填 */ Path?: string /** * 图片水印的Cos 信息,从Cos上拉取图片水印时必填。 */ CosInfo?: CosInfo /** * 图片水印宽度,不填为图片原始宽度。 */ Width?: number /** * 图片水印高度,不填为图片原始高度。 */ Height?: number /** * 添加图片水印的开始时间,单位:ms。 */ StartTime?: number /** * 添加图片水印的结束时间,单位:ms。 */ EndTime?: number } /** * 编辑处理/拼接任务信息 */ export interface MediaJoiningInfo { /** * 输出目标信息,拼接只采用FileName和Format,用于指定目标文件名和格式。 其中Format只支持mp4. */ TargetInfo: MediaTargetInfo } /** * DescribeMediaQualityRestorationTaskRusult请求参数结构体 */ export interface DescribeMediaQualityRestorationTaskRusultRequest { /** * 画质重生任务ID */ TaskId: string } /** * 颜色增强参数 */ export interface ColorEnhance { /** * 颜色增强类型,可选项: 1. tra; 2. weak; 3. normal; 4. strong; 注意:tra不支持自适应调整,处理速度更快;weak,normal,strong支持基于画面颜色自适应,处理速度更慢。 */ Type: string } /** * 输出文件切片信息 */ export interface SegmentInfo { /** * 每个切片平均时长,默认10s。 */ FragmentTime?: number /** * 切片类型,可选项:hls,不填时默认hls。 */ SegmentType?: string /** * 切片文件名字。注意: 1.不填切片文件名时,默认按照按照如下格式命名:m3u8文件名{order}。 2.若填了切片文件名字,则会按照如下格式命名:用户指定文件名{order}。 */ FragmentName?: string } /** * 片头片尾识别任务参数信息 */ export interface OpeningEndingEditingInfo { /** * 是否开启片头片尾识别。0为关闭,1为开启。其他非0非1值默认为0。 */ Switch: number /** * 额外定制化服务参数。参数为序列化的Json字符串,例如:{"k1":"v1"}。 */ CustomInfo?: string } /** * 目标媒体信息。 */ export interface MediaTargetInfo { /** * 目标文件名,不能带特殊字符(如/等),无需后缀名,最长200字符。 注1:部分子服务支持占位符,形式为: {parameter} 预设parameter有: index:序号; */ FileName: string /** * 媒体封装格式,最长5字符,具体格式支持根据子任务确定。 */ Format: string /** * 视频流信息。 */ TargetVideoInfo?: TargetVideoInfo /** * 【不再使用】 对于多输出任务,部分子服务推荐结果信息以列表文件形式,存储到用户存储服务中,可选值: UseSaveInfo:默认,结果列表和结果存储同一位置; NoListFile:不存储结果列表。 */ ResultListSaveType?: string } /** * 视频标签识别结果项 */ export interface TagTaskResultItem { /** * 标签名称。 */ Tag: string /** * 置信度,取值范围是 0 到 100。 */ Confidence: number } /** * 媒体质检任务参数信息 */ export interface QualityControlInfo { /** * 对流进行截图的间隔ms,默认1000ms */ Interval?: number /** * 是否保存截图 */ VideoShot?: boolean /** * 是否检测抖动重影 */ Jitter?: boolean /** * 是否检测模糊 */ Blur?: boolean /** * 是否检测低光照、过曝 */ AbnormalLighting?: boolean /** * 是否检测花屏 */ CrashScreen?: boolean /** * 是否检测黑边、白边、黑屏、白屏、绿屏 */ BlackWhiteEdge?: boolean /** * 是否检测噪点 */ Noise?: boolean /** * 是否检测马赛克 */ Mosaic?: boolean /** * 是否检测二维码,包括小程序码、条形码 */ QRCode?: boolean /** * 是否开启画面质量评价 */ QualityEvaluation?: boolean /** * 画面质量评价过滤阈值,结果只返回低于阈值的时间段,默认60 */ QualityEvalScore?: number /** * 是否检测视频音频,包含静音、低音、爆音 */ Voice?: boolean } /** * 视频源信息 */ export interface DownInfo { /** * 下载类型,可选值: 0:UrlInfo; 1:CosInfo。 */ Type: number /** * Url形式下载信息,当Type等于0时必选。 */ UrlInfo?: UrlInfo /** * Cos形式下载信息,当Type等于1时必选。 */ CosInfo?: CosInfo } /** * 视频分类识别任务参数信息 */ export interface ClassificationEditingInfo { /** * 是否开启视频分类识别。0为关闭,1为开启。其他非0非1值默认为0。 */ Switch: number /** * 额外定制化服务参数。参数为序列化的Json字符串,例如:{"k1":"v1"}。 */ CustomInfo?: string } /** * 智能集锦结果信息 */ export interface HighlightsTaskResult { /** * 编辑任务状态。 1:执行中;2:成功;3:失败。 */ Status: number /** * 编辑任务失败错误码。 0:成功;其他值:失败。 */ ErrCode: number /** * 编辑任务失败错误描述。 */ ErrMsg: string /** * 智能集锦结果集。 注意:此字段可能返回 null,表示取不到有效值。 */ ItemSet: Array<HighlightsTaskResultItem> } /** * DescribeEditingTaskResult请求参数结构体 */ export interface DescribeEditingTaskResultRequest { /** * 编辑任务 ID。 */ TaskId: string } /** * 任务结束后生成的文件音频信息 */ export interface AudioInfoResultItem { /** * 音频流的流id。 */ Stream: number /** * 音频采样率 。 注意:此字段可能返回 null,表示取不到有效值。 */ Sample: number /** * 音频声道数。 注意:此字段可能返回 null,表示取不到有效值。 */ Channel: number /** * 编码格式,如aac, mp3等。 注意:此字段可能返回 null,表示取不到有效值。 */ Codec: string /** * 码率,单位:bps。 注意:此字段可能返回 null,表示取不到有效值。 */ Bitrate: number /** * 音频时长,单位:ms。 注意:此字段可能返回 null,表示取不到有效值。 */ Duration: number } /** * 画质重生子任务视频剪辑参数 */ export interface EditInfo { /** * 剪辑开始时间,单位:ms。 */ StartTime: number /** * 剪辑结束时间,单位:ms */ EndTime: number } /** * 音频去除混响 */ export interface RemoveReverb { /** * 去混响类型,可选项:normal */ Type?: string } /** * StopMediaProcessTask返回参数结构体 */ export interface StopMediaProcessTaskResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeEditingTaskResult返回参数结构体 */ export interface DescribeEditingTaskResultResponse { /** * 编辑任务结果信息。 */ TaskResult: EditingTaskResult /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 媒体质检结果信息 */ export interface QualityControlInfoTaskResult { /** * 质检任务 ID */ TaskId: string /** * 质检任务状态。 1:执行中;2:成功;3:失败 */ Status: number /** * 表示处理进度百分比 */ Progress: number /** * 处理时长(s) */ UsedTime: number /** * 计费时长(s) */ Duration: number /** * 为true时表示视频无音频轨 注意:此字段可能返回 null,表示取不到有效值。 */ NoAudio: boolean /** * 为true时表示视频无视频轨 注意:此字段可能返回 null,表示取不到有效值。 */ NoVideo: boolean /** * 视频无参考质量打分,百分制 注意:此字段可能返回 null,表示取不到有效值。 */ QualityEvaluationScore: number /** * 视频画面无参考评分低于阈值的时间段 注意:此字段可能返回 null,表示取不到有效值。 */ QualityEvaluationResults: Array<QualityControlResultItems> /** * 视频画面抖动时间段 注意:此字段可能返回 null,表示取不到有效值。 */ JitterResults: Array<QualityControlResultItems> /** * 视频画面模糊时间段 注意:此字段可能返回 null,表示取不到有效值。 */ BlurResults: Array<QualityControlResultItems> /** * 视频画面低光、过曝时间段 注意:此字段可能返回 null,表示取不到有效值。 */ AbnormalLightingResults: Array<QualityControlResultItems> /** * 视频画面花屏时间段 注意:此字段可能返回 null,表示取不到有效值。 */ CrashScreenResults: Array<QualityControlResultItems> /** * 视频画面黑边、白边、黑屏、白屏、纯色屏时间段 注意:此字段可能返回 null,表示取不到有效值。 */ BlackWhiteEdgeResults: Array<QualityControlResultItems> /** * 视频画面有噪点时间段 注意:此字段可能返回 null,表示取不到有效值。 */ NoiseResults: Array<QualityControlResultItems> /** * 视频画面有马赛克时间段 注意:此字段可能返回 null,表示取不到有效值。 */ MosaicResults: Array<QualityControlResultItems> /** * 视频画面有二维码的时间段,包括小程序码、条形码 注意:此字段可能返回 null,表示取不到有效值。 */ QRCodeResults: Array<QualityControlResultItems> /** * 视频音频异常时间段,包括静音、低音、爆音 注意:此字段可能返回 null,表示取不到有效值。 */ VoiceResults: Array<QualityControlResultItems> /** * 任务错误码 注意:此字段可能返回 null,表示取不到有效值。 */ ErrCode: number /** * 任务错误信息 注意:此字段可能返回 null,表示取不到有效值。 */ ErrMsg: string } /** * 画质重生任务结果 */ export interface MediaQualityRestorationTaskResult { /** * 画质重生任务ID */ TaskId: string /** * 画质重生处理后文件的详细信息。 */ SubTaskResult: Array<SubTaskResultItem> } /** * 数字水印 */ export interface HiddenMarkInfo { /** * 数字水印路径,,如果不从Cos拉取水印,则必填 */ Path: string /** * 数字水印频率,可选值:[1,256],默认值为30 */ Frequency?: number /** * 数字水印强度,可选值:[32,128],默认值为64 */ Strength?: number /** * 数字水印的Cos 信息,从Cos上拉取图片水印时必填。 */ CosInfo?: CosInfo } /** * 编辑处理/剪切任务/输出形式信息 */ export interface MediaCuttingOutForm { /** * 输出类型,可选值: Static:静态图; Dynamic:动态图; Sprite:雪碧图; Video:视频。 注1:不同类型时,对应的 TargetInfo.Format 格式支持如下: Static:jpg、png; Dynamic:gif; Sprite:jpg、png; Video:mp4。 注2:当 Type=Sprite时,TargetInfo指定的尺寸表示小图的大小,最终结果尺寸以输出为准。 */ Type: string /** * 背景填充方式,可选值: White:白色填充; Black:黑色填充; Stretch:拉伸; Gaussian:高斯模糊; 默认White。 */ FillType?: string /** * Type=Sprite时有效,表示雪碧图行数,范围为 [1,200],默认100。 */ SpriteRowCount?: number /** * Type=Sprite时有效,表示雪碧图列数,范围为 [1,200],默认100。 */ SpriteColumnCount?: number } /** * StopMediaQualityRestorationTask请求参数结构体 */ export interface StopMediaQualityRestorationTaskRequest { /** * 要删除的画质重生任务ID。 */ TaskId: string } /** * DescribeQualityControlTaskResult返回参数结构体 */ export interface DescribeQualityControlTaskResultResponse { /** * 质检任务结果信息 */ TaskResult?: QualityControlInfoTaskResult /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 视频分类识别结果项 */ export interface ClassificationTaskResultItem { /** * 分类名称。 */ Classification: string /** * 置信度,取值范围是 0 到 100。 */ Confidence: number } /** * 音频参数信息 */ export interface AudioInfo { /** * 音频码率,取值范围:0 和 [26, 256],单位:kbps。 注意:当取值为 0,表示音频码率和原始音频保持一致。 */ Bitrate: number /** * 音频编码器,可选项:aac,mp3,ac3,flac,mp2。 */ Codec: string /** * 声道数,可选项: 1:单声道, 2:双声道, 6:立体声。 */ Channel: number /** * 采样率,单位:Hz。可选项:32000,44100,48000 */ SampleRate: number /** * 音频降噪信息 */ Denoise?: Denoise /** * 开启添加静音,可选项: 0:不开启, 1:开启, 默认不开启 */ EnableMuteAudio?: number /** * 音频响度信息 */ LoudnessInfo?: LoudnessInfo /** * 音频音效增强 */ AudioEnhance?: AudioEnhance /** * 去除混音 */ RemoveReverb?: RemoveReverb } /** * 画质重生子任务结果 */ export interface SubTaskResultItem { /** * 子任务名称。 注意:此字段可能返回 null,表示取不到有效值。 */ TaskName: string /** * 子任务状态。 0:成功; 1:执行中; 其他值:失败。 */ StatusCode: number /** * 子任务状态描述。 */ StatusMsg: string /** * 子任务进度。 注意:此字段可能返回 null,表示取不到有效值。 */ ProgressRate: number /** * 画质重生处理后文件的下载地址。 注意:此字段可能返回 null,表示取不到有效值。 */ DownloadUrl: string /** * 画质重生处理后文件的MD5。 注意:此字段可能返回 null,表示取不到有效值。 */ Md5: string /** * 画质重生处理后文件的详细信息。 注意:此字段可能返回 null,表示取不到有效值。 */ FileInfo: FileInfo } /** * 智能拆条结果信息 */ export interface StripTaskResult { /** * 编辑任务状态。 1:执行中;2:成功;3:失败。 */ Status: number /** * 编辑任务失败错误码。 0:成功;其他值:失败。 */ ErrCode: number /** * 编辑任务失败错误描述。 */ ErrMsg: string /** * 智能拆条结果集。 注意:此字段可能返回 null,表示取不到有效值。 */ ItemSet: Array<StripTaskResultItem> } /** * 智能集锦任务参数信息 */ export interface HighlightsEditingInfo { /** * 是否开启智能集锦。0为关闭,1为开启。其他非0非1值默认为0。 */ Switch: number /** * 额外定制化服务参数。参数为序列化的Json字符串,例如:{"k1":"v1"}。 */ CustomInfo?: string } /** * 画质重生处理后文件的详细信息 */ export interface FileInfo { /** * 任务结束后生成的文件大小。 注意:此字段可能返回 null,表示取不到有效值。 */ FileSize: number /** * 任务结束后生成的文件格式,例如:mp4,flv等等。 注意:此字段可能返回 null,表示取不到有效值。 */ FileType: string /** * 任务结束后生成的文件整体码率,单位:bps。 注意:此字段可能返回 null,表示取不到有效值。 */ Bitrate: number /** * 任务结束后生成的文件时长,单位:ms。 注意:此字段可能返回 null,表示取不到有效值。 */ Duration: number /** * 任务结束后生成的文件视频信息。 注意:此字段可能返回 null,表示取不到有效值。 */ VideoInfoResult: Array<VideoInfoResultItem> /** * 任务结束后生成的文件音频信息。 注意:此字段可能返回 null,表示取不到有效值。 */ AudioInfoResult: Array<AudioInfoResultItem> } /** * 结果媒体文件的视频流信息 */ export interface ResultAudioInfo { /** * 流在媒体文件中的流ID 注意:此字段可能返回 null,表示取不到有效值。 */ StreamId: number /** * 流的时长,单位:毫秒 注意:此字段可能返回 null,表示取不到有效值。 */ Duration: number } /** * 片头片尾识别结果信息 */ export interface OpeningEndingTaskResult { /** * 编辑任务状态。 1:执行中;2:成功;3:失败。 */ Status: number /** * 编辑任务失败错误码。 0:成功;其他值:失败。 */ ErrCode: number /** * 编辑任务失败错误描述。 */ ErrMsg: string /** * 片头片尾识别结果项。 注意:此字段可能返回 null,表示取不到有效值。 */ Item: OpeningEndingTaskResultItem } /** * 画质增强参数信息 */ export interface VideoEnhance { /** * 去编码毛刺、伪影参数。 */ ArtifactReduction?: ArtifactReduction /** * 去噪声参数。 */ Denoising?: Denoising /** * 颜色增强参数。 */ ColorEnhance?: ColorEnhance /** * 细节增强参数。 */ Sharp?: Sharp /** * 超分参数,可选项:2,目前仅支持2倍超分。 注意:此参数已经弃用,超分可以使用VideoSuperResolution参数 */ WdSuperResolution?: number /** * 人脸保护信息。 */ FaceProtect?: FaceProtect /** * 插帧,取值范围:[0, 60],单位:Hz。 注意:当取值为 0,表示帧率和原始视频保持一致。 */ WdFps?: number /** * 去划痕参数 */ ScratchRepair?: ScratchRepair /** * 低光照增强参数 */ LowLightEnhance?: LowLightEnhance /** * 视频超分参数 */ VideoSuperResolution?: VideoSuperResolution /** * 视频画质修复参数 */ VideoRepair?: VideoRepair } /** * 综合画质修复,包括:去噪,去毛刺,细节增强,主观画质提升。 */ export interface VideoRepair { /** * 画质修复类型,可选值:weak,normal,strong; 默认值: weak */ Type?: string } /** * 质检结果项数组 */ export interface QualityControlResultItems { /** * 异常类型 注意:此字段可能返回 null,表示取不到有效值。 */ Id: string /** * 质检结果项 */ QualityControlItems: Array<QualityControlItem> } /** * 帧标签 */ export interface FrameTagItem { /** * 标签起始时间戳PTS(ms) */ StartPts: number /** * 语句结束时间戳PTS(ms) */ EndPts: number /** * 字符串形式的起始结束时间 */ Period: string /** * 标签数组 */ TagItems: Array<TagItem> } /** * 质检结果项 */ export interface QualityControlItem { /** * 置信度,取值范围是 0 到 100 注意:此字段可能返回 null,表示取不到有效值。 */ Confidence: number /** * 出现的起始时间戳,秒 */ StartTimeOffset: number /** * 出现的结束时间戳,秒 */ EndTimeOffset: number /** * 区域坐标(px),即左上角坐标、右下角坐标 注意:此字段可能返回 null,表示取不到有效值。 */ AreaCoordsSet: Array<number> } /** * 智能封面结果信息 */ export interface CoverTaskResult { /** * 编辑任务状态。 1:执行中;2:成功;3:失败。 */ Status: number /** * 编辑任务失败错误码。 0:成功;其他值:失败。 */ ErrCode: number /** * 编辑任务失败错误描述。 */ ErrMsg: string /** * 智能封面结果集。 注意:此字段可能返回 null,表示取不到有效值。 */ ItemSet: Array<CoverTaskResultItem> } /** * 视频标签识别结果信息 */ export interface TagTaskResult { /** * 编辑任务状态。 1:执行中;2:成功;3:失败。 */ Status: number /** * 编辑任务失败错误码。 0:成功;其他值:失败。 */ ErrCode: number /** * 编辑任务失败错误描述。 */ ErrMsg: string /** * 视频标签识别结果集。 注意:此字段可能返回 null,表示取不到有效值。 */ ItemSet: Array<TagTaskResultItem> } /** * 音频音效增强,只支持无背景音的音频 */ export interface AudioEnhance { /** * 音效增强种类,可选项:normal */ Type?: string } /** * 任务视频cos信息 */ export interface CosInfo { /** * cos 区域值。例如:ap-beijing。 */ Region: string /** * cos 存储桶,格式为BuketName-AppId。例如:test-123456。 */ Bucket: string /** * cos 路径。 对于写表示目录,例如:/test; 对于读表示文件路径,例如:/test/test.mp4。 */ Path: string /** * cos 授权信息,不填默认为公有权限。 */ CosAuthMode?: CosAuthMode } /** * 结果文件媒体信息 */ export interface MediaResultInfo { /** * 媒体时长,单位:毫秒 注意:此字段可能返回 null,表示取不到有效值。 */ Duration: number /** * 视频流信息 注意:此字段可能返回 null,表示取不到有效值。 */ ResultVideoInfoSet: Array<ResultVideoInfo> /** * 音频流信息 注意:此字段可能返回 null,表示取不到有效值。 */ ResultAudioInfoSet: Array<ResultAudioInfo> } /** * 帧标签结果 */ export interface FrameTagResult { /** * 帧标签结果数组 */ FrameTagItems: Array<FrameTagItem> } /** * 画质重生子任务文字水印信息 */ export interface TextMarkInfoItem { /** * 文字内容。 */ Text: string /** * 文字水印X坐标。 */ PosX: number /** * 文字水印Y坐标。 */ PosY: number /** * 文字大小 */ FontSize: number /** * 字体,可选项:hei,song,simkai,arial;默认hei(黑体)。 */ FontFile?: string /** * 字体颜色,颜色见附录,不填默认black。 */ FontColor?: string /** * 文字透明度,可选值0-1。0:不透明,1:全透明。默认为0 */ FontAlpha?: number } /** * 编辑处理/剪切任务/时间信息 */ export interface MediaCuttingTimeInfo { /** * 时间类型,可选值: PointSet:时间点集合; IntervalPoint:周期采样点; SectionSet:时间片段集合。 */ Type: string /** * 截取时间点集合,单位毫秒,Type=PointSet时必选。 */ PointSet?: Array<number> /** * 周期采样点信息,Type=IntervalPoint时必选。 */ IntervalPoint?: IntervalTime /** * 时间区间集合信息,Type=SectionSet时必选。 */ SectionSet?: Array<SectionTime> } /** * 输出文件信息 */ export interface TargetInfo { /** * 目标文件名 */ FileName: string /** * 目标文件切片信息 */ SegmentInfo?: SegmentInfo } /** * CreateMediaQualityRestorationTask请求参数结构体 */ export interface CreateMediaQualityRestorationTaskRequest { /** * 源文件地址。 */ DownInfo: DownInfo /** * 画质重生任务参数信息。 */ TransInfo: Array<SubTaskTranscodeInfo> /** * 任务结束后文件存储信息。 */ SaveInfo: SaveInfo /** * 任务结果回调地址信息。 */ CallbackInfo?: CallbackInfo } /** * CreateEditingTask请求参数结构体 */ export interface CreateEditingTaskRequest { /** * 智能编辑任务参数。 */ EditingInfo: EditingInfo /** * 视频源信息。 */ DownInfo: DownInfo /** * 结果存储信息。对于包含智能拆条、智能集锦或者智能封面的任务必选。 */ SaveInfo?: SaveInfo /** * 任务结果回调地址信息。 */ CallbackInfo?: CallbackInfo } /** * 去噪参数 */ export interface Denoising { /** * 去噪方式,可选项: templ:时域降噪; spatial:空域降噪, fast-spatial:快速空域降噪。 注意:可选择组合方式: 1.type:"templ,spatial" ; 2.type:"templ,fast-spatial"。 */ Type: string /** * 时域去噪强度,可选值:0.0-1.0 。小于0.0的默认为0.0,大于1.0的默认为1.0。 */ TemplStrength?: number /** * 空域去噪强度,可选值:0.0-1.0 。小于0.0的默认为0.0,大于1.0的默认为1.0。 */ SpatialStrength?: number } /** * 人脸保护参数 */ export interface FaceProtect { /** * 人脸区域增强强度,可选项:0.0-1.0。小于0.0的默认为0.0,大于1.0的默认为1.0。 */ FaceUsmRatio?: number } /** * 任务结束后生成的文件视频信息 */ export interface VideoInfoResultItem { /** * 视频流的流id。 */ Stream: number /** * 视频宽度。 注意:此字段可能返回 null,表示取不到有效值。 */ Width: number /** * 视频高度。 注意:此字段可能返回 null,表示取不到有效值。 */ Height: number /** * 视频码率,单位:bps。 注意:此字段可能返回 null,表示取不到有效值。 */ Bitrate: number /** * 视频帧率,用分数格式表示,如:25/1, 99/32等等。 注意:此字段可能返回 null,表示取不到有效值。 */ Fps: string /** * 编码格式,如h264,h265等等 。 注意:此字段可能返回 null,表示取不到有效值。 */ Codec: string /** * 播放旋转角度,可选值0-360。 注意:此字段可能返回 null,表示取不到有效值。 */ Rotate: number /** * 视频时长,单位:ms 。 注意:此字段可能返回 null,表示取不到有效值。 */ Duration: number /** * 颜色空间,如yuv420p,yuv444p等等。 注意:此字段可能返回 null,表示取不到有效值。 */ PixFormat: string } /** * StopMediaProcessTask请求参数结构体 */ export interface StopMediaProcessTaskRequest { /** * 编辑处理任务ID。 */ TaskId: string } /** * 智能封面任务参数信息 */ export interface CoverEditingInfo { /** * 是否开启智能封面。0为关闭,1为开启。其他非0非1值默认为0。 */ Switch: number /** * 额外定制化服务参数。参数为序列化的Json字符串,例如:{"k1":"v1"}。 */ CustomInfo?: string } /** * 语音字幕识别项 */ export interface SubtitleItem { /** * 语音识别结果 */ Id: string /** * 中文翻译结果 注意:此字段可能返回 null,表示取不到有效值。 */ Zh: string /** * 英文翻译结果 注意:此字段可能返回 null,表示取不到有效值。 */ En: string /** * 语句起始时间戳PTS(ms) */ StartPts: number /** * 语句结束时间戳PTS(ms) */ EndPts: number /** * 字符串形式的起始结束时间 */ Period: string /** * 结果的置信度(百分制) */ Confidence: number /** * 当前语句是否结束 */ EndFlag: boolean /** * 语句分割时间戳 注意:此字段可能返回 null,表示取不到有效值。 */ PuncEndTs: string } /** * DescribeMediaProcessTaskResult请求参数结构体 */ export interface DescribeMediaProcessTaskResultRequest { /** * 编辑处理任务ID。 */ TaskId: string } /** * 编辑处理/任务处理结果 */ export interface MediaProcessTaskResult { /** * 编辑处理任务ID。 注意:此字段可能返回 null,表示取不到有效值。 */ TaskId: string /** * 编辑处理任务类型,取值: MediaEditing:视频编辑(待上线); MediaCutting:视频剪切; MediaJoining:视频拼接。 MediaRecognition:媒体识别; 注意:此字段可能返回 null,表示取不到有效值。 */ Type: string /** * 处理进度,范围:[0,100] 注意:此字段可能返回 null,表示取不到有效值。 */ Progress: number /** * 任务状态: 1100:等待中; 1200:执行中; 2000:成功; 5000:失败。 注意:此字段可能返回 null,表示取不到有效值。 */ Status: number /** * 任务错误码。 注意:此字段可能返回 null,表示取不到有效值。 */ ErrCode: number /** * 任务错误信息。 注意:此字段可能返回 null,表示取不到有效值。 */ ErrMsg: string /** * 剪切任务处理结果,当Type=MediaCutting时才有效。 注意:此字段可能返回 null,表示取不到有效值。 */ MediaCuttingTaskResult: MediaCuttingTaskResult /** * 拼接任务处理结果,当Type=MediaJoining时才有效。 注意:此字段可能返回 null,表示取不到有效值。 */ MediaJoiningTaskResult: MediaJoiningTaskResult /** * 媒体识别任务处理结果,当Type=MediaRecognition时才有效。 注意:此字段可能返回 null,表示取不到有效值。 */ MediaRecognitionTaskResult: MediaRecognitionTaskResult } /** * 智能识别任务结果信息 */ export interface EditingTaskResult { /** * 编辑任务 ID。 */ TaskId: string /** * 编辑任务状态。 1:执行中;2:已完成。 */ Status: number /** * 视频标签识别结果。 注意:此字段可能返回 null,表示取不到有效值。 */ TagTaskResult: TagTaskResult /** * 视频分类识别结果。 注意:此字段可能返回 null,表示取不到有效值。 */ ClassificationTaskResult: ClassificationTaskResult /** * 智能拆条结果。 注意:此字段可能返回 null,表示取不到有效值。 */ StripTaskResult: StripTaskResult /** * 智能集锦结果。 注意:此字段可能返回 null,表示取不到有效值。 */ HighlightsTaskResult: HighlightsTaskResult /** * 智能封面结果。 注意:此字段可能返回 null,表示取不到有效值。 */ CoverTaskResult: CoverTaskResult /** * 片头片尾识别结果。 注意:此字段可能返回 null,表示取不到有效值。 */ OpeningEndingTaskResult: OpeningEndingTaskResult } /** * 编辑处理/任务信息 */ export interface MediaProcessInfo { /** * 编辑处理任务类型,可选值: MediaEditing:媒体编辑(待上线); MediaCutting:媒体剪切; MediaJoining:媒体拼接。 MediaRecognition: 媒体识别。 */ Type: string /** * 视频剪切任务参数,Type=MediaCutting时必选。 */ MediaCuttingInfo?: MediaCuttingInfo /** * 视频拼接任务参数,Type=MediaJoining时必选。 */ MediaJoiningInfo?: MediaJoiningInfo /** * 媒体识别任务参数,Type=MediaRecognition时必选 */ MediaRecognitionInfo?: MediaRecognitionInfo } /** * 视频分类识别结果信息 */ export interface ClassificationTaskResult { /** * 编辑任务状态。 1:执行中;2:成功;3:失败。 */ Status: number /** * 编辑任务失败错误码。 0:成功;其他值:失败。 */ ErrCode: number /** * 编辑任务失败错误描述。 */ ErrMsg: string /** * 视频分类识别结果集。 注意:此字段可能返回 null,表示取不到有效值。 */ ItemSet: Array<ClassificationTaskResultItem> } /** * 标签项 */ export interface TagItem { /** * 标签内容 */ Id: string /** * 结果的置信度(百分制) */ Confidence: number /** * 分级数组 注意:此字段可能返回 null,表示取不到有效值。 */ Categorys: Array<string> /** * 标签备注 注意:此字段可能返回 null,表示取不到有效值。 */ Ext: string } /** * DescribeMediaProcessTaskResult返回参数结构体 */ export interface DescribeMediaProcessTaskResultResponse { /** * 任务处理结果。 注意:此字段可能返回 null,表示取不到有效值。 */ TaskResult?: MediaProcessTaskResult /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 智能集锦结果片段 */ export interface HighlightsTaskResultItemSegment { /** * 置信度,取值范围是 0 到 100。 */ Confidence: number /** * 集锦片段起始的偏移时间,单位:秒。 */ StartTimeOffset: number /** * 集锦片段终止的偏移时间,单位:秒。 */ EndTimeOffset: number }
the_stack
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { render, fireEvent } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { isConformant } from '../../common/isConformant'; import { useKeytipRef } from '../../Keytips'; import { SelectableOptionMenuItemType } from '../../SelectableOption'; import { resetIds } from '../../Utilities'; import { ComboBox } from './ComboBox'; import type { IComboBox, IComboBoxOption } from './ComboBox.types'; const RENDER_OPTIONS: IComboBoxOption[] = [ { key: 'header', text: 'Header', itemType: SelectableOptionMenuItemType.Header }, { key: '1', text: 'Option 1' }, { key: 'divider', text: '', itemType: SelectableOptionMenuItemType.Divider }, { key: '2', text: 'Option 2' }, ]; const DEFAULT_OPTIONS: IComboBoxOption[] = [ { key: '1', text: '1' }, { key: '2', text: '2' }, { key: '3', text: '3' }, ]; const DEFAULT_OPTIONS2: IComboBoxOption[] = [ { key: '1', text: 'One' }, { key: '2', text: 'Foo' }, { key: '3', text: 'Bar' }, ]; const DEFAULT_OPTIONS3: IComboBoxOption[] = [ { key: '0', text: 'Zero', itemType: SelectableOptionMenuItemType.Header }, { key: '1', text: 'One' }, { key: '2', text: 'Foo' }, { key: '3', text: 'Bar' }, ]; const RUSSIAN_OPTIONS: IComboBoxOption[] = [ { key: '0', text: 'сестра' }, { key: '1', text: 'брат' }, { key: '2', text: 'мама' }, { key: '3', text: 'папа' }, ]; const returnUndefined = () => undefined; describe('ComboBox', () => { const createPortal = ReactDOM.createPortal; function mockCreatePortal() { (ReactDOM as any).createPortal = (node: any) => node; } beforeEach(() => { resetIds(); }); afterEach(() => { (ReactDOM as any).createPortal = createPortal; }); isConformant({ Component: ComboBox, displayName: 'ComboBox', }); it('Renders correctly', () => { const { container } = render(<ComboBox options={DEFAULT_OPTIONS} text="testValue" />); expect(container).toMatchSnapshot(); }); it('Renders correctly when open', () => { // Mock createPortal so that the options list ends up inside the wrapper for snapshotting. mockCreatePortal(); const ref = React.createRef<IComboBox>(); const { container, getByRole } = render( <ComboBox options={RENDER_OPTIONS} defaultSelectedKey="2" componentRef={ref} />, ); userEvent.click(getByRole('combobox')); expect(container).toMatchSnapshot(); }); it('Renders correctly when opened in multi-select mode', () => { mockCreatePortal(); const ref = React.createRef<IComboBox>(); const { container, getByRole } = render( <ComboBox multiSelect options={RENDER_OPTIONS} defaultSelectedKey="2" componentRef={ref} />, ); userEvent.click(getByRole('combobox')); expect(container).toMatchSnapshot(); }); it('renders with a Keytip correctly', () => { const keytipProps = { content: 'A', keySequences: ['a'], }; const TestComponent: React.FunctionComponent = () => { const keytipRef = useKeytipRef<HTMLDivElement>({ keytipProps }); return <ComboBox ariaDescribedBy="test-foo" options={DEFAULT_OPTIONS} ref={keytipRef} />; }; const { container } = render(<TestComponent />); expect(container).toMatchSnapshot(); }); it('Can flip between enabled and disabled.', () => { const { getByRole, rerender } = render(<ComboBox disabled={false} options={DEFAULT_OPTIONS} />); const combobox = getByRole('combobox'); expect(combobox.getAttribute('aria-disabled')).toEqual('false'); rerender(<ComboBox disabled={true} options={DEFAULT_OPTIONS} />); expect(combobox.getAttribute('aria-disabled')).toEqual('true'); }); it('Renders no selected item in default case', () => { const { getByRole } = render(<ComboBox options={DEFAULT_OPTIONS} />); expect(getByRole('combobox').getAttribute('value')).toEqual(''); }); it('Renders a selected item in uncontrolled case', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS} />); expect(getByRole('combobox').getAttribute('value')).toEqual('1'); }); it('Renders a selected item in controlled case', () => { const { getByRole } = render(<ComboBox selectedKey="1" options={DEFAULT_OPTIONS} />); expect(getByRole('combobox').getAttribute('value')).toEqual('1'); }); it('Renders a selected item with zero key', () => { const options: IComboBoxOption[] = [ { key: 0, text: 'zero' }, { key: 1, text: 'one' }, ]; const { getByRole } = render(<ComboBox selectedKey={0} options={options} />); expect(getByRole('combobox').getAttribute('value')).toEqual('zero'); }); it('changes to a selected key change the input', () => { const options: IComboBoxOption[] = [ { key: 0, text: 'zero' }, { key: 1, text: 'one' }, ]; const { getByRole, rerender } = render(<ComboBox selectedKey={0} options={options} />); expect(getByRole('combobox').getAttribute('value')).toEqual('zero'); rerender(<ComboBox selectedKey={1} options={options} />); expect(getByRole('combobox').getAttribute('value')).toEqual('one'); }); it('changes to a selected item on key change', () => { const options: IComboBoxOption[] = [ { key: 0, text: 'zero' }, { key: 1, text: 'one' }, ]; const { getByRole, rerender } = render(<ComboBox selectedKey={0} options={options} />); expect(getByRole('combobox').getAttribute('value')).toEqual('zero'); rerender(<ComboBox selectedKey={null} options={options} />); expect(getByRole('combobox').getAttribute('value')).toEqual(''); }); it('Applies correct attributes to the selected option', () => { const { getByRole, getAllByRole } = render(<ComboBox options={DEFAULT_OPTIONS} defaultSelectedKey="2" />); const combobox = getByRole('combobox'); // open combobox to select one option userEvent.click(combobox); userEvent.click(getAllByRole('option')[0], undefined, { skipPointerEventsCheck: true }); // reopen combobox to check selected option userEvent.click(combobox); expect(getAllByRole('option')[0].getAttribute('aria-selected')).toEqual('true'); }); it('Renders a placeholder', () => { const placeholder = 'Select an option'; const { getByRole } = render(<ComboBox options={DEFAULT_OPTIONS} placeholder={placeholder} />); const combobox = getByRole('combobox'); expect(combobox.getAttribute('placeholder')).toEqual(placeholder); expect(combobox.getAttribute('value')).toEqual(''); }); it('Does not automatically add new options when allowFreeform is on in controlled case', () => { const { getByRole, getAllByRole } = render( <ComboBox options={DEFAULT_OPTIONS} allowFreeform onChange={returnUndefined} />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, 'f{enter}'); const caretdownButton = getByRole('presentation', { hidden: true }); userEvent.click(caretdownButton); expect(getAllByRole('option')).toHaveLength(DEFAULT_OPTIONS.length); }); it('Automatically adds new options when allowFreeform is on in uncontrolled case', () => { const { getByRole, getAllByRole } = render(<ComboBox options={DEFAULT_OPTIONS} allowFreeform />); const combobox = getByRole('combobox'); userEvent.type(combobox, 'f{enter}'); const caretdownButton = getByRole('presentation', { hidden: true }); userEvent.click(caretdownButton); const options = getAllByRole('option'); expect(options[options.length - 1].textContent).toEqual('f'); }); it('Renders a default value with options', () => { const { getByRole } = render(<ComboBox options={DEFAULT_OPTIONS} text="1" />); expect(getByRole('combobox').getAttribute('value')).toEqual('1'); }); it('Renders a default value with no options', () => { const { getByRole } = render(<ComboBox options={[]} text="1" />); expect(getByRole('combobox').getAttribute('value')).toEqual('1'); }); it('Can change items in uncontrolled case', () => { const { getByRole, getAllByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS} />); // open the menu and click the second item const combobox = getByRole('combobox'); userEvent.click(combobox); const selectedOption = getAllByRole('option')[1]; userEvent.click(selectedOption, undefined, { skipPointerEventsCheck: true }); // check item is selected expect(combobox.getAttribute('value')).toEqual('2'); }); it('Does not automatically change items in controlled case', () => { const { getByRole, getAllByRole } = render(<ComboBox selectedKey="1" options={DEFAULT_OPTIONS} />); // open the menu and click the second item const combobox = getByRole('combobox'); userEvent.click(combobox); const selectedOption = getAllByRole('option')[1]; userEvent.click(selectedOption, undefined, { skipPointerEventsCheck: true }); // check item is not selected since combobox is controlled expect(combobox.getAttribute('value')).toEqual('1'); }); it('Multiselect does not mutate props', () => { const { getByRole, getAllByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS} multiSelect />, ); // open combobox const combobox = getByRole('combobox'); userEvent.click(combobox); // select second option const secondOption = getAllByRole('option')[1]; expect(secondOption.getAttribute('aria-selected')).toEqual('false'); // ensure it's not already selected userEvent.click(secondOption, undefined, { skipPointerEventsCheck: true }); // checkbox selected expect(secondOption.getAttribute('aria-selected')).toEqual('true'); // option object not mutated expect(!!DEFAULT_OPTIONS[1].selected).toBeFalsy(); }); it('Can insert text in uncontrolled case with autoComplete and allowFreeform on', () => { const { getByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="on" allowFreeform />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, 'f'); expect(combobox.getAttribute('value')).toEqual('Foo'); }); it('Can insert text in uncontrolled case with autoComplete on and allowFreeform off', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="on" />); const combobox = getByRole('combobox'); userEvent.type(combobox, 'f'); expect(combobox.getAttribute('value')).toEqual('Foo'); }); it('Can insert non latin text in uncontrolled case with autoComplete on and allowFreeform off', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="0" options={RUSSIAN_OPTIONS} autoComplete="on" />); const combobox = getByRole('combobox'); userEvent.type(combobox, 'п'); expect(combobox.getAttribute('value')).toEqual('папа'); }); it('Can insert text in uncontrolled case with autoComplete off and allowFreeform on', () => { const { getByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="off" allowFreeform />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, 'f'); expect(combobox.getAttribute('value')).toEqual('f'); }); it('Can insert text in uncontrolled case with autoComplete and allowFreeform off', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="off" />); const combobox = getByRole('combobox'); userEvent.type(combobox, 'f'); expect(combobox.getAttribute('value')).toEqual('One'); }); it('Can insert an empty string in uncontrolled case with autoComplete and allowFreeform on', () => { const { getByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="on" allowFreeform />, ); const combobox = getByRole('combobox'); userEvent.clear(combobox); userEvent.type(combobox, '{enter}'); expect(combobox.getAttribute('value')).toEqual(''); }); it('Cannot insert an empty string in uncontrolled case with autoComplete on and allowFreeform off', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="on" />); const combobox = getByRole('combobox'); userEvent.clear(combobox); userEvent.type(combobox, '{enter}'); expect(combobox.getAttribute('value')).toEqual('One'); }); it('Can insert an empty string in uncontrolled case with autoComplete off and allowFreeform on', () => { const { getByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="off" allowFreeform />, ); const combobox = getByRole('combobox'); userEvent.clear(combobox); userEvent.type(combobox, '{enter}'); expect(combobox.getAttribute('value')).toEqual(''); }); it('Cannot insert an empty string in uncontrolled case with autoComplete and allowFreeform off', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="off" />); const combobox = getByRole('combobox'); userEvent.clear(combobox); userEvent.type(combobox, '{enter}'); expect(combobox.getAttribute('value')).toEqual('One'); }); it( 'Can insert an empty string after removing a pending value in uncontrolled case ' + 'with autoComplete and allowFreeform on', () => { const { getByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="on" allowFreeform />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, 'f'); userEvent.clear(combobox); userEvent.type(combobox, '{enter}'); expect(combobox.getAttribute('value')).toEqual(''); }, ); it( 'Cannot insert an empty string after removing a pending value in uncontrolled case ' + 'with autoComplete on and allowFreeform off', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="on" />); const combobox = getByRole('combobox'); userEvent.type(combobox, 'f'); userEvent.clear(combobox); userEvent.type(combobox, '{enter}'); expect(combobox.getAttribute('value')).toEqual('Foo'); }, ); it( 'Can insert an empty string after removing a pending value in uncontrolled case ' + 'with autoComplete off and allowFreeform on', () => { const { getByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="off" allowFreeform />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, 'f'); userEvent.clear(combobox); userEvent.type(combobox, '{enter}'); expect(combobox.getAttribute('value')).toEqual(''); }, ); it( 'Cannot insert an empty string after removing a pending value in uncontrolled case ' + 'with autoComplete and allowFreeform off', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} autoComplete="off" />); const combobox = getByRole('combobox'); userEvent.type(combobox, 'f'); userEvent.clear(combobox); userEvent.type(combobox, '{enter}'); expect(combobox.getAttribute('value')).toEqual('One'); }, ); it('Can change selected option with keyboard', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} />); const combobox = getByRole('combobox'); userEvent.type(combobox, '{arrowdown}'); expect(combobox.getAttribute('value')).toEqual('Foo'); }); it('Can change selected option with keyboard, looping from top to bottom', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} />); const combobox = getByRole('combobox'); userEvent.type(combobox, '{arrowup}'); expect(combobox.getAttribute('value')).toEqual('Bar'); }); it('Can change selected option with keyboard, looping from bottom to top', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="3" options={DEFAULT_OPTIONS2} />); const combobox = getByRole('combobox'); userEvent.type(combobox, '{arrowdown}'); expect(combobox.getAttribute('value')).toEqual('One'); }); it('Can change selected option with keyboard, looping from top to bottom', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS3} />); const combobox = getByRole('combobox'); userEvent.type(combobox, '{arrowup}'); expect(combobox.getAttribute('value')).toEqual('Bar'); }); it('Changing selected option with keyboard triggers onChange with the correct value', () => { const onChange = jest.fn< void, [React.FormEvent<IComboBox>, IComboBoxOption | undefined, number | undefined, string | undefined] >(); const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS3} onChange={onChange} />); const combobox = getByRole('combobox'); expect(onChange).not.toHaveBeenCalled(); userEvent.tab(); userEvent.keyboard('{arrowdown}'); userEvent.tab(); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange.mock.calls[0][1]).toEqual(DEFAULT_OPTIONS3[2]); expect(onChange.mock.calls[0][2]).toEqual(2); expect(onChange.mock.calls[0][3]).toEqual(DEFAULT_OPTIONS3[2].text); userEvent.type(combobox, '{arrowup}'); expect(combobox.getAttribute('value')).toEqual('One'); }); it('Cannot insert text while disabled', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} disabled />); const combobox = getByRole('combobox'); userEvent.type(combobox, 'a'); expect(combobox.getAttribute('value')).toEqual('One'); }); it('Cannot change selected option with keyboard while disabled', () => { const { getByRole } = render(<ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} disabled />); const combobox = getByRole('combobox'); userEvent.type(combobox, '{arrowdown}'); expect(combobox.getAttribute('value')).toEqual('One'); }); it('Cannot expand the menu when clicking on the input while disabled', () => { const { getByRole, queryAllByRole } = render(<ComboBox options={DEFAULT_OPTIONS2} disabled />); const combobox = getByRole('combobox'); userEvent.click(combobox); expect(queryAllByRole('option')).toHaveLength(0); }); it('Cannot expand the menu when clicking on the button while disabled', () => { const { getByRole, queryAllByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} disabled />, ); const caretdownButton = getByRole('presentation', { hidden: true }); userEvent.click(caretdownButton); expect(queryAllByRole('option')).toHaveLength(0); }); it('Cannot expand the menu when focused with a button while combobox is disabled', () => { const comboBoxRef = React.createRef<any>(); const { queryAllByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} componentRef={comboBoxRef} disabled />, ); comboBoxRef.current?.focus(true); expect(queryAllByRole('option')).toHaveLength(0); }); it('Calls onMenuOpen when clicking on the button', () => { const onMenuOpenMock = jest.fn(); const { getByRole, queryAllByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} onMenuOpen={onMenuOpenMock} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); expect(queryAllByRole('options')).toBeTruthy; }); it('Opens on focus when openOnKeyboardFocus is true', () => { const onMenuOpenMock = jest.fn(); const { queryAllByRole } = render( <ComboBox defaultSelectedKey="1" openOnKeyboardFocus options={DEFAULT_OPTIONS2} onMenuOpen={onMenuOpenMock} />, ); userEvent.tab(); expect(queryAllByRole('options')).toBeTruthy; }); it('Calls onMenuOpen when touch start on the input', () => { const onMenuOpenMock = jest.fn(); const { getByRole, queryAllByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS2} onMenuOpen={onMenuOpenMock} allowFreeform />, ); // in a normal scenario, when we do a touchstart we would also cause a click event to fire. // This doesn't happen in the simulator so we're manually adding this in. const combobox = getByRole('combobox'); fireEvent.touchStart(combobox); userEvent.click(combobox); expect(queryAllByRole('options')).toBeTruthy; }); it('onPendingValueChanged triggers for all indexes', () => { const indexSeen: number[] = []; const pendingValueChangedHandler = (option?: IComboBoxOption, index?: number, value?: string) => { if (index !== undefined) { indexSeen.push(index); } }; const { getByRole } = render( <ComboBox options={DEFAULT_OPTIONS} defaultSelectedKey="1" allowFreeform onPendingValueChanged={pendingValueChangedHandler} />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, 'f{arrowdown}{arrowup}'); expect(indexSeen).toContain(0); expect(indexSeen).toContain(1); }); it('onPendingValueChanged is called with an empty string when the input is cleared', () => { let changedValue: string | undefined = undefined; const pendingValueChangedHandler = (option?: IComboBoxOption, index?: number, value?: string) => { changedValue = value; }; const { getByRole } = render( <ComboBox options={DEFAULT_OPTIONS} allowFreeform onPendingValueChanged={pendingValueChangedHandler} />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, 'a'); userEvent.clear(combobox); expect(changedValue).toEqual(''); }); it('onInputValueChange is called whenever the input changes', () => { let changedValue: string | undefined = undefined; const onInputValueChangeHandler = (value: string) => { changedValue = value; }; const { getByRole } = render( <ComboBox options={DEFAULT_OPTIONS} allowFreeform onInputValueChange={onInputValueChangeHandler} />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, 'a'); expect(changedValue).toEqual('a'); userEvent.clear(combobox); expect(changedValue).toEqual(''); }); it('suggestedDisplayValue is set to undefined when the selected input is cleared', () => { const { getByRole, rerender } = render(<ComboBox selectedKey="1" options={DEFAULT_OPTIONS} />); const combobox = getByRole('combobox'); expect(combobox.getAttribute('value')).toEqual('1'); rerender(<ComboBox selectedKey={null} options={DEFAULT_OPTIONS} />); expect(combobox.getAttribute('value')).toEqual(''); }); it('Can type a complete option with autocomplete and allowFreeform on and submit it', () => { const onChange = jest.fn< void, [React.FormEvent<IComboBox>, IComboBoxOption | undefined, number | undefined, string | undefined] >(); const initialOption = { key: '1', text: 'Text' }; const { getByRole } = render( <ComboBox options={[initialOption]} autoComplete="on" allowFreeform onChange={onChange} />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, 'text{enter}'); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange.mock.calls[0][1]).toEqual(initialOption); expect(onChange.mock.calls[0][2]).toEqual(0); expect(onChange.mock.calls[0][3]).toEqual(initialOption.text); expect(combobox.getAttribute('value')).toEqual('Text'); }); it('merges callout classNames', () => { const { baseElement, getByRole } = render( <ComboBox defaultSelectedKey="1" options={DEFAULT_OPTIONS} calloutProps={{ className: 'foo' }} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); const callout = baseElement.querySelector('.ms-Callout'); expect(callout).toBeTruthy(); expect(callout!.classList.contains('ms-ComboBox-callout')).toBeTruthy(); expect(callout!.classList.contains('foo')).toBeTruthy(); }); it('Can clear text in controlled case with autoComplete off and allowFreeform on', () => { let updatedText: string | undefined; const { getByRole } = render( <ComboBox options={DEFAULT_OPTIONS} autoComplete="off" allowFreeform text="hikari" onChange={(event: React.FormEvent<IComboBox>, option?: IComboBoxOption, index?: number, value?: string) => { updatedText = value; }} />, ); const combobox = getByRole('combobox'); userEvent.clear(combobox); userEvent.type(combobox, '{enter}'); expect(updatedText).toEqual(''); }); it('Can clear text in controlled case with autoComplete off and allowFreeform on', () => { let updatedText: string | undefined; const { getByRole } = render( <ComboBox options={DEFAULT_OPTIONS} autoComplete="off" allowFreeform onChange={(event: React.FormEvent<IComboBox>, option?: IComboBoxOption, index?: number, value?: string) => { updatedText = value; }} />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, 'ab{backspace}a{backspace}'); userEvent.clear(combobox); expect(combobox.getAttribute('value')).toEqual(''); userEvent.type(combobox, '{enter}'); expect(updatedText).toEqual(''); }); it('in multiSelect mode, selectedOptions are correct after performing multiple selections using mouse click', () => { const comboBoxRef = React.createRef<IComboBox>(); const { getByRole, getAllByRole } = render( <ComboBox multiSelect options={DEFAULT_OPTIONS} componentRef={comboBoxRef} />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, '{enter}'); const options = getAllByRole('option'); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); userEvent.click(options[1], undefined, { skipPointerEventsCheck: true }); userEvent.click(options[2], undefined, { skipPointerEventsCheck: true }); expect(comboBoxRef.current!.selectedOptions.map(o => o.key)).toEqual(['1', '2', '3']); }); it('in multiSelect mode, defaultSelectedKey produces correct display input', () => { const comboBoxRef = React.createRef<any>(); const keys = [DEFAULT_OPTIONS[0].key as string, DEFAULT_OPTIONS[2].key as string]; const { getByRole, getAllByRole } = render( <ComboBox multiSelect options={DEFAULT_OPTIONS} componentRef={comboBoxRef} defaultSelectedKey={keys} />, ); const combobox = getByRole('combobox'); expect(combobox.getAttribute('value')).toEqual(keys.join(', ')); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[2], undefined, { skipPointerEventsCheck: true }); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); expect(combobox.getAttribute('value')).toEqual(''); }); it('in multiSelect mode, input has correct value after selecting options', () => { const { container, getByRole, getAllByRole } = render(<ComboBox multiSelect options={DEFAULT_OPTIONS} />); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); userEvent.click(options[2], undefined, { skipPointerEventsCheck: true }); userEvent.click(combobox); userEvent.click(container); const keys = [DEFAULT_OPTIONS[0].key, DEFAULT_OPTIONS[2].key]; expect(combobox.getAttribute('value')).toEqual(keys.join(', ')); }); it('in multiSelect mode, input has correct value when multiSelectDelimiter specified', () => { const delimiter = '; '; const { container, getByRole, getAllByRole } = render( <ComboBox multiSelect multiSelectDelimiter={delimiter} options={DEFAULT_OPTIONS} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); userEvent.click(options[2], undefined, { skipPointerEventsCheck: true }); userEvent.click(combobox); userEvent.click(container); const keys = [DEFAULT_OPTIONS[0].key, DEFAULT_OPTIONS[2].key]; expect(combobox.getAttribute('value')).toEqual(keys.join(delimiter)); }); it('in multiSelect mode, optional onItemClick callback invoked per option select', () => { const onItemClickMock = jest.fn(); const { getByRole, getAllByRole } = render( <ComboBox multiSelect options={DEFAULT_OPTIONS} onItemClick={onItemClickMock} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); userEvent.click(options[1], undefined, { skipPointerEventsCheck: true }); userEvent.click(options[2], undefined, { skipPointerEventsCheck: true }); expect(onItemClickMock).toHaveBeenCalledTimes(3); }); it('in multiSelect mode, selectAll selects all options', () => { const comboBoxRef = React.createRef<IComboBox>(); const SELECTALL_OPTIONS: IComboBoxOption[] = [ { key: 'selectAll', text: 'Select All', itemType: SelectableOptionMenuItemType.SelectAll }, ...DEFAULT_OPTIONS, ]; const { container, getByRole, getAllByRole } = render( <ComboBox multiSelect options={SELECTALL_OPTIONS} componentRef={comboBoxRef} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); userEvent.type(combobox, '{esc}'); userEvent.click(container); expect(comboBoxRef.current!.selectedOptions.map(o => o.key)).toEqual(['selectAll', '1', '2', '3']); expect(combobox.getAttribute('value')).toEqual('1, 2, 3'); }); it('in multiSelect mode, selectAll does not select disabled options', () => { const comboBoxRef = React.createRef<IComboBox>(); const SELECTALL_OPTIONS: IComboBoxOption[] = [ { key: 'selectAll', text: 'Select All', itemType: SelectableOptionMenuItemType.SelectAll }, ...DEFAULT_OPTIONS, ]; SELECTALL_OPTIONS[1] = { ...SELECTALL_OPTIONS[1], disabled: true }; const { getByRole, getAllByRole } = render( <ComboBox multiSelect options={SELECTALL_OPTIONS} componentRef={comboBoxRef} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); expect(comboBoxRef.current!.selectedOptions.map(o => o.key)).toEqual(['selectAll', '2', '3']); }); it('in multiSelect mode, selectAll does not select heeaders or dividers', () => { const comboBoxRef = React.createRef<IComboBox>(); const SELECTALL_OPTIONS: IComboBoxOption[] = [ { key: 'selectAll', text: 'Select All', itemType: SelectableOptionMenuItemType.SelectAll }, ...RENDER_OPTIONS, ]; const { getByRole, getAllByRole } = render( <ComboBox multiSelect options={SELECTALL_OPTIONS} componentRef={comboBoxRef} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); expect(comboBoxRef.current!.selectedOptions.map(o => o.key)).toEqual(['selectAll', '1', '2']); }); it('in multiSelect mode, selectAll checked calculation ignores headers, dividers, and disabled options', () => { const comboBoxRef = React.createRef<IComboBox>(); const SELECTALL_OPTIONS: IComboBoxOption[] = [ { key: 'selectAll', text: 'Select All', itemType: SelectableOptionMenuItemType.SelectAll }, ...RENDER_OPTIONS, ]; SELECTALL_OPTIONS[2] = { ...SELECTALL_OPTIONS[2], disabled: true }; const { getByRole, getAllByRole } = render( <ComboBox multiSelect options={SELECTALL_OPTIONS} componentRef={comboBoxRef} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[2], undefined, { skipPointerEventsCheck: true }); expect(comboBoxRef.current!.selectedOptions.map(o => o.key)).toEqual(['2', 'selectAll']); }); it('in multiSelect mode, modifying option selection updates selectAll', () => { const comboBoxRef = React.createRef<IComboBox>(); const SELECTALL_OPTIONS: IComboBoxOption[] = [ { key: 'selectAll', text: 'Select All', itemType: SelectableOptionMenuItemType.SelectAll }, ...DEFAULT_OPTIONS, ]; const { getByRole, getAllByRole } = render( <ComboBox multiSelect options={SELECTALL_OPTIONS} componentRef={comboBoxRef} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); // un-check one option userEvent.click(options[1], undefined, { skipPointerEventsCheck: true }); expect(comboBoxRef.current!.selectedOptions.map(o => o.key)).toEqual(['2', '3']); // re-check option userEvent.click(options[1], undefined, { skipPointerEventsCheck: true }); expect(comboBoxRef.current!.selectedOptions.map(o => o.key)).toEqual(['2', '3', '1', 'selectAll']); }); it('in multiSelect mode with mixed selected, selectAll is indeterminate', () => { const comboBoxRef = React.createRef<IComboBox>(); const SELECTALL_OPTIONS: IComboBoxOption[] = [ { key: 'selectAll', text: 'Select All', itemType: SelectableOptionMenuItemType.SelectAll }, ...DEFAULT_OPTIONS, ]; const { getByRole, getAllByRole } = render( <ComboBox multiSelect options={SELECTALL_OPTIONS} componentRef={comboBoxRef} defaultSelectedKey={['2']} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); expect(options[0].getAttribute('aria-checked')).toEqual('mixed'); }); it('in multiSelect mode, checking options sets selectAll to indeterminate', () => { const comboBoxRef = React.createRef<IComboBox>(); const SELECTALL_OPTIONS: IComboBoxOption[] = [ { key: 'selectAll', text: 'Select All', itemType: SelectableOptionMenuItemType.SelectAll }, ...DEFAULT_OPTIONS, ]; const { getByRole, getAllByRole } = render( <ComboBox multiSelect options={SELECTALL_OPTIONS} componentRef={comboBoxRef} defaultSelectedKey={['2']} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[1], undefined, { skipPointerEventsCheck: true }); expect(options[0].getAttribute('aria-checked')).toEqual('mixed'); userEvent.click(options[2], undefined, { skipPointerEventsCheck: true }); userEvent.click(options[3], undefined, { skipPointerEventsCheck: true }); expect(options[0].getAttribute('aria-checked')).toEqual('mixed'); }); it('in multiSelect mode, checking an indeterminate selectAll checks all options', () => { const comboBoxRef = React.createRef<IComboBox>(); const SELECTALL_OPTIONS: IComboBoxOption[] = [ { key: 'selectAll', text: 'Select All', itemType: SelectableOptionMenuItemType.SelectAll }, ...DEFAULT_OPTIONS, ]; const { getByRole, getAllByRole } = render( <ComboBox multiSelect options={SELECTALL_OPTIONS} componentRef={comboBoxRef} defaultSelectedKey={['2']} />, ); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); expect(comboBoxRef.current!.selectedOptions.map(o => o.key)).toEqual(['selectAll', '1', '2', '3']); }); it('in single-select mode, selectAll behaves as a normal option', () => { const comboBoxRef = React.createRef<IComboBox>(); const SELECTALL_OPTIONS: IComboBoxOption[] = [ { key: 'selectAll', text: 'Select All', itemType: SelectableOptionMenuItemType.SelectAll }, ...RENDER_OPTIONS, ]; const { getByRole, getAllByRole } = render(<ComboBox options={SELECTALL_OPTIONS} componentRef={comboBoxRef} />); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); expect(combobox.getAttribute('value')).toEqual('Select All'); }); it('invokes optional onItemClick callback on option select', () => { const onItemClickMock = jest.fn(); const { getByRole, getAllByRole } = render(<ComboBox options={DEFAULT_OPTIONS} onItemClick={onItemClickMock} />); const combobox = getByRole('combobox'); userEvent.click(combobox); const options = getAllByRole('option'); userEvent.click(options[0], undefined, { skipPointerEventsCheck: true }); expect(onItemClickMock).toHaveBeenCalledTimes(1); }); it('defaults to ariaDescribedBy prop when passing id to input', () => { const ariaId = 'customAriaDescriptionId'; const { getByRole } = render( <ComboBox options={DEFAULT_OPTIONS} ariaDescribedBy={ariaId} aria-describedby="usePropInstead" />, ); const combobox = getByRole('combobox'); expect(combobox.getAttribute('aria-describedby')).toBe(ariaId); }); it('allows adding a custom aria-describedby id to the input via an attribute', () => { const ariaId = 'customAriaDescriptionId'; const { getByRole } = render( <ComboBox options={DEFAULT_OPTIONS} ariaDescribedBy={ariaId} aria-describedby="usePropInstead" />, ); const combobox = getByRole('combobox'); expect(combobox.getAttribute('aria-describedby')).toBe(ariaId); }); it('correctly handles (aria-labelledby) when label is also provided', () => { const customId = 'customAriaLabelledById'; const { container, getByRole } = render( <ComboBox options={DEFAULT_OPTIONS} label="hello world" aria-labelledby={customId} />, ); const combobox = getByRole('combobox'); const labelElement = container.querySelector('.ms-Label'); const labelId = labelElement!.getAttribute('id'); expect(combobox.getAttribute('aria-labelledby')).toBe(customId + ' ' + labelId); }); it('sets ariaLabel on both the input and the dropdown list', () => { const { getByRole } = render(<ComboBox options={RENDER_OPTIONS} ariaLabel="customAriaLabel" persistMenu />); const combobox = getByRole('combobox'); expect(combobox.getAttribute('aria-label')).toBe('customAriaLabel'); expect(combobox.getAttribute('aria-labelledby')).toBeNull(); userEvent.click(combobox); const listElement = getByRole('listbox'); expect(listElement.getAttribute('aria-label')).toBe('customAriaLabel'); expect(listElement.getAttribute('aria-labelledby')).toBeNull(); }); it('adds aria-required to the DOM when the required prop is set to true', () => { const { getByRole } = render(<ComboBox options={DEFAULT_OPTIONS} required />); const combobox = getByRole('combobox'); expect(combobox.getAttribute('aria-required')).toEqual('true'); }); it('does not add aria-required to the DOM when the required prop is not set', () => { const { getByRole } = render(<ComboBox options={DEFAULT_OPTIONS} />); const combobox = getByRole('combobox'); expect(combobox.getAttribute('aria-required')).toBeNull(); }); it('with persistMenu, callout should exist before and after opening menu', () => { const onMenuOpenMock = jest.fn(); const onMenuDismissedMock = jest.fn(); const { baseElement, getByRole } = render( <ComboBox defaultSelectedKey="1" persistMenu options={DEFAULT_OPTIONS2} onMenuOpen={onMenuOpenMock} onMenuDismissed={onMenuDismissedMock} />, ); const combobox = getByRole('combobox'); // Find menu const calloutBeforeOpen = baseElement.querySelector('.ms-Callout'); expect(calloutBeforeOpen).toBeTruthy(); expect(calloutBeforeOpen!.classList.contains('ms-ComboBox-callout')).toBeTruthy(); userEvent.click(combobox); expect(onMenuOpenMock.mock.calls.length).toBe(1); userEvent.click(combobox); expect(onMenuDismissedMock.mock.calls.length).toBe(1); // Ensure menu is still there const calloutAfterClose = baseElement.querySelector('.ms-Callout'); expect(calloutAfterClose).toBeTruthy(); expect(calloutAfterClose!.classList.contains('ms-ComboBox-callout')).toBeTruthy(); }); // Adds currentPendingValue to options and makes it selected onBlur // if allowFreeFrom is true for multiselect with default selected values it('adds currentPendingValue to options and selects if multiSelected with default values', () => { const comboBoxOption: IComboBoxOption = { key: 'ManuallyEnteredValue', text: 'ManuallyEnteredValue', selected: true, }; const selectedKeys = ['1', '2', '3']; const { container, getByRole } = render( <ComboBox multiSelect options={DEFAULT_OPTIONS} defaultSelectedKey={selectedKeys} allowFreeform />, ); const combobox = getByRole('combobox'); userEvent.type(combobox, comboBoxOption.text); //click on container to trigger onBlur userEvent.click(container); expect(combobox.getAttribute('value')).toEqual(selectedKeys.concat(comboBoxOption.text).join(', ')); }); // Adds currentPendingValue to options and makes it selected onBlur // if allowFreeForm is true for multiSelect with no default value selected it('adds currentPendingValue to options and selects for multiSelect with no default value', () => { const comboBoxOption: IComboBoxOption = { key: 'ManuallyEnteredValue', text: 'ManuallyEnteredValue', selected: true, }; const { container, getByRole, getAllByRole } = render( <ComboBox multiSelect options={DEFAULT_OPTIONS} allowFreeform />, ); const combobox = getByRole('combobox'); const caretdownButton = getByRole('presentation', { hidden: true }); userEvent.type(combobox, comboBoxOption.text); //click on container to trigger onBlur userEvent.click(container); userEvent.type(combobox, comboBoxOption.text); userEvent.click(caretdownButton); const options = getAllByRole('option'); // This should toggle the checkbox off. With multi-select the currentPendingValue is not reset on input change // because it would break keyboard accessibility userEvent.click(options[3], undefined, { skipPointerEventsCheck: true }); // with 'ManuallyEnteredValue' still in the input, on blur it should toggle the check back to on userEvent.click(container); expect(combobox.getAttribute('value')).toEqual(comboBoxOption.text); }); // adds currentPendingValue to options and makes it selected onBlur // if allowFreeForm is true for singleSelect it('adds currentPendingValue to options and selects for singleSelect', () => { const comboBoxOption: IComboBoxOption = { key: 'ManuallyEnteredValue', text: 'ManuallyEnteredValue', }; const { container, getByRole, getAllByRole } = render(<ComboBox options={DEFAULT_OPTIONS} allowFreeform />); const combobox = getByRole('combobox'); const caretdownButton = getByRole('presentation', { hidden: true }); userEvent.type(combobox, comboBoxOption.text); userEvent.click(container); expect(combobox.getAttribute('value')).toEqual(comboBoxOption.text); userEvent.click(caretdownButton); const options = getAllByRole('option'); userEvent.click(options[2], undefined, { skipPointerEventsCheck: true }); //click on container to trigger onBlur userEvent.click(container); expect(combobox.getAttribute('value')).toEqual(DEFAULT_OPTIONS[2].text); }); });
the_stack
* @module DisplayStyles */ import { assert, BeEvent } from "@itwin/core-bentley"; import { SpatialClassifierProps, SpatialClassifiers } from "./SpatialClassification"; import { PlanarClipMaskMode, PlanarClipMaskProps, PlanarClipMaskSettings } from "./PlanarClipMask"; import { FeatureAppearance, FeatureAppearanceProps } from "./FeatureSymbology"; /** JSON representation of the blob properties for an OrbitGt property cloud. * @alpha */ export interface OrbitGtBlobProps { rdsUrl?: string; containerName: string; blobFileName: string; sasToken: string; accountName: string; } /** Identify the Reality Data service provider * @alpha */ export enum RealityDataProvider { /** * This is the legacy mode where the access to the 3d tiles is harcoded in ContextRealityModelProps.tilesetUrl property. * It was use to support RealityMesh3DTiles, Terrain3DTiles, Cesium3DTiles * You should use other mode when possible * @see [[RealityDataSource.createRealityDataSourceKeyFromUrl]] that will try to detect provider from an URL */ TilesetUrl = "TilesetUrl", /** * This is the legacy mode where the access to the 3d tiles is harcoded in ContextRealityModelProps.OrbitGtBlob property. * It was use to support OrbitPointCloud (OPC) from other server than ContextShare * You should use other mode when possible * @see [[RealityDataSource.createRealityDataSourceKeyFromUrl]] that will try to detect provider from an URL */ OrbitGtBlob = "OrbitGtBlob", /** * Will provide access url from realityDataId and iTwinId on contextShare for 3dTile storage format or OPC storage format * This provider support all type of 3dTile storage fomat and OrbitPointCloud: RealityMesh3DTiles, Terrain3DTiles, Cesium3DTiles, OPC * @see [[RealityDataFormat]]. */ ContextShare = "ContextShare", /** * Will provide Open Street Map Building (OSM) from Cesium Ion (in 3dTile format) */ CesiumIonAsset = "CesiumIonAsset", } /** Identify the Reality Data storage format * @alpha */ export enum RealityDataFormat { /** * 3dTile supported formats; RealityMesh3DTiles, Terrain3DTiles, Cesium3DTiles * */ ThreeDTile = "ThreeDTile", /** * Orbit Point Cloud (OPC) storage format (RealityDataType.OPC) */ OPC = "OPC", } /** * Key used by RealityDataConnection to identify RealityDataSource and reality data format * This key identify one and only one reality data on the provider * @alpha */ export interface RealityDataSourceKey { /** * The provider that supplies the access to reality data source for displaying the reality model * @see [[RealityDataProvider]] for default supported value; */ provider: string; /** * The format used by the provider to store the reality data * @see [[RealityDataFormat]] for default supported value; */ format: string; /** The reality data id that identify a reality data for the provider */ id: string; /** The context id that was used when reality data was attached - if none provided, current session iTwinId will be used */ iTwinId?: string; } /** JSON representation of the reality data reference attachment properties. * @alpha */ export interface RealityDataSourceProps { /** The source key that identify a reality data for the provider. */ sourceKey: RealityDataSourceKey; } /** JSON representation of a [[ContextRealityModel]]. * @public */ export interface ContextRealityModelProps { /** * The reality data source key identify the reality data provider and storage format. * It takes precedence over tilesetUrl and orbitGtBlob when present and can be use to actually replace these properties. * @alpha */ rdSourceKey?: RealityDataSourceKey; /** The URL that supplies the 3d tiles for displaying the reality model. */ tilesetUrl: string; /** @see [[ContextRealityModel.orbitGtBlob]]. * @alpha */ orbitGtBlob?: OrbitGtBlobProps; /** @see [[ContextRealityModel.realityDataId]]. */ realityDataId?: string; /** An optional, user-friendly name for the reality model suitable for display in a user interface. */ name?: string; /** An optional, user-friendly description of the reality model suitable for display in a user interface. */ description?: string; /** @see [[ContextRealityModel.classifiers]]. */ classifiers?: SpatialClassifierProps[]; /** @see [[ContextRealityModel.planarClipMask]]. */ planarClipMask?: PlanarClipMaskProps; /** @see [[ContextRealityModel.appearanceOverrides]]. */ appearanceOverrides?: FeatureAppearanceProps; } /** @public */ export namespace ContextRealityModelProps { /** Produce a deep copy of `input`. */ export function clone(input: ContextRealityModelProps) { // Spread operator is shallow, and includes `undefined` properties and empty strings. // We want to make deep copies, omit undefined properties and empty strings, and require tilesetUrl to be defined. const output: ContextRealityModelProps = { tilesetUrl: input.tilesetUrl ?? "" }; if (input.rdSourceKey) output.rdSourceKey = { ...input.rdSourceKey }; if (input.name) output.name = input.name; if (input.realityDataId) output.realityDataId = input.realityDataId; if (input.description) output.description = input.description; if (input.orbitGtBlob) output.orbitGtBlob = { ...input.orbitGtBlob }; if (input.appearanceOverrides) { output.appearanceOverrides = { ...input.appearanceOverrides }; if (input.appearanceOverrides.rgb) output.appearanceOverrides.rgb = { ...input.appearanceOverrides.rgb }; } if (input.planarClipMask) output.planarClipMask = { ...input.planarClipMask }; if (input.classifiers) output.classifiers = input.classifiers.map((x) => { return { ...x, flags: { ...x.flags } }; }); return output; } } /** A reality model not associated with a [GeometricModel]($backend) but instead defined in a [DisplayStyle]($backend) or [DisplayStyleState]($frontend). * Such reality models are displayed to provide context to the view and can be freely attached and detached at display time. * @see [this interactive example](https://www.itwinjs.org/sample-showcase/?group=Viewer&sample=reality-data-sample) * @see [[DisplayStyleSettings.contextRealityModels]] to define context reality models for a display style. * @public */ export class ContextRealityModel { protected readonly _props: ContextRealityModelProps; /** * The reality data source key identify the reality data provider and storage format. * @alpha */ public readonly rdSourceKey?: RealityDataSourceKey; /** A name suitable for display in a user interface. By default, an empty string. */ public readonly name: string; /** The URL that supplies the 3d tiles for displaying the reality model. */ public readonly url: string; /** A description of the model suitable for display in a user interface. By default, an empty string. */ public readonly description: string; /** An optional identifier that, if present, can be used to elide a request to the reality data service. */ public readonly realityDataId?: string; /** A set of [[SpatialClassifier]]s, of which one at any given time can be used to classify the reality model. */ public readonly classifiers?: SpatialClassifiers; /** @alpha */ public readonly orbitGtBlob?: Readonly<OrbitGtBlobProps>; protected _appearanceOverrides?: FeatureAppearance; protected _planarClipMask?: PlanarClipMaskSettings; /** Event dispatched just before assignment to [[planarClipMaskSettings]]. */ public readonly onPlanarClipMaskChanged = new BeEvent<(newSettings: PlanarClipMaskSettings | undefined, model: ContextRealityModel) => void>(); /** Event dispatched just before assignment to [[appearanceOverrides]]. */ public readonly onAppearanceOverridesChanged = new BeEvent<(newOverrides: FeatureAppearance | undefined, model: ContextRealityModel) => void>(); /** Construct a new context reality model. * @param props JSON representation of the reality model, which will be kept in sync with changes made via the ContextRealityModel's methods. */ public constructor(props: ContextRealityModelProps) { this._props = props; this.rdSourceKey = props.rdSourceKey; this.name = props.name ?? ""; this.url = props.tilesetUrl ?? ""; this.orbitGtBlob = props.orbitGtBlob; this.realityDataId = props.realityDataId; this.description = props.description ?? ""; this._appearanceOverrides = props.appearanceOverrides ? FeatureAppearance.fromJSON(props.appearanceOverrides) : undefined; if (props.planarClipMask && props.planarClipMask.mode !== PlanarClipMaskMode.None) this._planarClipMask = PlanarClipMaskSettings.fromJSON(props.planarClipMask); if (props.classifiers) this.classifiers = new SpatialClassifiers(props); } /** Optionally describes how the geometry of the reality model can be masked by other models. */ public get planarClipMaskSettings(): PlanarClipMaskSettings | undefined { return this._planarClipMask; } public set planarClipMaskSettings(settings: PlanarClipMaskSettings | undefined) { this.onPlanarClipMaskChanged.raiseEvent(settings, this); if (!settings) delete this._props.planarClipMask; else this._props.planarClipMask = settings.toJSON(); this._planarClipMask = settings; } /** Overrides applied to the appearance of the reality model. Only the rgb, transparency, nonLocatable, and emphasized properties are applicable - the rest are ignored. */ public get appearanceOverrides(): FeatureAppearance | undefined { return this._appearanceOverrides; } public set appearanceOverrides(overrides: FeatureAppearance | undefined) { this.onAppearanceOverridesChanged.raiseEvent(overrides, this); if (!overrides) delete this._props.appearanceOverrides; else this._props.appearanceOverrides = overrides.toJSON(); this._appearanceOverrides = overrides; } /** Convert this model to its JSON representation. */ public toJSON(): ContextRealityModelProps { return ContextRealityModelProps.clone(this._props); } /** Returns true if [[name]] and [[url]] match the specified name and url. */ public matchesNameAndUrl(name: string, url: string): boolean { return this.name === name && this.url === url; } } /** An object that can store the JSON representation of a list of [[ContextRealityModel]]s. * @see [[ContextRealityModels]]. * @see [[DisplayStyleSettingsProps.contextRealityModels]]. * @public */ export interface ContextRealityModelsContainer { /** The list of reality models. */ contextRealityModels?: ContextRealityModelProps[]; } /** A list of [[ContextRealityModel]]s attached to a [[DisplayStyleSettings]]. The list may be presented to the user with the name and description of each model. * The list is automatically synchronized with the underlying JSON representation provided by the input [[ContextRealityModelsContainer]]. * @see [this interactive example](https://www.itwinjs.org/sample-showcase/?group=Viewer&sample=reality-data-sample) * @see [[DisplayStyleSettings.contextRealityModels]]. * @public */ export class ContextRealityModels { private readonly _container: ContextRealityModelsContainer; private readonly _createModel: (props: ContextRealityModelProps) => ContextRealityModel; private readonly _models: ContextRealityModel[] = []; /** Event dispatched just before [[ContextRealityModel.planarClipMaskSettings]] is modified for one of the reality models. */ public readonly onPlanarClipMaskChanged = new BeEvent<(model: ContextRealityModel, newSettings: PlanarClipMaskSettings | undefined) => void>(); /** Event dispatched just before [[ContextRealityModel.appearanceOverrides]] is modified for one of the reality models. */ public readonly onAppearanceOverridesChanged = new BeEvent<(model: ContextRealityModel, newOverrides: FeatureAppearance | undefined) => void>(); /** Event dispatched when a model is [[add]]ed, [[delete]]d, [[replace]]d, or [[update]]d. */ public readonly onChanged = new BeEvent<(previousModel: ContextRealityModel | undefined, newModel: ContextRealityModel | undefined) => void>(); /** Construct a new list of reality models from its JSON representation. THe list will be initialized from `container.classifiers` and that JSON representation * will be kept in sync with changes made to the list. The caller should not directly modify `container.classifiers` or its contents as that will cause the list * to become out of sync with the JSON representation. * @param container The object that holds the JSON representation of the list. * @param createContextRealityModel Optional function used to instantiate ContextRealityModels added to the list. */ public constructor(container: ContextRealityModelsContainer, createContextRealityModel?: (props: ContextRealityModelProps) => ContextRealityModel) { this._container = container; this._createModel = createContextRealityModel ?? ((props) => new ContextRealityModel(props)); const models = container.contextRealityModels; if (models) for (const model of models) this._models.push(this.createModel(model)); } /** The read-only list of reality models. */ public get models(): ReadonlyArray<ContextRealityModel> { return this._models; } /** Append a new reality model to the list. * @param The JSON representation of the reality model. * @returns the newly-added reality model. */ public add(props: ContextRealityModelProps): ContextRealityModel { if (!this._container.contextRealityModels) this._container.contextRealityModels = []; props = ContextRealityModelProps.clone(props); const model = this.createModel(props); this.onChanged.raiseEvent(undefined, model); this._models.push(model); this._container.contextRealityModels.push(props); return model; } /** Remove the specified reality model from the list. * @param model The reality model to remove. * @returns true if the model was removed, or false if the model was not present in the list. */ public delete(model: ContextRealityModel): boolean { const index = this._models.indexOf(model); if (-1 === index) return false; assert(undefined !== this._container.contextRealityModels); assert(index < this._container.contextRealityModels.length); this.dropEventListeners(model); this.onChanged.raiseEvent(model, undefined); this._models.splice(index, 1); if (this.models.length === 0) this._container.contextRealityModels = undefined; else this._container.contextRealityModels.splice(index, 1); return true; } /** Remove all reality models from the list. */ public clear(): void { for (const model of this.models) { this.dropEventListeners(model); this.onChanged.raiseEvent(model, undefined); } this._container.contextRealityModels = undefined; this._models.length = 0; } /** Replace a reality model in the list. * @param toReplace The reality model to be replaced. * @param replaceWith The JSON representation of the replacement reality model. * @returns the newly-created reality model that replaced `toReplace`. * @throws Error if `toReplace` is not present in the list * @note The replacement occupies the same index in the list as `toReplace` did. */ public replace(toReplace: ContextRealityModel, replaceWith: ContextRealityModelProps): ContextRealityModel { const index = this._models.indexOf(toReplace); if (-1 === index) throw new Error("ContextRealityModel not present in list."); assert(undefined !== this._container.contextRealityModels); assert(index < this._container.contextRealityModels.length); replaceWith = ContextRealityModelProps.clone(replaceWith); const model = this.createModel(replaceWith); this.onChanged.raiseEvent(toReplace, model); this.dropEventListeners(toReplace); this._models[index] = model; this._container.contextRealityModels[index] = replaceWith; return model; } /** Change selected properties of a reality model. * @param toUpdate The reality model whose properties are to be modified. * @param updateProps The properties to change. * @returns The updated reality model, identical to `toUpdate` except for properties explicitly supplied by `updateProps`. * @throws Error if `toUpdate` is not present in the list. */ public update(toUpdate: ContextRealityModel, updateProps: Partial<ContextRealityModelProps>): ContextRealityModel { const props = { ...toUpdate.toJSON(), ...updateProps, }; // Partial<> makes it possible to pass `undefined` for tilesetUrl...preserve previous URL in that case. if (undefined === props.tilesetUrl) props.tilesetUrl = toUpdate.url; return this.replace(toUpdate, props); } private createModel(props: ContextRealityModelProps): ContextRealityModel { const model = this._createModel(props); // eslint-disable-next-line @typescript-eslint/unbound-method model.onPlanarClipMaskChanged.addListener(this.handlePlanarClipMaskChanged, this); // eslint-disable-next-line @typescript-eslint/unbound-method model.onAppearanceOverridesChanged.addListener(this.handleAppearanceOverridesChanged, this); return model; } private dropEventListeners(model: ContextRealityModel): void { // eslint-disable-next-line @typescript-eslint/unbound-method model.onPlanarClipMaskChanged.removeListener(this.handlePlanarClipMaskChanged, this); // eslint-disable-next-line @typescript-eslint/unbound-method model.onAppearanceOverridesChanged.removeListener(this.handleAppearanceOverridesChanged, this); } private handlePlanarClipMaskChanged(mask: PlanarClipMaskSettings | undefined, model: ContextRealityModel): void { this.onPlanarClipMaskChanged.raiseEvent(model, mask); } private handleAppearanceOverridesChanged(app: FeatureAppearance | undefined, model: ContextRealityModel): void { this.onAppearanceOverridesChanged.raiseEvent(model, app); } }
the_stack
import Command from '../../lib/structures/Command'; import { TypicalGuildMessage, SettingsData } from '../../lib/types/typicalbot'; import { MODE, PERMISSION_LEVEL, LINK } from '../../lib/utils/constants'; const roleRegex = /(?:(?:<@&)?(\d{17,20})>?|(.+))/i; const msRegex = /^(\d+)$/i; const channelRegex = /(?:(?:<#)?(\d{17,20})>?|(.+))/i; export const possibleLanguages = [ { name: 'bg-BG', canonical: 'Bulgarian', complete: false, aliases: ['bg', 'bulgarian'] }, { name: 'de-DE', canonical: 'German', complete: false, aliases: ['de', 'german'] }, { name: 'en-US', canonical: 'English', complete: true, aliases: ['en', 'english'] }, { name: 'es-ES', canonical: 'Spanish', complete: false, aliases: ['es', 'spanish'] }, { name: 'fr-FR', canonical: 'French', complete: true, aliases: ['fr', 'french'] }, { name: 'pl-PL', canonical: 'Polish', complete: false, aliases: ['pl', 'polish'] }, { name: 'ru-RU', canonical: 'Russian', complete: false, aliases: ['ru', 'russian'] }, { name: 'sl-SL', canonical: 'Slovenian', complete: true, aliases: ['sl', 'slovenian'] }, { name: 'sv-SE', canonical: 'Swedish', complete: false, aliases: ['se', 'swedish'] }, { name: 'tr-TR', canonical: 'Turkish', complete: true, aliases: ['tr', 'turkish'] } ]; export default class extends Command { aliases = ['set', 'settings']; mode = MODE.STRICT; permission = PERMISSION_LEVEL.SERVER_ADMINISTRATOR; async execute(message: TypicalGuildMessage, parameters: string) { const [setting, value] = parameters.split(/(?<=^\S+)\s/); const settings = message.guild.settings; const settingsData = { dmcommands: { description: 'administration/conf:DMCOMMANDS', value: settings.dm.commands, type: 'boolean', path: 'dm.commands' }, embed: { description: 'administration/conf:EMBED', value: settings.embed, type: 'boolean', path: 'embed' }, adminrole: { description: 'administration/conf:ADMINROLE', value: settings.roles.administrator, type: 'roles', path: 'roles.administrator' }, modrole: { description: 'administration/conf:MODROLE', value: settings.roles.moderator, type: 'roles', path: 'roles.moderator' }, muterole: { description: 'administration/conf:MUTEROLE', value: settings.roles.mute, type: 'role', path: 'roles.mute' }, blacklistrole: { description: 'administration/conf:BLACKLISTROLE', value: settings.roles.blacklist, type: 'roles', path: 'roles.blacklist' }, subscriberrole: { description: 'administration/conf:SUBSCRIBERROLE', value: settings.subscriber, type: 'role', path: 'subscriber' }, autorole: { description: 'administration/conf:AUTOROLE', value: settings.auto.role.id, type: 'role', path: 'auto.role.id' }, 'autorole-bots': { description: 'administration/conf:AUTOROLE-BOTS', value: settings.auto.role.bots, type: 'role', path: 'auto.role.bots' }, 'autorole-delay': { description: 'administration/conf:AUTOROLE-DELAY', value: settings.auto.role.delay, type: 'ms', path: 'auto.role.delay' }, 'autorole-silent': { description: 'administration/conf:AUTOROLE-SILENT', value: settings.auto.role.silent, type: 'boolean', path: 'auto.role.silent' }, announcements: { description: 'administration/conf:ANNOUNCEMENTS', value: settings.announcements.id, type: 'channel', path: 'announcements.id' }, 'announcements-mention': { description: 'administration/conf:ANNOUNCEMENTS-MENTION', value: settings.announcements.mention, type: 'role', path: 'announcements.mention' }, logs: { description: 'administration/conf:LOGS', value: settings.logs.id, type: 'channel', path: 'logs.id' }, 'logs-join': { description: 'administration/conf:LOGS-JOIN', value: settings.logs.join, type: 'log', path: 'logs.join' }, 'logs-leave': { description: 'administration/conf:LOGS-LEAVE', value: settings.logs.leave, type: 'log', path: 'logs.leave' }, 'logs-ban': { description: 'administration/conf:LOGS-BAN', value: settings.logs.ban, type: 'log', path: 'logs.ban' }, 'logs-unban': { description: 'administration/conf:LOGS-UNBAN', value: settings.logs.unban, type: 'log', path: 'logs.unban' }, 'logs-nickname': { description: 'administration/conf:LOGS-NICKNAME', value: settings.logs.nickname, type: 'log', path: 'logs.nickname' }, 'logs-invite': { description: 'administration/conf:LOGS-INVITE', value: settings.logs.invite, type: 'log', path: 'logs.invite' }, 'logs-say': { description: 'administration/conf:LOGS-SAY', value: settings.logs.say, type: 'log', path: 'logs.say' }, 'logs-slowmode': { description: 'administration/conf:LOGS-SLOWMODE', value: settings.logs.slowmode, type: 'log', path: 'logs.slowmode' }, modlogs: { description: 'administration/conf:MODLOGS', value: settings.logs.moderation, type: 'channel', path: 'logs.moderation' }, 'modlogs-purge': { description: 'administration/conf:MODLOGS-PURGE', value: settings.logs.purge, type: 'boolean', path: 'logs.purge' }, automessage: { description: 'administration/conf:AUTOMESSAGE', value: settings.auto.message, type: 'default', path: 'auto.message' }, autonickname: { description: 'administration/conf:AUTONICKNAME', value: settings.auto.nickname, type: 'default', path: 'auto.nickname' }, mode: { description: 'administration/conf:MODE', value: settings.mode, type: 'default', path: 'mode' }, customprefix: { description: 'administration/conf:CUSTOMPREFIX', value: settings.prefix.custom, type: 'default', path: 'prefix.custom' }, defaultprefix: { description: 'administration/conf:DEFAULTPREFIX', value: settings.prefix.default, type: 'boolean', path: 'prefix.default' }, 'antispam-mentions': { description: 'administration/conf:ANTISPAM-MENTIONS', value: settings.automod.spam.mentions.enabled, type: 'boolean', path: 'automod.spam.mentions.enabled' }, 'antispam-mentions-severity': { description: 'administration/conf:ANTISPAM-MENTIONS-SEVERITY', value: settings.automod.spam.mentions.severity, type: 'default', path: 'automod.spam.mentions.severity' }, 'antispam-caps': { description: 'administration/conf:ANTISPAM-CAPS', value: settings.automod.spam.caps.enabled, type: 'boolean', path: 'automod.spam.caps.enabled' }, 'antispam-caps-severity': { description: 'administration/conf:ANTISPAM-CAPS-SEVERITY', value: settings.automod.spam.caps.severity, type: 'default', path: 'automod.spam.caps.severity' }, 'antispam-zalgo': { description: 'administration/conf:ANTISPAM-ZALGO', value: settings.automod.spam.zalgo.enabled, type: 'boolean', path: 'automod.spam.zalgo.enabled' }, 'antispam-zalgo-severity': { description: 'administration/conf:ANTISPAM-ZALGO-SEVERITY', value: settings.automod.spam.zalgo.severity, type: 'default', path: 'automod.spam.zalgo.severity' }, 'antispam-scamlinks': { description: 'administration/conf:ANTISPAM-SCAMLINKS', value: settings.automod.spam.scamlinks.enabled, type: 'boolean', path: 'automod.spam.scamlinks.enabled' }, antiinvite: { description: 'administration/conf:ANTIINVITE', value: settings.automod.invite, type: 'boolean', path: 'automod.invite' }, 'antiinvite-action': { description: 'administration/conf:ANTIINVITE-ACTION', value: settings.automod.inviteaction, type: 'boolean', path: 'automod.inviteaction' }, 'antiinvite-warn': { description: 'administration/conf:ANTIINVITE-WARN', value: settings.automod.invitewarn, type: 'default', path: 'automod.invitewarn' }, 'antiinvite-kick': { description: 'administration/conf:ANTIINVITE-KICK', value: settings.automod.invitekick, type: 'default', path: 'automod.invitekick' }, nonickname: { description: 'administration/conf:NONICKNAME', value: settings.nonickname, type: 'boolean', path: 'nonickname' }, starboard: { description: 'administration/conf:STARBOARD', value: settings.starboard.id, type: 'channel', path: 'starboard.id' }, 'starboard-stars': { description: 'administration/conf:STARBOARD-STARS', value: settings.starboard.count, type: 'default', path: 'starboard.count' }, language: { description: 'administration/conf:LANGUAGE', value: settings.language, type: 'default', path: 'language' } }; if (!setting || /^\d+$/.test(setting)) { return this.list(message, setting, settingsData); } if (setting === 'clear') { return this.clear(message); } // @ts-ignore const selectedSetting = settingsData[setting]; if (!selectedSetting) { return message.error(message.translate('administration/conf:INVALID')); } if (setting && !value) { return this.view(message, selectedSetting); } return this.edit(message, selectedSetting, value); } // @ts-ignore list(message: TypicalGuildMessage, setting: string, settingsData, view = false) { let page = parseInt(setting, 10) || 1; const settings = Object.keys(settingsData); const count = Math.ceil(settings.length / 10); if (page < 1 || page > count) page = 1; const NA = message.translate('common:NA').toUpperCase(); const list = settings .splice((page - 1) * 10, 10) .map((k) => { if (!view) return `• **${k}:** ${message.translate(settingsData[k].description)}`; let response = ` • **${k}:** `; const type = settingsData[k].type; const value = settingsData[k].value; if (type === 'channel') { if (value && message.guild.channels.cache.has(value)) response += `<#${value}>`; else response += NA; } else if (type === 'channels') { if (value.length) response += value.map((id: string) => `<#${id}>`); else response += NA; } else if (type === 'role') { const role = message.guild.roles.cache.get(value); if (role) response += role.name; else response += NA; } else if (type === 'roles') { if (value.length) response += value.map((id: string) => message.guild.roles.cache.get(`${BigInt(id)}`)?.name ?? 'Unknown Role') .join(', '); else response += NA; } else if (type === 'boolean') response += message.translate(value ? 'common:ENABLED' : 'common:DISABLED'); else if (type === 'log' && value === '--embed') response += 'Embed'; else response += value || NA; return response; }); return message.send([ message.translate('administration/conf:AVAILABLE'), '', message.translate('administration/conf:PAGE', { page, count }), list.join('\n'), '', message.translate('administration/conf:USAGE_LIST', { prefix: process.env.PREFIX }) ].join('\n')); } async clear(message: TypicalGuildMessage) { const deleted = await this.client.database .delete('guilds', { id: message.guild.id }); this.client.settings.delete(message.guild.id); return deleted ? message.reply(message.translate('administration/conf:CLEARED')) : message.error(message.translate('administration/conf:CLEAR_ERROR')); } view(message: TypicalGuildMessage, setting: SettingsData) { const NONE = message.translate('common:NONE'); if (setting.type === 'boolean') { return message.reply(message.translate('administration/conf:CURRENT_VALUE', { value: message.translate(setting.value ? 'common:ENABLED' : 'common:DISABLED') })); } if (setting.type === 'roles') { const list = []; for (const roleID of setting.value as string[]) { const role = message.guild.roles.cache.get(`${BigInt(roleID)}`); if (!role) continue; list.push(`*${ message.guild.id === roleID ? role.name.slice(1) : role.name }*`); } return message.reply(message.translate('administration/conf:CURRENT_VALUE', { value: list.length ? list.join(', ') : NONE })); } if (setting.type === 'role') { const role = message.guild.roles.cache.get(`${BigInt(setting.value as string)}`); return message.reply(message.translate('administration/conf:CURRENT_VALUE', { value: role ? role.name : NONE })); } if (setting.type === 'ms') { return message.reply(message.translate('administration/conf:CURRENT_VALUE', { value: setting.value ? `${setting.value}ms` : message.translate('common:DEFAULT') })); } if (setting.type === 'channel') { const channel = message.guild.channels.cache.get(`${BigInt(setting.value as string)}`); return message.reply(message.translate('administration/conf:CURRENT_VALUE', { value: channel ? `<#${channel.id}>` : NONE })); } if (setting.type === 'log') { const disabled = setting.value === '--disabled'; const embed = setting.value === '--embed'; const logText = !setting.value ? message.translate('common:DEFAULT') : disabled ? message.translate('common:DISABLED') : embed ? message.translate('common:EMBED') : ['```txt', '', setting.value, '```'].join('\n'); return message.reply(message.translate('administration/conf:CURRENT_VALUE', { value: logText })); } return message.reply(message.translate('administration/conf:CURRENT_VALUE', { value: setting.value || NONE })); } async edit(message: TypicalGuildMessage, setting: SettingsData, value: string) { let payload; const HERE = message.translate('common:HERE'); const EMBED = message.translate('common:EMBED'); const english = this.client.translate.get('en-US'); const ENABLE_OPTIONS = message.translate('common:ENABLE_OPTIONS', { returnObjects: true }); const ENGLISH_ENABLE_OPTIONS = english!('common:ENABLE_OPTIONS', { returnObjects: true }); const DISABLE_OPTIONS = message.translate('common:DISABLE_OPTIONS', { returnObjects: true }); const ENGLISH_DISABLE_OPTIONS = english!('common:DISABLE_OPTIONS', { returnObjects: true }); if (setting.path.endsWith('language')) { const selectedLanguage = possibleLanguages.find((data) => data.name === value.toLowerCase() || data.aliases.includes(value.toLowerCase())); if (!selectedLanguage) return message.error(message.translate('administration/conf:INVALID_OPTION')); if (!selectedLanguage.complete) { // eslint-disable-next-line max-len await message.reply(`${selectedLanguage.canonical} is not fully translated yet. You can help translate TypicalBot at <${LINK.TRANSLATE}>`); } value = selectedLanguage.name; } if (setting.path === 'auto.role.id' || setting.path === 'auto.role.delay') if (message.guild.verificationLevel === 'VERY_HIGH') return message.error(message.translate('administration/conf:VERIFICATION_LEVEL_VERYHIGH')); if (setting.type === 'boolean') { if (![...ENABLE_OPTIONS, ...ENGLISH_ENABLE_OPTIONS, ...DISABLE_OPTIONS, ...ENGLISH_DISABLE_OPTIONS].includes(value.toLowerCase())) return message.error(message.translate('administration/conf:INVALID_OPTION')); const enableSetting = [...ENABLE_OPTIONS, ...ENGLISH_ENABLE_OPTIONS].includes(value.toLowerCase()); payload = this.stringToObject(setting.path, enableSetting); } if (setting.type === 'roles') { if ([...DISABLE_OPTIONS, ...ENGLISH_DISABLE_OPTIONS].includes(value.toLowerCase())) { payload = this.stringToObject(setting.path, []); } else { const args = roleRegex.exec(value.split(/(?<=^\S+)\s/)[1]); if (!args) return message.error(message.translate('misc:USAGE_ERROR', { name: this.name, prefix: process.env.PREFIX })); args.shift(); const [roleID, roleName] = args; const role = roleID ? message.guild.roles.cache.get(`${BigInt(roleID)}`) : message.guild.roles.cache.find((r) => r.name.toLowerCase() === roleName.toLowerCase()); if (!role) return message.error(message.translate('moderation/give:INVALID')); const currentValue = setting.value as string[]; const newValue = !currentValue.includes(role.id) ? [...currentValue, role.id] : currentValue.filter((id) => id !== role.id); payload = this.stringToObject(setting.path, newValue); } } if (setting.type === 'role') { if ([...DISABLE_OPTIONS, ...ENGLISH_DISABLE_OPTIONS].includes(value.toLowerCase())) { payload = this.stringToObject(setting.path, null); } else { const args = roleRegex.exec(value); if (!args) return message.error(message.translate('misc:USAGE_ERROR', { name: this.name, prefix: process.env.PREFIX })); args.shift(); const [roleID, roleName] = args; const role = roleID ? message.guild.roles.cache.get(`${BigInt(roleID)}`) : message.guild.roles.cache.find((r) => r.name.toLowerCase() === roleName.toLowerCase()); if (!role) return message.error(message.translate('moderation/give:INVALID')); payload = this.stringToObject(setting.path, role.id); } } if (setting.type === 'ms') { if ([...DISABLE_OPTIONS, ...ENGLISH_DISABLE_OPTIONS].includes(value.toLowerCase())) { payload = this.stringToObject(setting.path, null); } else { const args = msRegex.exec(value); if (!args) return message.error(message.translate('administration/conf:INVALID_MS')); args.shift(); const [ms] = args; const amount = parseInt(ms, 10); if (setting.path === 'auto.role.delay') if (message.guild.verificationLevel === 'HIGH' && amount < 60000) return message.error(message.translate('administration/conf:VERIFICATION_LEVEL_HIGH')); if (amount > 600000 || amount < 2000) return message.error(message.translate('administration/conf:INVALID_MS')); payload = this.stringToObject(setting.path, amount); } } if (setting.type === 'channel') { if ([...DISABLE_OPTIONS, ...ENGLISH_DISABLE_OPTIONS].includes(value.toLowerCase())) { payload = this.stringToObject(setting.path, null); } else if ([HERE, 'here'].includes(value.toLowerCase())) { payload = this.stringToObject(setting.path, message.channel.id); } else { const args = channelRegex.exec(value); if (!args) return message.error(message.translate('misc:USAGE_ERROR', { name: this.name, prefix: process.env.PREFIX })); args.shift(); const [channelID, channelName] = args; const channel = channelID ? message.guild.channels.cache.get(`${BigInt(channelID)}`) : message.guild.channels.cache.find((r) => r.name.toLowerCase() === channelName.toLowerCase()); if (!channel) return message.error(message.translate('administration/conf:INVALID_CHANNEL')); if (channel.type !== 'text' && channel.type !== 'news') return message.error(message.translate('administration/conf:NOT_TEXT_CHANNEL')); payload = this.stringToObject(setting.path, channel.id); } } if (setting.type === 'log') { if (!message.guild.settings.logs.id) return message.error(message.translate('administration/conf:NEED_LOG')); if ([...DISABLE_OPTIONS, ...ENGLISH_DISABLE_OPTIONS].includes(value.toLowerCase())) { payload = this.stringToObject(setting.path, '--disabled'); } else if ([...ENABLE_OPTIONS, ...ENGLISH_ENABLE_OPTIONS].includes(value.toLowerCase())) { payload = this.stringToObject(setting.path, null); } else if ([EMBED, 'embed'].includes(value.toLowerCase())) { payload = this.stringToObject(setting.path, '--embed'); } else { payload = this.stringToObject(setting.path, value); } } if (setting.type === 'default') { payload = this.stringToObject(setting.path, [...DISABLE_OPTIONS, ...ENGLISH_DISABLE_OPTIONS].includes(value.toLowerCase()) ? null : value); } // TODO: This is a temporary fix await this.client.settings.update(message.guild.id, setting.path, payload); return message.success(message.translate('administration/conf:UPDATED')); } // TODO: This is a temporary fix // eslint-disable-next-line @typescript-eslint/ban-types stringToObject(path: string, value: unknown) { // if (!path.includes('.')) return { [path]: value }; // const parts = path.split('.'); // return { // @ts-ignore // [parts.shift()]: this.stringToObject(parts.join('.'), value) // }; return value; } }
the_stack
import bunyan from 'bunyan'; import Web3 from 'web3'; import { StringMap, SourceMap, PathBuffer, PathContent, CheckedContract, InvalidSources, MissingSources } from '@ethereum-sourcify/core'; import AdmZip from 'adm-zip'; import fs from 'fs'; import Path from 'path'; /** * Regular expression matching metadata nested within another json. */ const NESTED_METADATA_REGEX = /"{\\"compiler\\":{\\"version\\".*?},\\"version\\":1}"/; const HARDHAT_OUTPUT_FORMAT_REGEX = /"hh-sol-build-info-1"/; const CONTENT_VARIATORS = [ (content: string) => content, (content: string) => content.replace(/\r?\n/g, "\r\n"), (content: string) => content.replace(/\r\n/g, "\n") ]; const ENDING_VARIATORS = [ (content: string) => content, (content: string) => content.trimEnd(), (content: string) => content.trimEnd() + "\n", (content: string) => content.trimEnd() + "\r\n", (content: string) => content + "\n", (content: string) => content + "\r\n" ]; export interface IValidationService { /** * Checks all metadata files found in the provided paths. Paths may include regular files, directoris and zip archives. * * @param paths The array of paths to be searched and checked. * @param ignoring Optional array where all unreadable paths can be stored. * @returns An array of CheckedContract objects. * @throws Error if no metadata files are found. */ checkPaths(paths: string[], ignoring?: string[]): CheckedContract[]; /** * Checks the provided files. Works with zips. * Attempts to find all the resources specified in every metadata file found. * * @param files The array or object of buffers to be checked. * @returns An array of CheckedContract objets. * @throws Error if no metadata files are found. */ checkFiles(files: PathBuffer[], unused?: string[]): CheckedContract[]; useAllSources(contract: CheckedContract, files: PathBuffer[]): CheckedContract; } export class ValidationService implements IValidationService { logger: bunyan; /** * @param logger a custom logger that logs all errors; undefined or no logger provided turns the logging off */ constructor(logger?: bunyan) { this.logger = logger; } checkPaths(paths: string[], ignoring?: string[]): CheckedContract[] { const files: PathBuffer[] = []; paths.forEach(path => { if (fs.existsSync(path)) { this.traversePathRecursively(path, filePath => { const fullPath = Path.resolve(filePath); const file = {buffer: fs.readFileSync(filePath), path: fullPath}; files.push(file); }); } else if (ignoring) { ignoring.push(path); } }); return this.checkFiles(files); } // Pass all input source files to the CheckedContract, not just those stated in metadata. useAllSources(contract: CheckedContract, files: PathBuffer[]) { const unzippedFiles = this.traverseAndUnzipFiles(files); const parsedFiles = unzippedFiles.map(pathBuffer => ({ content: pathBuffer.buffer.toString(), path: pathBuffer.path })); const { sourceFiles } = this.splitFiles(parsedFiles); const stringMapSourceFiles = this.pathContentArrayToStringMap(sourceFiles) // Files at contract.solidity are already hash matched with the sources in metadata. Use them instead of the user input .sol files. Object.assign(stringMapSourceFiles, contract.solidity) const contractWithAllSources = new CheckedContract(contract.metadata, stringMapSourceFiles, contract.missing, contract.invalid); return contractWithAllSources; } checkFiles(files: PathBuffer[], unused?: string[]): CheckedContract[] { const unzippedFiles = this.traverseAndUnzipFiles(files); const parsedFiles = unzippedFiles.map(pathBuffer => ({ content: pathBuffer.buffer.toString(), path: pathBuffer.path })); const { metadataFiles, sourceFiles } = this.splitFiles(parsedFiles); const checkedContracts: CheckedContract[] = []; const errorMsgMaterial: string[] = []; const byHash = this.storeByHash(sourceFiles); const usedFiles: string[] = []; metadataFiles.forEach(metadata => { const { foundSources, missingSources, invalidSources, metadata2provided } = this.rearrangeSources(metadata, byHash); const currentUsedFiles = Object.values(metadata2provided); usedFiles.push(...currentUsedFiles); const checkedContract = new CheckedContract(metadata, foundSources, missingSources, invalidSources); checkedContracts.push(checkedContract); if (!CheckedContract.isValid(checkedContract)) { errorMsgMaterial.push(checkedContract.getInfo()); } }); if (errorMsgMaterial.length) { const msg = errorMsgMaterial.join("\n"); if (this.logger) this.logger.error(msg); } if (unused) { this.extractUnused(sourceFiles, usedFiles, unused); } return checkedContracts; } /** * Traverses the given files, unzipping any zip archive. * * @param files the array containing the files to be checked * @returns an array containing the provided files, with any zips being unzipped and returned */ private traverseAndUnzipFiles(files: PathBuffer[]): PathBuffer[] { const inputFiles: PathBuffer[] = []; for (const file of files) { if (this.isZip(file.buffer)) { this.unzip(file, files); } else { inputFiles.push(file); } } return inputFiles; } /** * Checks whether the provided file is in fact zipped. * @param file the buffered file to be checked * @returns true if the file is zipped; false otherwise */ private isZip(file: Buffer): boolean { try { new AdmZip(file); return true; } catch (err) { undefined } return false; } /** * Unzips the provided file buffer to the provided array. * * @param zippedFile the buffer containin the zipped file to be unpacked * @param files the array to be filled with the content of the zip */ private unzip(zippedFile: PathBuffer, files: PathBuffer[]): void { const timestamp = Date.now().toString() + "-" + Math.random().toString().slice(2); const tmpDir = `tmp-unzipped-${timestamp}`; new AdmZip(zippedFile.buffer).extractAllTo(tmpDir); this.traversePathRecursively(tmpDir, filePath => { const file = { buffer: fs.readFileSync(filePath), // remove the zip-folder name from the path e.g. tmp-unzipped-1652274174745-9239260350002245/contracts/Token.sol --> contracts/Token.sol path: filePath.slice(tmpDir.length + 1)}; files.push(file); }); this.traversePathRecursively(tmpDir, fs.unlinkSync, fs.rmdirSync); } /** * Selects metadata files from an array of files that may include sources, etc * @param {string[]} files * @return {string[]} metadata */ private splitFiles(files: PathContent[]): { metadataFiles: any[], sourceFiles: PathContent[] } { const metadataFiles = []; const sourceFiles: PathContent[] = []; const malformedMetadataFiles = []; for (const file of files) { // If hardhat output file, extract source and metadatas. if (file.content.match(HARDHAT_OUTPUT_FORMAT_REGEX)) { const {hardhatMetadataFiles, hardhatSourceFiles} = this.extractHardhatMetadataAndSources(file); sourceFiles.push(...hardhatSourceFiles); metadataFiles.push(...hardhatMetadataFiles); continue; } let metadata = this.extractMetadataFromString(file.content); if (!metadata) { const matchRes = file.content.match(NESTED_METADATA_REGEX); if (matchRes) { metadata = this.extractMetadataFromString(matchRes[0]); } } if (metadata) { try { this.assertObjectSize(metadata.settings.compilationTarget, 1); metadataFiles.push(metadata); } catch (err) { malformedMetadataFiles.push(file.path); } } else { sourceFiles.push(file); } } let msg = ""; if (malformedMetadataFiles.length) { const responsibleFiles = malformedMetadataFiles.every(Boolean) ? malformedMetadataFiles.join(", ") : `${malformedMetadataFiles.length} metadata files`; msg = `Malformed settings.compilationTarget in: ${responsibleFiles}`; } else if (!metadataFiles.length) { msg = "Metadata file not found. Did you include \"metadata.json\"?"; } if (msg) { if (this.logger) this.logger.error(msg); throw new Error(msg); } return { metadataFiles, sourceFiles }; } /** * Validates metadata content keccak hashes for all files and * returns mapping of file contents by file name * @param {any} metadata * @param {Map<string, any>} byHash Map from keccak to source * @return foundSources, missingSources, invalidSources */ private rearrangeSources(metadata: any, byHash: Map<string, PathContent>) { const foundSources: StringMap = {}; const missingSources: MissingSources = {}; const invalidSources: InvalidSources = {}; const metadata2provided: StringMap = {}; // maps fileName as in metadata to the fileName of the provided file for (const sourcePath in metadata.sources) { const sourceInfoFromMetadata = metadata.sources[sourcePath]; let file: PathContent = { content: undefined }; file.content = sourceInfoFromMetadata.content; const expectedHash: string = sourceInfoFromMetadata.keccak256; if (file.content) { // Source content already in metadata const contentHash = Web3.utils.keccak256(file.content) if (contentHash != expectedHash) { invalidSources[sourcePath] = { expectedHash: expectedHash, calculatedHash: contentHash, msg: `The keccak256 given in the metadata and the calculated keccak256 of the source content in metadata don't match` } continue; } } else { // Get source from input files by hash const pathContent = byHash.get(expectedHash); if (pathContent) { file = pathContent; metadata2provided[sourcePath] = pathContent.path; } // else: no file has the hash that was searched for } if (file && file.content) { foundSources[sourcePath] = file.content; } else { missingSources[sourcePath] = { keccak256: expectedHash, urls: sourceInfoFromMetadata.urls }; } } return { foundSources, missingSources, invalidSources, metadata2provided }; } /** * Generates a map of files indexed by the keccak hash of their content. * * @param {string[]} files Array containing sources. * @returns Map object that maps hash to PathContent. */ private storeByHash(files: PathContent[]): Map<string, PathContent> { const byHash: Map<string, PathContent> = new Map(); for (const pathContent of files) { for (const variation of this.generateVariations(pathContent)) { const calculatedHash = Web3.utils.keccak256(variation.content); byHash.set(calculatedHash, variation); } } return byHash; } private generateVariations(pathContent: PathContent): PathContent[] { const variations: string[] = []; const original = pathContent.content; for (const contentVariator of CONTENT_VARIATORS) { const variatedContent = contentVariator(original); for (const endingVariator of ENDING_VARIATORS) { const variation = endingVariator(variatedContent); variations.push(variation); } } return variations.map(content => { return { content, path: pathContent.path } }); } private extractUnused(inputFiles: PathContent[], usedFiles: string[], unused: string[]): void { const usedFilesSet = new Set(usedFiles); const tmpUnused = inputFiles.map(pc => pc.path).filter(file => !usedFilesSet.has(file)); unused.push(...tmpUnused); } private extractMetadataFromString(file: string): any { try { let obj = JSON.parse(file); if (this.isMetadata(obj)) { return obj; } // if the input string originates from a file where it was double encoded (e.g. truffle) obj = JSON.parse(obj); if (this.isMetadata(obj)) { return obj; } } catch (err) { undefined } // Don't throw here as other files can be metadata files. return null; } /** * A method that checks if the provided object was generated as a metadata file of a Solidity contract. * Current implementation is rather simplistic and may require further engineering. * * @param metadata the JSON to be checked * @returns true if the provided object is a Solidity metadata file; false otherwise */ private isMetadata(obj: any): boolean { return (obj.language === "Solidity") && !!obj.compiler; } /** * Applies the provided worker function to the provided path recursively. * * @param path the path to be traversed * @param worker the function to be applied on each file that is not a directory * @param afterDir the function to be applied on the directory after traversing its children */ private traversePathRecursively(path: string, worker: (filePath: string) => void, afterDirectory?: (filePath: string) => void) { if (!fs.existsSync(path)) { const msg = `Encountered a nonexistent path: ${path}`; if (this.logger) {this.logger.error(msg);} throw new Error(msg); } const fileStat = fs.lstatSync(path); if (fileStat.isFile()) { worker(path); } else if (fileStat.isDirectory()) { fs.readdirSync(path).forEach(nestedName => { const nestedPath = Path.join(path, nestedName); this.traversePathRecursively(nestedPath, worker, afterDirectory); }); if (afterDirectory) { afterDirectory(path); } } } /** * Asserts that the number of keys of the provided object is expectedSize. * If not, logs an appropriate message (if log function provided) and throws an Error. * @param object the object to check * @param expectedSize the size that the object should have */ private assertObjectSize(object: any, expectedSize: number) { let err = ""; if (!object) { err = `Cannot assert for ${object}.`; } else { const objectSize = Object.keys(object).length; if (objectSize !== expectedSize) { err = `Error in size assertion! Actual size: ${objectSize}. Expected size: ${expectedSize}.`; } } if (err) { if (this.logger) { this.logger.error({ loc: "[VALIDATION:SIZE_ASSERTION]" }, err); } throw new Error(err); } } /** * Hardhat build output can contain metadata and source files of every contract used in compilation. * Extracts these files from a given hardhat file following the hardhat output format. * * @param hardhatFile * @returns - {hardhatMetadataFiles, hardhatSourceFiles} */ private extractHardhatMetadataAndSources(hardhatFile: PathContent) { const hardhatMetadataFiles: any[] = []; const hardhatSourceFiles: PathContent[] = []; const hardhatJson = JSON.parse(hardhatFile.content); // Extract source files const hardhatSourceFilesObject = hardhatJson.input.sources; for (const path in hardhatSourceFilesObject) { if (hardhatSourceFilesObject[path].content) { hardhatSourceFiles.push({path: path, content: hardhatSourceFilesObject[path].content}) } } // Extract metadata files const contractsObject = hardhatJson.output.contracts; for (const path in contractsObject) { for (const contractName in contractsObject[path]) { if(contractsObject[path][contractName].metadata) { const metadataObj = this.extractMetadataFromString(contractsObject[path][contractName].metadata) hardhatMetadataFiles.push(metadataObj) } } } return {hardhatMetadataFiles, hardhatSourceFiles} } pathContentArrayToStringMap(pathContentArr: PathContent[]) { const stringMapResult: StringMap = {}; pathContentArr.forEach((elem, i) => { if (elem.path) { stringMapResult[elem.path] = elem.content; } else { stringMapResult[`path-${i}`] = elem.content; } }) return stringMapResult; } }
the_stack
import BN from 'bn.js'; import { Account, AccountInfo, Commitment, Connection, PublicKey, RpcResponseAndContext, SimulatedTransactionResponse, SystemProgram, Transaction, TransactionConfirmationStatus, TransactionInstruction, TransactionSignature, } from '@solana/web3.js'; import { OpenOrders, TokenInstructions } from '@project-serum/serum'; import { I80F48, ONE_I80F48 } from './fixednum'; import MangoGroup from './MangoGroup'; import { HealthType } from './MangoAccount'; /** @internal */ export const ZERO_BN = new BN(0); /** @internal */ export const ONE_BN = new BN(1); /** @internal */ export const zeroKey = new PublicKey(new Uint8Array(32)); /** @internal */ export async function promiseUndef(): Promise<undefined> { return undefined; } export function uiToNative(amount: number, decimals: number): BN { return new BN(Math.round(amount * Math.pow(10, decimals))); } export function nativeToUi(amount: number, decimals: number): number { return amount / Math.pow(10, decimals); } export function nativeI80F48ToUi(amount: I80F48, decimals: number): I80F48 { return amount.div(I80F48.fromNumber(Math.pow(10, decimals))); } export class TimeoutError extends Error { message: string; txid: string; constructor({ txid }) { super(); this.message = `Timed out awaiting confirmation. Please confirm in the explorer: `; this.txid = txid; } } export class MangoError extends Error { message: string; txid: string; constructor({ txid, message }) { super(); this.message = message; this.txid = txid; } } /** * Return weights corresponding to health type; * Weights are all 1 if no healthType provided */ export function getWeights( mangoGroup: MangoGroup, marketIndex: number, healthType?: HealthType, ): { spotAssetWeight: I80F48; spotLiabWeight: I80F48; perpAssetWeight: I80F48; perpLiabWeight: I80F48; } { if (healthType === 'Maint') { return { spotAssetWeight: mangoGroup.spotMarkets[marketIndex].maintAssetWeight, spotLiabWeight: mangoGroup.spotMarkets[marketIndex].maintLiabWeight, perpAssetWeight: mangoGroup.perpMarkets[marketIndex].maintAssetWeight, perpLiabWeight: mangoGroup.perpMarkets[marketIndex].maintLiabWeight, }; } else if (healthType === 'Init') { return { spotAssetWeight: mangoGroup.spotMarkets[marketIndex].initAssetWeight, spotLiabWeight: mangoGroup.spotMarkets[marketIndex].initLiabWeight, perpAssetWeight: mangoGroup.perpMarkets[marketIndex].initAssetWeight, perpLiabWeight: mangoGroup.perpMarkets[marketIndex].initLiabWeight, }; } else { return { spotAssetWeight: ONE_I80F48, spotLiabWeight: ONE_I80F48, perpAssetWeight: ONE_I80F48, perpLiabWeight: ONE_I80F48, }; } } export function splitOpenOrders(openOrders: OpenOrders): { quoteFree: I80F48; quoteLocked: I80F48; baseFree: I80F48; baseLocked: I80F48; } { const quoteFree = I80F48.fromU64( openOrders.quoteTokenFree.add(openOrders['referrerRebatesAccrued']), ); const quoteLocked = I80F48.fromU64( openOrders.quoteTokenTotal.sub(openOrders.quoteTokenFree), ); const baseFree = I80F48.fromU64(openOrders.baseTokenFree); const baseLocked = I80F48.fromU64( openOrders.baseTokenTotal.sub(openOrders.baseTokenFree), ); return { quoteFree, quoteLocked, baseFree, baseLocked }; } export async function awaitTransactionSignatureConfirmation( txid: TransactionSignature, timeout: number, connection: Connection, confirmLevel: TransactionConfirmationStatus, ) { let done = false; const confirmLevels: (TransactionConfirmationStatus | null | undefined)[] = [ 'finalized', ]; if (confirmLevel === 'confirmed') { confirmLevels.push('confirmed'); } else if (confirmLevel === 'processed') { confirmLevels.push('confirmed'); confirmLevels.push('processed'); } const result = await new Promise((resolve, reject) => { (async () => { setTimeout(() => { if (done) { return; } done = true; console.log('Timed out for txid', txid); reject({ timeout: true }); }, timeout); try { connection.onSignature( txid, (result) => { // console.log('WS confirmed', txid, result); done = true; if (result.err) { reject(result.err); } else { resolve(result); } }, 'processed', ); // console.log('Set up WS connection', txid); } catch (e) { done = true; console.log('WS error in setup', txid, e); } while (!done) { // eslint-disable-next-line no-loop-func (async () => { try { const signatureStatuses = await connection.getSignatureStatuses([ txid, ]); const result = signatureStatuses && signatureStatuses.value[0]; if (!done) { if (!result) { // console.log('REST null result for', txid, result); } else if (result.err) { console.log('REST error for', txid, result); done = true; reject(result.err); } else if ( !( result.confirmations || confirmLevels.includes(result.confirmationStatus) ) ) { console.log('REST not confirmed', txid, result); } else { console.log('REST confirmed', txid, result); done = true; resolve(result); } } } catch (e) { if (!done) { console.log('REST connection error: txid', txid, e); } } })(); await sleep(300); } })(); }); done = true; return result; } export async function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } export async function simulateTransaction( connection: Connection, transaction: Transaction, commitment: Commitment, ): Promise<RpcResponseAndContext<SimulatedTransactionResponse>> { // @ts-ignore transaction.recentBlockhash = await connection._recentBlockhash( // @ts-ignore connection._disableBlockhashCaching, ); const signData = transaction.serializeMessage(); // @ts-ignore const wireTransaction = transaction._serialize(signData); const encodedTransaction = wireTransaction.toString('base64'); const config: any = { encoding: 'base64', commitment }; const args = [encodedTransaction, config]; // @ts-ignore const res = await connection._rpcRequest('simulateTransaction', args); if (res.error) { throw new Error('failed to simulate transaction: ' + res.error.message); } return res.result; } export async function createAccountInstruction( connection: Connection, payer: PublicKey, space: number, owner: PublicKey, lamports?: number, ): Promise<{ account: Account; instruction: TransactionInstruction }> { const account = new Account(); const instruction = SystemProgram.createAccount({ fromPubkey: payer, newAccountPubkey: account.publicKey, lamports: lamports ? lamports : await connection.getMinimumBalanceForRentExemption(space), space, programId: owner, }); return { account, instruction }; } export async function createTokenAccountInstructions( connection: Connection, payer: PublicKey, account: PublicKey, mint: PublicKey, owner: PublicKey, ): Promise<TransactionInstruction[]> { return [ SystemProgram.createAccount({ fromPubkey: payer, newAccountPubkey: account, lamports: await connection.getMinimumBalanceForRentExemption(165), space: 165, programId: TokenInstructions.TOKEN_PROGRAM_ID, }), TokenInstructions.initializeAccount({ account: account, mint, owner, }), ]; } export async function createSignerKeyAndNonce( programId: PublicKey, accountKey: PublicKey, ): Promise<{ signerKey: PublicKey; signerNonce: number }> { // let res = await PublicKey.findProgramAddress([accountKey.toBuffer()], programId); // console.log(res); // return { // signerKey: res[0], // signerNonce: res[1] // }; for (let nonce = 0; nonce <= Number.MAX_SAFE_INTEGER; nonce++) { try { const nonceBuffer = Buffer.alloc(8); nonceBuffer.writeUInt32LE(nonce, 0); const seeds = [accountKey.toBuffer(), nonceBuffer]; const key = await PublicKey.createProgramAddress(seeds, programId); return { signerKey: key, signerNonce: nonce, }; } catch (e) { continue; } } throw new Error('Could not generate signer key'); } export async function getFilteredProgramAccounts( connection: Connection, programId: PublicKey, filters, ): Promise<{ publicKey: PublicKey; accountInfo: AccountInfo<Buffer> }[]> { // @ts-ignore const resp = await connection._rpcRequest('getProgramAccounts', [ programId.toBase58(), { commitment: connection.commitment, filters, encoding: 'base64', }, ]); if (resp.error) { throw new Error(resp.error.message); } return resp.result.map( ({ pubkey, account: { data, executable, owner, lamports } }) => ({ publicKey: new PublicKey(pubkey), accountInfo: { data: Buffer.from(data[0], 'base64'), executable, owner: new PublicKey(owner), lamports, }, }), ); } // Clamp number between two values export function clamp(x: number, min: number, max: number): number { if (x < min) { return min; } else if (x > max) { return max; } else { return x; } } export async function getMultipleAccounts( connection: Connection, publicKeys: PublicKey[], commitment?: Commitment, ): Promise< { publicKey: PublicKey; context: { slot: number }; accountInfo: AccountInfo<Buffer>; }[] > { const len = publicKeys.length; if (len === 0) { return []; } if (len > 100) { const mid = Math.floor(publicKeys.length / 2); return Promise.all([ getMultipleAccounts(connection, publicKeys.slice(0, mid), commitment), getMultipleAccounts(connection, publicKeys.slice(mid, len), commitment), ]).then((a) => a[0].concat(a[1])); } const publicKeyStrs = publicKeys.map((pk) => pk.toBase58()); // load connection commitment as a default commitment ||= connection.commitment; const args = commitment ? [publicKeyStrs, { commitment }] : [publicKeyStrs]; // @ts-ignore const resp = await connection._rpcRequest('getMultipleAccounts', args); if (resp.error) { throw new Error(resp.error.message); } return resp.result.value.map( ({ data, executable, lamports, owner }, i: number) => ({ publicKey: publicKeys[i], context: resp.result.context, accountInfo: { data: Buffer.from(data[0], 'base64'), executable, owner: new PublicKey(owner), lamports, }, }), ); } /** * Throw if undefined; return value otherwise * @internal */ export function throwUndefined<T>(x: T | undefined): T { if (x === undefined) { throw new Error('Undefined'); } return x; } /** * Calculate the base lot size and quote lot size given a desired min tick and min size in the UI */ export function calculateLotSizes( baseDecimals: number, quoteDecimals: number, minTick: number, minSize: number, ): { baseLotSize: BN; quoteLotSize: BN } { const baseLotSize = minSize * Math.pow(10, baseDecimals); const quoteLotSize = (minTick * baseLotSize) / Math.pow(10, baseDecimals - quoteDecimals); return { baseLotSize: new BN(baseLotSize), quoteLotSize: new BN(quoteLotSize), }; } /** * Return some standard params for a new perp market * oraclePrice is the current oracle price for the perp market being added * Assumes a rate 1000 MNGO per hour for 500k liquidity rewarded * `nativeBaseDecimals` are the decimals for the asset on the native chain */ export function findPerpMarketParams( nativeBaseDecimals: number, quoteDecimals: number, oraclePrice: number, leverage: number, mngoPerHour: number, ) { // wormhole wrapped tokens on solana will have a max of 8 decimals const baseDecimals = Math.min(nativeBaseDecimals, 8); // min tick targets around 1 basis point or 0.01% of price const minTick = Math.pow(10, Math.round(Math.log10(oraclePrice)) - 4); // minSize is targeted to be between 0.1 - 1 assuming USDC quote currency const minSize = Math.pow(10, -Math.round(Math.log10(oraclePrice))); const LIQUIDITY_PER_MNGO = 500; // implies 1000 MNGO per $500k top of book const contractVal = minSize * oraclePrice; const maxDepthBps = Math.floor( (mngoPerHour * LIQUIDITY_PER_MNGO) / contractVal, ); const lmSizeShift = Math.floor(Math.log2(maxDepthBps) - 3); const { baseLotSize, quoteLotSize } = calculateLotSizes( baseDecimals, quoteDecimals, minTick, minSize, ); return { maintLeverage: leverage * 2, initLeverage: leverage, liquidationFee: 1 / (leverage * 4), makerFee: -0.0004, takerFee: 0.0005, baseLotSize: baseLotSize.toNumber(), quoteLotSize: quoteLotSize.toNumber(), rate: 0.03, maxDepthBps, exp: 2, maxNumEvents: 256, targetPeriodLength: 3600, mngoPerPeriod: mngoPerHour, version: 1, lmSizeShift, decimals: baseDecimals, minTick, minSize, baseDecimals, }; }
the_stack
declare module com { export module google { export module android { export module gms { export module dynamite { export module descriptors { export module com { export module google { export module android { export module gms { export module vision { export module dynamite { export module face { export class ModuleDescriptor { public static class: java.lang.Class<com.google.android.gms.dynamite.descriptors.com.google.android.gms.vision.dynamite.face.ModuleDescriptor>; public static MODULE_ID: string; public static MODULE_VERSION: number; public constructor(); } } } } } } } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzbl extends java.lang.Object /* com.google.android.gms.internal.vision.zzgb*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzbl>; public static values(): any /* native.Array<com.google.android.gms.internal.vision.zzbl>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzbm extends java.lang.Object /* com.google.android.gms.internal.vision.zzgc<com.google.android.gms.internal.vision.zzbl>*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzbm>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzbn { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzbn>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzbo extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzbo,com.google.android.gms.internal.vision.zzbo.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzbo>; } export module zzbo { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzbo,com.google.android.gms.internal.vision.zzbo.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzbo.zza>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzbp { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzbp>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzbq extends java.lang.Object /* com.google.android.gms.internal.vision.zzgb*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzbq>; public static values(): any /* native.Array<com.google.android.gms.internal.vision.zzbq>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzbr extends java.lang.Object /* com.google.android.gms.internal.vision.zzgc<com.google.android.gms.internal.vision.zzbq>*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzbr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzbs { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzbs>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzca { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca>; } export module zzca { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzca.zza,com.google.android.gms.internal.vision.zzca.zza.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zza>; } export module zza { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzca.zza,com.google.android.gms.internal.vision.zzca.zza.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zza.zza>; } } export class zzb extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzca.zzb,com.google.android.gms.internal.vision.zzca.zzb.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzb>; } export module zzb { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzca.zzb,com.google.android.gms.internal.vision.zzca.zzb.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzb.zza>; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzca.zzb.zzb,com.google.android.gms.internal.vision.zzca.zzb.zzb.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzb.zzb>; public getY(): number; public getX(): number; } export module zzb { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzca.zzb.zzb,com.google.android.gms.internal.vision.zzca.zzb.zzb.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzb.zzb.zza>; } } export class zzc extends java.lang.Object /* com.google.android.gms.internal.vision.zzgb*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzb.zzc>; public static values(): any /* native.Array<com.google.android.gms.internal.vision.zzca.zzb.zzc>*/; } } export class zzc extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzca.zzc,com.google.android.gms.internal.vision.zzca.zzc.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzc>; } export module zzc { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzca.zzc,com.google.android.gms.internal.vision.zzca.zzc.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzc.zza>; } } export class zzd extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzca.zzd,com.google.android.gms.internal.vision.zzca.zzd.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzd>; } export module zzd { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzca.zzd,com.google.android.gms.internal.vision.zzca.zzd.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzd.zza>; } } export class zze extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzca.zze,com.google.android.gms.internal.vision.zzca.zze.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zze>; } export module zze { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzca.zze,com.google.android.gms.internal.vision.zzca.zze.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zze.zza>; } } export class zzf extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzca.zzf,com.google.android.gms.internal.vision.zzca.zzf.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzf>; } export module zzf { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzca.zzf,com.google.android.gms.internal.vision.zzca.zzf.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzf.zza>; } } export class zzg extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzca.zzg,com.google.android.gms.internal.vision.zzca.zzg.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzg>; } export module zzg { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzca.zzg,com.google.android.gms.internal.vision.zzca.zzg.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzca.zzg.zza>; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzcb { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzcb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzcc extends java.lang.Object /* com.google.android.gms.internal.vision.zzgb*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzcc>; public static values(): any /* native.Array<com.google.android.gms.internal.vision.zzcc>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzcd extends java.lang.Object /* com.google.android.gms.internal.vision.zzgc<com.google.android.gms.internal.vision.zzcc>*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzcd>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzce { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzce>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzcf extends java.lang.Object /* com.google.android.gms.internal.vision.zzgc<com.google.android.gms.internal.vision.zzca.zzb.zzc>*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzcf>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzcg { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzcg>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzch extends java.lang.Object /* com.google.android.gms.internal.vision.zzgb*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzch>; public static values(): any /* native.Array<com.google.android.gms.internal.vision.zzch>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzci extends java.lang.Object /* com.google.android.gms.internal.vision.zzgc<com.google.android.gms.internal.vision.zzch>*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzci>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzcj { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzcj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzck extends java.lang.Object /* com.google.android.gms.internal.vision.zzgb*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzck>; public static values(): any /* native.Array<com.google.android.gms.internal.vision.zzck>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzcl extends java.lang.Object /* com.google.android.gms.internal.vision.zzgc<com.google.android.gms.internal.vision.zzck>*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzcl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzcm { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzcm>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzjx extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zzd<com.google.android.gms.internal.vision.zzjx,com.google.android.gms.internal.vision.zzjx.zzc>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx>; } export module zzjx { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzjx.zza,com.google.android.gms.internal.vision.zzjx.zza.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zza>; public getConfidence(): number; public getName(): string; } export module zza { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzjx.zza,com.google.android.gms.internal.vision.zzjx.zza.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zza.zza>; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.vision.zzgb*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zza.zzb>; public static values(): any /* native.Array<com.google.android.gms.internal.vision.zzjx.zza.zzb>*/; } } export class zzb extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzjx.zzb,com.google.android.gms.internal.vision.zzjx.zzb.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zzb>; } export module zzb { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzjx.zzb,com.google.android.gms.internal.vision.zzjx.zzb.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zzb.zza>; } } export class zzc extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zzc<com.google.android.gms.internal.vision.zzjx,com.google.android.gms.internal.vision.zzjx.zzc>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zzc>; } export class zzd extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzjx.zzd,com.google.android.gms.internal.vision.zzjx.zzd.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zzd>; } export module zzd { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzjx.zzd,com.google.android.gms.internal.vision.zzjx.zzd.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zzd.zza>; } } export class zze extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzjx.zze,com.google.android.gms.internal.vision.zzjx.zze.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zze>; public getX(): number; public getY(): number; } export module zze { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzjx.zze,com.google.android.gms.internal.vision.zzjx.zze.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zze.zza>; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.vision.zzgb*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zze.zzb>; public static values(): any /* native.Array<com.google.android.gms.internal.vision.zzjx.zze.zzb>*/; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.vision.zzgb*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjx.zze.zzc>; public static values(): any /* native.Array<com.google.android.gms.internal.vision.zzjx.zze.zzc>*/; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzjy { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjy>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzjz extends java.lang.Object /* com.google.android.gms.internal.vision.zzgc<com.google.android.gms.internal.vision.zzjx.zza.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzjz>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzka { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzka>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzkb extends java.lang.Object /* com.google.android.gms.internal.vision.zzgc<com.google.android.gms.internal.vision.zzjx.zze.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzkb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzkc { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzkc>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzkd extends java.lang.Object /* com.google.android.gms.internal.vision.zzgc<com.google.android.gms.internal.vision.zzjx.zze.zzc>*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzkd>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzke { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzke>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzkf extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy<com.google.android.gms.internal.vision.zzkf,com.google.android.gms.internal.vision.zzkf.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzkf>; } export module zzkf { export class zza extends java.lang.Object /* com.google.android.gms.internal.vision.zzfy.zza<com.google.android.gms.internal.vision.zzkf,com.google.android.gms.internal.vision.zzkf.zza>*/ implements any /* com.google.android.gms.internal.vision.zzhh*/ { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzkf.zza>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzkg { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzkg>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module vision { export class zzl { public static class: java.lang.Class<com.google.android.gms.internal.vision.zzl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module vision { export module face { export abstract class ChimeraNativeBaseFaceDetectorCreator { public static class: java.lang.Class<com.google.android.gms.vision.face.ChimeraNativeBaseFaceDetectorCreator>; public constructor(); public newFaceDetector(param0: com.google.android.gms.dynamic.IObjectWrapper, param1: any /* com.google.android.gms.vision.face.internal.client.zze*/): any /* com.google.android.gms.vision.face.internal.client.zzg*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module vision { export module face { export class ChimeraNativeFaceDetectorCreator extends com.google.android.gms.vision.face.ChimeraNativeBaseFaceDetectorCreator { public static class: java.lang.Class<com.google.android.gms.vision.face.ChimeraNativeFaceDetectorCreator>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module vision { export module face { export class FaceDetectorV2Jni { public static class: java.lang.Class<com.google.android.gms.vision.face.FaceDetectorV2Jni>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module vision { export module face { export class NativeFaceDetectorImpl { public static class: java.lang.Class<com.google.android.gms.vision.face.NativeFaceDetectorImpl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module vision { export module face { export class NativeFaceDetectorV2Creator extends com.google.android.gms.vision.face.ChimeraNativeBaseFaceDetectorCreator { public static class: java.lang.Class<com.google.android.gms.vision.face.NativeFaceDetectorV2Creator>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module vision { export module face { export class NativeFaceDetectorV2Impl { public static class: java.lang.Class<com.google.android.gms.vision.face.NativeFaceDetectorV2Impl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module vision { export module face { export class NativeFaceSettings { public static class: java.lang.Class<com.google.android.gms.vision.face.NativeFaceSettings>; public detectionType: number; public landmarkType: number; public confidenceThreshold: number; public fastDetectorAggressiveness: number; public maxNumFaces: number; public proportionalMinFaceSize: number; public trackingEnabled: boolean; public classifyEyesOpen: boolean; public classifySmiling: boolean; public numThreads: number; public constructor(); } } } } } } } //Generics information:
the_stack
import type { Mount } from '@opentrons/components' import { MAGNETIC_MODULE_TYPE, TEMPERATURE_MODULE_TYPE, THERMOCYCLER_MODULE_TYPE, } from '@opentrons/shared-data' import type { LabwareDefinition2, ModuleType, ModuleModel, PipetteNameSpecs, PipetteName, } from '@opentrons/shared-data' import type { AtomicProfileStep, EngageMagnetParams, ModuleOnlyParams, } from '@opentrons/shared-data/protocol/types/schemaV4' import type { Command } from '@opentrons/shared-data/protocol/types/schemaV5Addendum' import type { TEMPERATURE_DEACTIVATED, TEMPERATURE_AT_TARGET, TEMPERATURE_APPROACHING_TARGET, } from './constants' export type { Command } // Copied from PD export type DeckSlot = string type THERMOCYCLER_STATE = 'thermocyclerState' type THERMOCYCLER_PROFILE = 'thermocyclerProfile' export interface LabwareTemporalProperties { slot: DeckSlot } export interface PipetteTemporalProperties { mount: Mount } export interface MagneticModuleState { type: typeof MAGNETIC_MODULE_TYPE engaged: boolean } export type TemperatureStatus = | typeof TEMPERATURE_DEACTIVATED | typeof TEMPERATURE_AT_TARGET | typeof TEMPERATURE_APPROACHING_TARGET export interface TemperatureModuleState { type: typeof TEMPERATURE_MODULE_TYPE status: TemperatureStatus targetTemperature: number | null } export interface ThermocyclerModuleState { type: typeof THERMOCYCLER_MODULE_TYPE blockTargetTemp: number | null // null means block is deactivated lidTargetTemp: number | null // null means lid is deactivated lidOpen: boolean | null // if false, closed. If null, unknown } export interface ModuleTemporalProperties { slot: DeckSlot moduleState: | MagneticModuleState | TemperatureModuleState | ThermocyclerModuleState } export interface LabwareEntity { id: string labwareDefURI: string def: LabwareDefinition2 } export interface LabwareEntities { [labwareId: string]: LabwareEntity } export interface ModuleEntity { id: string type: ModuleType model: ModuleModel } export interface ModuleEntities { [moduleId: string]: ModuleEntity } export interface NormalizedPipetteById { [pipetteId: string]: { name: PipetteName id: string tiprackDefURI: string } } export type NormalizedPipette = NormalizedPipetteById[keyof NormalizedPipetteById] // "entities" have only properties that are time-invariant // when they are de-normalized, the definitions they reference are baked in // =========== PIPETTES ======== export type PipetteEntity = NormalizedPipette & { tiprackLabwareDef: LabwareDefinition2 spec: PipetteNameSpecs } export interface PipetteEntities { [pipetteId: string]: PipetteEntity } // ===== MIX-IN TYPES ===== export type ChangeTipOptions = | 'always' | 'once' | 'never' | 'perDest' | 'perSource' export interface InnerMixArgs { volume: number times: number } export interface InnerDelayArgs { seconds: number mmFromBottom: number } interface CommonArgs { /** Optional user-readable name for this step */ name: string | null | undefined /** Optional user-readable description/notes for this step */ description: string | null | undefined } // ===== Processed form types. Used as args to call command creator fns ===== export type SharedTransferLikeArgs = CommonArgs & { pipette: string // PipetteId sourceLabware: string destLabware: string /** volume is interpreted differently by different Step types */ volume: number // ===== ASPIRATE SETTINGS ===== /** Pre-wet tip with ??? uL liquid from the first source well. */ preWetTip: boolean /** Touch tip after every aspirate */ touchTipAfterAspirate: boolean /** Optional offset for touch tip after aspirate (if null, use PD default) */ touchTipAfterAspirateOffsetMmFromBottom: number /** changeTip is interpreted differently by different Step types */ changeTip: ChangeTipOptions /** Delay after every aspirate */ aspirateDelay: InnerDelayArgs | null | undefined /** Air gap after every aspirate */ aspirateAirGapVolume: number | null /** Flow rate in uL/sec for all aspirates */ aspirateFlowRateUlSec: number /** offset from bottom of well in mm */ aspirateOffsetFromBottomMm: number // ===== DISPENSE SETTINGS ===== /** Air gap after dispense */ dispenseAirGapVolume: number | null /** Delay after every dispense */ dispenseDelay: InnerDelayArgs | null | undefined /** Touch tip in destination well after dispense */ touchTipAfterDispense: boolean /** Optional offset for touch tip after dispense (if null, use PD default) */ touchTipAfterDispenseOffsetMmFromBottom: number /** Flow rate in uL/sec for all dispenses */ dispenseFlowRateUlSec: number /** offset from bottom of well in mm */ dispenseOffsetFromBottomMm: number } export type ConsolidateArgs = SharedTransferLikeArgs & { commandCreatorFnName: 'consolidate' sourceWells: string[] destWell: string /** If given, blow out in the specified destination after dispense at the end of each asp-asp-dispense cycle */ blowoutLocation: string | null | undefined blowoutFlowRateUlSec: number blowoutOffsetFromTopMm: number /** Mix in first well in chunk */ mixFirstAspirate: InnerMixArgs | null | undefined /** Mix in destination well after dispense */ mixInDestination: InnerMixArgs | null | undefined } export type TransferArgs = SharedTransferLikeArgs & { commandCreatorFnName: 'transfer' sourceWells: string[] destWells: string[] /** If given, blow out in the specified destination after dispense at the end of each asp-dispense cycle */ blowoutLocation: string | null | undefined blowoutFlowRateUlSec: number blowoutOffsetFromTopMm: number /** Mix in first well in chunk */ mixBeforeAspirate: InnerMixArgs | null | undefined /** Mix in destination well after dispense */ mixInDestination: InnerMixArgs | null | undefined } export type DistributeArgs = SharedTransferLikeArgs & { commandCreatorFnName: 'distribute' sourceWell: string destWells: string[] /** Disposal volume is added to the volume of the first aspirate of each asp-asp-disp cycle */ disposalVolume: number | null | undefined /** pass to blowout **/ /** If given, blow out in the specified destination after dispense at the end of each asp-dispense cycle */ blowoutLocation: string | null | undefined blowoutFlowRateUlSec: number blowoutOffsetFromTopMm: number /** Mix in first well in chunk */ mixBeforeAspirate: InnerMixArgs | null | undefined } export type MixArgs = CommonArgs & { commandCreatorFnName: 'mix' labware: string pipette: string wells: string[] /** Mix volume (should not exceed pipette max) */ volume: number /** Times to mix (should be integer) */ times: number /** Touch tip after mixing */ touchTip: boolean touchTipMmFromBottom: number /** change tip: see comments in step-generation/mix.js */ changeTip: ChangeTipOptions /** If given, blow out in the specified destination after mixing each well */ blowoutLocation: string | null | undefined blowoutFlowRateUlSec: number blowoutOffsetFromTopMm: number /** offset from bottom of well in mm */ aspirateOffsetFromBottomMm: number dispenseOffsetFromBottomMm: number /** flow rates in uL/sec */ aspirateFlowRateUlSec: number dispenseFlowRateUlSec: number /** delays */ aspirateDelaySeconds: number | null | undefined dispenseDelaySeconds: number | null | undefined } export type PauseArgs = CommonArgs & { commandCreatorFnName: 'delay' message?: string wait: number | true pauseTemperature?: number | null meta: | { hours?: number minutes?: number seconds?: number } | null | undefined } export interface AwaitTemperatureArgs { module: string | null commandCreatorFnName: 'awaitTemperature' temperature: number message?: string } export type EngageMagnetArgs = EngageMagnetParams & { module: string commandCreatorFnName: 'engageMagnet' message?: string } export type DisengageMagnetArgs = ModuleOnlyParams & { module: string commandCreatorFnName: 'disengageMagnet' message?: string } export interface SetTemperatureArgs { module: string | null commandCreatorFnName: 'setTemperature' targetTemperature: number message?: string } export interface DeactivateTemperatureArgs { module: string | null commandCreatorFnName: 'deactivateTemperature' message?: string } const PROFILE_CYCLE: 'profileCycle' = 'profileCycle' const PROFILE_STEP: 'profileStep' = 'profileStep' interface ProfileStepItem { type: typeof PROFILE_STEP id: string title: string temperature: string durationMinutes: string durationSeconds: string } interface ProfileCycleItem { type: typeof PROFILE_CYCLE id: string steps: ProfileStepItem[] repetitions: string } // TODO IMMEDIATELY: ProfileStepItem -> ProfileStep, ProfileCycleItem -> ProfileCycle export type ProfileItem = ProfileStepItem | ProfileCycleItem export interface ThermocyclerProfileStepArgs { module: string commandCreatorFnName: THERMOCYCLER_PROFILE blockTargetTempHold: number | null lidOpenHold: boolean lidTargetTempHold: number | null message?: string profileSteps: AtomicProfileStep[] profileTargetLidTemp: number profileVolume: number meta?: { rawProfileItems: ProfileItem[] } } export interface ThermocyclerStateStepArgs { module: string commandCreatorFnName: THERMOCYCLER_STATE blockTargetTemp: number | null lidTargetTemp: number | null lidOpen: boolean message?: string } export type CommandCreatorArgs = | ConsolidateArgs | DistributeArgs | MixArgs | PauseArgs | TransferArgs | EngageMagnetArgs | DisengageMagnetArgs | SetTemperatureArgs | AwaitTemperatureArgs | DeactivateTemperatureArgs | ThermocyclerProfileStepArgs | ThermocyclerStateStepArgs export interface LocationLiquidState { [ingredGroup: string]: { volume: number } } export interface SingleLabwareLiquidState { [well: string]: LocationLiquidState } export interface LabwareLiquidState { [labwareId: string]: SingleLabwareLiquidState } export interface SourceAndDest { source: LocationLiquidState dest: LocationLiquidState } // Data that never changes across time export interface Config { OT_PD_DISABLE_MODULE_RESTRICTIONS: boolean } export interface InvariantContext { labwareEntities: LabwareEntities moduleEntities: ModuleEntities pipetteEntities: PipetteEntities config: Config } // TODO Ian 2018-02-09 Rename this so it's less ambigious with what we call "robot state": `TimelineFrame`? export interface RobotState { pipettes: { [pipetteId: string]: PipetteTemporalProperties } labware: { [labwareId: string]: LabwareTemporalProperties } modules: { [moduleId: string]: ModuleTemporalProperties } tipState: { tipracks: { [labwareId: string]: { [wellName: string]: boolean // true if tip is in there } } pipettes: { [pipetteId: string]: boolean // true if pipette has tip(s) } } liquidState: { pipettes: { [pipetteId: string]: { /** tips are numbered 0-7. 0 is the furthest to the back of the robot. * For an 8-channel, on a 96-flat, Tip 0 is in row A, Tip 7 is in row H. */ [tipId: string]: LocationLiquidState } } labware: { [labwareId: string]: { [well: string]: LocationLiquidState } } } } export type ErrorType = | 'INSUFFICIENT_TIPS' | 'LABWARE_DOES_NOT_EXIST' | 'MISMATCHED_SOURCE_DEST_WELLS' | 'MISSING_MODULE' | 'MODULE_PIPETTE_COLLISION_DANGER' | 'NO_TIP_ON_PIPETTE' | 'PIPETTE_DOES_NOT_EXIST' | 'PIPETTE_VOLUME_EXCEEDED' | 'TIP_VOLUME_EXCEEDED' | 'MISSING_TEMPERATURE_STEP' | 'THERMOCYCLER_LID_CLOSED' | 'INVALID_SLOT' export interface CommandCreatorError { message: string type: ErrorType } export type WarningType = | 'ASPIRATE_MORE_THAN_WELL_CONTENTS' | 'ASPIRATE_FROM_PRISTINE_WELL' export interface CommandCreatorWarning { message: string type: WarningType } export interface CommandsAndRobotState { commands: Command[] robotState: RobotState warnings?: CommandCreatorWarning[] } export interface CommandCreatorErrorResponse { errors: CommandCreatorError[] warnings?: CommandCreatorWarning[] } export interface CommandsAndWarnings { commands: Command[] warnings?: CommandCreatorWarning[] } export type CommandCreatorResult = | CommandsAndWarnings | CommandCreatorErrorResponse export type CommandCreator<Args> = ( args: Args, invariantContext: InvariantContext, prevRobotState: RobotState ) => CommandCreatorResult export type CurriedCommandCreator = ( invariantContext: InvariantContext, prevRobotState: RobotState ) => CommandCreatorResult export interface Timeline { timeline: CommandsAndRobotState[] // TODO: Ian 2018-06-14 avoid timeline.timeline shape, better names errors?: CommandCreatorError[] | null } export interface RobotStateAndWarnings { robotState: RobotState warnings: CommandCreatorWarning[] } // Copied from PD export type WellOrderOption = 'l2r' | 'r2l' | 't2b' | 'b2t'
the_stack
import React, {useState, useEffect, useCallback, useReducer} from 'react'; import { NativeEventEmitter, ScrollView, Text, View, Alert, StyleSheet } from 'react-native'; import {format} from 'date-fns'; import ExposureNotification, { useExposure, getConfigData, CloseContact } from 'react-native-exposure-notification-service'; import * as SecureStore from 'expo-secure-store'; import {Button} from '../../atoms/button'; import Layouts from '../../../theme/layouts'; import {useApplication} from '../../../providers/context'; import {useSettings} from '../../../providers/settings'; import {useCheckinReminder} from '../../../providers/reminders/checkin-reminder'; import {usePause} from '../../../providers/reminders/pause-reminder'; import {useExposureReminder} from '../../../providers/reminders/exposure-reminder'; import {useCaseReminder} from '../../../providers/reminders/case-reminder'; import {ReminderState} from '../../../providers/reminders/reminder'; import AsyncStorage from '@react-native-community/async-storage'; //import {showRiskyVenueNotification} from '../../../venue-check-in'; const emitter = new NativeEventEmitter(ExposureNotification); type StateData = null | Record<string, any>; interface DebugEvent { status?: any; scheduledTask?: any; } const testRecaptchaKey = 'debug.test-recaptcha'; export const Debug = () => { const exposure = useExposure(); const app = useApplication(); const settings = useSettings(); const [, forceUpdate] = useReducer((x: number) => x + 1, 0); const [events, setEvents] = useState<DebugEvent[]>([]); const [contacts, setContacts] = useState<CloseContact[]>([]); const [logData, setLogData] = useState<StateData>(null); const [configData, setConfigData] = useState<StateData>(null); const [appData, setAppData] = useState<StateData>(null); const [testRecaptcha, setTestRecaptcha] = useState(false); useEffect(() => { const loadTestRecaptcha = async () => { const isTestRecaptchaOn = await AsyncStorage.getItem(testRecaptchaKey); setTestRecaptcha(!!isTestRecaptchaOn); }; loadTestRecaptcha(); }, []); const testRecaptchaOn = async () => { await AsyncStorage.setItem(testRecaptchaKey, 'y'); Alert.alert( 'Recaptcha testing on', 'After using "Leave" (but not after uninstall), recaptcha will be required on signup' ); setTestRecaptcha(true); }; const testRecaptchaOff = async () => { await AsyncStorage.removeItem(testRecaptchaKey); Alert.alert( 'Recaptcha testing off', 'Recaptcha will no longer be required when signing up' ); setTestRecaptcha(false); }; const testRecaptchaLabel = `${ testRecaptcha ? 'Stop' : 'Start' } requiring recaptcha`; const toggleRecaptcha = testRecaptcha ? testRecaptchaOff : testRecaptchaOn; const loadData = useCallback(async () => { const newContacts = await exposure.getCloseContacts(); const config = await getConfigData(); const newLogData = await exposure.getLogData(); const refreshToken = await SecureStore.getItemAsync('refreshToken'); const authToken = await SecureStore.getItemAsync('token'); const appInfo = { userValid: app.user?.valid, onboarded: app.completedExposureOnboarding, refreshToken, authToken }; setAppData(appInfo); const runDates = newLogData.lastRun; if (runDates && typeof runDates === 'string') { const dates = runDates .replace(/^,/, '') .split(',') .map((d) => { return format(parseInt(d, 10), 'dd/MM HH:mm:ss'); }); newLogData.lastRun = dates.join(', '); } else { newLogData.lastRun ? format(newLogData.lastRun, 'dd/MM HH:mm:ss') : 'Unknown'; } setLogData(newLogData); setConfigData(config); console.log('logdata', newLogData); console.log( 'has api message', Boolean(newLogData.lastApiError && newLogData.lastApiError.length) ); setContacts(newContacts); console.log('contacts', newContacts); }, [setLogData, setContacts]); const checkinReminder = useCheckinReminder(); const pauseReminder = usePause(); const exposureReminder = useExposureReminder(); const caseReminder = useCaseReminder(); const getReminderDebugInfo = (rs: Partial<ReminderState>) => ({ active: rs.active, timestamp: rs.timestamp, readable_time: rs.timestamp ? format(rs.timestamp, 'dd/MMM HH:mm:ss') : '' }); const reminderDebugInfo = { checkin: getReminderDebugInfo(checkinReminder), pause: getReminderDebugInfo(pauseReminder), exposure: { reminder: getReminderDebugInfo(exposureReminder.exposureReminderState), restrictionEnd: getReminderDebugInfo(exposureReminder.restrictionEndState) }, case: { reminder: getReminderDebugInfo(caseReminder.caseReminderState) } }; useEffect(() => { loadData(); }, [loadData]); function handleEvent(ev: DebugEvent = {}) { events.push(ev); setEvents([...events]); } const checkExposure = async () => { try { setEvents([]); subscription.remove(); emitter.removeListener('exposureEvent', handleEvent); } catch (e) {} let subscription = emitter.addListener('exposureEvent', handleEvent); await exposure.checkExposure(true); }; useEffect(() => { function handleSilentEvent(ev: Record<string, any>) { if (ev.exposure || (ev.info && ev.info.includes('saveDailyMetric'))) { loadData(); } } let subscription = emitter.addListener('exposureEvent', handleSilentEvent); return () => { try { subscription.remove(); } catch (e) { console.log('Remove error', e); } }; }, []); const simulateExposure = async () => { exposure.simulateExposure(3, 6); }; const deleteAllData = async () => { Alert.alert('Delete Data', 'Are you asure you want to delete all data.', [ { text: 'No', onPress: () => console.log('No Pressed'), style: 'cancel' }, { text: 'Yes', onPress: async () => { await exposure.deleteAllData(); setEvents([]); setContacts([]); setLogData(null); setAppData(null); setConfigData(null); await exposure.configure(); // reconfigure as delete all deletes sharedprefs on android }, style: 'cancel' } ]); }; /* const checkRiskyVenues = () => { showRiskyVenueNotification(); }; */ const simulateUpload = () => { app.setContext({uploadDate: Date.now()}); }; const displayContact = (contact: CloseContact) => { const displayData = [ `Alert: ${format(contact.exposureAlertDate, 'dd/MM HH:mm')}`, `Contact: ${format(contact.exposureDate, 'dd/MM')}`, `Score: ${contact.maxRiskScore}`, `Keys: ${contact.matchedKeyCount}`, `Durations: ${contact.attenuationDurations}`, `maximumRiskScoreFullRange: ${contact.maxRiskScoreFullRange}`, `riskScoreSumFullRange: ${contact.riskScoreSumFullRange}` ]; if (contact.windows) { contact.windows.forEach((d) => { displayData.push(`When: ${format(d.date, 'dd/MM')}`); displayData.push(`calibrationConfidence: ${d.calibrationConfidence}`); displayData.push(`diagnosisReportType: ${d.diagnosisReportType}`); displayData.push(`infectiousness: ${d.infectiousness}`); displayData.push(`buckets: ${d.buckets}`); displayData.push(`weightedBuckets: ${d.weightedBuckets}`); displayData.push(`numScans: ${d.numScans}`); displayData.push(`exceedsThreshold: ${d.exceedsThreshold}`); }); } Alert.alert('Exposure Details', displayData.join('\n'), [ { text: 'OK', onPress: () => console.log('OK Pressed'), style: 'cancel' } ]); }; const listContactInfo = (contact: CloseContact) => { return `Alert: ${format( contact.exposureAlertDate, 'dd/MM HH:mm' )}, Contact: ${format(contact.exposureDate, 'dd/MM')}, Score: ${ contact.maxRiskScore }, Keys: ${contact.matchedKeyCount} ${contact.windows ? ', *' : ''}`; }; const oldLength = settings.appConfig.codeLength; const newLength = oldLength === 6 ? 8 : 6; const changeCodeLengthLabel = `Switch to ${newLength}-digit codes`; const changeCodeLength = () => { settings.appConfig.codeLength = newLength; // Alert.prompt doesn't work on Android, just toggle 6 to 8 Alert.alert( `Code length now ${settings.appConfig.codeLength}`, 'This is temporary and will revert to server settings if the app is closed or left in the background long enough for settings to be reloaded.' ); forceUpdate(); }; return ( <Layouts.Basic heading="Debug"> <ScrollView> <Button type="danger" onPress={checkExposure}> Check Exposure </Button> <Button type="danger" onPress={simulateExposure}> Simulate Exposure </Button> <Button type="danger" onPress={simulateUpload}> Simulate Upload Keys </Button> <Button type="danger" onPress={deleteAllData}> Delete All Data </Button> {/*<Button type="default" onPress={checkRiskyVenues}> Check Risky Venues </Button>*/} <Button type="default" onPress={changeCodeLength}> {changeCodeLengthLabel} </Button> <Button type="default" onPress={toggleRecaptcha}> {testRecaptchaLabel} </Button> {logData && ( <View style={styles.logScroll}> <ScrollView style={styles.contactsScroll} nestedScrollEnabled={true}> {logData.installedPlayServicesVersion > 0 && ( <Text> Play Services Version: {logData.installedPlayServicesVersion} </Text> )} {logData.nearbyApiSupported === true || (logData.nearbyApiSupported === false && ( <Text> Exposure API Supported: {`${logData.nearbyApiSupported}`} </Text> ))} {<Text>Last Index: {logData.lastIndex}</Text>} {<Text>Last Ran: {logData.lastRun}</Text>} {Boolean(logData.lastError && logData.lastError.length) && ( <Text selectable={true}> Last Message: {`${logData.lastError}`} </Text> )} {Boolean(logData.lastApiError && logData.lastApiError.length) && ( <Text selectable={true}> Last Exposure API Error: {`${logData.lastApiError}`} </Text> )} </ScrollView> </View> )} {settings && ( <> <View style={styles.contacts}> <Text selectable={true} style={styles.title}> Settings </Text> </View> <ScrollView style={styles.contactsScroll}> <Text selectable={true}> {JSON.stringify( { loaded: settings.loaded, loadedTime: settings.loadedTime ? { timestamp: settings.loadedTime.getTime(), readable: format( settings.loadedTime, 'dd/MMM HH:mm:ss' ) } : settings.loadedTime }, null, 2 )} {JSON.stringify( { appConfig: settings.appConfig, user: settings.user, traceConfiguration: settings.traceConfiguration }, null, 2 )} </Text> </ScrollView> </> )} {appData && ( <> <View style={styles.contacts}> <Text selectable={true} style={styles.title}> App Config </Text> </View> <ScrollView style={styles.appInfo} nestedScrollEnabled={true}> <Text selectable={true}>{JSON.stringify(appData, null, 2)}</Text> </ScrollView> </> )} {configData && ( <> <View style={styles.contacts}> <Text selectable={true} style={styles.title}> Module Config </Text> </View> <ScrollView style={styles.appInfo} nestedScrollEnabled={true}> <Text selectable={true}> {JSON.stringify(configData, null, 2)} </Text> </ScrollView> </> )} <View style={styles.contacts}> <Text selectable={true} style={styles.title}> Reminders </Text> </View> <ScrollView style={styles.appInfo} nestedScrollEnabled={true}> <Text selectable={true}> {JSON.stringify(reminderDebugInfo, null, 2)} </Text> </ScrollView> <View style={styles.contacts}> <Text style={styles.title}>Contacts</Text> </View> <ScrollView style={styles.contactInfo} nestedScrollEnabled={true}> {contacts && contacts.map((c, index) => ( <Text key={index} style={styles.row} onPress={() => displayContact(c)}> {listContactInfo(c)} </Text> ))} </ScrollView> <View style={styles.contacts}> <Text selectable={true} style={styles.title}> Logs </Text> </View> <ScrollView style={styles.eventsScroll} nestedScrollEnabled={true}> <Text selectable={true}>{JSON.stringify(events, null, 2)}</Text> </ScrollView> </ScrollView> </Layouts.Basic> ); }; const styles = StyleSheet.create({ stats: { marginTop: 24, paddingTop: 8, borderTopWidth: 1 }, contacts: { marginTop: 12, borderTopWidth: 1 }, appInfo: { height: 200 }, logScroll: { height: 150 }, contactInfo: { height: 100 }, eventsScroll: { height: 450 }, contactsScroll: { height: 100 }, title: { fontSize: 24, marginBottom: 12 }, row: { height: 28 } });
the_stack
import {Component, Inject, Input, OnInit} from '@angular/core'; import {Agent} from "../../../agents/models/agent.model"; import {Page} from "../../models/page"; import {AgentService} from "../../../agents/services/agent.service"; import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms'; import {AgentDevice} from "../../../agents/models/agent-device.model"; import {UploadService} from "../../services/upload.service"; import {Upload} from "../../models/upload.model"; import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from '@angular/material/dialog'; import {WorkspaceVersion} from "../../../models/workspace-version.model"; import {WorkspaceVersionService} from "../../services/workspace-version.service"; import {MirroringData} from "../../../agents/models/mirroring-data.model"; import {WorkspaceType} from "../../../enums/workspace-type.enum"; import {MobileOsVersionService} from "../../../agents/services/mobile-os-version.service"; import {CloudDevice} from "../../../agents/models/cloud-device.model"; import {AuthenticationGuard} from "../../guards/authentication.guard"; import {BaseComponent} from "../base.component"; import {NotificationsService} from 'angular2-notifications'; import {TranslateService} from '@ngx-translate/core'; import {ToastrService} from "ngx-toastr"; import {MobileOsType} from "../../../agents/enums/mobile-os-type.enum"; import {TestPlanLabType} from "../../../enums/test-plan-lab-type.enum"; import {PlatformService} from "../../../agents/services/platform.service"; import {PlatformOsVersion} from "../../../agents/models/platform-os-version.model"; import {Platform} from "../../../agents/models/platform.model"; import {Pageable} from "../../models/pageable"; import {UploadType} from "../../enums/upload-type.enum"; import {ActivatedRoute, Params} from "@angular/router"; import {MobileInspectionComponent} from "../../../agents/components/webcomponents/mobile-inspection.component"; @Component({ selector: 'app-inspection-modal', templateUrl: './inspection-modal.component.html', host: {'class': 'ts-col-100'}, }) export class InspectionModalComponent extends BaseComponent implements OnInit { @Input('elementInspection') elementInspection: boolean; @Input('versionId') versionId: number; @Input('uiId') uiId: number; public physicalDeviceForm: FormGroup; public manuallyInstalledAppForm: FormGroup; public uploadSelectionForm: FormGroup; public agents: Page<Agent>; public devices: Page<AgentDevice>; public uploads: Page<Upload>; public isPhysicalDevice: Boolean = true; public isManually: Boolean; public version: WorkspaceVersion; public platformOsVersions: PlatformOsVersion[]; public isPhysicalDeviceSupported: Boolean = true; public formSubmitted: boolean; public appSubmitted: boolean; public workspaceType = WorkspaceType; public mobileOsType: MobileOsType; public launchAllowed: boolean = false; public agentChecksFailed: boolean = false; public agentCheckFailedMessage: String; private platForm: Platform; private platForms: Platform[]; public capabilitiesForm: FormGroup; public testsigmaAgentEnabled: boolean = false; public deviceList: Page<AgentDevice>; public isDevicesAvailable: boolean = true; public cloudDevicesPage = new Page<CloudDevice>(); public agentId: number; public platformOsVersion: PlatformOsVersion; public testPlanLabType = TestPlanLabType.TestsigmaLab; public agent: Agent; public platformOsVersionsPage: Page<PlatformOsVersion>; public isContainsApp: boolean = false; public refreshAppUpload: boolean = false; public showUploadDropDown: boolean = true; public upload: Upload; public uploading: boolean = false; public selectedTestsigmaLab:boolean = false; public isStepGroup:boolean; public isStepRecord: Boolean; get showInlineLaunch() { return this.show(this.agentChecksFailed, this.isPhysicalDevice) && this.elementInspection; }; constructor( @Inject(MAT_DIALOG_DATA) public data: MirroringData, public authGuard: AuthenticationGuard, public notificationsService: NotificationsService, public translate: TranslateService, public toastrService: ToastrService, private route: ActivatedRoute, private dialogRef: MatDialogRef<InspectionModalComponent>, private uploadService: UploadService, private mobileOsVersionService: MobileOsVersionService, private workspaceVersionService: WorkspaceVersionService, private agentService: AgentService, private formBuilder: FormBuilder, private matDialog: MatDialog, private platformService: PlatformService) { super(authGuard, notificationsService, translate, toastrService); } ngOnInit() { let id; this.isStepRecord = this.data.isStepRecord; if (this.data.workspaceVersionId == undefined) { id = this.versionId; } else { id = this.data.workspaceVersionId; } this.workspaceVersionService.show(id).subscribe((version) => { this.setInitialData(version); this.fetchPlatForms(); this.initManualInstalledAppForm(); this.fetchUploads(); }); this.initPhysicalDeviceForm(); this.initUploadSelectionForm(); this.addFormControls(); this.isStepGroup = this.route.snapshot.queryParams.isStepRecord; this.route.params.subscribe((params: Params) => { this.data = new MirroringData(); this.data.recording = true; this.data.uiId = null; }); } hasInspectorFeature() { return ( this.version && this.version.workspace.isAndroidNative) || (this.version && this.version.workspace.isIosNative); } get disableRecordButton() { return !this.launchAllowed || !this.showUploadDropDown || this.uploading || (this.uploads && this.uploads.content.length == 0) } public uploadSuccess(event) { if (event) { this.showUploadDropDown = true; this.uploading = false; this.upload = event; this.uploads.content.push(event); } if (this.uploads.content.length == 0 || (this.uploads.content.length > 0 && !event)) { this.showUploadDropDown = true; } } public openUploadForm() { this.showUploadDropDown = false; this.upload = new Upload(); } fetchUploads() { let termQuery = ''; if (this.version.workspace.workspaceType == WorkspaceType.AndroidNative) { termQuery += ",workspaceId:" + this.version.workspace.id; } else { termQuery += ",workspaceId:" + this.version.workspace.id; } this.uploadService.findAll(termQuery, "name").subscribe(res => { this.uploads = res; }); } addFormControls() { this.capabilitiesForm = this.formBuilder.group({}); this.triggerAgentChecks(); } setInitialData(version: WorkspaceVersion) { this.version = version; this.data.workspaceVersion = this.version; this.data.workspaceVersionId = this.version.id; if (this.version.workspace.workspaceType == WorkspaceType.AndroidNative) { this.isManually = false; this.isPhysicalDeviceSupported = true; this.mobileOsType = MobileOsType.ANDROID; } else { this.isManually = false; this.isPhysicalDeviceSupported = true; this.mobileOsType = MobileOsType.IOS; } } get isIOS() { return this.mobileOsType == MobileOsType.IOS; } initPhysicalDeviceForm() { this.physicalDeviceForm = new FormGroup({ deviceId: new FormControl(this.data.device?.id, [Validators.required]) }); } get deviceId() { return this.physicalDeviceForm.controls['deviceId']?.value?.id; } initUploadSelectionForm() { this.uploadSelectionForm = new FormGroup({ app_upload_id: new FormControl(this.data.uploadId, [Validators.required]), upload_version_id: new FormControl(null, []), }); } initManualInstalledAppForm() { this.manuallyInstalledAppForm = new FormGroup({ app_package: new FormControl(this.data.app_package, [this.requiredIfValidator(() => this.version.workspace.isAndroidNative)]), app_activity: new FormControl(this.data.app_activity, [this.requiredIfValidator(() => this.version.workspace.isAndroidNative)]), bundle_id: new FormControl(this.data.bundleId, [this.requiredIfValidator(() => this.version.workspace.isIosNative)]) }); } triggerAgentChecks() { this.agentService.ping().subscribe({ next: (agentInfo) => { if (agentInfo.isRegistered == true) { this.agentService.findByUuid(agentInfo.uniqueId).subscribe({ next: (agent) => { this.agent = agent; this.agentId = agent.id; this.launchAllowed = true; }, error: () => { this.agentChecksFailed = true; this.agentCheckFailedMessage = "agents.not_found"; } }) } else { this.agentChecksFailed = true; this.agentCheckFailedMessage = "agents.not_registered"; } }, error: () => { this.agentChecksFailed = true; this.agentCheckFailedMessage = "agents.unable_to_reach"; } }); } launch() { this.data.uiId = this.uiId; this.data.agent = this.agent; this.data.uploadId = this.uploadSelectionForm.getRawValue().app_upload_id; this.uploadService.find(this.data.uploadId).subscribe((upload) => { this.data.uploadVersionId = this.uploadSelectionForm.getRawValue().upload_version_id || upload.latestVersionId; this.data.os_version = this.platformOsVersion; this.data.isManually = this.isManually; this.data.capabilities = this.capabilitiesForm.getRawValue().capabilities; this.data.testsigmaAgentEnabled = <boolean>this.isPhysicalDevice || this.testsigmaAgentEnabled; console.log("testsigma agent enabled: " + this.data.testsigmaAgentEnabled); this.formSubmitted = true; this.appSubmitted = true if (this.isPhysicalDevice && this.physicalDeviceForm.invalid) { return false; } if (!this.isManually && this.uploadSelectionForm.invalid) { return false } if (this.isManually && this.manuallyInstalledAppForm.invalid) { return false } if (!this.isPhysicalDevice) { this.data.device = null; } this.data.testPlanLabType = this.testPlanLabType; this.dialogRef.close(this.data); if (this.elementInspection) { this.launchRecording(); } }) } launchRecording() { this.matDialog.open(MobileInspectionComponent, { data: this.data, panelClass: ['mat-dialog', 'full-width', 'rds-none', 'w-100', 'h-100'], disableClose: true }); } setAgentDevice(device) { this.data.device = device; } fetchPlatForms() { this.platformService .findAll(this.version.workspace.workspaceType, this.testPlanLabType) .subscribe(res => { this.platForms = res; if (!this.platForm) { this.platForm = this.platForms[0]; } this.fetchOsVersions(); }); } fetchOsVersions(setValue?: Boolean) { this.platformService.findAllOsVersions(this.platForm, this.version.workspace.workspaceType, this.testPlanLabType).subscribe(res => { this.platformOsVersions = res; this.setPlatformOsVersionsPage(); // if (this.settingsFormGroup?.controls['osVersion'].value) //this.platformOsVersion = this.platformOsVersions.find(osVersion => osVersion.version == this.settingsFormGroup?.controls['osVersion'].value) if (!this.platformOsVersion || setValue) { this.platformOsVersion = this.platformOsVersions[0]; } }); } searchPlatforms(term) { this.platformOsVersionsPage = new Page<PlatformOsVersion>(); if (!term) { this.platformOsVersionsPage.content = this.platformOsVersions; } else { this.platformOsVersionsPage.content = this.platformOsVersions.filter(device => { return device.name.toLowerCase().indexOf(term.toLowerCase()) > -1 }); } } setAgent(agent: Agent) { this.agentId = agent.id; this.agent = agent; } setPlatformOsVersionsPage() { let platformsPage = new Page<PlatformOsVersion>(); platformsPage.content = this.platformOsVersions; platformsPage.pageable = new Pageable(); platformsPage.pageable.pageNumber = 0; platformsPage.totalPages = 1; platformsPage.totalElements = this.platformOsVersions?.length; platformsPage.content?.forEach((platform, i) => { platformsPage.content[i].name = platform.displayName; }) this.platformOsVersionsPage = platformsPage; }; setDeviceList($event: Page<AgentDevice>) { this.deviceList = $event; if (this.deviceList?.empty) { this.isDevicesAvailable = false } } openChat() { // @ts-ignore window.fcWidget.open(); } setContainsApp(contains: boolean) { this.isContainsApp = contains; } navigateToUploads() { window.open(`${window.location.origin}/#/td/${this.version?.id}/uploads`, '_blank'); } show(agentCheckFailed: boolean, isPhysicalDevice: Boolean) { if (agentCheckFailed) { this.launchAllowed = true; this.testsigmaAgentEnabled = false; return !isPhysicalDevice; } else { return true; } } settestPlanLabType(testPlanLabType: TestPlanLabType) { if(testPlanLabType == TestPlanLabType.Hybrid){ this.isPhysicalDevice = true; this.formSubmitted=false; this.appSubmitted=false; this.selectedTestsigmaLab = false; return }else if(testPlanLabType == TestPlanLabType.TestsigmaLab){ this.isPhysicalDevice = false; this.formSubmitted=false; this.appSubmitted=false; this.selectedTestsigmaLab = true; } this.isPhysicalDevice = false; this.formSubmitted=false; this.appSubmitted=false; this.isManually=false; this.testPlanLabType = testPlanLabType; this.platformOsVersion = null; this.fetchPlatForms(); } isTestStep(){ return this.isStepGroup; } }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { CreateBotVersionCommand, CreateBotVersionCommandInput, CreateBotVersionCommandOutput, } from "./commands/CreateBotVersionCommand"; import { CreateIntentVersionCommand, CreateIntentVersionCommandInput, CreateIntentVersionCommandOutput, } from "./commands/CreateIntentVersionCommand"; import { CreateSlotTypeVersionCommand, CreateSlotTypeVersionCommandInput, CreateSlotTypeVersionCommandOutput, } from "./commands/CreateSlotTypeVersionCommand"; import { DeleteBotAliasCommand, DeleteBotAliasCommandInput, DeleteBotAliasCommandOutput, } from "./commands/DeleteBotAliasCommand"; import { DeleteBotChannelAssociationCommand, DeleteBotChannelAssociationCommandInput, DeleteBotChannelAssociationCommandOutput, } from "./commands/DeleteBotChannelAssociationCommand"; import { DeleteBotCommand, DeleteBotCommandInput, DeleteBotCommandOutput } from "./commands/DeleteBotCommand"; import { DeleteBotVersionCommand, DeleteBotVersionCommandInput, DeleteBotVersionCommandOutput, } from "./commands/DeleteBotVersionCommand"; import { DeleteIntentCommand, DeleteIntentCommandInput, DeleteIntentCommandOutput, } from "./commands/DeleteIntentCommand"; import { DeleteIntentVersionCommand, DeleteIntentVersionCommandInput, DeleteIntentVersionCommandOutput, } from "./commands/DeleteIntentVersionCommand"; import { DeleteSlotTypeCommand, DeleteSlotTypeCommandInput, DeleteSlotTypeCommandOutput, } from "./commands/DeleteSlotTypeCommand"; import { DeleteSlotTypeVersionCommand, DeleteSlotTypeVersionCommandInput, DeleteSlotTypeVersionCommandOutput, } from "./commands/DeleteSlotTypeVersionCommand"; import { DeleteUtterancesCommand, DeleteUtterancesCommandInput, DeleteUtterancesCommandOutput, } from "./commands/DeleteUtterancesCommand"; import { GetBotAliasCommand, GetBotAliasCommandInput, GetBotAliasCommandOutput } from "./commands/GetBotAliasCommand"; import { GetBotAliasesCommand, GetBotAliasesCommandInput, GetBotAliasesCommandOutput, } from "./commands/GetBotAliasesCommand"; import { GetBotChannelAssociationCommand, GetBotChannelAssociationCommandInput, GetBotChannelAssociationCommandOutput, } from "./commands/GetBotChannelAssociationCommand"; import { GetBotChannelAssociationsCommand, GetBotChannelAssociationsCommandInput, GetBotChannelAssociationsCommandOutput, } from "./commands/GetBotChannelAssociationsCommand"; import { GetBotCommand, GetBotCommandInput, GetBotCommandOutput } from "./commands/GetBotCommand"; import { GetBotsCommand, GetBotsCommandInput, GetBotsCommandOutput } from "./commands/GetBotsCommand"; import { GetBotVersionsCommand, GetBotVersionsCommandInput, GetBotVersionsCommandOutput, } from "./commands/GetBotVersionsCommand"; import { GetBuiltinIntentCommand, GetBuiltinIntentCommandInput, GetBuiltinIntentCommandOutput, } from "./commands/GetBuiltinIntentCommand"; import { GetBuiltinIntentsCommand, GetBuiltinIntentsCommandInput, GetBuiltinIntentsCommandOutput, } from "./commands/GetBuiltinIntentsCommand"; import { GetBuiltinSlotTypesCommand, GetBuiltinSlotTypesCommandInput, GetBuiltinSlotTypesCommandOutput, } from "./commands/GetBuiltinSlotTypesCommand"; import { GetExportCommand, GetExportCommandInput, GetExportCommandOutput } from "./commands/GetExportCommand"; import { GetImportCommand, GetImportCommandInput, GetImportCommandOutput } from "./commands/GetImportCommand"; import { GetIntentCommand, GetIntentCommandInput, GetIntentCommandOutput } from "./commands/GetIntentCommand"; import { GetIntentsCommand, GetIntentsCommandInput, GetIntentsCommandOutput } from "./commands/GetIntentsCommand"; import { GetIntentVersionsCommand, GetIntentVersionsCommandInput, GetIntentVersionsCommandOutput, } from "./commands/GetIntentVersionsCommand"; import { GetMigrationCommand, GetMigrationCommandInput, GetMigrationCommandOutput, } from "./commands/GetMigrationCommand"; import { GetMigrationsCommand, GetMigrationsCommandInput, GetMigrationsCommandOutput, } from "./commands/GetMigrationsCommand"; import { GetSlotTypeCommand, GetSlotTypeCommandInput, GetSlotTypeCommandOutput } from "./commands/GetSlotTypeCommand"; import { GetSlotTypesCommand, GetSlotTypesCommandInput, GetSlotTypesCommandOutput, } from "./commands/GetSlotTypesCommand"; import { GetSlotTypeVersionsCommand, GetSlotTypeVersionsCommandInput, GetSlotTypeVersionsCommandOutput, } from "./commands/GetSlotTypeVersionsCommand"; import { GetUtterancesViewCommand, GetUtterancesViewCommandInput, GetUtterancesViewCommandOutput, } from "./commands/GetUtterancesViewCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { PutBotAliasCommand, PutBotAliasCommandInput, PutBotAliasCommandOutput } from "./commands/PutBotAliasCommand"; import { PutBotCommand, PutBotCommandInput, PutBotCommandOutput } from "./commands/PutBotCommand"; import { PutIntentCommand, PutIntentCommandInput, PutIntentCommandOutput } from "./commands/PutIntentCommand"; import { PutSlotTypeCommand, PutSlotTypeCommandInput, PutSlotTypeCommandOutput } from "./commands/PutSlotTypeCommand"; import { StartImportCommand, StartImportCommandInput, StartImportCommandOutput } from "./commands/StartImportCommand"; import { StartMigrationCommand, StartMigrationCommandInput, StartMigrationCommandOutput, } from "./commands/StartMigrationCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { LexModelBuildingServiceClient } from "./LexModelBuildingServiceClient"; /** * <fullname>Amazon Lex Build-Time Actions</fullname> * <p> Amazon Lex is an AWS service for building conversational voice and text * interfaces. Use these actions to create, update, and delete conversational * bots for new and existing client applications. </p> */ export class LexModelBuildingService extends LexModelBuildingServiceClient { /** * <p>Creates a new version of the bot based on the <code>$LATEST</code> * version. If the <code>$LATEST</code> version of this resource hasn't * changed since you created the last version, Amazon Lex doesn't create a new * version. It returns the last created version.</p> * <note> * <p>You can update only the <code>$LATEST</code> version of the bot. * You can't update the numbered versions that you create with the * <code>CreateBotVersion</code> operation.</p> * </note> * <p> When you create the first version of a bot, Amazon Lex sets the version * to 1. Subsequent versions increment by 1. For more information, see <a>versioning-intro</a>. </p> * <p> This operation requires permission for the * <code>lex:CreateBotVersion</code> action. </p> */ public createBotVersion( args: CreateBotVersionCommandInput, options?: __HttpHandlerOptions ): Promise<CreateBotVersionCommandOutput>; public createBotVersion( args: CreateBotVersionCommandInput, cb: (err: any, data?: CreateBotVersionCommandOutput) => void ): void; public createBotVersion( args: CreateBotVersionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateBotVersionCommandOutput) => void ): void; public createBotVersion( args: CreateBotVersionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateBotVersionCommandOutput) => void), cb?: (err: any, data?: CreateBotVersionCommandOutput) => void ): Promise<CreateBotVersionCommandOutput> | void { const command = new CreateBotVersionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new version of an intent based on the * <code>$LATEST</code> version of the intent. If the <code>$LATEST</code> * version of this intent hasn't changed since you last updated it, Amazon Lex * doesn't create a new version. It returns the last version you * created.</p> * <note> * <p>You can update only the <code>$LATEST</code> version of the * intent. You can't update the numbered versions that you create with the * <code>CreateIntentVersion</code> operation.</p> * </note> * <p> When you create a version of an intent, Amazon Lex sets the version to * 1. Subsequent versions increment by 1. For more information, see <a>versioning-intro</a>. </p> * <p>This operation requires permissions to perform the * <code>lex:CreateIntentVersion</code> action. </p> */ public createIntentVersion( args: CreateIntentVersionCommandInput, options?: __HttpHandlerOptions ): Promise<CreateIntentVersionCommandOutput>; public createIntentVersion( args: CreateIntentVersionCommandInput, cb: (err: any, data?: CreateIntentVersionCommandOutput) => void ): void; public createIntentVersion( args: CreateIntentVersionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateIntentVersionCommandOutput) => void ): void; public createIntentVersion( args: CreateIntentVersionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateIntentVersionCommandOutput) => void), cb?: (err: any, data?: CreateIntentVersionCommandOutput) => void ): Promise<CreateIntentVersionCommandOutput> | void { const command = new CreateIntentVersionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new version of a slot type based on the * <code>$LATEST</code> version of the specified slot type. If the * <code>$LATEST</code> version of this resource has not changed since the * last version that you created, Amazon Lex doesn't create a new version. It * returns the last version that you created. </p> * <note> * <p>You can update only the <code>$LATEST</code> version of a slot * type. You can't update the numbered versions that you create with the * <code>CreateSlotTypeVersion</code> operation.</p> * </note> * * <p>When you create a version of a slot type, Amazon Lex sets the version to * 1. Subsequent versions increment by 1. For more information, see <a>versioning-intro</a>. </p> * * <p>This operation requires permissions for the * <code>lex:CreateSlotTypeVersion</code> action.</p> */ public createSlotTypeVersion( args: CreateSlotTypeVersionCommandInput, options?: __HttpHandlerOptions ): Promise<CreateSlotTypeVersionCommandOutput>; public createSlotTypeVersion( args: CreateSlotTypeVersionCommandInput, cb: (err: any, data?: CreateSlotTypeVersionCommandOutput) => void ): void; public createSlotTypeVersion( args: CreateSlotTypeVersionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateSlotTypeVersionCommandOutput) => void ): void; public createSlotTypeVersion( args: CreateSlotTypeVersionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateSlotTypeVersionCommandOutput) => void), cb?: (err: any, data?: CreateSlotTypeVersionCommandOutput) => void ): Promise<CreateSlotTypeVersionCommandOutput> | void { const command = new CreateSlotTypeVersionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes all versions of the bot, including the <code>$LATEST</code> * version. To delete a specific version of the bot, use the <a>DeleteBotVersion</a> operation. The <code>DeleteBot</code> * operation doesn't immediately remove the bot schema. Instead, it is marked * for deletion and removed later.</p> * <p>Amazon Lex stores utterances indefinitely for improving the ability of * your bot to respond to user inputs. These utterances are not removed when * the bot is deleted. To remove the utterances, use the <a>DeleteUtterances</a> operation.</p> * <p>If a bot has an alias, you can't delete it. Instead, the * <code>DeleteBot</code> operation returns a * <code>ResourceInUseException</code> exception that includes a reference * to the alias that refers to the bot. To remove the reference to the bot, * delete the alias. If you get the same exception again, delete the * referring alias until the <code>DeleteBot</code> operation is * successful.</p> * * <p>This operation requires permissions for the * <code>lex:DeleteBot</code> action.</p> */ public deleteBot(args: DeleteBotCommandInput, options?: __HttpHandlerOptions): Promise<DeleteBotCommandOutput>; public deleteBot(args: DeleteBotCommandInput, cb: (err: any, data?: DeleteBotCommandOutput) => void): void; public deleteBot( args: DeleteBotCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteBotCommandOutput) => void ): void; public deleteBot( args: DeleteBotCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteBotCommandOutput) => void), cb?: (err: any, data?: DeleteBotCommandOutput) => void ): Promise<DeleteBotCommandOutput> | void { const command = new DeleteBotCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes an alias for the specified bot. </p> * <p>You can't delete an alias that is used in the association between a * bot and a messaging channel. If an alias is used in a channel association, * the <code>DeleteBot</code> operation returns a * <code>ResourceInUseException</code> exception that includes a reference * to the channel association that refers to the bot. You can remove the * reference to the alias by deleting the channel association. If you get the * same exception again, delete the referring association until the * <code>DeleteBotAlias</code> operation is successful.</p> */ public deleteBotAlias( args: DeleteBotAliasCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteBotAliasCommandOutput>; public deleteBotAlias( args: DeleteBotAliasCommandInput, cb: (err: any, data?: DeleteBotAliasCommandOutput) => void ): void; public deleteBotAlias( args: DeleteBotAliasCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteBotAliasCommandOutput) => void ): void; public deleteBotAlias( args: DeleteBotAliasCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteBotAliasCommandOutput) => void), cb?: (err: any, data?: DeleteBotAliasCommandOutput) => void ): Promise<DeleteBotAliasCommandOutput> | void { const command = new DeleteBotAliasCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the association between an Amazon Lex bot and a messaging * platform.</p> * <p>This operation requires permission for the * <code>lex:DeleteBotChannelAssociation</code> action.</p> */ public deleteBotChannelAssociation( args: DeleteBotChannelAssociationCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteBotChannelAssociationCommandOutput>; public deleteBotChannelAssociation( args: DeleteBotChannelAssociationCommandInput, cb: (err: any, data?: DeleteBotChannelAssociationCommandOutput) => void ): void; public deleteBotChannelAssociation( args: DeleteBotChannelAssociationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteBotChannelAssociationCommandOutput) => void ): void; public deleteBotChannelAssociation( args: DeleteBotChannelAssociationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteBotChannelAssociationCommandOutput) => void), cb?: (err: any, data?: DeleteBotChannelAssociationCommandOutput) => void ): Promise<DeleteBotChannelAssociationCommandOutput> | void { const command = new DeleteBotChannelAssociationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a specific version of a bot. To delete all versions of a * bot, use the <a>DeleteBot</a> operation. </p> * <p>This operation requires permissions for the * <code>lex:DeleteBotVersion</code> action.</p> */ public deleteBotVersion( args: DeleteBotVersionCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteBotVersionCommandOutput>; public deleteBotVersion( args: DeleteBotVersionCommandInput, cb: (err: any, data?: DeleteBotVersionCommandOutput) => void ): void; public deleteBotVersion( args: DeleteBotVersionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteBotVersionCommandOutput) => void ): void; public deleteBotVersion( args: DeleteBotVersionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteBotVersionCommandOutput) => void), cb?: (err: any, data?: DeleteBotVersionCommandOutput) => void ): Promise<DeleteBotVersionCommandOutput> | void { const command = new DeleteBotVersionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes all versions of the intent, including the * <code>$LATEST</code> version. To delete a specific version of the * intent, use the <a>DeleteIntentVersion</a> operation.</p> * <p> You can delete a version of an intent only if it is not * referenced. To delete an intent that is referred to in one or more bots * (see <a>how-it-works</a>), you must remove those references * first. </p> * <note> * <p> If you get the <code>ResourceInUseException</code> exception, it * provides an example reference that shows where the intent is referenced. * To remove the reference to the intent, either update the bot or delete * it. If you get the same exception when you attempt to delete the intent * again, repeat until the intent has no references and the call to * <code>DeleteIntent</code> is successful. </p> * </note> * * <p> This operation requires permission for the * <code>lex:DeleteIntent</code> action. </p> */ public deleteIntent( args: DeleteIntentCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteIntentCommandOutput>; public deleteIntent(args: DeleteIntentCommandInput, cb: (err: any, data?: DeleteIntentCommandOutput) => void): void; public deleteIntent( args: DeleteIntentCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteIntentCommandOutput) => void ): void; public deleteIntent( args: DeleteIntentCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteIntentCommandOutput) => void), cb?: (err: any, data?: DeleteIntentCommandOutput) => void ): Promise<DeleteIntentCommandOutput> | void { const command = new DeleteIntentCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a specific version of an intent. To delete all versions of * a intent, use the <a>DeleteIntent</a> operation. </p> * <p>This operation requires permissions for the * <code>lex:DeleteIntentVersion</code> action.</p> */ public deleteIntentVersion( args: DeleteIntentVersionCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteIntentVersionCommandOutput>; public deleteIntentVersion( args: DeleteIntentVersionCommandInput, cb: (err: any, data?: DeleteIntentVersionCommandOutput) => void ): void; public deleteIntentVersion( args: DeleteIntentVersionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteIntentVersionCommandOutput) => void ): void; public deleteIntentVersion( args: DeleteIntentVersionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteIntentVersionCommandOutput) => void), cb?: (err: any, data?: DeleteIntentVersionCommandOutput) => void ): Promise<DeleteIntentVersionCommandOutput> | void { const command = new DeleteIntentVersionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes all versions of the slot type, including the * <code>$LATEST</code> version. To delete a specific version of the slot * type, use the <a>DeleteSlotTypeVersion</a> operation.</p> * <p> You can delete a version of a slot type only if it is not * referenced. To delete a slot type that is referred to in one or more * intents, you must remove those references first. </p> * <note> * <p> If you get the <code>ResourceInUseException</code> exception, * the exception provides an example reference that shows the intent where * the slot type is referenced. To remove the reference to the slot type, * either update the intent or delete it. If you get the same exception * when you attempt to delete the slot type again, repeat until the slot * type has no references and the <code>DeleteSlotType</code> call is * successful. </p> * </note> * <p>This operation requires permission for the * <code>lex:DeleteSlotType</code> action.</p> */ public deleteSlotType( args: DeleteSlotTypeCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteSlotTypeCommandOutput>; public deleteSlotType( args: DeleteSlotTypeCommandInput, cb: (err: any, data?: DeleteSlotTypeCommandOutput) => void ): void; public deleteSlotType( args: DeleteSlotTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteSlotTypeCommandOutput) => void ): void; public deleteSlotType( args: DeleteSlotTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteSlotTypeCommandOutput) => void), cb?: (err: any, data?: DeleteSlotTypeCommandOutput) => void ): Promise<DeleteSlotTypeCommandOutput> | void { const command = new DeleteSlotTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a specific version of a slot type. To delete all versions * of a slot type, use the <a>DeleteSlotType</a> operation. </p> * <p>This operation requires permissions for the * <code>lex:DeleteSlotTypeVersion</code> action.</p> */ public deleteSlotTypeVersion( args: DeleteSlotTypeVersionCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteSlotTypeVersionCommandOutput>; public deleteSlotTypeVersion( args: DeleteSlotTypeVersionCommandInput, cb: (err: any, data?: DeleteSlotTypeVersionCommandOutput) => void ): void; public deleteSlotTypeVersion( args: DeleteSlotTypeVersionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteSlotTypeVersionCommandOutput) => void ): void; public deleteSlotTypeVersion( args: DeleteSlotTypeVersionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteSlotTypeVersionCommandOutput) => void), cb?: (err: any, data?: DeleteSlotTypeVersionCommandOutput) => void ): Promise<DeleteSlotTypeVersionCommandOutput> | void { const command = new DeleteSlotTypeVersionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes stored utterances.</p> * <p>Amazon Lex stores the utterances that users send to your bot. Utterances * are stored for 15 days for use with the <a>GetUtterancesView</a> operation, and then stored indefinitely for use in improving the * ability of your bot to respond to user input.</p> * <p>Use the <code>DeleteUtterances</code> operation to manually delete * stored utterances for a specific user. When you use the * <code>DeleteUtterances</code> operation, utterances stored for improving * your bot's ability to respond to user input are deleted immediately. * Utterances stored for use with the <code>GetUtterancesView</code> * operation are deleted after 15 days.</p> * <p>This operation requires permissions for the * <code>lex:DeleteUtterances</code> action.</p> */ public deleteUtterances( args: DeleteUtterancesCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteUtterancesCommandOutput>; public deleteUtterances( args: DeleteUtterancesCommandInput, cb: (err: any, data?: DeleteUtterancesCommandOutput) => void ): void; public deleteUtterances( args: DeleteUtterancesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteUtterancesCommandOutput) => void ): void; public deleteUtterances( args: DeleteUtterancesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteUtterancesCommandOutput) => void), cb?: (err: any, data?: DeleteUtterancesCommandOutput) => void ): Promise<DeleteUtterancesCommandOutput> | void { const command = new DeleteUtterancesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns metadata information for a specific bot. You must provide * the bot name and the bot version or alias. </p> * <p> This operation requires permissions for the * <code>lex:GetBot</code> action. </p> */ public getBot(args: GetBotCommandInput, options?: __HttpHandlerOptions): Promise<GetBotCommandOutput>; public getBot(args: GetBotCommandInput, cb: (err: any, data?: GetBotCommandOutput) => void): void; public getBot( args: GetBotCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBotCommandOutput) => void ): void; public getBot( args: GetBotCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBotCommandOutput) => void), cb?: (err: any, data?: GetBotCommandOutput) => void ): Promise<GetBotCommandOutput> | void { const command = new GetBotCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about an Amazon Lex bot alias. For more information * about aliases, see <a>versioning-aliases</a>.</p> * <p>This operation requires permissions for the * <code>lex:GetBotAlias</code> action.</p> */ public getBotAlias(args: GetBotAliasCommandInput, options?: __HttpHandlerOptions): Promise<GetBotAliasCommandOutput>; public getBotAlias(args: GetBotAliasCommandInput, cb: (err: any, data?: GetBotAliasCommandOutput) => void): void; public getBotAlias( args: GetBotAliasCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBotAliasCommandOutput) => void ): void; public getBotAlias( args: GetBotAliasCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBotAliasCommandOutput) => void), cb?: (err: any, data?: GetBotAliasCommandOutput) => void ): Promise<GetBotAliasCommandOutput> | void { const command = new GetBotAliasCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of aliases for a specified Amazon Lex bot.</p> * <p>This operation requires permissions for the * <code>lex:GetBotAliases</code> action.</p> */ public getBotAliases( args: GetBotAliasesCommandInput, options?: __HttpHandlerOptions ): Promise<GetBotAliasesCommandOutput>; public getBotAliases( args: GetBotAliasesCommandInput, cb: (err: any, data?: GetBotAliasesCommandOutput) => void ): void; public getBotAliases( args: GetBotAliasesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBotAliasesCommandOutput) => void ): void; public getBotAliases( args: GetBotAliasesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBotAliasesCommandOutput) => void), cb?: (err: any, data?: GetBotAliasesCommandOutput) => void ): Promise<GetBotAliasesCommandOutput> | void { const command = new GetBotAliasesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the association between an Amazon Lex bot and * a messaging platform.</p> * <p>This operation requires permissions for the * <code>lex:GetBotChannelAssociation</code> action.</p> */ public getBotChannelAssociation( args: GetBotChannelAssociationCommandInput, options?: __HttpHandlerOptions ): Promise<GetBotChannelAssociationCommandOutput>; public getBotChannelAssociation( args: GetBotChannelAssociationCommandInput, cb: (err: any, data?: GetBotChannelAssociationCommandOutput) => void ): void; public getBotChannelAssociation( args: GetBotChannelAssociationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBotChannelAssociationCommandOutput) => void ): void; public getBotChannelAssociation( args: GetBotChannelAssociationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBotChannelAssociationCommandOutput) => void), cb?: (err: any, data?: GetBotChannelAssociationCommandOutput) => void ): Promise<GetBotChannelAssociationCommandOutput> | void { const command = new GetBotChannelAssociationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> Returns a list of all of the channels associated with the * specified bot. </p> * <p>The <code>GetBotChannelAssociations</code> operation requires * permissions for the <code>lex:GetBotChannelAssociations</code> * action.</p> */ public getBotChannelAssociations( args: GetBotChannelAssociationsCommandInput, options?: __HttpHandlerOptions ): Promise<GetBotChannelAssociationsCommandOutput>; public getBotChannelAssociations( args: GetBotChannelAssociationsCommandInput, cb: (err: any, data?: GetBotChannelAssociationsCommandOutput) => void ): void; public getBotChannelAssociations( args: GetBotChannelAssociationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBotChannelAssociationsCommandOutput) => void ): void; public getBotChannelAssociations( args: GetBotChannelAssociationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBotChannelAssociationsCommandOutput) => void), cb?: (err: any, data?: GetBotChannelAssociationsCommandOutput) => void ): Promise<GetBotChannelAssociationsCommandOutput> | void { const command = new GetBotChannelAssociationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns bot information as follows: </p> * <ul> * <li> * <p>If you provide the <code>nameContains</code> field, the * response includes information for the <code>$LATEST</code> version of * all bots whose name contains the specified string.</p> * </li> * <li> * <p>If you don't specify the <code>nameContains</code> field, the * operation returns information about the <code>$LATEST</code> version * of all of your bots.</p> * </li> * </ul> * <p>This operation requires permission for the <code>lex:GetBots</code> * action.</p> */ public getBots(args: GetBotsCommandInput, options?: __HttpHandlerOptions): Promise<GetBotsCommandOutput>; public getBots(args: GetBotsCommandInput, cb: (err: any, data?: GetBotsCommandOutput) => void): void; public getBots( args: GetBotsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBotsCommandOutput) => void ): void; public getBots( args: GetBotsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBotsCommandOutput) => void), cb?: (err: any, data?: GetBotsCommandOutput) => void ): Promise<GetBotsCommandOutput> | void { const command = new GetBotsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets information about all of the versions of a bot.</p> * <p>The <code>GetBotVersions</code> operation returns a * <code>BotMetadata</code> object for each version of a bot. For example, * if a bot has three numbered versions, the <code>GetBotVersions</code> * operation returns four <code>BotMetadata</code> objects in the response, * one for each numbered version and one for the <code>$LATEST</code> * version. </p> * <p>The <code>GetBotVersions</code> operation always returns at least * one version, the <code>$LATEST</code> version.</p> * <p>This operation requires permissions for the * <code>lex:GetBotVersions</code> action.</p> */ public getBotVersions( args: GetBotVersionsCommandInput, options?: __HttpHandlerOptions ): Promise<GetBotVersionsCommandOutput>; public getBotVersions( args: GetBotVersionsCommandInput, cb: (err: any, data?: GetBotVersionsCommandOutput) => void ): void; public getBotVersions( args: GetBotVersionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBotVersionsCommandOutput) => void ): void; public getBotVersions( args: GetBotVersionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBotVersionsCommandOutput) => void), cb?: (err: any, data?: GetBotVersionsCommandOutput) => void ): Promise<GetBotVersionsCommandOutput> | void { const command = new GetBotVersionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about a built-in intent.</p> * <p>This operation requires permission for the * <code>lex:GetBuiltinIntent</code> action.</p> */ public getBuiltinIntent( args: GetBuiltinIntentCommandInput, options?: __HttpHandlerOptions ): Promise<GetBuiltinIntentCommandOutput>; public getBuiltinIntent( args: GetBuiltinIntentCommandInput, cb: (err: any, data?: GetBuiltinIntentCommandOutput) => void ): void; public getBuiltinIntent( args: GetBuiltinIntentCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBuiltinIntentCommandOutput) => void ): void; public getBuiltinIntent( args: GetBuiltinIntentCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBuiltinIntentCommandOutput) => void), cb?: (err: any, data?: GetBuiltinIntentCommandOutput) => void ): Promise<GetBuiltinIntentCommandOutput> | void { const command = new GetBuiltinIntentCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets a list of built-in intents that meet the specified * criteria.</p> * <p>This operation requires permission for the * <code>lex:GetBuiltinIntents</code> action.</p> */ public getBuiltinIntents( args: GetBuiltinIntentsCommandInput, options?: __HttpHandlerOptions ): Promise<GetBuiltinIntentsCommandOutput>; public getBuiltinIntents( args: GetBuiltinIntentsCommandInput, cb: (err: any, data?: GetBuiltinIntentsCommandOutput) => void ): void; public getBuiltinIntents( args: GetBuiltinIntentsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBuiltinIntentsCommandOutput) => void ): void; public getBuiltinIntents( args: GetBuiltinIntentsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBuiltinIntentsCommandOutput) => void), cb?: (err: any, data?: GetBuiltinIntentsCommandOutput) => void ): Promise<GetBuiltinIntentsCommandOutput> | void { const command = new GetBuiltinIntentsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets a list of built-in slot types that meet the specified * criteria.</p> * <p>For a list of built-in slot types, see <a href="https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference">Slot Type Reference</a> in the <i>Alexa Skills * Kit</i>.</p> * * <p>This operation requires permission for the * <code>lex:GetBuiltInSlotTypes</code> action.</p> */ public getBuiltinSlotTypes( args: GetBuiltinSlotTypesCommandInput, options?: __HttpHandlerOptions ): Promise<GetBuiltinSlotTypesCommandOutput>; public getBuiltinSlotTypes( args: GetBuiltinSlotTypesCommandInput, cb: (err: any, data?: GetBuiltinSlotTypesCommandOutput) => void ): void; public getBuiltinSlotTypes( args: GetBuiltinSlotTypesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBuiltinSlotTypesCommandOutput) => void ): void; public getBuiltinSlotTypes( args: GetBuiltinSlotTypesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBuiltinSlotTypesCommandOutput) => void), cb?: (err: any, data?: GetBuiltinSlotTypesCommandOutput) => void ): Promise<GetBuiltinSlotTypesCommandOutput> | void { const command = new GetBuiltinSlotTypesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Exports the contents of a Amazon Lex resource in a specified format. * </p> */ public getExport(args: GetExportCommandInput, options?: __HttpHandlerOptions): Promise<GetExportCommandOutput>; public getExport(args: GetExportCommandInput, cb: (err: any, data?: GetExportCommandOutput) => void): void; public getExport( args: GetExportCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetExportCommandOutput) => void ): void; public getExport( args: GetExportCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetExportCommandOutput) => void), cb?: (err: any, data?: GetExportCommandOutput) => void ): Promise<GetExportCommandOutput> | void { const command = new GetExportCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets information about an import job started with the * <code>StartImport</code> operation.</p> */ public getImport(args: GetImportCommandInput, options?: __HttpHandlerOptions): Promise<GetImportCommandOutput>; public getImport(args: GetImportCommandInput, cb: (err: any, data?: GetImportCommandOutput) => void): void; public getImport( args: GetImportCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetImportCommandOutput) => void ): void; public getImport( args: GetImportCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetImportCommandOutput) => void), cb?: (err: any, data?: GetImportCommandOutput) => void ): Promise<GetImportCommandOutput> | void { const command = new GetImportCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> Returns information about an intent. In addition to the intent * name, you must specify the intent version. </p> * <p> This operation requires permissions to perform the * <code>lex:GetIntent</code> action. </p> */ public getIntent(args: GetIntentCommandInput, options?: __HttpHandlerOptions): Promise<GetIntentCommandOutput>; public getIntent(args: GetIntentCommandInput, cb: (err: any, data?: GetIntentCommandOutput) => void): void; public getIntent( args: GetIntentCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetIntentCommandOutput) => void ): void; public getIntent( args: GetIntentCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetIntentCommandOutput) => void), cb?: (err: any, data?: GetIntentCommandOutput) => void ): Promise<GetIntentCommandOutput> | void { const command = new GetIntentCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns intent information as follows: </p> * <ul> * <li> * <p>If you specify the <code>nameContains</code> field, returns the * <code>$LATEST</code> version of all intents that contain the * specified string.</p> * </li> * <li> * <p> If you don't specify the <code>nameContains</code> field, * returns information about the <code>$LATEST</code> version of all * intents. </p> * </li> * </ul> * <p> The operation requires permission for the * <code>lex:GetIntents</code> action. </p> */ public getIntents(args: GetIntentsCommandInput, options?: __HttpHandlerOptions): Promise<GetIntentsCommandOutput>; public getIntents(args: GetIntentsCommandInput, cb: (err: any, data?: GetIntentsCommandOutput) => void): void; public getIntents( args: GetIntentsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetIntentsCommandOutput) => void ): void; public getIntents( args: GetIntentsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetIntentsCommandOutput) => void), cb?: (err: any, data?: GetIntentsCommandOutput) => void ): Promise<GetIntentsCommandOutput> | void { const command = new GetIntentsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets information about all of the versions of an intent.</p> * <p>The <code>GetIntentVersions</code> operation returns an * <code>IntentMetadata</code> object for each version of an intent. For * example, if an intent has three numbered versions, the * <code>GetIntentVersions</code> operation returns four * <code>IntentMetadata</code> objects in the response, one for each * numbered version and one for the <code>$LATEST</code> version. </p> * <p>The <code>GetIntentVersions</code> operation always returns at * least one version, the <code>$LATEST</code> version.</p> * <p>This operation requires permissions for the * <code>lex:GetIntentVersions</code> action.</p> */ public getIntentVersions( args: GetIntentVersionsCommandInput, options?: __HttpHandlerOptions ): Promise<GetIntentVersionsCommandOutput>; public getIntentVersions( args: GetIntentVersionsCommandInput, cb: (err: any, data?: GetIntentVersionsCommandOutput) => void ): void; public getIntentVersions( args: GetIntentVersionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetIntentVersionsCommandOutput) => void ): void; public getIntentVersions( args: GetIntentVersionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetIntentVersionsCommandOutput) => void), cb?: (err: any, data?: GetIntentVersionsCommandOutput) => void ): Promise<GetIntentVersionsCommandOutput> | void { const command = new GetIntentVersionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Provides details about an ongoing or complete migration from an * Amazon Lex V1 bot to an Amazon Lex V2 bot. Use this operation to view the migration * alerts and warnings related to the migration.</p> */ public getMigration( args: GetMigrationCommandInput, options?: __HttpHandlerOptions ): Promise<GetMigrationCommandOutput>; public getMigration(args: GetMigrationCommandInput, cb: (err: any, data?: GetMigrationCommandOutput) => void): void; public getMigration( args: GetMigrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetMigrationCommandOutput) => void ): void; public getMigration( args: GetMigrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMigrationCommandOutput) => void), cb?: (err: any, data?: GetMigrationCommandOutput) => void ): Promise<GetMigrationCommandOutput> | void { const command = new GetMigrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets a list of migrations between Amazon Lex V1 and Amazon Lex V2.</p> */ public getMigrations( args: GetMigrationsCommandInput, options?: __HttpHandlerOptions ): Promise<GetMigrationsCommandOutput>; public getMigrations( args: GetMigrationsCommandInput, cb: (err: any, data?: GetMigrationsCommandOutput) => void ): void; public getMigrations( args: GetMigrationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetMigrationsCommandOutput) => void ): void; public getMigrations( args: GetMigrationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMigrationsCommandOutput) => void), cb?: (err: any, data?: GetMigrationsCommandOutput) => void ): Promise<GetMigrationsCommandOutput> | void { const command = new GetMigrationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about a specific version of a slot type. In * addition to specifying the slot type name, you must specify the slot type * version.</p> * <p>This operation requires permissions for the * <code>lex:GetSlotType</code> action.</p> */ public getSlotType(args: GetSlotTypeCommandInput, options?: __HttpHandlerOptions): Promise<GetSlotTypeCommandOutput>; public getSlotType(args: GetSlotTypeCommandInput, cb: (err: any, data?: GetSlotTypeCommandOutput) => void): void; public getSlotType( args: GetSlotTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetSlotTypeCommandOutput) => void ): void; public getSlotType( args: GetSlotTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetSlotTypeCommandOutput) => void), cb?: (err: any, data?: GetSlotTypeCommandOutput) => void ): Promise<GetSlotTypeCommandOutput> | void { const command = new GetSlotTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns slot type information as follows: </p> * <ul> * <li> * <p>If you specify the <code>nameContains</code> field, returns the * <code>$LATEST</code> version of all slot types that contain the * specified string.</p> * </li> * <li> * <p> If you don't specify the <code>nameContains</code> field, * returns information about the <code>$LATEST</code> version of all slot * types. </p> * </li> * </ul> * <p> The operation requires permission for the * <code>lex:GetSlotTypes</code> action. </p> */ public getSlotTypes( args: GetSlotTypesCommandInput, options?: __HttpHandlerOptions ): Promise<GetSlotTypesCommandOutput>; public getSlotTypes(args: GetSlotTypesCommandInput, cb: (err: any, data?: GetSlotTypesCommandOutput) => void): void; public getSlotTypes( args: GetSlotTypesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetSlotTypesCommandOutput) => void ): void; public getSlotTypes( args: GetSlotTypesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetSlotTypesCommandOutput) => void), cb?: (err: any, data?: GetSlotTypesCommandOutput) => void ): Promise<GetSlotTypesCommandOutput> | void { const command = new GetSlotTypesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets information about all versions of a slot type.</p> * <p>The <code>GetSlotTypeVersions</code> operation returns a * <code>SlotTypeMetadata</code> object for each version of a slot type. * For example, if a slot type has three numbered versions, the * <code>GetSlotTypeVersions</code> operation returns four * <code>SlotTypeMetadata</code> objects in the response, one for each * numbered version and one for the <code>$LATEST</code> version. </p> * <p>The <code>GetSlotTypeVersions</code> operation always returns at * least one version, the <code>$LATEST</code> version.</p> * <p>This operation requires permissions for the * <code>lex:GetSlotTypeVersions</code> action.</p> */ public getSlotTypeVersions( args: GetSlotTypeVersionsCommandInput, options?: __HttpHandlerOptions ): Promise<GetSlotTypeVersionsCommandOutput>; public getSlotTypeVersions( args: GetSlotTypeVersionsCommandInput, cb: (err: any, data?: GetSlotTypeVersionsCommandOutput) => void ): void; public getSlotTypeVersions( args: GetSlotTypeVersionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetSlotTypeVersionsCommandOutput) => void ): void; public getSlotTypeVersions( args: GetSlotTypeVersionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetSlotTypeVersionsCommandOutput) => void), cb?: (err: any, data?: GetSlotTypeVersionsCommandOutput) => void ): Promise<GetSlotTypeVersionsCommandOutput> | void { const command = new GetSlotTypeVersionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Use the <code>GetUtterancesView</code> operation to get information * about the utterances that your users have made to your bot. You can use * this list to tune the utterances that your bot responds to.</p> * <p>For example, say that you have created a bot to order flowers. * After your users have used your bot for a while, use the * <code>GetUtterancesView</code> operation to see the requests that they * have made and whether they have been successful. You might find that the * utterance "I want flowers" is not being recognized. You could add this * utterance to the <code>OrderFlowers</code> intent so that your bot * recognizes that utterance.</p> * <p>After you publish a new version of a bot, you can get information * about the old version and the new so that you can compare the performance * across the two versions. </p> * <p>Utterance statistics are generated once a day. Data is available * for the last 15 days. You can request information for up to 5 versions of * your bot in each request. Amazon Lex returns the most frequent utterances * received by the bot in the last 15 days. The response contains information * about a maximum of 100 utterances for each version.</p> * <p>If you set <code>childDirected</code> field to true when you * created your bot, if you are using slot obfuscation with one or more * slots, or if you opted out of participating in improving Amazon Lex, utterances * are not available.</p> * <p>This operation requires permissions for the * <code>lex:GetUtterancesView</code> action.</p> */ public getUtterancesView( args: GetUtterancesViewCommandInput, options?: __HttpHandlerOptions ): Promise<GetUtterancesViewCommandOutput>; public getUtterancesView( args: GetUtterancesViewCommandInput, cb: (err: any, data?: GetUtterancesViewCommandOutput) => void ): void; public getUtterancesView( args: GetUtterancesViewCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetUtterancesViewCommandOutput) => void ): void; public getUtterancesView( args: GetUtterancesViewCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetUtterancesViewCommandOutput) => void), cb?: (err: any, data?: GetUtterancesViewCommandOutput) => void ): Promise<GetUtterancesViewCommandOutput> | void { const command = new GetUtterancesViewCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets a list of tags associated with the specified resource. Only bots, * bot aliases, and bot channels can have tags associated with them.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an Amazon Lex conversational bot or replaces an existing bot. * When you create or update a bot you are only required to specify a name, a * locale, and whether the bot is directed toward children under age 13. You * can use this to add intents later, or to remove intents from an existing * bot. When you create a bot with the minimum information, the bot is * created or updated but Amazon Lex returns the <code></code> response * <code>FAILED</code>. You can build the bot after you add one or more * intents. For more information about Amazon Lex bots, see <a>how-it-works</a>. </p> * <p>If you specify the name of an existing bot, the fields in the * request replace the existing values in the <code>$LATEST</code> version of * the bot. Amazon Lex removes any fields that you don't provide values for in the * request, except for the <code>idleTTLInSeconds</code> and * <code>privacySettings</code> fields, which are set to their default * values. If you don't specify values for required fields, Amazon Lex throws an * exception.</p> * * <p>This operation requires permissions for the <code>lex:PutBot</code> * action. For more information, see <a>security-iam</a>.</p> */ public putBot(args: PutBotCommandInput, options?: __HttpHandlerOptions): Promise<PutBotCommandOutput>; public putBot(args: PutBotCommandInput, cb: (err: any, data?: PutBotCommandOutput) => void): void; public putBot( args: PutBotCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutBotCommandOutput) => void ): void; public putBot( args: PutBotCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutBotCommandOutput) => void), cb?: (err: any, data?: PutBotCommandOutput) => void ): Promise<PutBotCommandOutput> | void { const command = new PutBotCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an alias for the specified version of the bot or replaces * an alias for the specified bot. To change the version of the bot that the * alias points to, replace the alias. For more information about aliases, * see <a>versioning-aliases</a>.</p> * <p>This operation requires permissions for the * <code>lex:PutBotAlias</code> action. </p> */ public putBotAlias(args: PutBotAliasCommandInput, options?: __HttpHandlerOptions): Promise<PutBotAliasCommandOutput>; public putBotAlias(args: PutBotAliasCommandInput, cb: (err: any, data?: PutBotAliasCommandOutput) => void): void; public putBotAlias( args: PutBotAliasCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutBotAliasCommandOutput) => void ): void; public putBotAlias( args: PutBotAliasCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutBotAliasCommandOutput) => void), cb?: (err: any, data?: PutBotAliasCommandOutput) => void ): Promise<PutBotAliasCommandOutput> | void { const command = new PutBotAliasCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an intent or replaces an existing intent.</p> * <p>To define the interaction between the user and your bot, you use * one or more intents. For a pizza ordering bot, for example, you would * create an <code>OrderPizza</code> intent. </p> * <p>To create an intent or replace an existing intent, you must provide * the following:</p> * <ul> * <li> * <p>Intent name. For example, <code>OrderPizza</code>.</p> * </li> * <li> * <p>Sample utterances. For example, "Can I order a pizza, please." * and "I want to order a pizza."</p> * </li> * <li> * <p>Information to be gathered. You specify slot types for the * information that your bot will request from the user. You can specify * standard slot types, such as a date or a time, or custom slot types * such as the size and crust of a pizza.</p> * </li> * <li> * <p>How the intent will be fulfilled. You can provide a Lambda * function or configure the intent to return the intent information to * the client application. If you use a Lambda function, when all of the * intent information is available, Amazon Lex invokes your Lambda function. * If you configure your intent to return the intent information to the * client application. </p> * </li> * </ul> * <p>You can specify other optional information in the request, such * as:</p> * * <ul> * <li> * <p>A confirmation prompt to ask the user to confirm an intent. For * example, "Shall I order your pizza?"</p> * </li> * <li> * <p>A conclusion statement to send to the user after the intent has * been fulfilled. For example, "I placed your pizza order."</p> * </li> * <li> * <p>A follow-up prompt that asks the user for additional activity. * For example, asking "Do you want to order a drink with your * pizza?"</p> * </li> * </ul> * <p>If you specify an existing intent name to update the intent, Amazon Lex * replaces the values in the <code>$LATEST</code> version of the intent with * the values in the request. Amazon Lex removes fields that you don't provide in * the request. If you don't specify the required fields, Amazon Lex throws an * exception. When you update the <code>$LATEST</code> version of an intent, * the <code>status</code> field of any bot that uses the * <code>$LATEST</code> version of the intent is set to * <code>NOT_BUILT</code>.</p> * <p>For more information, see <a>how-it-works</a>.</p> * <p>This operation requires permissions for the * <code>lex:PutIntent</code> action.</p> */ public putIntent(args: PutIntentCommandInput, options?: __HttpHandlerOptions): Promise<PutIntentCommandOutput>; public putIntent(args: PutIntentCommandInput, cb: (err: any, data?: PutIntentCommandOutput) => void): void; public putIntent( args: PutIntentCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutIntentCommandOutput) => void ): void; public putIntent( args: PutIntentCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutIntentCommandOutput) => void), cb?: (err: any, data?: PutIntentCommandOutput) => void ): Promise<PutIntentCommandOutput> | void { const command = new PutIntentCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a custom slot type or replaces an existing custom slot * type.</p> * <p>To create a custom slot type, specify a name for the slot type and * a set of enumeration values, which are the values that a slot of this type * can assume. For more information, see <a>how-it-works</a>.</p> * <p>If you specify the name of an existing slot type, the fields in the * request replace the existing values in the <code>$LATEST</code> version of * the slot type. Amazon Lex removes the fields that you don't provide in the * request. If you don't specify required fields, Amazon Lex throws an exception. * When you update the <code>$LATEST</code> version of a slot type, if a bot * uses the <code>$LATEST</code> version of an intent that contains the slot * type, the bot's <code>status</code> field is set to * <code>NOT_BUILT</code>.</p> * * <p>This operation requires permissions for the * <code>lex:PutSlotType</code> action.</p> */ public putSlotType(args: PutSlotTypeCommandInput, options?: __HttpHandlerOptions): Promise<PutSlotTypeCommandOutput>; public putSlotType(args: PutSlotTypeCommandInput, cb: (err: any, data?: PutSlotTypeCommandOutput) => void): void; public putSlotType( args: PutSlotTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutSlotTypeCommandOutput) => void ): void; public putSlotType( args: PutSlotTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutSlotTypeCommandOutput) => void), cb?: (err: any, data?: PutSlotTypeCommandOutput) => void ): Promise<PutSlotTypeCommandOutput> | void { const command = new PutSlotTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Starts a job to import a resource to Amazon Lex.</p> */ public startImport(args: StartImportCommandInput, options?: __HttpHandlerOptions): Promise<StartImportCommandOutput>; public startImport(args: StartImportCommandInput, cb: (err: any, data?: StartImportCommandOutput) => void): void; public startImport( args: StartImportCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: StartImportCommandOutput) => void ): void; public startImport( args: StartImportCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartImportCommandOutput) => void), cb?: (err: any, data?: StartImportCommandOutput) => void ): Promise<StartImportCommandOutput> | void { const command = new StartImportCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Starts migrating a bot from Amazon Lex V1 to Amazon Lex V2. Migrate your bot when * you want to take advantage of the new features of Amazon Lex V2.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/lex/latest/dg/migrate.html">Migrating a bot</a> in the <i>Amazon Lex * developer guide</i>.</p> */ public startMigration( args: StartMigrationCommandInput, options?: __HttpHandlerOptions ): Promise<StartMigrationCommandOutput>; public startMigration( args: StartMigrationCommandInput, cb: (err: any, data?: StartMigrationCommandOutput) => void ): void; public startMigration( args: StartMigrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: StartMigrationCommandOutput) => void ): void; public startMigration( args: StartMigrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartMigrationCommandOutput) => void), cb?: (err: any, data?: StartMigrationCommandOutput) => void ): Promise<StartMigrationCommandOutput> | void { const command = new StartMigrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds the specified tags to the specified resource. If a tag key * already exists, the existing value is replaced with the new value.</p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes tags from a bot, bot alias or bot channel.</p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import {Colony} from '../../Colony'; import {coordName} from '../../utilities/utils'; import {getAllStructureCoordsFromLayout, StructureLayout} from '../RoomPlanner'; export const BUNKER_RADIUS = 6; export const bunkerLayout: StructureLayout = { data: { anchor: {'x': 25, 'y': 25} }, 1 : { 'name' : 'bunkerCore', 'shard' : 'shard2', 'rcl' : '1', 'buildings': { 'spawn': {'pos': [{'x': 29, 'y': 25}]} } }, 2 : { 'name' : 'bunkerCore', 'shard' : 'shard2', 'rcl' : '2', 'buildings': { 'extension': { 'pos': [{'x': 28, 'y': 26}, {'x': 28, 'y': 27}, {'x': 27, 'y': 27}, { 'x': 27, 'y': 28 }, {'x': 29, 'y': 26}] }, 'spawn' : {'pos': [{'x': 29, 'y': 25}]}, 'container': {'pos': [{'x': 27, 'y': 30}]} } }, 3 : { 'name' : 'bunkerCore', 'shard' : 'shard2', 'rcl' : '3', 'buildings': { 'tower' : {'pos': [{'x': 25, 'y': 26}]}, 'extension': { 'pos': [{'x': 28, 'y': 26}, {'x': 29, 'y': 27}, {'x': 28, 'y': 27}, { 'x': 27, 'y': 27 }, {'x': 27, 'y': 28}, {'x': 28, 'y': 28}, {'x': 29, 'y': 28}, {'x': 28, 'y': 29}, { 'x': 27, 'y': 29 }, {'x': 29, 'y': 26}] }, 'spawn' : {'pos': [{'x': 29, 'y': 25}]}, 'container': {'pos': [{'x': 27, 'y': 30}]} } }, 4 : { 'name' : 'bunkerCore', 'shard' : 'shard2', 'rcl' : '4', 'buildings': { 'storage' : {'pos': [{'x': 24, 'y': 25}]}, 'terminal' : {'pos': []}, 'nuker' : {'pos': []}, 'tower' : {'pos': [{'x': 25, 'y': 26}]}, 'powerSpawn': {'pos': []}, 'link' : {'pos': []}, 'road' : { 'pos': [{'x': 24, 'y': 23}, {'x': 25, 'y': 22}, {'x': 26, 'y': 23}, { 'x': 27, 'y': 24 }, {'x': 28, 'y': 25}, {'x': 27, 'y': 26}, {'x': 26, 'y': 27}, {'x': 25, 'y': 28}, { 'x': 24, 'y': 27 }, {'x': 23, 'y': 26}, {'x': 22, 'y': 25}, {'x': 23, 'y': 24}, {'x': 28, 'y': 20}, { 'x': 30, 'y': 22 }, {'x': 24, 'y': 21}, {'x': 30, 'y': 28}, {'x': 28, 'y': 30}, {'x': 26, 'y': 29}, { 'x': 20, 'y': 22 }, {'x': 22, 'y': 20}, {'x': 20, 'y': 28}, {'x': 22, 'y': 30}, {'x': 24, 'y': 19}, { 'x': 26, 'y': 19 }, {'x': 27, 'y': 19}, {'x': 31, 'y': 23}, {'x': 31, 'y': 24}, {'x': 31, 'y': 25}, { 'x': 31, 'y': 26 }, {'x': 31, 'y': 27}, {'x': 27, 'y': 31}, {'x': 27, 'y': 31}, {'x': 26, 'y': 31}, { 'x': 24, 'y': 31 }, {'x': 23, 'y': 31}, {'x': 19, 'y': 27}, {'x': 19, 'y': 26}, {'x': 19, 'y': 25}, { 'x': 19, 'y': 24 }, {'x': 25, 'y': 19}, {'x': 19, 'y': 23}, {'x': 25, 'y': 31}, {'x': 23, 'y': 19}, { 'x': 29, 'y': 21 }, {'x': 21, 'y': 21}, {'x': 21, 'y': 29}, {'x': 29, 'y': 29}, {'x': 21, 'y': 26}, { 'x': 29, 'y': 24 }, {'x': 30, 'y': 23}, {'x': 20, 'y': 27}, {'x': 23, 'y': 25}, {'x': 27, 'y': 25}, { 'x': 23, 'y': 20 }, {'x': 24, 'y': 28}, {'x': 23, 'y': 29}, {'x': 23, 'y': 30}, {'x': 27, 'y': 30}] }, 'observer' : {'pos': []}, 'lab' : {'pos': []}, 'extension' : { 'pos': [{'x': 30, 'y': 24}, {'x': 30, 'y': 25}, {'x': 30, 'y': 26}, { 'x': 28, 'y': 26 }, {'x': 29, 'y': 27}, {'x': 28, 'y': 27}, {'x': 27, 'y': 27}, {'x': 27, 'y': 28}, { 'x': 28, 'y': 28 }, {'x': 29, 'y': 28}, {'x': 28, 'y': 29}, {'x': 27, 'y': 29}, {'x': 26, 'y': 28}, { 'x': 24, 'y': 30 }, {'x': 25, 'y': 30}, {'x': 26, 'y': 30}, {'x': 29, 'y': 26}, {'x': 24, 'y': 29}, { 'x': 30, 'y': 27 }, {'x': 25, 'y': 29}] }, 'spawn' : {'pos': [{'x': 29, 'y': 25}]}, 'container' : {'pos': [{'x': 27, 'y': 30}]} } }, 5 : { 'name' : 'bunkerCore', 'shard' : 'shard2', 'rcl' : '5', 'buildings': { 'storage' : {'pos': [{'x': 24, 'y': 25}]}, 'terminal' : {'pos': []}, 'nuker' : {'pos': []}, 'tower' : {'pos': [{'x': 25, 'y': 24}, {'x': 25, 'y': 26}]}, 'powerSpawn': {'pos': []}, 'link' : {'pos': [{'x': 26, 'y': 26}]}, 'road' : { 'pos': [{'x': 24, 'y': 23}, {'x': 25, 'y': 22}, {'x': 26, 'y': 23}, { 'x': 27, 'y': 24 }, {'x': 28, 'y': 25}, {'x': 27, 'y': 26}, {'x': 26, 'y': 27}, {'x': 25, 'y': 28}, { 'x': 24, 'y': 27 }, {'x': 23, 'y': 26}, {'x': 22, 'y': 25}, {'x': 23, 'y': 24}, {'x': 28, 'y': 20}, { 'x': 30, 'y': 22 }, {'x': 24, 'y': 21}, {'x': 30, 'y': 28}, {'x': 28, 'y': 30}, {'x': 26, 'y': 29}, { 'x': 20, 'y': 22 }, {'x': 22, 'y': 20}, {'x': 20, 'y': 28}, {'x': 22, 'y': 30}, {'x': 24, 'y': 19}, { 'x': 26, 'y': 19 }, {'x': 27, 'y': 19}, {'x': 31, 'y': 23}, {'x': 31, 'y': 24}, {'x': 31, 'y': 25}, { 'x': 31, 'y': 26 }, {'x': 31, 'y': 27}, {'x': 27, 'y': 31}, {'x': 27, 'y': 31}, {'x': 26, 'y': 31}, { 'x': 24, 'y': 31 }, {'x': 23, 'y': 31}, {'x': 19, 'y': 27}, {'x': 19, 'y': 26}, {'x': 19, 'y': 25}, { 'x': 19, 'y': 24 }, {'x': 25, 'y': 19}, {'x': 19, 'y': 23}, {'x': 25, 'y': 31}, {'x': 23, 'y': 19}, { 'x': 29, 'y': 21 }, {'x': 21, 'y': 21}, {'x': 21, 'y': 29}, {'x': 29, 'y': 29}, {'x': 21, 'y': 26}, { 'x': 29, 'y': 24 }, {'x': 30, 'y': 23}, {'x': 20, 'y': 27}, {'x': 23, 'y': 25}, {'x': 27, 'y': 25}, { 'x': 23, 'y': 20 }, {'x': 27, 'y': 30}] }, 'observer' : {'pos': []}, 'lab' : {'pos': []}, 'extension' : { 'pos': [{'x': 30, 'y': 24}, {'x': 30, 'y': 25}, {'x': 30, 'y': 26}, { 'x': 28, 'y': 26 }, {'x': 29, 'y': 27}, {'x': 28, 'y': 27}, {'x': 27, 'y': 27}, {'x': 27, 'y': 28}, { 'x': 28, 'y': 28 }, {'x': 29, 'y': 28}, {'x': 28, 'y': 29}, {'x': 27, 'y': 29}, {'x': 26, 'y': 28}, { 'x': 23, 'y': 27 }, {'x': 24, 'y': 28}, {'x': 23, 'y': 28}, {'x': 22, 'y': 27}, {'x': 21, 'y': 27}, { 'x': 22, 'y': 28 }, {'x': 23, 'y': 29}, {'x': 21, 'y': 28}, {'x': 24, 'y': 30}, {'x': 25, 'y': 30}, { 'x': 26, 'y': 30 }, {'x': 29, 'y': 26}, {'x': 24, 'y': 29}, {'x': 23, 'y': 30}, {'x': 30, 'y': 27}, { 'x': 25, 'y': 29 }, {'x': 22, 'y': 29}] }, 'spawn' : {'pos': [{'x': 29, 'y': 25}]}, 'container' : {'pos': [{'x': 27, 'y': 30}]} } }, 6 : { 'name' : 'bunkerCore', 'shard' : 'shard2', 'rcl' : '6', 'buildings': { 'storage' : {'pos': [{'x': 24, 'y': 25}]}, 'terminal' : {'pos': [{'x': 26, 'y': 25}]}, 'nuker' : {'pos': []}, 'tower' : {'pos': [{'x': 25, 'y': 24}, {'x': 25, 'y': 26}]}, 'powerSpawn': {'pos': []}, 'link' : {'pos': [{'x': 26, 'y': 26}]}, 'road' : { 'pos': [{'x': 24, 'y': 23}, {'x': 25, 'y': 22}, {'x': 26, 'y': 23}, { 'x': 27, 'y': 24 }, {'x': 28, 'y': 25}, {'x': 27, 'y': 26}, {'x': 26, 'y': 27}, {'x': 25, 'y': 28}, { 'x': 24, 'y': 27 }, {'x': 23, 'y': 26}, {'x': 22, 'y': 25}, {'x': 23, 'y': 24}, {'x': 28, 'y': 20}, { 'x': 30, 'y': 22 }, {'x': 24, 'y': 21}, {'x': 30, 'y': 28}, {'x': 28, 'y': 30}, {'x': 26, 'y': 29}, { 'x': 20, 'y': 22 }, {'x': 22, 'y': 20}, {'x': 20, 'y': 28}, {'x': 22, 'y': 30}, {'x': 24, 'y': 19}, { 'x': 26, 'y': 19 }, {'x': 27, 'y': 19}, {'x': 31, 'y': 23}, {'x': 31, 'y': 24}, {'x': 31, 'y': 25}, { 'x': 31, 'y': 26 }, {'x': 31, 'y': 27}, {'x': 27, 'y': 31}, {'x': 27, 'y': 31}, {'x': 26, 'y': 31}, { 'x': 24, 'y': 31 }, {'x': 23, 'y': 31}, {'x': 19, 'y': 27}, {'x': 19, 'y': 26}, {'x': 19, 'y': 25}, { 'x': 19, 'y': 24 }, {'x': 25, 'y': 19}, {'x': 19, 'y': 23}, {'x': 25, 'y': 31}, {'x': 23, 'y': 19}, { 'x': 29, 'y': 21 }, {'x': 21, 'y': 21}, {'x': 21, 'y': 29}, {'x': 29, 'y': 29}, {'x': 21, 'y': 26}, { 'x': 29, 'y': 24 }, {'x': 30, 'y': 23}, {'x': 20, 'y': 27}, {'x': 23, 'y': 25}, {'x': 27, 'y': 25}, { 'x': 22, 'y': 22 }, {'x': 23, 'y': 23}, {'x': 23, 'y': 20}, {'x': 27, 'y': 30}] }, 'observer' : {'pos': []}, 'lab' : {'pos': [{'x': 27, 'y': 23}, {'x': 28, 'y': 24}, {'x': 28, 'y': 23}]}, 'extension' : { 'pos': [{'x': 22, 'y': 24}, {'x': 22, 'y': 23}, {'x': 21, 'y': 23}, { 'x': 30, 'y': 24 }, {'x': 30, 'y': 25}, {'x': 30, 'y': 26}, {'x': 20, 'y': 24}, {'x': 20, 'y': 25}, { 'x': 20, 'y': 26 }, {'x': 21, 'y': 22}, {'x': 28, 'y': 26}, {'x': 29, 'y': 27}, {'x': 28, 'y': 27}, { 'x': 27, 'y': 27 }, {'x': 27, 'y': 28}, {'x': 28, 'y': 28}, {'x': 29, 'y': 28}, {'x': 28, 'y': 29}, { 'x': 27, 'y': 29 }, {'x': 26, 'y': 28}, {'x': 22, 'y': 26}, {'x': 23, 'y': 27}, {'x': 24, 'y': 28}, { 'x': 23, 'y': 28 }, {'x': 22, 'y': 27}, {'x': 21, 'y': 27}, {'x': 22, 'y': 28}, {'x': 23, 'y': 29}, { 'x': 22, 'y': 29 }, {'x': 21, 'y': 28}, {'x': 24, 'y': 30}, {'x': 25, 'y': 30}, {'x': 26, 'y': 30}, { 'x': 29, 'y': 26 }, {'x': 21, 'y': 24}, {'x': 24, 'y': 29}, {'x': 23, 'y': 30}, {'x': 20, 'y': 23}, { 'x': 30, 'y': 27 }, {'x': 25, 'y': 29}] }, 'spawn' : {'pos': [{'x': 29, 'y': 25}]}, 'container' : {'pos': [{'x': 27, 'y': 30}]} } }, 7 : { 'name' : 'bunkerCore', 'shard' : 'shard2', 'rcl' : '7', 'buildings': { 'storage' : {'pos': [{'x': 24, 'y': 25}]}, 'terminal' : {'pos': [{'x': 26, 'y': 25}]}, 'nuker' : {'pos': []}, 'tower' : {'pos': [{'x': 25, 'y': 24}, {'x': 25, 'y': 26}, {'x': 25, 'y': 23}]}, 'powerSpawn': {'pos': []}, 'link' : {'pos': [{'x': 26, 'y': 26}]}, 'road' : { 'pos': [{'x': 24, 'y': 23}, {'x': 25, 'y': 22}, {'x': 26, 'y': 23}, { 'x': 27, 'y': 24 }, {'x': 28, 'y': 25}, {'x': 27, 'y': 26}, {'x': 26, 'y': 27}, {'x': 25, 'y': 28}, { 'x': 24, 'y': 27 }, {'x': 23, 'y': 26}, {'x': 22, 'y': 25}, {'x': 23, 'y': 24}, {'x': 28, 'y': 20}, { 'x': 30, 'y': 22 }, {'x': 24, 'y': 21}, {'x': 30, 'y': 28}, {'x': 28, 'y': 30}, {'x': 26, 'y': 29}, { 'x': 20, 'y': 22 }, {'x': 22, 'y': 20}, {'x': 20, 'y': 28}, {'x': 22, 'y': 30}, {'x': 24, 'y': 19}, { 'x': 26, 'y': 19 }, {'x': 27, 'y': 19}, {'x': 31, 'y': 23}, {'x': 31, 'y': 24}, {'x': 31, 'y': 25}, { 'x': 31, 'y': 26 }, {'x': 31, 'y': 27}, {'x': 27, 'y': 31}, {'x': 27, 'y': 31}, {'x': 26, 'y': 31}, { 'x': 24, 'y': 31 }, {'x': 23, 'y': 31}, {'x': 19, 'y': 27}, {'x': 19, 'y': 26}, {'x': 19, 'y': 25}, { 'x': 19, 'y': 24 }, {'x': 25, 'y': 19}, {'x': 19, 'y': 23}, {'x': 25, 'y': 31}, {'x': 23, 'y': 19}, { 'x': 29, 'y': 21 }, {'x': 21, 'y': 21}, {'x': 21, 'y': 29}, {'x': 29, 'y': 29}, {'x': 21, 'y': 26}, { 'x': 29, 'y': 24 }, {'x': 30, 'y': 23}, {'x': 20, 'y': 27}, {'x': 27, 'y': 22}, {'x': 28, 'y': 21}, { 'x': 23, 'y': 25 }, {'x': 27, 'y': 25}, {'x': 27, 'y': 30}, {'x': 23, 'y': 20}] }, 'observer' : {'pos': []}, 'lab' : { 'pos': [{'x': 27, 'y': 23}, {'x': 28, 'y': 24}, {'x': 28, 'y': 22}, { 'x': 28, 'y': 23 }, {'x': 29, 'y': 23}, {'x': 29, 'y': 22}] }, 'extension' : { 'pos': [{'x': 24, 'y': 22}, {'x': 23, 'y': 23}, {'x': 22, 'y': 24}, { 'x': 22, 'y': 23 }, {'x': 23, 'y': 22}, {'x': 23, 'y': 21}, {'x': 22, 'y': 22}, {'x': 21, 'y': 23}, { 'x': 25, 'y': 20 }, {'x': 26, 'y': 20}, {'x': 30, 'y': 24}, {'x': 30, 'y': 25}, {'x': 30, 'y': 26}, { 'x': 20, 'y': 24 }, {'x': 20, 'y': 25}, {'x': 20, 'y': 26}, {'x': 22, 'y': 21}, {'x': 21, 'y': 22}, { 'x': 28, 'y': 26 }, {'x': 29, 'y': 27}, {'x': 28, 'y': 27}, {'x': 27, 'y': 27}, {'x': 27, 'y': 28}, { 'x': 28, 'y': 28 }, {'x': 29, 'y': 28}, {'x': 28, 'y': 29}, {'x': 27, 'y': 29}, {'x': 26, 'y': 28}, { 'x': 22, 'y': 26 }, {'x': 23, 'y': 27}, {'x': 24, 'y': 28}, {'x': 23, 'y': 28}, {'x': 22, 'y': 27}, { 'x': 21, 'y': 27 }, {'x': 22, 'y': 28}, {'x': 23, 'y': 29}, {'x': 22, 'y': 29}, {'x': 21, 'y': 28}, { 'x': 24, 'y': 30 }, {'x': 25, 'y': 30}, {'x': 26, 'y': 30}, {'x': 29, 'y': 26}, {'x': 21, 'y': 24}, { 'x': 26, 'y': 21 }, {'x': 24, 'y': 29}, {'x': 23, 'y': 30}, {'x': 20, 'y': 23}, {'x': 27, 'y': 20}, { 'x': 30, 'y': 27 }, {'x': 25, 'y': 29}] }, 'spawn' : {'pos': [{'x': 29, 'y': 25}, {'x': 26, 'y': 24}]}, 'container' : {'pos': [{'x': 27, 'y': 30}, {'x': 23, 'y': 20}]} } }, 8 : { 'name' : 'bunkerCore', 'shard' : 'shard2', 'rcl' : '8', 'buildings': { 'storage' : {'pos': [{'x': 24, 'y': 25}]}, 'terminal' : {'pos': [{'x': 26, 'y': 25}]}, 'nuker' : {'pos': [{'x': 24, 'y': 24}]}, 'tower' : { 'pos': [{'x': 27, 'y': 25}, {'x': 23, 'y': 25}, {'x': 25, 'y': 27}, { 'x': 25, 'y': 23 }, {'x': 25, 'y': 24}, {'x': 25, 'y': 26}] }, 'powerSpawn': {'pos': [{'x': 24, 'y': 26}]}, 'link' : {'pos': [{'x': 26, 'y': 26}]}, 'road' : { 'pos': [{'x': 24, 'y': 23}, {'x': 25, 'y': 22}, {'x': 26, 'y': 23}, { 'x': 27, 'y': 24 }, {'x': 28, 'y': 25}, {'x': 27, 'y': 26}, {'x': 26, 'y': 27}, {'x': 25, 'y': 28}, { 'x': 24, 'y': 27 }, {'x': 23, 'y': 26}, {'x': 22, 'y': 25}, {'x': 23, 'y': 24}, {'x': 28, 'y': 20}, { 'x': 30, 'y': 22 }, {'x': 24, 'y': 21}, {'x': 30, 'y': 28}, {'x': 28, 'y': 30}, {'x': 26, 'y': 29}, { 'x': 20, 'y': 22 }, {'x': 22, 'y': 20}, {'x': 20, 'y': 28}, {'x': 22, 'y': 30}, {'x': 24, 'y': 19}, { 'x': 26, 'y': 19 }, {'x': 27, 'y': 19}, {'x': 31, 'y': 23}, {'x': 31, 'y': 24}, {'x': 31, 'y': 25}, { 'x': 31, 'y': 26 }, {'x': 31, 'y': 27}, {'x': 27, 'y': 31}, {'x': 27, 'y': 31}, {'x': 26, 'y': 31}, { 'x': 24, 'y': 31 }, {'x': 23, 'y': 31}, {'x': 19, 'y': 27}, {'x': 19, 'y': 26}, {'x': 19, 'y': 25}, { 'x': 19, 'y': 24 }, {'x': 25, 'y': 19}, {'x': 19, 'y': 23}, {'x': 25, 'y': 31}, {'x': 23, 'y': 19}, { 'x': 29, 'y': 21 }, {'x': 21, 'y': 21}, {'x': 21, 'y': 29}, {'x': 29, 'y': 29}, {'x': 21, 'y': 26}, { 'x': 29, 'y': 24 }, {'x': 30, 'y': 23}, {'x': 20, 'y': 27}, {'x': 27, 'y': 30}, {'x': 23, 'y': 20}] }, 'observer' : {'pos': [{'x': 21, 'y': 25}]}, 'lab' : { 'pos': [{'x': 26, 'y': 22}, {'x': 27, 'y': 23}, {'x': 28, 'y': 24}, { 'x': 27, 'y': 22 }, {'x': 27, 'y': 21}, {'x': 28, 'y': 22}, {'x': 28, 'y': 23}, {'x': 29, 'y': 23}, { 'x': 28, 'y': 21 }, {'x': 29, 'y': 22}] }, 'extension' : { 'pos': [{'x': 24, 'y': 22}, {'x': 23, 'y': 23}, {'x': 22, 'y': 24}, { 'x': 22, 'y': 23 }, {'x': 23, 'y': 22}, {'x': 23, 'y': 21}, {'x': 22, 'y': 22}, {'x': 21, 'y': 23}, { 'x': 24, 'y': 20 }, {'x': 25, 'y': 20}, {'x': 26, 'y': 20}, {'x': 30, 'y': 24}, {'x': 30, 'y': 25}, { 'x': 30, 'y': 26 }, {'x': 20, 'y': 24}, {'x': 20, 'y': 25}, {'x': 20, 'y': 26}, {'x': 22, 'y': 21}, { 'x': 21, 'y': 22 }, {'x': 28, 'y': 26}, {'x': 29, 'y': 27}, {'x': 28, 'y': 27}, {'x': 27, 'y': 27}, { 'x': 27, 'y': 28 }, {'x': 28, 'y': 28}, {'x': 29, 'y': 28}, {'x': 28, 'y': 29}, {'x': 27, 'y': 29}, { 'x': 26, 'y': 28 }, {'x': 22, 'y': 26}, {'x': 23, 'y': 27}, {'x': 24, 'y': 28}, {'x': 23, 'y': 28}, { 'x': 22, 'y': 27 }, {'x': 21, 'y': 27}, {'x': 22, 'y': 28}, {'x': 23, 'y': 29}, {'x': 22, 'y': 29}, { 'x': 21, 'y': 28 }, {'x': 24, 'y': 30}, {'x': 25, 'y': 30}, {'x': 26, 'y': 30}, {'x': 29, 'y': 26}, { 'x': 21, 'y': 24 }, {'x': 26, 'y': 21}, {'x': 24, 'y': 29}, {'x': 23, 'y': 30}, {'x': 20, 'y': 23}, { 'x': 27, 'y': 20 }, {'x': 30, 'y': 27}, {'x': 25, 'y': 29}] }, 'spawn' : {'pos': [{'x': 29, 'y': 25}, {'x': 26, 'y': 24}, {'x': 25, 'y': 21}]}, 'container' : {'pos': [{'x': 27, 'y': 30}, {'x': 23, 'y': 20}]} } } }; let _allBunkerCoords: { [rcl: number]: Coord[] } = {}; for (let rcl of [1, 2, 3, 4, 5, 6, 7, 8]) { if (bunkerLayout[rcl]!.buildings) { _allBunkerCoords[rcl] = getAllStructureCoordsFromLayout(bunkerLayout, rcl); } if (rcl == 7 || rcl == 8) { // add center tile for advanced bunkers _allBunkerCoords[rcl].push(bunkerLayout.data.anchor); } } export const allBunkerCoords = _allBunkerCoords; export const bunkerCoordLookup = _.mapValues(_allBunkerCoords, (coordArr: Coord[]) => _.zipObject(_.map(coordArr, c => [coordName(c), true]) )) as { [rcl: number]: { [coordName: string]: true | undefined } }; // Fast function for checking if a position is inside the bunker export function insideBunkerBounds(pos: RoomPosition, colony: Colony): boolean { if (colony.roomPlanner.memory.bunkerData && colony.roomPlanner.memory.bunkerData.anchor) { const dx = bunkerLayout.data.anchor.x - colony.roomPlanner.memory.bunkerData.anchor.x; const dy = bunkerLayout.data.anchor.y - colony.roomPlanner.memory.bunkerData.anchor.y; const coord = {x: pos.x + dx, y: pos.y + dy}; return (!!bunkerCoordLookup[colony.level][coordName(coord)]); } return false; } export function getPosFromBunkerCoord(coord: Coord, colony: Colony): RoomPosition { if (colony.roomPlanner.memory.bunkerData && colony.roomPlanner.memory.bunkerData.anchor) { let dx = colony.roomPlanner.memory.bunkerData.anchor.x - bunkerLayout.data.anchor.x; let dy = colony.roomPlanner.memory.bunkerData.anchor.y - bunkerLayout.data.anchor.y; return new RoomPosition(coord.x + dx, coord.y + dy, colony.room.name); } console.log('getPosFromBunkerCoord: shouldn\'t reach here! Unprotected call from non-bunker?'); return new RoomPosition(-1, -1, 'invalid'); } // Spots where queens can sit to be renewed when idle export const bunkerChargingSpots: Coord[] = [{'x': 29, 'y': 24}, {'x': 24, 'y': 21}]; // Efficient, hard-coded order in which to refill extensions, spawns, labs, and towers export const quadrantFillOrder = { lowerRight: [{'x': 30, 'y': 24}, {'x': 30, 'y': 25}, {'x': 29, 'y': 25}, {'x': 29, 'y': 26}, {'x': 28, 'y': 26}, { 'x': 27, 'y': 25 }, {'x': 28, 'y': 27}, {'x': 27, 'y': 27}, {'x': 27, 'y': 28}, {'x': 26, 'y': 28}, {'x': 27, 'y': 29}, { 'x': 28, 'y': 29 }, {'x': 28, 'y': 28}, {'x': 29, 'y': 28}, {'x': 29, 'y': 27}, {'x': 30, 'y': 27}, {'x': 30, 'y': 26}], lowerLeft : [{'x': 22, 'y': 26}, {'x': 22, 'y': 27}, {'x': 23, 'y': 27}, {'x': 23, 'y': 28}, { 'x': 24, 'y': 28 }, {'x': 25, 'y': 27}, {'x': 24, 'y': 29}, {'x': 25, 'y': 29}, {'x': 25, 'y': 30}, {'x': 26, 'y': 30}, { 'x': 24, 'y': 30 }, {'x': 23, 'y': 30}, {'x': 23, 'y': 29}, {'x': 22, 'y': 29}, {'x': 22, 'y': 28}, {'x': 21, 'y': 28}, { 'x': 21, 'y': 27 }], upperLeft : [{'x': 23, 'y': 21}, {'x': 23, 'y': 22}, {'x': 24, 'y': 22}, {'x': 23, 'y': 23}, { 'x': 22, 'y': 23 }, {'x': 22, 'y': 24}, {'x': 23, 'y': 25}, {'x': 21, 'y': 24}, {'x': 21, 'y': 25}, {'x': 20, 'y': 25}, { 'x': 20, 'y': 26 }, {'x': 22, 'y': 21}, {'x': 22, 'y': 22}, {'x': 21, 'y': 22}, {'x': 21, 'y': 23}, {'x': 20, 'y': 23}, { 'x': 20, 'y': 24 }], upperRight: [{'x': 24, 'y': 20}, {'x': 25, 'y': 20}, {'x': 25, 'y': 21}, {'x': 26, 'y': 21}, { 'x': 26, 'y': 22 }, {'x': 27, 'y': 22}, {'x': 27, 'y': 23}, {'x': 25, 'y': 23}, {'x': 28, 'y': 23}, {'x': 28, 'y': 24}, { 'x': 29, 'y': 23 }, {'x': 29, 'y': 22}, {'x': 28, 'y': 22}, {'x': 28, 'y': 21}, {'x': 27, 'y': 21}, {'x': 27, 'y': 20}, { 'x': 26, 'y': 20 }] }; // Used to generate energy structure ordering for spawn.spawnCreep() export const energyStructureOrder: Coord[] = (<Coord[]>[]).concat(quadrantFillOrder.lowerRight, quadrantFillOrder.upperLeft, quadrantFillOrder.lowerLeft, quadrantFillOrder.upperRight);
the_stack
import { getStrokeRadius } from './getStrokeRadius' import type { StrokeOptions, StrokePoint } from './types' import { add, dist2, dpr, lrp, med, mul, neg, per, prj, rotAround, sub, uni, } from './vec' const { min, PI } = Math // This is the rate of change for simulated pressure. It could be an option. const RATE_OF_PRESSURE_CHANGE = 0.275 // Browser strokes seem to be off if PI is regular, a tiny offset seems to fix it const FIXED_PI = PI + 0.0001 /** * ## getStrokeOutlinePoints * @description Get an array of points (as `[x, y]`) representing the outline of a stroke. * @param points An array of StrokePoints as returned from `getStrokePoints`. * @param options (optional) An object with options. * @param options.size The base size (diameter) of the stroke. * @param options.thinning The effect of pressure on the stroke's size. * @param options.smoothing How much to soften the stroke's edges. * @param options.easing An easing function to apply to each point's pressure. * @param options.simulatePressure Whether to simulate pressure based on velocity. * @param options.start Cap, taper and easing for the start of the line. * @param options.end Cap, taper and easing for the end of the line. * @param options.last Whether to handle the points as a completed stroke. */ export function getStrokeOutlinePoints( points: StrokePoint[], options: Partial<StrokeOptions> = {} as Partial<StrokeOptions> ): number[][] { const { size = 16, smoothing = 0.5, thinning = 0.5, simulatePressure = true, easing = (t) => t, start = {}, end = {}, last: isComplete = false, } = options const { cap: capStart = true, taper: taperStart = 0, easing: taperStartEase = (t) => t * (2 - t), } = start const { cap: capEnd = true, taper: taperEnd = 0, easing: taperEndEase = (t) => --t * t * t + 1, } = end // We can't do anything with an empty array or a stroke with negative size. if (points.length === 0 || size <= 0) { return [] } // The total length of the line const totalLength = points[points.length - 1].runningLength // The minimum allowed distance between points (squared) const minDistance = Math.pow(size * smoothing, 2) // Our collected left and right points const leftPts: number[][] = [] const rightPts: number[][] = [] // Previous pressure (start with average of first five pressures, // in order to prevent fat starts for every line. Drawn lines // almost always start slow! let prevPressure = points.slice(0, 10).reduce((acc, curr) => { let pressure = curr.pressure if (simulatePressure) { // Speed of change - how fast should the the pressure changing? const sp = min(1, curr.distance / size) // Rate of change - how much of a change is there? const rp = min(1, 1 - sp) // Accelerate the pressure pressure = min(1, acc + (rp - acc) * (sp * RATE_OF_PRESSURE_CHANGE)) } return (acc + pressure) / 2 }, points[0].pressure) // The current radius let radius = getStrokeRadius( size, thinning, points[points.length - 1].pressure, easing ) // The radius of the first saved point let firstRadius: number | undefined = undefined // Previous vector let prevVector = points[0].vector // Previous left and right points let pl = points[0].point let pr = pl // Temporary left and right points let tl = pl let tr = pr // let short = true /* Find the outline's left and right points Iterating through the points and populate the rightPts and leftPts arrays, skipping the first and last pointsm, which will get caps later on. */ for (let i = 0; i < points.length; i++) { let { pressure } = points[i] const { point, vector, distance, runningLength } = points[i] // Removes noise from the end of the line if (i < points.length - 1 && totalLength - runningLength < 3) { continue } /* Calculate the radius If not thinning, the current point's radius will be half the size; or otherwise, the size will be based on the current (real or simulated) pressure. */ if (thinning) { if (simulatePressure) { // If we're simulating pressure, then do so based on the distance // between the current point and the previous point, and the size // of the stroke. Otherwise, use the input pressure. const sp = min(1, distance / size) const rp = min(1, 1 - sp) pressure = min( 1, prevPressure + (rp - prevPressure) * (sp * RATE_OF_PRESSURE_CHANGE) ) } radius = getStrokeRadius(size, thinning, pressure, easing) } else { radius = size / 2 } if (firstRadius === undefined) { firstRadius = radius } /* Apply tapering If the current length is within the taper distance at either the start or the end, calculate the taper strengths. Apply the smaller of the two taper strengths to the radius. */ const ts = runningLength < taperStart ? taperStartEase(runningLength / taperStart) : 1 const te = totalLength - runningLength < taperEnd ? taperEndEase((totalLength - runningLength) / taperEnd) : 1 radius = Math.max(0.01, radius * Math.min(ts, te)) /* Add points to left and right */ // Handle the last point if (i === points.length - 1) { const offset = mul(per(vector), radius) leftPts.push(sub(point, offset)) rightPts.push(add(point, offset)) continue } const nextVector = points[i + 1].vector const nextDpr = dpr(vector, nextVector) /* Handle sharp corners Find the difference (dot product) between the current and next vector. If the next vector is at more than a right angle to the current vector, draw a cap at the current point. */ if (nextDpr < 0) { // It's a sharp corner. Draw a rounded cap and move on to the next point // Considering saving these and drawing them later? So that we can avoid // crossing future points. const offset = mul(per(prevVector), radius) for (let step = 1 / 13, t = 0; t <= 1; t += step) { tl = rotAround(sub(point, offset), point, FIXED_PI * t) leftPts.push(tl) tr = rotAround(add(point, offset), point, FIXED_PI * -t) rightPts.push(tr) } pl = tl pr = tr continue } /* Add regular points Project points to either side of the current point, using the calculated size as a distance. If a point's distance to the previous point on that side greater than the minimum distance (or if the corner is kinda sharp), add the points to the side's points array. */ const offset = mul(per(lrp(nextVector, vector, nextDpr)), radius) tl = sub(point, offset) if (i <= 1 || dist2(pl, tl) > minDistance) { leftPts.push(tl) pl = tl } tr = add(point, offset) if (i <= 1 || dist2(pr, tr) > minDistance) { rightPts.push(tr) pr = tr } // Set variables for next iteration prevPressure = pressure prevVector = vector } /* Drawing caps Now that we have our points on either side of the line, we need to draw caps at the start and end. Tapered lines don't have caps, but may have dots for very short lines. */ const firstPoint = points[0].point.slice(0, 2) const lastPoint = points.length > 1 ? points[points.length - 1].point.slice(0, 2) : add(points[0].point, [1, 1]) const startCap: number[][] = [] const endCap: number[][] = [] /* Draw a dot for very short or completed strokes If the line is too short to gather left or right points and if the line is not tapered on either side, draw a dot. If the line is tapered, then only draw a dot if the line is both very short and complete. If we draw a dot, we can just return those points. */ if (points.length === 1) { if (!(taperStart || taperEnd) || isComplete) { const start = prj( firstPoint, uni(per(sub(firstPoint, lastPoint))), -(firstRadius || radius) ) const dotPts: number[][] = [] for (let step = 1 / 13, t = step; t <= 1; t += step) { dotPts.push(rotAround(start, firstPoint, FIXED_PI * 2 * t)) } return dotPts } } else { /* Draw a start cap Unless the line has a tapered start, or unless the line has a tapered end and the line is very short, draw a start cap around the first point. Use the distance between the second left and right point for the cap's radius. Finally remove the first left and right points. :psyduck: */ if (taperStart || (taperEnd && points.length === 1)) { // The start point is tapered, noop } else if (capStart) { // Draw the round cap - add thirteen points rotating the right point around the start point to the left point for (let step = 1 / 13, t = step; t <= 1; t += step) { const pt = rotAround(rightPts[0], firstPoint, FIXED_PI * t) startCap.push(pt) } } else { // Draw the flat cap - add a point to the left and right of the start point const cornersVector = sub(leftPts[0], rightPts[0]) const offsetA = mul(cornersVector, 0.5) const offsetB = mul(cornersVector, 0.51) startCap.push( sub(firstPoint, offsetA), sub(firstPoint, offsetB), add(firstPoint, offsetB), add(firstPoint, offsetA) ) } /* Draw an end cap If the line does not have a tapered end, and unless the line has a tapered start and the line is very short, draw a cap around the last point. Finally, remove the last left and right points. Otherwise, add the last point. Note that This cap is a full-turn-and-a-half: this prevents incorrect caps on sharp end turns. */ const direction = per(neg(points[points.length - 1].vector)) if (taperEnd || (taperStart && points.length === 1)) { // Tapered end - push the last point to the line endCap.push(lastPoint) } else if (capEnd) { // Draw the round end cap const start = prj(lastPoint, direction, radius) for (let step = 1 / 29, t = step; t < 1; t += step) { endCap.push(rotAround(start, lastPoint, FIXED_PI * 3 * t)) } } else { // Draw the flat end cap endCap.push( add(lastPoint, mul(direction, radius)), add(lastPoint, mul(direction, radius * 0.99)), sub(lastPoint, mul(direction, radius * 0.99)), sub(lastPoint, mul(direction, radius)) ) } } /* Return the points in the correct winding order: begin on the left side, then continue around the end cap, then come back along the right side, and finally complete the start cap. */ return leftPts.concat(endCap, rightPts.reverse(), startCap) }
the_stack
import ArtistContract from '@DataContracts/Artist/ArtistContract'; import ArtistForArtistContract from '@DataContracts/Artist/ArtistForArtistContract'; import ArtistForEditContract from '@DataContracts/Artist/ArtistForEditContract'; import TranslatedEnumField from '@DataContracts/TranslatedEnumField'; import ArtistHelper from '@Helpers/ArtistHelper'; import { ArtistAutoCompleteParams } from '@KnockoutExtensions/AutoCompleteParams'; import ArtistType from '@Models/Artists/ArtistType'; import EntryType from '@Models/EntryType'; import ArtistRepository from '@Repositories/ArtistRepository'; import UserRepository from '@Repositories/UserRepository'; import { IDialogService } from '@Shared/DialogService'; import GlobalValues from '@Shared/GlobalValues'; import UrlMapper from '@Shared/UrlMapper'; import $ from 'jquery'; import ko, { Computed, Observable, ObservableArray } from 'knockout'; import _ from 'lodash'; import moment from 'moment'; import BasicEntryLinkViewModel from '../BasicEntryLinkViewModel'; import DeleteEntryViewModel from '../DeleteEntryViewModel'; import EntryPictureFileListEditViewModel from '../EntryPictureFileListEditViewModel'; import EnglishTranslatedStringEditViewModel from '../Globalization/EnglishTranslatedStringEditViewModel'; import NamesEditViewModel from '../Globalization/NamesEditViewModel'; import WebLinksEditViewModel from '../WebLinksEditViewModel'; export default class ArtistEditViewModel { public addAssociatedArtist = (): void => { if (this.newAssociatedArtist.isEmpty()) return; this.associatedArtists.push( new ArtistForArtistEditViewModel({ parent: this.newAssociatedArtist.entry(), linkType: this.newAssociatedArtistType(), }), ); this.newAssociatedArtist.clear(); }; private addGroup = (artistId?: number): void => { if (artistId) { this.artistRepo .getOne({ id: artistId, lang: this.values.languagePreference }) .then((artist: ArtistContract) => { this.groups.push({ id: 0, parent: artist }); }); } }; public artistType: Computed<ArtistType>; public artistTypeStr: Observable<string>; public allowBaseVoicebank: Computed<boolean>; public associatedArtists: ObservableArray<ArtistForArtistEditViewModel>; public baseVoicebank: BasicEntryLinkViewModel<ArtistContract>; public baseVoicebankSearchParams: ArtistAutoCompleteParams; public canHaveCircles: Computed<boolean>; // Can have related artists (associatedArtists) such as voice provider and illustrator public canHaveRelatedArtists: Computed<boolean>; public canHaveReleaseDate: Computed<boolean>; // Clears fields that are not valid for the selected artist type. private clearInvalidData = (): void => { if (!this.canHaveReleaseDate()) { this.releaseDate(null!); } if (!this.canHaveRelatedArtists()) { this.associatedArtists([]); } if (!this.allowBaseVoicebank()) { this.baseVoicebank.clear(); } if (!this.canHaveCircles()) { this.groups([]); } }; public defaultNameLanguage: Observable<string>; public deleteViewModel = new DeleteEntryViewModel((notes) => { $.ajax( this.urlMapper.mapRelative( 'api/artists/' + this.id + '?notes=' + encodeURIComponent(notes), ), { type: 'DELETE', success: () => { window.location.href = this.urlMapper.mapRelative( '/Artist/Details/' + this.id, ); }, }, ); }); public description: EnglishTranslatedStringEditViewModel; public groups: ObservableArray<ArtistForArtistContract>; public groupSearchParams: ArtistAutoCompleteParams = { acceptSelection: this.addGroup, extraQueryParams: { artistTypes: 'Label,Circle,OtherGroup,Band' }, height: 300, }; public hasValidationErrors: Computed<boolean>; public id: number; public illustrator: BasicEntryLinkViewModel<ArtistContract>; public names: NamesEditViewModel; public newAssociatedArtist: BasicEntryLinkViewModel<ArtistContract>; public newAssociatedArtistType = ko.observable<string>(); public pictures: EntryPictureFileListEditViewModel; public releaseDate: Observable<Date>; public removeGroup = (group: ArtistForArtistContract): void => { this.groups.remove(group); }; public status: Observable<string>; public submit = (): boolean => { if ( this.hasValidationErrors() && this.status() !== 'Draft' && this.dialogService.confirm(vdb.resources.entryEdit.saveWarning) === false ) { return false; } this.clearInvalidData(); this.submitting(true); var submittedModel: ArtistForEditContract = { artistType: this.artistTypeStr(), associatedArtists: _.map(this.associatedArtists(), (a) => a.toContract()), baseVoicebank: this.baseVoicebank.entry(), defaultNameLanguage: this.defaultNameLanguage(), description: this.description.toContract(), groups: this.groups(), id: this.id, illustrator: this.illustrator.entry(), names: this.names.toContracts(), pictures: this.pictures.toContracts(), releaseDate: this.releaseDate() ? this.releaseDate().toISOString() : null!, status: this.status(), updateNotes: this.updateNotes(), voiceProvider: this.voiceProvider.entry(), webLinks: this.webLinks.toContracts(), pictureMime: '', }; this.submittedJson(ko.toJSON(submittedModel)); return true; }; public submittedJson = ko.observable(''); public submitting = ko.observable(false); public updateNotes = ko.observable(''); public validationExpanded = ko.observable(false); public validationError_needReferences: Computed<boolean>; public validationError_needType: Computed<boolean>; public validationError_unnecessaryPName: Computed<boolean>; public validationError_unspecifiedNames: Computed<boolean>; public voiceProvider: BasicEntryLinkViewModel<ArtistContract>; public webLinks: WebLinksEditViewModel; private canHaveBaseVoicebank(at: ArtistType): boolean { return ( (ArtistHelper.isVocalistType(at) || at === ArtistType.OtherIndividual) && at !== ArtistType.Vocalist ); } public constructor( private readonly values: GlobalValues, private artistRepo: ArtistRepository, userRepository: UserRepository, private urlMapper: UrlMapper, webLinkCategories: TranslatedEnumField[], data: ArtistForEditContract, private dialogService: IDialogService, ) { this.artistTypeStr = ko.observable(data.artistType); this.artistType = ko.computed( () => ArtistType[this.artistTypeStr() as keyof typeof ArtistType], ); this.allowBaseVoicebank = ko.computed(() => this.canHaveBaseVoicebank(this.artistType()), ); this.associatedArtists = ko.observableArray( _.map(data.associatedArtists, (a) => new ArtistForArtistEditViewModel(a)), ); this.baseVoicebank = new BasicEntryLinkViewModel( data.baseVoicebank, (entryId) => artistRepo.getOne({ id: entryId, lang: values.languagePreference }), ); this.description = new EnglishTranslatedStringEditViewModel( data.description, ); this.defaultNameLanguage = ko.observable(data.defaultNameLanguage); this.groups = ko.observableArray(data.groups); this.id = data.id; this.illustrator = new BasicEntryLinkViewModel( data.illustrator, (entryId) => artistRepo.getOne({ id: entryId, lang: values.languagePreference }), ); this.names = NamesEditViewModel.fromContracts(data.names); this.newAssociatedArtist = new BasicEntryLinkViewModel<ArtistContract>( null!, (entryId) => artistRepo.getOne({ id: entryId, lang: values.languagePreference }), ); this.pictures = new EntryPictureFileListEditViewModel(data.pictures); this.releaseDate = ko.observable( data.releaseDate ? moment(data.releaseDate).toDate() : null!, ); // Assume server date is UTC this.status = ko.observable(data.status); this.voiceProvider = new BasicEntryLinkViewModel( data.voiceProvider, (entryId) => artistRepo.getOne({ id: entryId, lang: values.languagePreference }), ); this.webLinks = new WebLinksEditViewModel(data.webLinks, webLinkCategories); this.baseVoicebankSearchParams = { acceptSelection: this.baseVoicebank.id, extraQueryParams: { artistTypes: 'Vocaloid,UTAU,CeVIO,OtherVocalist,OtherVoiceSynthesizer,Unknown', }, ignoreId: this.id, }; this.canHaveCircles = ko.computed(() => { return this.artistType() !== ArtistType.Label; }); this.canHaveRelatedArtists = ko.computed(() => { return ArtistHelper.canHaveChildVoicebanks(this.artistType()); }); this.canHaveReleaseDate = ko.computed(() => { const vocaloidTypes = [ ArtistType.Vocaloid, ArtistType.UTAU, ArtistType.CeVIO, ArtistType.OtherVoiceSynthesizer, ArtistType.SynthesizerV, ]; return _.includes(vocaloidTypes, this.artistType()); }); this.newAssociatedArtist.entry.subscribe(this.addAssociatedArtist); this.validationError_needReferences = ko.computed( () => (this.description.original() == null || this.description.original().length) === 0 && this.webLinks.items().length === 0, ); this.validationError_needType = ko.computed( () => this.artistType() === ArtistType.Unknown, ); this.validationError_unspecifiedNames = ko.computed( () => !this.names.hasPrimaryName(), ); this.validationError_unnecessaryPName = ko.computed(() => { var allNames = this.names.getAllNames(); return _.some(allNames, (n) => _.some( allNames, (n2) => n !== n2 && (n.value() === n2.value() + 'P' || n.value() === n2.value() + '-P' || n.value() === n2.value() + 'p' || n.value() === n2.value() + '-p'), ), ); }); this.hasValidationErrors = ko.computed( () => this.validationError_needReferences() || this.validationError_needType() || this.validationError_unspecifiedNames() || this.validationError_unnecessaryPName(), ); window.setInterval( () => userRepository.refreshEntryEdit({ entryType: EntryType.Artist, entryId: data.id, }), 10000, ); } } export class ArtistForArtistEditViewModel { public constructor(link: ArtistForArtistContract) { this.linkType = ko.observable(link.linkType!); this.parent = link.parent; } public linkType: Observable<string>; public parent: ArtistContract; public toContract = (): ArtistForArtistContract => { return { linkType: this.linkType(), parent: this.parent, } as ArtistForArtistContract; }; }
the_stack
import { TestBed, fakeAsync, tick } from '@angular/core/testing'; import { IgxGridModule } from './public_api'; import { GridWithUndefinedDataComponent } from '../../test-utils/grid-samples.spec'; import { PagingComponent } from '../../test-utils/grid-base-components.spec'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { configureTestSuite } from '../../test-utils/configure-suite'; import { wait } from '../../test-utils/ui-interactions.spec'; import { IgxNumberFilteringOperand } from '../../data-operations/filtering-condition'; import { GridFunctions, PAGER_CLASS } from '../../test-utils/grid-functions.spec'; import { ControlsFunction, BUTTON_DISABLED_CLASS } from '../../test-utils/controls-functions.spec'; const verifyGridPager = (fix, rowsCount, firstCellValue, pagerText, buttonsVisibility) => { const grid = fix.componentInstance.grid; expect(grid.getCellByColumn(0, 'ID').value).toMatch(firstCellValue); expect(grid.rowList.length).toEqual(rowsCount, 'Invalid number of rows initialized'); if (pagerText != null) { expect(grid.nativeElement.querySelector(PAGER_CLASS)).toBeDefined(); expect(grid.nativeElement.querySelectorAll('igx-select').length).toEqual(1); expect(grid.nativeElement.querySelector('.igx-page-nav__text').textContent).toMatch(pagerText); } if (buttonsVisibility != null && buttonsVisibility.length === 4) { const pagingButtons = GridFunctions.getPagingButtons(grid.nativeElement); expect(pagingButtons.length).toEqual(4); expect(pagingButtons[0].className.includes(BUTTON_DISABLED_CLASS)).toBe(buttonsVisibility[0]); expect(pagingButtons[1].className.includes(BUTTON_DISABLED_CLASS)).toBe(buttonsVisibility[1]); expect(pagingButtons[2].className.includes(BUTTON_DISABLED_CLASS)).toBe(buttonsVisibility[2]); expect(pagingButtons[3].className.includes(BUTTON_DISABLED_CLASS)).toBe(buttonsVisibility[3]); } }; describe('IgxGrid - Grid Paging #grid', () => { configureTestSuite((() => { TestBed.configureTestingModule({ declarations: [ PagingComponent, GridWithUndefinedDataComponent ], imports: [IgxGridModule, NoopAnimationsModule] }); })); let fix; let grid; describe('General', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(PagingComponent); fix.detectChanges(); grid = fix.componentInstance.grid; })); it('should paginate data UI', () => { fix.detectChanges(); expect(grid.paginator).toBeDefined(); verifyGridPager(fix, 3, '1', '1\xA0of\xA04', [true, true, false, false]); // Go to next page GridFunctions.navigateToNextPage(grid.nativeElement); fix.detectChanges(); verifyGridPager(fix, 3, '4', '2\xA0of\xA04', [false, false, false, false]); // Go to last page GridFunctions.navigateToLastPage(grid.nativeElement); fix.detectChanges(); verifyGridPager(fix, 1, '10', '4\xA0of\xA04', [false, false, true, true]); // Go to previous page GridFunctions.navigateToPrevPage(grid.nativeElement); fix.detectChanges(); verifyGridPager(fix, 3, '7', '3\xA0of\xA04', [false, false, false, false]); // Go to first page GridFunctions.navigateToFirstPage(grid.nativeElement); fix.detectChanges(); verifyGridPager(fix, 3, '1', '1\xA0of\xA04', [true, true, false, false]); }); it('should paginate data API', () => { fix.detectChanges(); // Goto page 3 through API and listen for event spyOn(grid.pagingDone, 'emit'); grid.paginate(2); fix.detectChanges(); expect(grid.pagingDone.emit).toHaveBeenCalled(); verifyGridPager(fix, 3, '7', '3\xA0of\xA04', []); // Go to next page grid.nextPage(); fix.detectChanges(); expect(grid.pagingDone.emit).toHaveBeenCalledTimes(2); expect(grid.paginator.isLastPage).toBe(true); verifyGridPager(fix, 1, '10', '4\xA0of\xA04', []); // Go to next page when last page is selected grid.nextPage(); fix.detectChanges(); expect(grid.paginator.isLastPage).toBe(true); expect(grid.pagingDone.emit).toHaveBeenCalledTimes(2); verifyGridPager(fix, 1, '10', '4\xA0of\xA04', []); // Go to previous page grid.previousPage(); fix.detectChanges(); expect(grid.pagingDone.emit).toHaveBeenCalledTimes(3); verifyGridPager(fix, 3, '7', '3\xA0of\xA04', []); expect(grid.paginator.isLastPage).toBe(false); expect(grid.paginator.isFirstPage).toBe(false); // Go to first page grid.paginate(0); fix.detectChanges(); expect(grid.pagingDone.emit).toHaveBeenCalledTimes(4); verifyGridPager(fix, 3, '1', '1\xA0of\xA04', []); expect(grid.paginator.isFirstPage).toBe(true); // Go to previous page when first page is selected grid.previousPage(); fix.detectChanges(); expect(grid.pagingDone.emit).toHaveBeenCalledTimes(4); verifyGridPager(fix, 3, '1', '1\xA0of\xA04', []); expect(grid.paginator.isFirstPage).toBe(true); // Go to negative page number grid.paginate(-3); fix.detectChanges(); expect(grid.pagingDone.emit).toHaveBeenCalledTimes(4); verifyGridPager(fix, 3, '1', '1\xA0of\xA04', []); }); it('should be able to set totalRecords', () => { grid.perPage = 5; fix.detectChanges(); expect(grid.paginator).toBeDefined(); expect(grid.perPage).toEqual(5, 'Invalid page size'); expect(grid.totalRecords).toBe(10); verifyGridPager(fix, 5, '1', '1\xA0of\xA02', []); grid.totalRecords = 4; fix.detectChanges(); expect(grid.perPage).toEqual(5, 'Invalid page size'); expect(grid.totalRecords).toBe(4); verifyGridPager(fix, 4, '1', '1\xA0of\xA01', []); }); it('change paging settings UI', () => { fix.detectChanges(); expect(grid.paginator).toBeDefined(); expect(grid.perPage).toEqual(3, 'Invalid page size'); verifyGridPager(fix, 3, '1', '1\xA0of\xA04', []); // Change page size GridFunctions.clickOnPageSelectElement(fix); fix.detectChanges(); ControlsFunction.clickDropDownItem(fix, 2); expect(grid.paginator).toBeDefined(); expect(grid.perPage).toEqual(10, 'Invalid page size'); verifyGridPager(fix, 10, '1', '1\xA0of\xA01', []); }); it('change paging settings API', () => { fix.detectChanges(); // Change page size grid.perPage = 2; fix.detectChanges(); expect(grid.paginator).toBeDefined(); expect(grid.perPage).toEqual(2, 'Invalid page size'); verifyGridPager(fix, 2, '1', '1\xA0of\xA05', []); // Turn off paging fix.componentInstance.paging = false; fix.detectChanges(); expect(grid.paginator).not.toBeDefined(); verifyGridPager(fix, 10, '1', null, []); expect(GridFunctions.getGridPaginator(grid)).toBeNull(); expect(grid.nativeElement.querySelectorAll('.igx-paginator > select').length).toEqual(0); }); it('change paging pages per page API', (async () => { fix.detectChanges(); grid.height = '300px'; grid.perPage = 2; await wait(); fix.detectChanges(); grid.page = 1; await wait(); fix.detectChanges(); expect(grid.paginator).toBeDefined(); expect(grid.perPage).toEqual(2, 'Invalid page size'); verifyGridPager(fix, 2, '3', '2\xA0of\xA05', []); // Change page size to be 5 spyOn(grid.pagingDone, 'emit'); grid.perPage = 5; await wait(); fix.detectChanges(); grid.notifyChanges(true); let vScrollBar = grid.verticalScrollContainer.getScroll(); expect(grid.pagingDone.emit).toHaveBeenCalledTimes(1); verifyGridPager(fix, 5, '1', '1\xA0of\xA02', [true, true, false, false]); expect(vScrollBar.scrollHeight).toBeGreaterThanOrEqual(250); expect(vScrollBar.scrollHeight).toBeLessThanOrEqual(255); // Change page size to be 33 grid.perPage = 33; await wait(); fix.detectChanges(); vScrollBar = grid.verticalScrollContainer.getScroll(); // pagingDone should be emitted only if we have a change in the page number expect(grid.pagingDone.emit).toHaveBeenCalledTimes(1); verifyGridPager(fix, 5, '1', '1\xA0of\xA01', [true, true, true, true]); expect(vScrollBar.scrollHeight).toBeGreaterThanOrEqual(500); expect(vScrollBar.scrollHeight).toBeLessThanOrEqual(510); // Change page size to be negative grid.perPage = -7; await wait(); fix.detectChanges(); expect(grid.pagingDone.emit).toHaveBeenCalledTimes(1); verifyGridPager(fix, 5, '1', '1\xA0of\xA01', [true, true, true, true]); expect(vScrollBar.scrollHeight).toBeGreaterThanOrEqual(500); expect(vScrollBar.scrollHeight).toBeLessThanOrEqual(510); })); it('activate/deactivate paging', () => { let paginator = GridFunctions.getGridPaginator(grid); expect(paginator).toBeDefined(); fix.componentInstance.paging = !fix.componentInstance.paging; fix.detectChanges(); paginator = GridFunctions.getGridPaginator(grid); expect(paginator).toBeNull(); fix.componentInstance.paging = !fix.componentInstance.paging; fix.detectChanges(); paginator = GridFunctions.getGridPaginator(grid); expect(paginator).not.toBeNull(); }); it('should change not leave prev page data after scorlling', (async () => { fix.componentInstance.perPage = 5; fix.componentInstance.data = fix.componentInstance.data.slice(0, 7); grid.height = '300px'; fix.detectChanges(); fix.componentInstance.scrollTop(25); fix.detectChanges(); await wait(100); grid.paginate(1); fix.detectChanges(); await wait(100); grid.paginate(0); fix.detectChanges(); await wait(100); expect(grid.rowList.first._rowData).toEqual(grid.data[0]); })); it('should work correct with filtering', () => { grid.getColumnByName('ID').filterable = true; fix.detectChanges(); // Filter column grid.filter('ID', 1, IgxNumberFilteringOperand.instance().condition('greaterThan')); fix.detectChanges(); verifyGridPager(fix, 3, '2', '1\xA0of\xA03', [true, true, false, false]); // Filter column grid.filter('ID', 1, IgxNumberFilteringOperand.instance().condition('equals')); fix.detectChanges(); verifyGridPager(fix, 1, '1', '1\xA0of\xA01', [true, true, true, true]); // Reset filters grid.clearFilter('ID'); fix.detectChanges(); verifyGridPager(fix, 3, '1', '1\xA0of\xA04', [true, true, false, false]); }); it('should work correct with crud operations', () => { grid.primaryKey = 'ID'; fix.detectChanges(); // Delete first row grid.deleteRow(1); fix.detectChanges(); verifyGridPager(fix, 3, '2', '1\xA0of\xA03', [true, true, false, false]); expect(grid.totalPages).toBe(3); // Delete all rows on first page grid.deleteRow(2); grid.deleteRow(3); grid.deleteRow(4); fix.detectChanges(); verifyGridPager(fix, 3, '5', '1\xA0of\xA02', []); expect(grid.totalPages).toBe(2); // Delete all rows on first page grid.deleteRow(5); grid.deleteRow(6); grid.deleteRow(7); fix.detectChanges(); verifyGridPager(fix, 3, '8', '1\xA0of\xA01', [true, true, true, true]); expect(grid.totalPages).toBe(1); // Add new row grid.addRow({ ID: 1, Name: 'Test Name', JobTitle: 'Test Job Title' }); fix.detectChanges(); verifyGridPager(fix, 3, '8', '1\xA0of\xA02', [true, true, false, false]); expect(grid.totalPages).toBe(2); grid.nextPage(); fix.detectChanges(); verifyGridPager(fix, 1, '1', '2\xA0of\xA02', []); // Add new rows on second page grid.addRow({ ID: 2, Name: 'Test Name', JobTitle: 'Test Job Title' }); grid.addRow({ ID: 3, Name: 'Test Name', JobTitle: 'Test Job Title' }); grid.addRow({ ID: 4, Name: 'Test Name', JobTitle: 'Test Job Title' }); fix.detectChanges(); verifyGridPager(fix, 3, '1', '2\xA0of\xA03', [false, false, false, false]); expect(grid.totalPages).toBe(3); // Go to last page and delete the row grid.nextPage(); fix.detectChanges(); grid.deleteRow(4); fix.detectChanges(); verifyGridPager(fix, 3, '1', '2\xA0of\xA02', [false, false, true, true]); }); it('should not throw when initialized in a grid with % height', () => { grid.paging = true; expect(() => { fix.detectChanges(); }).not.toThrow(); }); it('"paginate" method should paginate correctly', () => { const page = (index: number) => grid.paginate(index); let desiredPageIndex = 2; page(2); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); // non-existent page, should not paginate page(-2); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); // non-existent page, should not paginate page(666); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); // first page desiredPageIndex = 0; page(desiredPageIndex); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); // last page desiredPageIndex = grid.totalPages - 1; page(desiredPageIndex); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); // last page + 1, should not paginate page(grid.totalPages); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); }); it('"page" property should paginate correctly', () => { const page = (index: number) => grid.page = index; let desiredPageIndex = 2; page(2); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); // non-existent page, should not paginate page(-2); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); // non-existent page, should not paginate page(666); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); // first page desiredPageIndex = 0; page(desiredPageIndex); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); // last page desiredPageIndex = grid.totalPages - 1; page(desiredPageIndex); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); // last page + 1, should not paginate page(grid.totalPages); fix.detectChanges(); expect(grid.page).toBe(desiredPageIndex); }); it('should hide paginator when there is no data or all records are filtered out.', () => { fix.detectChanges(); verifyGridPager(fix, 3, '1', '1\xA0of\xA04', [true, true, false, false]); // Filter out all records grid.filter('ID', 1000, IgxNumberFilteringOperand.instance().condition('greaterThan')); fix.detectChanges(); expect(GridFunctions.getGridPaginator(grid)).toBeNull(); grid.filter('ID', 1, IgxNumberFilteringOperand.instance().condition('greaterThan')); fix.detectChanges(); expect(GridFunctions.getGridPaginator(grid)).not.toBeNull(); grid.data = null; fix.detectChanges(); expect(GridFunctions.getGridPaginator(grid)).toBeNull(); grid.data = fix.componentInstance.data; fix.detectChanges(); expect(GridFunctions.getGridPaginator(grid)).not.toBeNull(); }); }); it('should not throw error when data is undefined', fakeAsync(() => { let errorMessage = ''; fix = TestBed.createComponent(GridWithUndefinedDataComponent); try { fix.detectChanges(); } catch (ex) { errorMessage = ex.message; } expect(errorMessage).toBe(''); grid = fix.componentInstance.grid; let paginator = GridFunctions.getGridPaginator(grid); expect(paginator).toBeNull(); expect(grid.rowList.length).toBe(0); tick(305); fix.detectChanges(); paginator = GridFunctions.getGridPaginator(grid); expect(paginator).toBeDefined(); expect(grid.rowList.length).toBe(5); })); });
the_stack
import { HttpHeaders, HttpStatusCodes } from "../Common/Constants"; import { DatabaseAccount } from "../Contracts/DataModels"; import { updateUserContext, userContext } from "../UserContext"; import { getAuthorizationHeader } from "../Utils/AuthorizationUtils"; import { IPinnedRepo, IPublishNotebookRequest, JunoClient } from "./JunoClient"; const sampleSubscriptionId = "subscriptionId"; const sampleDatabaseAccount: DatabaseAccount = { id: "id", name: "name", location: "location", type: "type", kind: "kind", properties: { documentEndpoint: "documentEndpoint", gremlinEndpoint: "gremlinEndpoint", tableEndpoint: "tableEndpoint", cassandraEndpoint: "cassandraEndpoint", }, }; const samplePinnedRepos: IPinnedRepo[] = [ { owner: "owner", name: "name", private: false, branches: [ { name: "name", }, ], }, ]; describe("Pinned repos", () => { const junoClient = new JunoClient(); beforeEach(() => { window.fetch = jest.fn().mockImplementation(() => { return { status: HttpStatusCodes.OK, text: () => JSON.stringify(samplePinnedRepos), }; }); }); afterEach(() => { jest.resetAllMocks(); }); it("updatePinnedRepos invokes pinned repos subscribers", async () => { // eslint-disable-next-line @typescript-eslint/no-empty-function const callback = jest.fn().mockImplementation(() => {}); junoClient.subscribeToPinnedRepos(callback); const response = await junoClient.updatePinnedRepos(samplePinnedRepos); expect(response.status).toBe(HttpStatusCodes.OK); expect(callback).toBeCalledWith(samplePinnedRepos); }); it("getPinnedRepos invokes pinned repos subscribers", async () => { // eslint-disable-next-line @typescript-eslint/no-empty-function const callback = jest.fn().mockImplementation(() => {}); junoClient.subscribeToPinnedRepos(callback); const response = await junoClient.getPinnedRepos("scope"); expect(response.status).toBe(HttpStatusCodes.OK); expect(callback).toBeCalledWith(samplePinnedRepos); }); }); describe("GitHub", () => { const junoClient = new JunoClient(); afterEach(() => { jest.resetAllMocks(); }); it("getGitHubToken", async () => { let fetchUrl: string; window.fetch = jest.fn().mockImplementation((url: string) => { fetchUrl = url; return { status: HttpStatusCodes.OK, text: () => JSON.stringify({ access_token: "token" }), }; }); const response = await junoClient.getGitHubToken("code"); expect(response.status).toBe(HttpStatusCodes.OK); expect(response.data.access_token).toBeDefined(); expect(window.fetch).toBeCalled(); const fetchUrlParams = new URLSearchParams(new URL(fetchUrl).search); let fetchUrlParamsCount = 0; fetchUrlParams.forEach(() => fetchUrlParamsCount++); expect(fetchUrlParamsCount).toBe(2); expect(fetchUrlParams.get("code")).toBeDefined(); expect(fetchUrlParams.get("client_id")).toBeDefined(); }); it("deleteAppauthorization", async () => { let fetchUrl: string; window.fetch = jest.fn().mockImplementation((url: string) => { fetchUrl = url; return { status: HttpStatusCodes.NoContent, text: () => undefined as string, }; }); const response = await junoClient.deleteAppAuthorization("token"); expect(response.status).toBe(HttpStatusCodes.NoContent); expect(window.fetch).toBeCalled(); const fetchUrlParams = new URLSearchParams(new URL(fetchUrl).search); let fetchUrlParamsCount = 0; fetchUrlParams.forEach(() => fetchUrlParamsCount++); expect(fetchUrlParamsCount).toBe(2); expect(fetchUrlParams.get("access_token")).toBeDefined(); expect(fetchUrlParams.get("client_id")).toBeDefined(); }); }); describe("Gallery", () => { const junoClient = new JunoClient(); const originalSubscriptionId = userContext.subscriptionId; beforeAll(() => { updateUserContext({ databaseAccount: { name: "name", } as DatabaseAccount, subscriptionId: sampleSubscriptionId, }); }); afterEach(() => { jest.resetAllMocks(); }); afterAll(() => { updateUserContext({ subscriptionId: originalSubscriptionId }); }); it("getSampleNotebooks", async () => { window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, json: () => undefined as undefined, }); const response = await junoClient.getSampleNotebooks(); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith(`${JunoClient.getJunoEndpoint()}/api/notebooks/gallery/samples`, undefined); }); it("getPublicNotebooks", async () => { window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, json: () => undefined as undefined, }); const response = await junoClient.getPublicNotebooks(); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith(`${JunoClient.getJunoEndpoint()}/api/notebooks/gallery/public`, undefined); }); it("getNotebook", async () => { const id = "id"; window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, json: () => undefined as undefined, }); const response = await junoClient.getNotebookInfo(id); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith(`${JunoClient.getJunoEndpoint()}/api/notebooks/gallery/${id}`); }); it("getNotebookContent", async () => { const id = "id"; window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, text: () => undefined as undefined, }); const response = await junoClient.getNotebookContent(id); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith(`${JunoClient.getJunoEndpoint()}/api/notebooks/gallery/${id}/content`); }); it("increaseNotebookViews", async () => { const id = "id"; window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, json: () => undefined as undefined, }); const response = await junoClient.increaseNotebookViews(id); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith(`${JunoClient.getJunoEndpoint()}/api/notebooks/gallery/${id}/views`, { method: "PATCH", }); }); it("increaseNotebookDownloadCount", async () => { const id = "id"; window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, json: () => undefined as undefined, }); const response = await junoClient.increaseNotebookDownloadCount(id); const authorizationHeader = getAuthorizationHeader(); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith( `${JunoClient.getJunoEndpoint()}/api/notebooks/subscriptions/${sampleSubscriptionId}/databaseAccounts/${ sampleDatabaseAccount.name }/gallery/${id}/downloads`, { method: "PATCH", headers: { [authorizationHeader.header]: authorizationHeader.token, [HttpHeaders.contentType]: "application/json", }, } ); }); it("favoriteNotebook", async () => { const id = "id"; window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, json: () => undefined as undefined, }); const response = await junoClient.favoriteNotebook(id); const authorizationHeader = getAuthorizationHeader(); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith( `${JunoClient.getJunoEndpoint()}/api/notebooks/subscriptions/${sampleSubscriptionId}/databaseAccounts/${ sampleDatabaseAccount.name }/gallery/${id}/favorite`, { method: "PATCH", headers: { [authorizationHeader.header]: authorizationHeader.token, [HttpHeaders.contentType]: "application/json", }, } ); }); it("unfavoriteNotebook", async () => { const id = "id"; window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, json: () => undefined as undefined, }); const response = await junoClient.unfavoriteNotebook(id); const authorizationHeader = getAuthorizationHeader(); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith( `${JunoClient.getJunoEndpoint()}/api/notebooks/subscriptions/${sampleSubscriptionId}/databaseAccounts/${ sampleDatabaseAccount.name }/gallery/${id}/unfavorite`, { method: "PATCH", headers: { [authorizationHeader.header]: authorizationHeader.token, [HttpHeaders.contentType]: "application/json", }, } ); }); it("getFavoriteNotebooks", async () => { window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, json: () => undefined as undefined, }); const response = await junoClient.getFavoriteNotebooks(); const authorizationHeader = getAuthorizationHeader(); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith( `${JunoClient.getJunoEndpoint()}/api/notebooks/subscriptions/${sampleSubscriptionId}/databaseAccounts/${ sampleDatabaseAccount.name }/gallery/favorites`, { headers: { [authorizationHeader.header]: authorizationHeader.token, [HttpHeaders.contentType]: "application/json", }, } ); }); it("getPublishedNotebooks", async () => { window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, json: () => undefined as undefined, }); const response = await junoClient.getPublishedNotebooks(); const authorizationHeader = getAuthorizationHeader(); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith( `${JunoClient.getJunoEndpoint()}/api/notebooks/subscriptions/${sampleSubscriptionId}/databaseAccounts/${ sampleDatabaseAccount.name }/gallery/published`, { headers: { [authorizationHeader.header]: authorizationHeader.token, [HttpHeaders.contentType]: "application/json", }, } ); }); it("deleteNotebook", async () => { const id = "id"; window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, json: () => undefined as undefined, }); const response = await junoClient.deleteNotebook(id); const authorizationHeader = getAuthorizationHeader(); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith( `${JunoClient.getJunoEndpoint()}/api/notebooks/subscriptions/${sampleSubscriptionId}/databaseAccounts/${ sampleDatabaseAccount.name }/gallery/${id}`, { method: "DELETE", headers: { [authorizationHeader.header]: authorizationHeader.token, [HttpHeaders.contentType]: "application/json", }, } ); }); it("publishNotebook", async () => { const name = "name"; const description = "description"; const tags = ["tag"]; const thumbnailUrl = "thumbnailUrl"; const content = `{ "key": "value" }`; const addLinkToNotebookViewer = true; window.fetch = jest.fn().mockReturnValue({ status: HttpStatusCodes.OK, json: () => undefined as undefined, }); const response = await junoClient.publishNotebook(name, description, tags, thumbnailUrl, content); const authorizationHeader = getAuthorizationHeader(); expect(response.status).toBe(HttpStatusCodes.OK); expect(window.fetch).toBeCalledWith( `${JunoClient.getJunoEndpoint()}/api/notebooks/subscriptions/${sampleSubscriptionId}/databaseAccounts/${ sampleDatabaseAccount.name }/gallery`, { method: "PUT", headers: { [authorizationHeader.header]: authorizationHeader.token, [HttpHeaders.contentType]: "application/json", }, body: JSON.stringify({ name, description, tags, thumbnailUrl, content: JSON.parse(content), addLinkToNotebookViewer, } as IPublishNotebookRequest), } ); }); });
the_stack
$(document).ready(function () { $('.tooltip').tooltipster(); }); $('.tooltip').tooltipster({ theme: 'tooltipster-noir' }); $('.tooltip').tooltipster({ contentCloning: true }); $('.tooltip').tooltipster({ animation: 'fade', delay: 200, theme: 'tooltipster-punk', trigger: 'click' }); // initialize your tooltip as usual: $('#my-tooltip').tooltipster({}); // at some point you may decide to update its content: $('#my-tooltip').tooltipster('content', 'My new content'); // ...and open it: $('#my-tooltip').tooltipster('open'); // NOTE: most methods are actually chainable, as you would expect them to be: $('#my-other-tooltip') .tooltipster({}) .tooltipster('content', 'My new content') .tooltipster('open'); $('.tooltip').tooltipster({ functionBefore: function (instance, helper) { instance.content('My new content'); } }); // Set default options for all future tooltip instantiations $.tooltipster.setDefaults({ side: 'bottom' }); // The `instances` method, when used without a second parameter, allows you to access all tooltips present in the page. // That may be useful to close all tooltips at once for example: var instances = $.tooltipster.instances(); $.each(instances, function (i, instance) { instance.close(); }); $('.tooltip1').tooltipster(); $('.tooltip2').tooltipster(); // this method call will only return an array with the instances created for the elements that matched '.tooltip2' because that's the latest initializing call. var instances = $.tooltipster.instancesLatest(); $('.tooltip').tooltipster({ theme: ['tooltipster-noir', 'tooltipster-noir-customized'] }); $('#myelement').tooltipster('content', 'My new content'); // or when you have the instance of the tooltip: let instance: JQueryTooltipster.ITooltipsterInstance; instance.content('My new content'); $('.tooltip').tooltipster({ content: 'Loading...', // 'instance' is basically the tooltip. More details in the "Object-oriented Tooltipster" section. functionBefore: function (instance, helper) { var $origin = $(helper.origin); // we set a variable so the data is only loaded once via Ajax, not every time the tooltip opens if ($origin.data('loaded') !== true) { $.get('http://example.com/ajax.php', function (data) { // call the 'content' method to update the content of our tooltip with the returned data. // note: this content update will trigger an update animation (see the updateAnimation option) instance.content(data); // to remember that the data has been loaded $origin.data('loaded', true); }); } } }); $(document).ready(function () { $('.tooltip').tooltipster(); $('#example').tooltipster('open', function (instance, helper) { alert('The tooltip is now fully shown. Its content is: ' + instance.content()); }); $(window).keypress(function () { $('#example').tooltipster('close', function (instance, helper) { alert('The tooltip is now fully hidden'); }); }); }); $('#example').tooltipster({ trigger: 'custom', triggerOpen: { mouseenter: true }, triggerClose: { click: true, scroll: true } }); $('#example').tooltipster({ trigger: 'custom', triggerOpen: { mouseenter: true, touchstart: true }, triggerClose: { click: true, scroll: true, tap: true } }); $('#example').tooltipster({ trigger: 'custom', triggerOpen: { mouseenter: true, touchstart: true }, triggerClose: { mouseleave: true, originClick: true, touchleave: true } }); $('#example').tooltipster({ trigger: 'custom', triggerOpen: { click: true, tap: true }, triggerClose: { click: true, tap: true } }); $(document).ready(function () { // first on page load, initialize all tooltips $('.tooltip').tooltipster(); // then immediately open the tooltip of the element named "example" $('#example').tooltipster('open'); // as soon as a key is pressed on the keyboard, close the tooltip. $(window).keypress(function () { $('#example').tooltipster('close'); }); }); $('#my-tooltip').tooltipster({ functionPosition: function (instance, helper, position) { position.coord.top += 10; position.coord.left += 10; return position; } }); $('#tooltip').tooltipster({ content: $('#tooltip_content'), // if you use a single element as content for several tooltips, set this option to true contentCloning: false }); $('.tooltip').tooltipster({ functionInit: function (instance, helper) { var content = $(helper.origin).find('.tooltip_content').detach(); instance.content(content); } }); $('.tooltip').tooltipster({ functionInit: function (instance, helper) { var $origin = $(helper.origin); const dataOptionsJson = $origin.attr('data-tooltipster'); if (dataOptionsJson) { const dataOptions = JSON.parse(dataOptionsJson); // example in the documentation isn't valid: // $.each(dataOptions, function(name, option){ // instance.option(name, option); // }); Object.keys(dataOptions).forEach(key => { instance.option(key, dataOptions[key]); }); } } }); $('#example').tooltipster({ functionInit: function (instance, helper) { // parse the content var content = instance.content(), people = JSON.parse(content), // and use it to make a sentence newContent = 'We have ' + people.length + ' people today. Say hello to ' + people.join(', '); // save the edited content instance.content(newContent); } }); // this logs: "We have 3 people today. Say hello to Sarah, John, Matthew" console.log($('#example').tooltipster('content')); $('#example').tooltipster({ functionInit: function (instance, helper) { var content = instance.content(), people = JSON.parse(content); instance.content(people); }, // this formats the content on the fly when it needs to be displayed but does not modify its value functionFormat: function (instance, helper, content) { var displayedContent = 'We have ' + content.length + ' people today. Say hello to ' + content.join(', '); return displayedContent; } }); // Alright! this logs: ["Sarah", "John", "Matthew"] console.log($('#example').tooltipster('content')); $('#my-element').tooltipster(); $('#my-element').tooltipster('open').tooltipster('content', 'My new content'); $('#my-element').tooltipster(); instance = $('#my-element').tooltipster('instance'); instance.open().content('My new content'); $('#origin').tooltipster({ functionBefore: function (instance, helper) { instance.content('Random content'); } }); var $myElement = $('#my-element'); // create a first tooltip as usual. The multiple option is actually optional for the first tooltip $myElement.tooltipster({ content: 'My first tooltip', side: 'top' }); // initialize a second tooltip $myElement.tooltipster({ // don't forget to provide content here as the first tooltip will have deleted the original title attribute of the element content: 'My second tooltip', multiple: true, side: 'bottom' }); var instances = $.tooltipster.instances($myElement); // use the instances to make any method calls on the tooltips instances[0].content('New content for my first tooltip').open(); instances[1].content('New content for my second tooltip').open(); // WARNING: calling methods in the usual way only affects the first tooltip that was created on the element $myElement.tooltipster('content', 'New content for my first tooltip') $('#my-element').tooltipster({ content: 'HELLO', functionInit: function (instance, helper) { var string = instance.content(); instance.content(string.toLowerCase()); }, multiple: true }); $('body').on('mouseenter', '.tooltip:not(.tooltipstered)', function () { $(this) .tooltipster({}) .tooltipster('open'); }); const doThis = () => { }; const doThat = () => { }; $("#my-tooltip").tooltipster({ functionBefore: function (instance, helper) { doThis(); doThat(); } }); instance = $("#my-tooltip").tooltipster({}).tooltipster('instance'); instance .on('before', doThis) .on('before', doThat); $.tooltipster.on('init', function (event) { doThis(); }); $("#my-tooltip").tooltipster({ functionInit: doThat }); $('#example').tooltipster({ plugins: ['pluginNamespace.pluginName'] }); $('#example').tooltipster({ plugins: ['laa.follower'] }); $('#example').tooltipster({ content: 'Hello', theme: 'tooltipster-noir', 'laa.follower': { anchor: 'top-center' }, 'some.otherPlugin': { anchor: 'value' } }); $('#example').tooltipster({ functionBefore: function(instance, helper) { instance['laa.follower'].methodName(); } }); $('#nesting').tooltipster({ content: $('<span>Hover me too!</span>'), functionReady: function(instance, helper){ // the nested tooltip must be initialized once the first tooltip is open, that's why we do this inside functionReady() instance.content().tooltipster({ content: 'I am a nested tooltip!', distance: 0 }); }, interactive: true }); // initialize tooltips in the page as usual $('.tooltip').tooltipster(); // bind on start events (triggered on mouseenter) $.tooltipster.on('start', function(event) { if ($(event.instance.elementOrigin()).hasClass('tooltip_group')) { var instances = $.tooltipster.instances('.tooltip_group'), open = false, duration; $.each(instances, function (i, instance) { if (instance !== event.instance) { // if another instance is already open if (instance.status().open){ open = true; // get the current animationDuration duration = instance.option('animationDuration'); // close the tooltip without animation instance.option('animationDuration', 0); instance.close(); // restore the animationDuration to its normal value instance.option('animationDuration', duration); } } }); // if another instance was open if (open) { duration = event.instance.option('animationDuration'); // open the tooltip without animation event.instance.option('animationDuration', 0); event.instance.open(); // restore the animationDuration to its normal value event.instance.option('animationDuration', duration); // now that we have opened the tooltip, the hover trigger must be stopped event.instance.stop(); } } }); $('#myfield').tooltipster({ functionInit: function(instance, helper){ var content = $('#myfield_description').html(); instance.content(content); }, functionReady: function(instance, helper){ $('#myfield_description').attr('aria-hidden', 'false'); }, functionAfter: function(instance, helper){ $('#myfield_description').attr('aria-hidden', 'true'); } }); // if in addition you want the tooltip to be displayed when the field gets focus, add these custom triggers : $('#myfield') .focus(function(){ $(this).tooltipster('open'); }) .blur(function(){ $(this).tooltipster('close'); });
the_stack
import * as React from "react"; import { translate } from "react-i18next"; import Redirect from "react-router-dom/Redirect"; import Grid from "@material-ui/core/Grid"; import Paper from "@material-ui/core/Paper"; import Select from "@material-ui/core/Select"; import Button from "@material-ui/core/Button"; import Switch from "@material-ui/core/Switch"; import Divider from "@material-ui/core/Divider"; import MenuItemObj from "@material-ui/core/MenuItem"; import TextField from "@material-ui/core/TextField"; import InputLabel from "@material-ui/core/InputLabel"; import Typography from "@material-ui/core/Typography"; import FormControl from "@material-ui/core/FormControl"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import TableCell from "@material-ui/core/TableCell"; import CategoryChip from "../../Components/Categories/CategoryChip"; import ExportDialog2 from "../../Components/ExportDialog"; const ExportDialog: any = ExportDialog2; import ImportDialog from "../../Components/ImportDialog"; import NewRuleItemMenu from "./NewRuleItemMenu"; import RuleCollectionMenu2 from "./RuleCollectionMenu"; const RuleCollectionMenu: any = RuleCollectionMenu2; const MenuItem: any = MenuItemObj; import AccountRuleItem from "./RuleTypeItems/AccountRuleItem"; import ValueRuleItem from "./RuleTypeItems/ValueRuleItem"; import TransactionAmountRuleItem from "./RuleTypeItems/TransactionAmountRuleItem"; import ItemTypeRuleItem from "./RuleTypeItems/ItemTypeRuleItem"; import Rule from "../../Types/Rules/Rule"; import { RuleTypes } from "../../Types/Types"; import { default as RuleCollection, RuleCollectionMatchType } from "../../Types/RuleCollection"; const styles = { title: { textAlign: "center", marginBottom: 16 }, subTitle: { margin: 12 }, saveButtonGridWrapper: { paddingTop: 18 }, checkboxGridWrapper: { paddingTop: 12, paddingBottom: 0, paddingLeft: 16 }, chipsWrapper: { display: "flex", justifyContent: "center" }, matchTypeCell: { padding: 4 }, inputField: { width: "100%" }, wrapper: { padding: 16, marginBottom: 8 } }; class RuleCreator extends React.Component<any, any> { constructor(props: any, context: any) { super(props, context); const matchType: RuleCollectionMatchType = "AND"; this.state = { id: null, title: "", matchType: matchType, categories: [], rules: [], enabled: false, titleError: false, openImportDialog: false, openExportDialog: false, exportData: null, goToDashboard: false }; } componentDidMount() { const ruleCollection: RuleCollection = this.props.ruleCollection; const ruleCollectionId = ruleCollection.getId(); if (ruleCollectionId !== null) { // we should have a valid rule collection so extract the data this.setState( { id: ruleCollectionId, title: ruleCollection.getTitle(), matchType: ruleCollection.getMatchType(), categories: ruleCollection.getCategories(), rules: ruleCollection.getRules(), enabled: ruleCollection.isEnabled() }, this.updatePreview ); } else { this.setState({ titleError: true }, this.updatePreview); } } // sends an update event to the parent class to update the preview list updatePreview = () => { const ruleCollection = new RuleCollection(); ruleCollection.fromObject(this.state); this.props.updatePreview(ruleCollection); }; addCategory = categoryInfo => event => { const categories: string[] = [...this.state.categories]; if (!categories.includes(categoryInfo.id)) { categories.push(categoryInfo.id); this.setState({ categories: categories }); } }; removeCategory = categoryInfo => event => { const categories: string[] = [...this.state.categories]; const index = categories.indexOf(categoryInfo.id); if (index !== -1) { categories.splice(index, 1); this.setState({ categories: categories }); } }; removeRule = ruleKey => event => { const rules: Rule[] = [...this.state.rules]; rules.splice(ruleKey, 1); this.setState({ rules: rules }, this.updatePreview); }; updateRule = ruleKey => (rule: Rule) => { const rules: Rule[] = [...this.state.rules]; rules[ruleKey] = rule; this.setState({ rules: rules }); }; addRule = (ruleType: RuleTypes) => { let rules = [...this.state.rules]; let newRule: Rule; switch (ruleType) { case "VALUE": newRule = { ruleType: "VALUE", field: "DESCRIPTION", matchType: "CONTAINS", value: "" }; break; case "TRANSACTION_AMOUNT": newRule = { ruleType: "TRANSACTION_AMOUNT", matchType: "MORE", amount: 5 }; break; case "ITEM_TYPE": newRule = { ruleType: "ITEM_TYPE", matchType: "PAYMENT" }; break; case "ACCOUNT_TYPE": newRule = { ruleType: "ACCOUNT_TYPE", paymentType: "ALL", accountId: 0 }; break; default: return false; } // add the new rule to the list rules.push(newRule); // put the item_type first because these are checked the fastest rules = rules.sort((ruleA: Rule, ruleB: Rule) => { if (ruleA.ruleType === "ITEM_TYPE" && ruleB.ruleType === "ITEM_TYPE") { return 0; } else if (ruleA.ruleType !== "ITEM_TYPE" && ruleB.ruleType === "ITEM_TYPE") { return 1; } else if (ruleA.ruleType === "ITEM_TYPE" && ruleB.ruleType !== "ITEM_TYPE") { return -1; } }); this.setState({ rules: rules }, this.updatePreview); }; handleMatchTypeChange = (event: any) => { this.setState({ matchType: event.target.value }, this.updatePreview); }; handleTitleChange = (event: any) => { const title = event.target.value; const titleError = title.length <= 0 || title.length > 32; this.setState({ title: title, titleError: titleError }); }; handleEnabledToggle = (event: any) => { this.setState({ enabled: !this.state.enabled }); }; saveRuleCollection = (event: any) => { if (this.state.titleError) { return; } const ruleCollection = this.createRuleCollection(); // get the new ID so we can update instead of creating infinite clones this.setState({ id: ruleCollection.getId() }, this.updatePreview); // send the updated class to the parent this.props.saveRuleCollection(ruleCollection); // display a confirmation message this.props.openSnackbar(this.props.t("Changes were saved!")); }; createRuleCollection = (): RuleCollection => { const ruleCollection = new RuleCollection(); // parse the current state ruleCollection.fromObject(this.state); // make sure this collection has a valid ID ruleCollection.ensureId(); return ruleCollection; }; deleteRuleCollection = () => { this.props.removeCategoryCollection(this.state.id); this.setState({ goToDashboard: true }); }; openExportDialog = (data = false) => { this.setState({ openExportDialog: true, exportData: data === false ? this.createRuleCollection() : data }); }; closeExportDialog = (event: any) => { this.setState({ openExportDialog: false, exportData: null }); }; openImportDialog = (event: any) => { this.setState({ openImportDialog: true }); }; closeImportDialog = (event: any) => { this.setState({ openImportDialog: false }); }; importRule = (rule: Rule) => { this.closeImportDialog(null); const isValid = RuleCollection.validateRule(rule); if (isValid !== true) { // display error this.props.openSnackbar(isValid.message); return; } // add the rule to the ruleset const rules: Rule[] = [...this.state.rules]; rules.push(rule); this.setState({ rules: rules }, this.updatePreview); }; render() { const { categories, title, rules, titleError, goToDashboard } = this.state; const t = this.props.t; if (goToDashboard) { return <Redirect to="/rules-dashboard" />; } const categoriesIncluded = []; const categoriesExcluded = []; Object.keys(this.props.categories).map(categoryId => { if (categories.includes(categoryId)) { categoriesIncluded.push(this.props.categories[categoryId]); } else { categoriesExcluded.push(this.props.categories[categoryId]); } }); const includedChips = Object.keys(categoriesIncluded).map(categoryId => { const categoryInfo = categoriesIncluded[categoryId]; return ( <CategoryChip key={categoryId} category={categoryInfo} onDelete={this.removeCategory(categoryInfo)} /> ); }); const excludedChips = Object.keys(categoriesExcluded).map(categoryId => { const categoryInfo = categoriesExcluded[categoryId]; return <CategoryChip key={categoryId} category={categoryInfo} onClick={this.addCategory(categoryInfo)} />; }); const ruleItems = rules.map((rule: Rule, ruleKey: string) => { switch (rule.ruleType) { case "VALUE": return ( <ValueRuleItem openExportDialog={this.openExportDialog} removeRule={this.removeRule(ruleKey)} updateRule={this.updateRule(ruleKey)} rule={rule} key={ruleKey} /> ); case "TRANSACTION_AMOUNT": return ( <TransactionAmountRuleItem openExportDialog={this.openExportDialog} removeRule={this.removeRule(ruleKey)} updateRule={this.updateRule(ruleKey)} rule={rule} key={ruleKey} /> ); case "ITEM_TYPE": return ( <ItemTypeRuleItem openExportDialog={this.openExportDialog} removeRule={this.removeRule(ruleKey)} updateRule={this.updateRule(ruleKey)} rule={rule} key={ruleKey} /> ); case "ACCOUNT_TYPE": return ( <AccountRuleItem BunqJSClient={this.props.BunqJSClient} openExportDialog={this.openExportDialog} removeRule={this.removeRule(ruleKey)} updateRule={this.updateRule(ruleKey)} accounts={this.props.accounts} rule={rule} key={ruleKey} /> ); } }); return ( <React.Fragment> <Paper style={styles.wrapper}> <Grid container spacing={16}> <Grid item xs={11}> <Typography variant="h6" style={styles.subTitle}> {t("Settings")} </Typography> </Grid> <Grid item xs={1}> <RuleCollectionMenu canBeDeleted={this.state.id !== null} deleteRuleCollection={this.deleteRuleCollection} openExportDialog={this.openExportDialog} /> </Grid> <Grid item xs={12} sm={6}> <TextField label={t("Ruleset title")} value={title} style={styles.inputField} onChange={this.handleTitleChange} error={titleError} /> </Grid> <Grid item xs={12} sm={6} style={styles.checkboxGridWrapper}> <FormControlLabel control={ <Switch color="primary" checked={this.state.enabled} onChange={this.handleEnabledToggle} /> } label={t("Enable or disable this ruleset")} /> </Grid> <Grid item xs={12} sm={6}> <FormControl style={styles.inputField}> <InputLabel>{t("Match requirements")}</InputLabel> <Select value={this.state.matchType} onChange={this.handleMatchTypeChange}> <MenuItem value={"AND"}>{t("Require all rules to match")}</MenuItem> <MenuItem value={"OR"}>{t("Only require 1 rule to match")}</MenuItem> </Select> </FormControl> </Grid> <Grid item xs={12} sm={6} style={styles.saveButtonGridWrapper}> <Button variant="contained" color="primary" style={{ width: "100%" }} onClick={this.saveRuleCollection} disabled={titleError} > {t("Save")} </Button> </Grid> </Grid> </Paper> <Paper style={styles.wrapper} key={"rulesWrapper"}> <Table> <TableHead key={"tableHead"}> <TableRow> <TableCell style={{ paddingLeft: 0 }}> <Typography variant="h6" style={styles.subTitle}> {t("Rules")} </Typography> </TableCell> <TableCell>{null}</TableCell> <TableCell>{null}</TableCell> <TableCell> <NewRuleItemMenu addRule={this.addRule} openImportDialog={this.openImportDialog} /> </TableCell> </TableRow> </TableHead> <TableBody>{ruleItems}</TableBody> </Table> </Paper> <Paper style={styles.wrapper} key={"categoryChipsWrapper"}> <Typography variant="h6" style={styles.subTitle}> {t("Categories")} </Typography> <div> <Typography variant="subtitle1" style={styles.subTitle}> {t("Categories that will be added")} </Typography> {includedChips} </div> <Divider /> <div>{excludedChips}</div> </Paper> <ExportDialog closeModal={this.closeExportDialog} title={t("Export data")} open={this.state.openExportDialog} object={this.state.exportData} /> <ImportDialog closeModal={this.closeImportDialog} importData={this.importRule} title={t("Import rule")} open={this.state.openImportDialog} /> </React.Fragment> ); } } export default translate("translations")(RuleCreator);
the_stack
import { useIsRTL, useSyncRef } from '@ui5/webcomponents-react-base/dist/hooks'; import { ThemingParameters } from '@ui5/webcomponents-react-base/dist/ThemingParameters'; import { enrichEventWithDetails } from '@ui5/webcomponents-react-base/dist/Utils'; import { BulletChartPlaceholder } from '@ui5/webcomponents-react-charts/dist/BulletChartPlaceholder'; import { ChartContainer } from '@ui5/webcomponents-react-charts/dist/components/ChartContainer'; import { ChartDataLabel } from '@ui5/webcomponents-react-charts/dist/components/ChartDataLabel'; import { XAxisTicks } from '@ui5/webcomponents-react-charts/dist/components/XAxisTicks'; import { YAxisTicks } from '@ui5/webcomponents-react-charts/dist/components/YAxisTicks'; import { useLegendItemClick } from '@ui5/webcomponents-react-charts/dist/useLegendItemClick'; import { getCellColors, resolvePrimaryAndSecondaryMeasures } from '@ui5/webcomponents-react-charts/dist/Utils'; import React, { CSSProperties, FC, forwardRef, Ref, useCallback, useMemo } from 'react'; import { Bar, Brush, CartesianGrid, Cell, ComposedChart as ComposedChartLib, Label, Legend, ReferenceLine, Tooltip, XAxis, YAxis } from 'recharts'; import { useChartMargin } from '../../hooks/useChartMargin'; import { useLabelFormatter } from '../../hooks/useLabelFormatter'; import { useLongestYAxisLabel } from '../../hooks/useLongestYAxisLabel'; import { useObserveXAxisHeights } from '../../hooks/useObserveXAxisHeights'; import { useOnClickInternal } from '../../hooks/useOnClickInternal'; import { usePrepareDimensionsAndMeasures } from '../../hooks/usePrepareDimensionsAndMeasures'; import { useTooltipFormatter } from '../../hooks/useTooltipFormatter'; import { IChartBaseProps } from '../../interfaces/IChartBaseProps'; import { IChartDimension } from '../../interfaces/IChartDimension'; import { IChartMeasure } from '../../interfaces/IChartMeasure'; import { defaultFormatter } from '../../internal/defaults'; import { tickLineConfig, tooltipContentStyle, tooltipFillOpacity } from '../../internal/staticProps'; import { ComparisonLine } from './ComparisonLine'; const dimensionDefaults = { formatter: defaultFormatter }; const measureDefaults = { formatter: defaultFormatter, opacity: 1 }; interface MeasureConfig extends IChartMeasure { /** * width of the current chart element, defaults to `1` for `lines` and `20` for bars */ width?: number; /** * Opacity * @default 1 */ opacity?: number; /** * Chart type */ type: AvailableChartTypes; /** * Highlight color of defined elements * @param value {string | number} Current value of the highlighted measure * @param measure {IChartMeasure} Current measure object * @param dataElement {object} Current data element */ highlightColor?: (value: number, measure: MeasureConfig, dataElement: Record<string, any>) => CSSProperties['color']; } interface DimensionConfig extends IChartDimension { interval?: number; } export interface BulletChartProps extends IChartBaseProps { /** * An array of config objects. Each object will define one dimension of the chart. * * #### Required Properties * - `accessor`: string containing the path to the dataset key the dimension should display. Supports object structures by using <code>'parent.child'</code>. * Can also be a getter. * * #### Optional Properties * - `formatter`: function will be called for each data label and allows you to format it according to your needs * - `interval`: number that controls how many ticks are rendered on the x axis * */ dimensions: DimensionConfig[]; /** * An array of config objects. Each object is defining one element in the chart. * * #### Required properties * - `accessor`: string containing the path to the dataset key this element should display. Supports object structures by using <code>'parent.child'</code>. * Can also be a getter. * - `type`: string which chart element (value type) to show. Possible values: `primary`, `comparison`, `additional`. * * #### Optional properties * * - `label`: Label to display in legends or tooltips. Falls back to the <code>accessor</code> if not present. * - `color`: any valid CSS Color or CSS Variable. Defaults to the `sapChart_Ordinal` colors * - `formatter`: function will be called for each data label and allows you to format it according to your needs * - `hideDataLabel`: flag whether the data labels should be hidden in the chart for this element. * - `DataLabel`: a custom component to be used for the data label * - `width`: width of the current chart element, defaults to `1` for `lines` and `20` for bars * - `opacity`: element opacity, defaults to `1` * - `highlightColor`: function will be called to define a custom color of a specific element which matches the * defined condition. Overwrites code>color</code> of the element. * */ measures: MeasureConfig[]; /** * layout for showing measures. `horizontal` bars would equal the column chart, `vertical` would be a bar chart. * Default Value: `horizontal` */ layout?: 'horizontal' | 'vertical'; } type AvailableChartTypes = 'primary' | 'comparison' | 'additional' | string; /** * The `BulletChart` is used to compare primary and secondary (comparison) values. The primary and additional values * are rendered as a stacked Bar Chart while the comparison value is displayed as a line above. */ const BulletChart: FC<BulletChartProps> = forwardRef((props: BulletChartProps, ref: Ref<HTMLDivElement>) => { const { loading, dataset, onDataPointClick, noLegend, noAnimation, tooltipConfig, onLegendClick, onClick, layout, style, className, tooltip, slot, syncId, ChartPlaceholder, children, ...rest } = props; const [componentRef, chartRef] = useSyncRef<any>(ref); const chartConfig = { yAxisVisible: false, xAxisVisible: true, gridStroke: ThemingParameters.sapList_BorderColor, gridHorizontal: true, gridVertical: false, legendPosition: 'bottom', legendHorizontalAlign: 'left', zoomingTool: false, resizeDebounce: 250, yAxisConfig: {}, xAxisConfig: {}, secondYAxisConfig: {}, secondXAxisConfig: {}, ...props.chartConfig }; const { dimensions, measures } = usePrepareDimensionsAndMeasures( props.dimensions, props.measures, dimensionDefaults, measureDefaults ); const sortedMeasures = useMemo(() => { return measures.sort((measure) => { if (measure.type === 'comparison') { return 1; } if (measure.type === 'primary') { return -1; } return 0; }); }, [measures]); const tooltipValueFormatter = useTooltipFormatter(sortedMeasures); const primaryDimension = dimensions[0]; const { primaryMeasure, secondaryMeasure } = resolvePrimaryAndSecondaryMeasures( sortedMeasures, chartConfig?.secondYAxis?.dataKey ); const labelFormatter = useLabelFormatter(primaryDimension); const dataKeys = sortedMeasures.map(({ accessor }) => accessor); const colorSecondY = chartConfig.secondYAxis ? dataKeys.findIndex((key) => key === chartConfig.secondYAxis?.dataKey) : 0; const onDataPointClickInternal = useCallback( (payload, eventOrIndex, event) => { if (typeof onDataPointClick === 'function') { if (payload.name) { const payloadValueLength = payload?.value?.length; onDataPointClick( enrichEventWithDetails(event ?? eventOrIndex, { value: payloadValueLength ? payload.value[1] - payload.value[0] : payload.value, dataIndex: payload.index ?? eventOrIndex, dataKey: payloadValueLength ? Object.keys(payload).filter((key) => payload.value.length ? payload[key] === payload.value[1] - payload.value[0] : payload[key] === payload.value && key !== 'value' )[0] : payload.dataKey ?? Object.keys(payload).find((key) => payload[key] === payload.value && key !== 'value'), payload: payload.payload }) ); } else { onDataPointClick( enrichEventWithDetails({} as any, { value: eventOrIndex.value, dataKey: eventOrIndex.dataKey, dataIndex: eventOrIndex.index, payload: eventOrIndex.payload }) ); } } }, [onDataPointClick] ); const onItemLegendClick = useLegendItemClick(onLegendClick); const onClickInternal = useOnClickInternal(onClick); const isBigDataSet = dataset?.length > 30 ?? false; const primaryDimensionAccessor = primaryDimension?.accessor; const [yAxisWidth, legendPosition] = useLongestYAxisLabel( dataset, layout === 'vertical' ? dimensions : sortedMeasures ); const marginChart = useChartMargin(chartConfig.margin, chartConfig.zoomingTool); const xAxisHeights = useObserveXAxisHeights(chartRef, layout === 'vertical' ? 1 : props.dimensions.length); const measureAxisProps = { axisLine: chartConfig.yAxisVisible, tickLine: tickLineConfig, tickFormatter: primaryMeasure?.formatter, interval: 0 }; const isRTL = useIsRTL(chartRef); const Placeholder = useCallback(() => { return <BulletChartPlaceholder layout={layout} measures={measures} />; }, [layout, measures]); const { chartConfig: _0, dimensions: _1, measures: _2, ...propsWithoutOmitted } = rest; return ( <ChartContainer ref={componentRef} loading={loading} dataset={dataset} Placeholder={ChartPlaceholder ?? Placeholder} style={style} className={className} tooltip={tooltip} slot={slot} resizeDebounce={chartConfig.resizeDebounce} {...propsWithoutOmitted} > <ComposedChartLib syncId={syncId} onClick={onClickInternal} stackOffset="sign" margin={marginChart} data={dataset} layout={layout} className={ typeof onDataPointClick === 'function' || typeof onClick === 'function' ? 'has-click-handler' : undefined } > <CartesianGrid vertical={chartConfig.gridVertical} horizontal={chartConfig.gridHorizontal} stroke={chartConfig.gridStroke} /> {chartConfig.xAxisVisible && dimensions.map((dimension, index) => { let AxisComponent; const axisProps: any = { dataKey: dimension.accessor, interval: dimension?.interval ?? (isBigDataSet ? 'preserveStart' : 0), tickLine: index < 1, axisLine: index < 1, allowDuplicatedCategory: index === 0 }; if (layout === 'vertical') { axisProps.type = 'category'; axisProps.tick = <YAxisTicks config={dimension} />; axisProps.yAxisId = index; axisProps.width = yAxisWidth; AxisComponent = YAxis; axisProps.orientation = isRTL ? 'right' : 'left'; } else { axisProps.dataKey = dimension.accessor; axisProps.tick = <XAxisTicks config={dimension} />; axisProps.xAxisId = index; axisProps.height = xAxisHeights[index]; AxisComponent = XAxis; axisProps.reversed = isRTL; } return <AxisComponent key={dimension.accessor} {...axisProps} />; })} {layout === 'horizontal' && ( <YAxis {...measureAxisProps} yAxisId="primary" width={yAxisWidth} orientation={isRTL ? 'right' : 'left'} tick={<YAxisTicks config={primaryMeasure} />} {...chartConfig.yAxisConfig} /> )} {layout === 'vertical' && ( <XAxis {...measureAxisProps} reversed={isRTL} xAxisId="primary" type="number" tick={<XAxisTicks config={primaryMeasure} />} {...chartConfig.xAxisConfig} /> )} {chartConfig.secondYAxis?.dataKey && layout === 'horizontal' && ( <YAxis dataKey={chartConfig.secondYAxis.dataKey} axisLine={{ stroke: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 11) + 1})` }} tick={ <YAxisTicks config={secondaryMeasure} secondYAxisConfig={{ color: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 11) + 1})` }} /> } tickLine={{ stroke: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 11) + 1})` }} // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore label={{ value: chartConfig.secondYAxis.name, offset: 2, angle: +90, position: 'center' }} orientation={isRTL ? 'left' : 'right'} interval={0} yAxisId="secondary" {...chartConfig.secondYAxisConfig} /> )} {chartConfig.secondYAxis?.dataKey && layout === 'vertical' && ( <XAxis dataKey={chartConfig.secondYAxis.dataKey} axisLine={{ stroke: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 11) + 1})` }} tick={ <XAxisTicks config={secondaryMeasure} secondYAxisConfig={{ color: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 11) + 1})` }} /> } tickLine={{ stroke: chartConfig.secondYAxis.color ?? `var(--sapChart_OrderedColor_${(colorSecondY % 11) + 1})` }} // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore label={{ value: chartConfig.secondYAxis.name, offset: 2, angle: +90, position: 'center' }} orientation="top" interval={0} xAxisId="secondary" type="number" {...chartConfig.secondXAxisConfig} /> )} {layout === 'horizontal' && <XAxis xAxisId={'comparisonXAxis'} hide />} {layout === 'vertical' && <YAxis yAxisId={'comparisonYAxis'} type={'category'} hide />} {chartConfig.referenceLine && ( <ReferenceLine stroke={chartConfig.referenceLine.color} y={layout === 'horizontal' ? chartConfig.referenceLine.value : undefined} x={layout === 'vertical' ? chartConfig.referenceLine.value : undefined} yAxisId={layout === 'horizontal' ? 'primary' : undefined} xAxisId={layout === 'vertical' ? 'primary' : undefined} > <Label>{chartConfig.referenceLine.label}</Label> </ReferenceLine> )} <Tooltip cursor={tooltipFillOpacity} formatter={tooltipValueFormatter} labelFormatter={labelFormatter} contentStyle={tooltipContentStyle} {...tooltipConfig} /> {!noLegend && ( // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore <Legend verticalAlign={chartConfig.legendPosition} align={chartConfig.legendHorizontalAlign} onClick={onItemLegendClick} wrapperStyle={legendPosition} /> )} {sortedMeasures?.map((element, index) => { const chartElementProps: any = { isAnimationActive: noAnimation === false }; let labelPosition = 'top'; switch (element.type) { case 'primary': case 'additional': chartElementProps.fillOpacity = element.opacity; chartElementProps.strokeOpacity = element.opacity; chartElementProps.barSize = element.width; chartElementProps.onClick = onDataPointClickInternal; chartElementProps.stackId = 'A'; chartElementProps.labelPosition = element.stackId ? 'insideTop' : 'top'; if (layout === 'vertical') { labelPosition = 'insideRight'; } else { labelPosition = 'insideTop'; } break; case 'comparison': chartElementProps.onClick = onDataPointClickInternal; chartElementProps.fill = element.color ?? 'black'; chartElementProps.strokeWidth = element.width; chartElementProps.shape = <ComparisonLine layout={layout} />; chartElementProps.strokeOpacity = element.opacity; chartElementProps.label = false; chartElementProps.xAxisId = 'comparisonXAxis'; chartElementProps.yAxisId = 'comparisonYAxis'; chartElementProps.dot = !isBigDataSet; break; } if (layout === 'vertical') { chartElementProps.xAxisId = chartConfig.secondYAxis?.dataKey === element.accessor ? 'secondary' : 'primary'; } else { chartElementProps.yAxisId = chartConfig.secondYAxis?.dataKey === element.accessor ? 'secondary' : 'primary'; } return ( <Bar key={element.accessor} name={element.label ?? element.accessor} label={ isBigDataSet ? null : <ChartDataLabel config={element} chartType={'bar'} position={labelPosition} /> } stroke={element.color ?? `var(--sapChart_OrderedColor_${(index % 11) + 1})`} fill={element.color ?? `var(--sapChart_OrderedColor_${(index % 11) + 1})`} type="monotone" dataKey={element.accessor} {...chartElementProps} > {element.type !== 'comparison' && dataset.map((data, i) => { return ( <Cell key={i} fill={getCellColors(element, data, index)} stroke={getCellColors(element, data, index)} /> ); })} </Bar> ); })} {chartConfig.zoomingTool && ( <Brush y={10} dataKey={primaryDimensionAccessor} tickFormatter={primaryDimension.formatter} stroke={ThemingParameters.sapObjectHeader_BorderColor} travellerWidth={10} height={20} /> )} {children} </ComposedChartLib> </ChartContainer> ); }); BulletChart.defaultProps = { noLegend: false, noAnimation: false, layout: 'horizontal' }; BulletChart.displayName = 'BulletChart'; export { BulletChart };
the_stack
// This doesn't import all of CodeMirror, instead it only imports // a small subset. This hack is brought to you by webpack and you // can read all about it in webpack.common.js. import { getMode, innerMode, StringStream, } from 'codemirror/addon/runmode/runmode.node.js' import { ITokens, IHighlightRequest } from '../lib/highlighter/types' /** * A mode definition object is used to map a certain file * extension to a mode loader (see the documentation for * the install property). */ interface IModeDefinition { /** * A function that, when called, will attempt to asynchronously * load the required modules for a particular mode. This function * is idempotent and can be called multiple times with no adverse * effect. */ readonly install: () => Promise<void> /** * A map between file extensions (including the leading dot, i.e. * ".jpeg") or basenames (i.e. "dockerfile") and the selected mime * type to use when highlighting that extension as specified in * the CodeMirror mode itself. */ readonly mappings: { readonly [key: string]: string } } /** * Array describing all currently supported extensionModes and the file extensions * that they cover. */ const extensionModes: ReadonlyArray<IModeDefinition> = [ { install: () => import('codemirror/mode/javascript/javascript'), mappings: { '.ts': 'text/typescript', '.js': 'text/javascript', '.json': 'application/json', }, }, { install: () => import('codemirror/mode/coffeescript/coffeescript'), mappings: { '.coffee': 'text/x-coffeescript', }, }, { install: () => import('codemirror/mode/jsx/jsx'), mappings: { '.tsx': 'text/typescript-jsx', '.jsx': 'text/jsx', }, }, { install: () => import('codemirror/mode/htmlmixed/htmlmixed'), mappings: { '.html': 'text/html', '.htm': 'text/html', }, }, { install: () => import('codemirror/mode/htmlembedded/htmlembedded'), mappings: { '.aspx': 'application/x-aspx', '.cshtml': 'application/x-aspx', '.jsp': 'application/x-jsp', }, }, { install: () => import('codemirror/mode/css/css'), mappings: { '.css': 'text/css', '.scss': 'text/x-scss', '.less': 'text/x-less', }, }, { install: () => import('codemirror/mode/vue/vue'), mappings: { '.vue': 'text/x-vue', }, }, { install: () => import('codemirror/mode/markdown/markdown'), mappings: { '.markdown': 'text/x-markdown', '.md': 'text/x-markdown', }, }, { install: () => import('codemirror/mode/yaml/yaml'), mappings: { '.yaml': 'text/yaml', '.yml': 'text/yaml', }, }, { install: () => import('codemirror/mode/xml/xml'), mappings: { '.xml': 'text/xml', '.xaml': 'text/xml', '.csproj': 'text/xml', '.fsproj': 'text/xml', '.vcxproj': 'text/xml', '.vbproj': 'text/xml', '.svg': 'text/xml', '.resx': 'text/xml', '.props': 'text/xml', '.targets': 'text/xml', }, }, { install: () => import('codemirror/mode/diff/diff'), mappings: { '.diff': 'text/x-diff', '.patch': 'text/x-diff', }, }, { install: () => import('codemirror/mode/clike/clike'), mappings: { '.m': 'text/x-objectivec', '.scala': 'text/x-scala', '.sc': 'text/x-scala', '.cs': 'text/x-csharp', '.cake': 'text/x-csharp', '.java': 'text/x-java', '.c': 'text/x-c', '.h': 'text/x-c', '.cpp': 'text/x-c++src', '.hpp': 'text/x-c++src', '.kt': 'text/x-kotlin', }, }, { install: () => import('codemirror/mode/mllike/mllike'), mappings: { '.ml': 'text/x-ocaml', '.fs': 'text/x-fsharp', '.fsx': 'text/x-fsharp', '.fsi': 'text/x-fsharp', }, }, { install: () => import('codemirror/mode/swift/swift'), mappings: { '.swift': 'text/x-swift', }, }, { install: () => import('codemirror/mode/shell/shell'), mappings: { '.sh': 'text/x-sh', }, }, { install: () => import('codemirror/mode/sql/sql'), mappings: { '.sql': 'text/x-sql', }, }, { install: () => import('codemirror/mode/cypher/cypher'), mappings: { '.cql': 'application/x-cypher-query', }, }, { install: () => import('codemirror/mode/go/go'), mappings: { '.go': 'text/x-go', }, }, { install: () => import('codemirror/mode/perl/perl'), mappings: { '.pl': 'text/x-perl', }, }, { install: () => import('codemirror/mode/php/php'), mappings: { '.php': 'application/x-httpd-php', }, }, { install: () => import('codemirror/mode/python/python'), mappings: { '.py': 'text/x-python', }, }, { install: () => import('codemirror/mode/ruby/ruby'), mappings: { '.rb': 'text/x-ruby', }, }, { install: () => import('codemirror/mode/clojure/clojure'), mappings: { '.clj': 'text/x-clojure', '.cljc': 'text/x-clojure', '.cljs': 'text/x-clojure', '.edn': 'text/x-clojure', }, }, { install: () => import('codemirror/mode/rust/rust'), mappings: { '.rs': 'text/x-rustsrc', }, }, { install: () => import('codemirror-mode-elixir'), mappings: { '.ex': 'text/x-elixir', '.exs': 'text/x-elixir', }, }, { install: () => import('codemirror/mode/haxe/haxe'), mappings: { '.hx': 'text/x-haxe', }, }, { install: () => import('codemirror/mode/r/r'), mappings: { '.r': 'text/x-rsrc', }, }, { install: () => import('codemirror/mode/powershell/powershell'), mappings: { '.ps1': 'application/x-powershell', }, }, { install: () => import('codemirror/mode/vb/vb'), mappings: { '.vb': 'text/x-vb', }, }, { install: () => import('codemirror/mode/fortran/fortran'), mappings: { '.f': 'text/x-fortran', '.f90': 'text/x-fortran', }, }, { install: () => import('codemirror/mode/lua/lua'), mappings: { '.lua': 'text/x-lua', }, }, { install: () => import('codemirror/mode/crystal/crystal'), mappings: { '.cr': 'text/x-crystal', }, }, { install: () => import('codemirror/mode/julia/julia'), mappings: { '.jl': 'text/x-julia', }, }, { install: () => import('codemirror/mode/stex/stex'), mappings: { '.tex': 'text/x-stex', }, }, { install: () => import('codemirror/mode/sparql/sparql'), mappings: { '.rq': 'application/sparql-query', }, }, { install: () => import('codemirror/mode/stylus/stylus'), mappings: { '.styl': 'text/x-styl', }, }, { install: () => import('codemirror/mode/soy/soy'), mappings: { '.soy': 'text/x-soy', }, }, { install: () => import('codemirror/mode/smalltalk/smalltalk'), mappings: { '.st': 'text/x-stsrc', }, }, { install: () => import('codemirror/mode/slim/slim'), mappings: { '.slim': 'application/x-slim', }, }, { install: () => import('codemirror/mode/haml/haml'), mappings: { '.haml': 'text/x-haml', }, }, { install: () => import('codemirror/mode/sieve/sieve'), mappings: { '.sieve': 'application/sieve', }, }, { install: () => import('codemirror/mode/scheme/scheme'), mappings: { '.ss': 'text/x-scheme', '.sls': 'text/x-scheme', '.scm': 'text/x-scheme', }, }, { install: () => import('codemirror/mode/rst/rst'), mappings: { '.rst': 'text/x-rst', }, }, { install: () => import('codemirror/mode/rpm/rpm'), mappings: { '.rpm': 'text/x-rpm-spec', }, }, { install: () => import('codemirror/mode/q/q'), mappings: { '.q': 'text/x-q', }, }, { install: () => import('codemirror/mode/puppet/puppet'), mappings: { '.pp': 'text/x-puppet', }, }, { install: () => import('codemirror/mode/pug/pug'), mappings: { '.pug': 'text/x-pug', }, }, { install: () => import('codemirror/mode/protobuf/protobuf'), mappings: { '.proto': 'text/x-protobuf', }, }, { install: () => import('codemirror/mode/properties/properties'), mappings: { '.properties': 'text/x-properties', '.gitattributes': 'text/x-properties', '.gitignore': 'text/x-properties', '.editorconfig': 'text/x-properties', '.ini': 'text/x-ini', }, }, { install: () => import('codemirror/mode/pig/pig'), mappings: { '.pig': 'text/x-pig', }, }, { install: () => import('codemirror/mode/asciiarmor/asciiarmor'), mappings: { '.pgp': 'application/pgp', }, }, { install: () => import('codemirror/mode/oz/oz'), mappings: { '.oz': 'text/x-oz', }, }, { install: () => import('codemirror/mode/pascal/pascal'), mappings: { '.pas': 'text/x-pascal', }, }, { install: () => import('codemirror/mode/toml/toml'), mappings: { '.toml': 'text/x-toml', }, }, { install: () => import('codemirror/mode/dart/dart'), mappings: { '.dart': 'application/dart', }, }, ] /** * A map between file extensions and mime types, see * the 'mappings' property on the IModeDefinition interface * for more information */ const extensionMIMEMap = new Map<string, string>() /** * Array describing all currently supported basenameModes and the file names * that they cover. */ const basenameModes: ReadonlyArray<IModeDefinition> = [ { install: () => import('codemirror/mode/dockerfile/dockerfile'), mappings: { dockerfile: 'text/x-dockerfile', }, }, ] /** * A map between file basenames and mime types, see * the 'basenames' property on the IModeDefinition interface * for more information */ const basenameMIMEMap = new Map<string, string>() /** * A map between mime types and mode definitions. See the * documentation for the IModeDefinition interface * for more information */ const mimeModeMap = new Map<string, IModeDefinition>() for (const extensionMode of extensionModes) { for (const [mapping, mimeType] of Object.entries(extensionMode.mappings)) { extensionMIMEMap.set(mapping, mimeType) mimeModeMap.set(mimeType, extensionMode) } } for (const basenameMode of basenameModes) { for (const [mapping, mimeType] of Object.entries(basenameMode.mappings)) { basenameMIMEMap.set(mapping, mimeType) mimeModeMap.set(mimeType, basenameMode) } } function guessMimeType(contents: ReadonlyArray<string>) { const firstLine = contents[0] if (firstLine.startsWith('<?xml')) { return 'text/xml' } if (firstLine.startsWith('#!')) { const m = /^#!.*?(ts-node|node|bash|sh|python(?:[\d.]+)?)/g.exec(firstLine) if (m) { switch (m[1]) { case 'ts-node': return 'text/typescript' case 'node': return 'text/javascript' case 'sh': case 'bash': return 'text/x-sh' case 'perl': return 'text/x-perl' } if (m[1].startsWith('python')) { return 'text/x-python' } } } return null } async function detectMode( request: IHighlightRequest ): Promise<CodeMirror.Mode<{}> | null> { const mimeType = extensionMIMEMap.get(request.extension.toLowerCase()) || basenameMIMEMap.get(request.basename.toLowerCase()) || guessMimeType(request.contentLines) if (!mimeType) { return null } const modeDefinition = mimeModeMap.get(mimeType) if (modeDefinition === undefined) { return null } await modeDefinition.install() return getMode({}, mimeType) || null } function getModeName(mode: CodeMirror.Mode<{}>): string | null { const name = (mode as any).name return name && typeof name === 'string' ? name : null } /** * Helper method to determine the name of the innermost (i.e. current) * mode. Think of this as an abstraction over CodeMirror's innerMode * with added type guards. */ function getInnerModeName( mode: CodeMirror.Mode<{}>, state: any ): string | null { const inner = innerMode(mode, state) return inner && inner.mode ? getModeName(inner.mode) : null } /** * Extract the next token from the line stream or null if no token * could be extracted from the current position in the line stream. * * This method is more or less equal to the readToken method in * CodeMirror but since the readToken class in CodeMirror isn't included * in the Node runmode we're not able to use it. * * Worth noting here is that we're also replicated the workaround for * modes that aren't adhering to the rules of never returning without * advancing the line stream by trying it again (up to ten times). See * https://github.com/codemirror/CodeMirror/commit/2c60a2 for more * details on that. * * @param mode The current (outer) mode * @param stream The StringStream for the current line * @param state The current mode state (if any) * @param addModeClass Whether or not to append the current (inner) mode name * as an extra CSS class to the token, indicating the mode * that produced it, prefixed with "cm-m-". For example, * tokens from the XML mode will get the cm-m-xml class. */ function readToken( mode: CodeMirror.Mode<{}>, stream: StringStream, state: any, addModeClass: boolean ): string | null { for (let i = 0; i < 10; i++) { const innerModeName = addModeClass ? getInnerModeName(mode, state) : null const token = mode.token(stream, state) if (stream.pos > stream.start) { return token && innerModeName ? `m-${innerModeName} ${token}` : token } } throw new Error(`Mode ${getModeName(mode)} failed to advance stream.`) } onmessage = async (ev: MessageEvent) => { const request = ev.data as IHighlightRequest const tabSize = request.tabSize || 4 const addModeClass = request.addModeClass === true const mode = await detectMode(request) if (!mode) { postMessage({}) return } const lineFilter = request.lines && request.lines.length ? new Set<number>(request.lines) : null // If we've got a set of requested lines we can keep track of the maximum // line we need so that we can bail immediately when we've reached it. const maxLine = lineFilter ? Math.max(...lineFilter) : null const lines = request.contentLines.concat() const state: any = mode.startState ? mode.startState() : null const tokens: ITokens = {} for (const [ix, line] of lines.entries()) { // No need to continue after the max line if (maxLine !== null && ix > maxLine) { break } // For stateless modes we can optimize by only running // the tokenizer over lines we care about. if (lineFilter && !state) { if (!lineFilter.has(ix)) { continue } } if (!line.length) { if (mode.blankLine) { mode.blankLine(state) } continue } const lineCtx = { lines, line: ix } const lineStream = new StringStream(line, tabSize, lineCtx) while (!lineStream.eol()) { const token = readToken(mode, lineStream, state, addModeClass) if (token && (!lineFilter || lineFilter.has(ix))) { tokens[ix] = tokens[ix] || {} tokens[ix][lineStream.start] = { length: lineStream.pos - lineStream.start, token, } } lineStream.start = lineStream.pos } } postMessage(tokens) }
the_stack
import { MappingTemplate } from '@aws-cdk/aws-appsync'; import { Transformer, TransformerContext, getFieldArguments } from 'graphql-transformer-core'; const graphqlTypeStatements = ['Query', 'Mutation', 'Subscription']; export interface CdkTransformerTableKey { readonly name: string; readonly type: string; } export interface CdkTransformerLocalSecondaryIndex { readonly indexName: string; readonly projection: any; readonly sortKey: CdkTransformerTableKey; } export interface CdkTransformerGlobalSecondaryIndex { readonly indexName: string; readonly projection: any; readonly partitionKey: CdkTransformerTableKey; readonly sortKey: CdkTransformerTableKey; } export interface CdkTransformerTableTtl { readonly attributeName: string; readonly enabled: boolean; } export interface CdkTransformerTable { readonly tableName: string; readonly partitionKey: CdkTransformerTableKey; readonly sortKey?: CdkTransformerTableKey; readonly ttl?: CdkTransformerTableTtl; readonly localSecondaryIndexes: CdkTransformerLocalSecondaryIndex[]; readonly globalSecondaryIndexes: CdkTransformerGlobalSecondaryIndex[]; readonly resolvers: string[]; readonly gsiResolvers: string[]; } export interface CdkTransformerResolver { readonly typeName: string; readonly fieldName: string; } export interface CdkTransformerHttpResolver extends CdkTransformerResolver { readonly httpConfig: any; readonly defaultRequestMappingTemplate: string; readonly defaultResponseMappingTemplate: string; } export interface CdkTransformerFunctionResolver extends CdkTransformerResolver { readonly defaultRequestMappingTemplate: string; readonly defaultResponseMappingTemplate: string; } export class CdkTransformer extends Transformer { tables: { [name: string]: CdkTransformerTable }; noneDataSources: { [name: string]: CdkTransformerResolver }; functionResolvers: { [name: string]: CdkTransformerFunctionResolver[] }; httpResolvers: { [name: string]: CdkTransformerHttpResolver[] }; resolverTableMap: { [name: string]: string }; gsiResolverTableMap: { [name: string]: string }; constructor() { super( 'CdkTransformer', 'directive @nullable on FIELD_DEFINITION', // this is unused ); this.tables = {}; this.noneDataSources = {}; this.functionResolvers = {}; this.httpResolvers = {}; this.resolverTableMap = {}; this.gsiResolverTableMap = {}; } public after = (ctx: TransformerContext): void => { this.buildResources(ctx); // TODO: Improve this iteration Object.keys(this.tables).forEach(tableName => { let table = this.tables[tableName]; Object.keys(this.resolverTableMap).forEach(resolverName => { if (this.resolverTableMap[resolverName] === tableName) table.resolvers.push(resolverName); }); Object.keys(this.gsiResolverTableMap).forEach(resolverName => { if (this.gsiResolverTableMap[resolverName] === tableName) table.gsiResolvers.push(resolverName); }); }); // @ts-ignore - we are overloading the use of outputs here... ctx.setOutput('cdkTables', this.tables); // @ts-ignore - we are overloading the use of outputs here... ctx.setOutput('noneResolvers', this.noneDataSources); // @ts-ignore - we are overloading the use of outputs here... ctx.setOutput('functionResolvers', this.functionResolvers); // @ts-ignore - we are overloading the use of outputs here... ctx.setOutput('httpResolvers', this.httpResolvers); const query = ctx.getQuery(); if (query) { const queryFields = getFieldArguments(query); ctx.setOutput('queries', queryFields); } const mutation = ctx.getMutation(); if (mutation) { const mutationFields = getFieldArguments(mutation); ctx.setOutput('mutations', mutationFields); } const subscription = ctx.getSubscription(); if (subscription) { const subscriptionFields = getFieldArguments(subscription); ctx.setOutput('subscriptions', subscriptionFields); } } private buildResources(ctx: TransformerContext): void { const templateResources = ctx.template.Resources; if (!templateResources) return; for (const [resourceName, resource] of Object.entries(templateResources)) { if (resource.Type === 'AWS::DynamoDB::Table') { this.buildTablesFromResource(resourceName, ctx); } else if (resource.Type === 'AWS::AppSync::Resolver') { if (resource.Properties?.DataSourceName === 'NONE') { this.noneDataSources[`${resource.Properties.TypeName}${resource.Properties.FieldName}`] = { typeName: resource.Properties.TypeName, fieldName: resource.Properties.FieldName, }; } else if (resource.Properties?.Kind === 'PIPELINE') { // Inspired by: // https://github.com/aws-amplify/amplify-cli/blob/master/packages/graphql-function-transformer/src/__tests__/FunctionTransformer.test.ts#L20 const dependsOn = resource.DependsOn as string ?? ''; const functionConfiguration = templateResources[dependsOn]; const functionDependsOn = functionConfiguration.DependsOn as string ?? ''; const functionDataSource = templateResources[functionDependsOn]; const functionArn = functionDataSource.Properties?.LambdaConfig?.LambdaFunctionArn?.payload[1].payload[0]; const functionName = functionArn.split(':').slice(-1)[0]; const fieldName = resource.Properties.FieldName; const typeName = resource.Properties.TypeName; if (!this.functionResolvers[functionName]) this.functionResolvers[functionName] = []; this.functionResolvers[functionName].push({ typeName: typeName, fieldName: fieldName, defaultRequestMappingTemplate: MappingTemplate.lambdaRequest().renderTemplate(), defaultResponseMappingTemplate: functionConfiguration.Properties?.ResponseMappingTemplate, // This should handle error messages }); } else { // Should be a table/model resolver -> Maybe not true when we add in @searchable, etc const dataSourceName = resource.Properties?.DataSourceName?.payload[0]; const dataSource = templateResources[dataSourceName]; const dataSourceType = dataSource.Properties?.Type; let typeName = resource.Properties?.TypeName; let fieldName = resource.Properties?.FieldName; switch (dataSourceType) { case 'AMAZON_DYNAMODB': let tableName = dataSourceName.replace('DataSource', 'Table'); if (graphqlTypeStatements.indexOf(typeName) >= 0) { this.resolverTableMap[fieldName] = tableName; } else { // this is a GSI this.gsiResolverTableMap[`${typeName}${fieldName}`] = tableName; } break; case 'HTTP': const httpConfig = dataSource.Properties?.HttpConfig; const endpoint = httpConfig.Endpoint; if (!this.httpResolvers[endpoint]) this.httpResolvers[endpoint] = []; this.httpResolvers[endpoint].push({ typeName, fieldName, httpConfig, defaultRequestMappingTemplate: resource.Properties?.RequestMappingTemplate, defaultResponseMappingTemplate: resource.Properties?.ResponseMappingTemplate, }); break; default: throw new Error(`Unsupported Data Source Type: ${dataSourceType}`); } } } } } private buildTablesFromResource(resourceName: string, ctx: TransformerContext): void { const tableResource = ctx.template.Resources ? ctx.template.Resources[resourceName] : undefined; const attributeDefinitions = tableResource?.Properties?.AttributeDefinitions; const keySchema = tableResource?.Properties?.KeySchema; const keys = this.parseKeySchema(keySchema, attributeDefinitions); let ttl = tableResource?.Properties?.TimeToLiveSpecification; if (ttl) { ttl = { attributeName: ttl.AttributeName, enabled: ttl.Enabled, }; } let table: CdkTransformerTable = { tableName: resourceName, partitionKey: keys.partitionKey, sortKey: keys.sortKey, ttl: ttl, localSecondaryIndexes: [], globalSecondaryIndexes: [], resolvers: [], gsiResolvers: [], }; const lsis = tableResource?.Properties?.LocalSecondaryIndexes; if (lsis) { lsis.forEach((lsi: any) => { const lsiKeys = this.parseKeySchema(lsi.KeySchema, attributeDefinitions); const lsiDefinition = { indexName: lsi.IndexName, projection: lsi.Projection, sortKey: lsiKeys.sortKey, }; table.localSecondaryIndexes.push(lsiDefinition); }); } const gsis = tableResource?.Properties?.GlobalSecondaryIndexes; if (gsis) { gsis.forEach((gsi: any) => { const gsiKeys = this.parseKeySchema(gsi.KeySchema, attributeDefinitions); const gsiDefinition = { indexName: gsi.IndexName, projection: gsi.Projection, partitionKey: gsiKeys.partitionKey, sortKey: gsiKeys.sortKey, }; table.globalSecondaryIndexes.push(gsiDefinition); }); } this.tables[resourceName] = table; } private parseKeySchema(keySchema: any, attributeDefinitions: any) { let partitionKey: any = {}; let sortKey: any = {}; keySchema.forEach((key: any) => { const keyType = key.KeyType; const attributeName = key.AttributeName; const attribute = attributeDefinitions.find((attr: any) => attr.AttributeName === attributeName); if (keyType === 'HASH') { partitionKey = { name: attribute.AttributeName, type: attribute.AttributeType, }; } else if (keyType === 'RANGE') { sortKey = { name: attribute.AttributeName, type: attribute.AttributeType, }; } }); return { partitionKey, sortKey }; } }
the_stack
import {Component, Injector, Input, OnInit, ViewContainerRef} from "@angular/core"; import {StateService} from "@uirouter/angular"; import {FEED_DEFINITION_SECTION_STATE_NAME, FEED_DEFINITION_STATE_NAME, FEED_DEFINITION_SUMMARY_STATE_NAME} from '../../model/feed/feed-constants'; import * as _ from 'underscore'; import {Sla} from '../model/sla.model'; import {Feed, FeedState} from '../../model/feed/feed.model'; import {FormGroup} from '@angular/forms'; import {LoadingMode, LoadingType, TdLoadingService} from '@covalent/core/loading'; import {MatSnackBar} from '@angular/material/snack-bar'; import {TdDialogService} from '@covalent/core/dialogs'; import {TranslateService} from '@ngx-translate/core'; import AccessConstants from '../../../constants/AccessConstants'; import {SlaService} from "../../services/sla.service"; import "rxjs/add/observable/empty"; import 'rxjs/add/observable/forkJoin' import "rxjs/add/observable/of"; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import "rxjs/add/observable/from"; import 'rxjs/add/observable/fromPromise'; import {Observable} from "rxjs/Observable"; import {PartialObserver} from "rxjs/Observer"; import {catchError} from "rxjs/operators/catchError"; import {concatMap} from "rxjs/operators/concatMap"; import {filter} from "rxjs/operators/filter"; import {finalize} from "rxjs/operators/finalize"; import {map} from "rxjs/operators/map"; import {switchMap} from "rxjs/operators/switchMap"; import {tap} from "rxjs/operators/tap"; import {Subject} from "rxjs/Subject"; import {error} from "ng-packagr/lib/util/log"; export enum FormMode { ModeEdit = "EDIT", ModeNew = "NEW", } export class RuleType { name: string; mode: FormMode; constructor() { this.name = ''; this.mode = FormMode.ModeNew; } } @Component({ selector: "sla-details", styleUrls: ["./sla-details.component.scss"], templateUrl: "./sla-details.component.html" }) export class SlaDetailsComponent implements OnInit { private static feedLoader: string = "SlaDetailsComponent.feedLoader"; private static slaLoader: string = "SlaDetailsComponent.slaLoader"; private static saveLoader: string = "SlaDetailsComponent.saveLoader"; private static deleteLoader: string = "SlaDetailsComponent.deleteLoader"; @Input() stateParams:any; @Input("feed") feedModel: Feed; private slaId: string; private accessControlService: any; private policyInputFormService: any; allowEdit = false; sla: Sla; /** * a copy of the loaded SLA name (separate from the modifiable sla object (sla.name) for display purposes */ slaName:string; slaForm: FormGroup = new FormGroup({}); private feedId: string; private savingSla = false; loadingFeed = false; loadingSla = false; private deletingSla = false; mode: FormMode; editMode = FormMode.ModeEdit; newMode = FormMode.ModeNew; stateDisabled = FeedState.DISABLED; private labelErrorLoadingSla: string; private labelAccessDenied: string; private labelOk: string; private labelSavedSla: string; private labelFailedToSaveSla: string; private labelDeleteSla: string; private labelConfirm: string; private labelCancel: string; private labelDelete: string; private labelDeleted: string; private labelErrorDeletingSla: string; constructor(private $$angularInjector: Injector, private state: StateService, private loadingService: TdLoadingService, private snackBar: MatSnackBar, private dialogService: TdDialogService, private viewContainerRef: ViewContainerRef, private translateService: TranslateService,private slaService:SlaService) { this.accessControlService = $$angularInjector.get("AccessControlService"); this.policyInputFormService = $$angularInjector.get("PolicyInputFormService"); this.createLoader(SlaDetailsComponent.feedLoader); this.createLoader(SlaDetailsComponent.slaLoader); this.createLoader(SlaDetailsComponent.saveLoader); this.createLoader(SlaDetailsComponent.deleteLoader); this.labelErrorLoadingSla = this.translateService.instant("Sla.Details.ErrorLoadingSla"); this.labelAccessDenied = this.translateService.instant("Sla.Details.AccessDenied"); this.labelOk = this.translateService.instant("Sla.Details.Ok"); this.labelSavedSla = this.translateService.instant("Sla.Details.SavedSla"); this.labelFailedToSaveSla = this.translateService.instant("Sla.Details.FailedToSaveSla"); this.labelDeleteSla = this.translateService.instant("Sla.Details.DeleteSla"); this.labelConfirm = this.translateService.instant("Sla.Details.Confirm"); this.labelCancel = this.translateService.instant("Sla.Details.Cancel"); this.labelDelete = this.translateService.instant("Sla.Details.Delete"); this.labelDeleted = this.translateService.instant("Sla.Details.DeletedSla"); this.labelErrorDeletingSla = this.translateService.instant("Sla.Details.ErrorDeletingSla"); } private createLoader(name: string) { this.loadingService.create({ name: name, mode: LoadingMode.Indeterminate, type: LoadingType.Linear, color: 'accent', }); } ngOnInit() { this.slaId = this.stateParams ? this.stateParams.slaId : undefined; if (this.slaId) { this.loadSla(this.slaId); this.mode = FormMode.ModeEdit; } else { this.mode = FormMode.ModeNew; this.sla = new Sla(); //allow the user to edit this SLA if it is new this.sla.canEdit = true; this.sla.editable = true; this.applyEditPermissionsToSLA(this.sla); } this.feedId = this.stateParams ? this.stateParams.feedId : undefined; } loadSla(slaId: string) { this.loadingService.register(SlaDetailsComponent.slaLoader); this.loadingSla = true; Observable.fromPromise<Sla>( <Promise<Sla>>this.slaService.getSlaForEditForm(slaId)) .pipe( catchError(err => { this.loadingService.resolve(SlaDetailsComponent.slaLoader); const msg = err.data.message || this.labelErrorLoadingSla; this.loadingSla = false; console.error(msg); this.snackBar.open(this.labelAccessDenied, this.labelOk, { duration: 5000 }); throw err; } ), switchMap((sla:Sla) => this.applyEditPermissionsToSLA(sla)), finalize(() =>{ this.loadingService.resolve(SlaDetailsComponent.slaLoader); this.loadingSla = false; }) ).subscribe(sla => { this.sla = sla; this.slaName = sla.name; _.each(sla.rules, (rule: any) => { rule.editable = sla.canEdit; rule.mode = FormMode.ModeEdit; rule.groups = this.policyInputFormService.groupProperties(rule); this.policyInputFormService.updatePropertyIndex(rule); }); _.each(sla.actionConfigurations, (rule: any) => { rule.editable = sla.canEdit; rule.mode = FormMode.ModeEdit; rule.groups = this.policyInputFormService.groupProperties(rule); this.policyInputFormService.updatePropertyIndex(rule); //validate the rules this.slaService.validateSlaActionRule(rule); }); }); } private applyEditPermissionsToSLA(sla: Sla) :Observable<Sla> { const entityAccessControlled = this.accessControlService.isEntityAccessControlled(); let promise = this.accessControlService.getUserAllowedActions(); let subject = new Subject<Sla>(); promise.then((response: any) => { const allowFeedEdit = this.accessControlService.hasAction(AccessConstants.FEEDS_EDIT, response.actions); const allowSlaEdit = this.accessControlService.hasAction(AccessConstants.SLA_EDIT, response.actions); if (entityAccessControlled) { this.allowEdit = sla.canEdit && allowSlaEdit && allowFeedEdit; sla.editable = this.allowEdit; } else { this.allowEdit = allowFeedEdit && allowSlaEdit; sla.editable = this.allowEdit; } subject.next(sla); subject.complete(); }, (error:any) => { subject.next(sla) subject.complete(); }); return subject.asObservable(); } onSaveSla():void { this.savingSla = true; this.loadingService.register(SlaDetailsComponent.saveLoader); if(this.feedModel) { this.slaService.saveFeedSla(this.feedId, this.sla).then((response: any) => { this.loadingService.resolve(SlaDetailsComponent.saveLoader); this.savingSla = false; this.snackBar.open(this.labelSavedSla, this.labelOk, {duration: 3000}); this.state.go("^.list"); }, function () { this.loadingService.resolve(SlaDetailsComponent.saveLoader); this.savingSla = false; this.snackBar.open(this.labelFailedToSaveSla, this.labelOk, {duration: 3000}); }); } else { this.slaService.saveSla(this.sla).then((response: any) => { this.loadingService.resolve(SlaDetailsComponent.saveLoader); this.savingSla = false; this.snackBar.open(this.labelSavedSla, this.labelOk, {duration: 3000}); this.state.go("^.list"); }, function () { this.loadingService.resolve(SlaDetailsComponent.saveLoader); this.savingSla = false; this.snackBar.open(this.labelFailedToSaveSla, this.labelOk, {duration: 3000}); }); } } onCancelSaveSla(): void { this.state.go("^.list"); } onDeleteSla(): void { this.dialogService.openConfirm({ message: this.labelDeleteSla, disableClose: true, viewContainerRef: this.viewContainerRef, title: this.labelConfirm, cancelButton: this.labelCancel, acceptButton: this.labelDelete, width: '300px', }).afterClosed().subscribe((accept: boolean) => { if (accept) { this.doDeleteSla(); } }); } doDeleteSla() { this.loadingService.register(SlaDetailsComponent.deleteLoader); this.deletingSla = true; this.slaService.deleteSla(this.sla.id).then(() => { this.loadingService.resolve(SlaDetailsComponent.deleteLoader); this.snackBar.open(this.labelDeleted, this.labelOk, { duration: 3000 }); this.deletingSla = false; this.state.go("^.list"); }, () => { this.loadingService.resolve(SlaDetailsComponent.deleteLoader); this.deletingSla = false; this.snackBar.open(this.labelErrorDeletingSla, this.labelOk, { duration: 3000 }); }); } }
the_stack
import { orderHashUtils } from '@0x/contracts-test-utils'; import { ReferenceFunctions } from '@0x/contracts-utils'; import { FillResults, MatchedFillResults, Order } from '@0x/types'; import { BigNumber, ExchangeRevertErrors, LibMathRevertErrors } from '@0x/utils'; const { safeAdd, safeSub, safeMul, safeDiv } = ReferenceFunctions; /** * Checks if rounding error >= 0.1% when rounding down. */ export function isRoundingErrorFloor(numerator: BigNumber, denominator: BigNumber, target: BigNumber): boolean { if (denominator.eq(0)) { throw new LibMathRevertErrors.DivisionByZeroError(); } if (numerator.eq(0) || target.eq(0)) { return false; } const remainder = numerator.times(target).mod(denominator); // Need to do this separately because solidity evaluates RHS of the comparison expression first. const rhs = safeMul(numerator, target); const lhs = safeMul(remainder, new BigNumber(1000)); return lhs.gte(rhs); } /** * Checks if rounding error >= 0.1% when rounding up. */ export function isRoundingErrorCeil(numerator: BigNumber, denominator: BigNumber, target: BigNumber): boolean { if (denominator.eq(0)) { throw new LibMathRevertErrors.DivisionByZeroError(); } if (numerator.eq(0) || target.eq(0)) { return false; } let remainder = numerator.times(target).mod(denominator); remainder = safeSub(denominator, remainder).mod(denominator); // Need to do this separately because solidity evaluates RHS of the comparison expression first. const rhs = safeMul(numerator, target); const lhs = safeMul(remainder, new BigNumber(1000)); return lhs.gte(rhs); } /** * Calculates partial value given a numerator and denominator rounded down. * Reverts if rounding error is >= 0.1% */ export function safeGetPartialAmountFloor(numerator: BigNumber, denominator: BigNumber, target: BigNumber): BigNumber { if (isRoundingErrorFloor(numerator, denominator, target)) { throw new LibMathRevertErrors.RoundingError(numerator, denominator, target); } return safeDiv(safeMul(numerator, target), denominator); } /** * Calculates partial value given a numerator and denominator rounded down. * Reverts if rounding error is >= 0.1% */ export function safeGetPartialAmountCeil(numerator: BigNumber, denominator: BigNumber, target: BigNumber): BigNumber { if (isRoundingErrorCeil(numerator, denominator, target)) { throw new LibMathRevertErrors.RoundingError(numerator, denominator, target); } return safeDiv(safeAdd(safeMul(numerator, target), safeSub(denominator, new BigNumber(1))), denominator); } /** * Calculates partial value given a numerator and denominator rounded down. */ export function getPartialAmountFloor(numerator: BigNumber, denominator: BigNumber, target: BigNumber): BigNumber { return safeDiv(safeMul(numerator, target), denominator); } /** * Calculates partial value given a numerator and denominator rounded down. */ export function getPartialAmountCeil(numerator: BigNumber, denominator: BigNumber, target: BigNumber): BigNumber { const sub = safeSub(denominator, new BigNumber(1)); // This is computed first to simulate Solidity's order of operations return safeDiv(safeAdd(safeMul(numerator, target), sub), denominator); } /** * Adds properties of two `FillResults`. */ export function addFillResults(a: FillResults, b: FillResults): FillResults { return { makerAssetFilledAmount: safeAdd(a.makerAssetFilledAmount, b.makerAssetFilledAmount), takerAssetFilledAmount: safeAdd(a.takerAssetFilledAmount, b.takerAssetFilledAmount), makerFeePaid: safeAdd(a.makerFeePaid, b.makerFeePaid), takerFeePaid: safeAdd(a.takerFeePaid, b.takerFeePaid), protocolFeePaid: safeAdd(a.protocolFeePaid, b.protocolFeePaid), }; } /** * Calculates amounts filled and fees paid by maker and taker. */ export function calculateFillResults( order: Order, takerAssetFilledAmount: BigNumber, protocolFeeMultiplier: BigNumber, gasPrice: BigNumber, ): FillResults { const makerAssetFilledAmount = safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerAssetAmount, ); const makerFeePaid = safeGetPartialAmountFloor(takerAssetFilledAmount, order.takerAssetAmount, order.makerFee); const takerFeePaid = safeGetPartialAmountFloor(takerAssetFilledAmount, order.takerAssetAmount, order.takerFee); return { makerAssetFilledAmount, takerAssetFilledAmount, makerFeePaid, takerFeePaid, protocolFeePaid: safeMul(protocolFeeMultiplier, gasPrice), }; } /** * Calculates amounts filled and fees paid by maker and taker. */ export function calculateMatchResults( leftOrder: Order, rightOrder: Order, protocolFeeMultiplier: BigNumber, gasPrice: BigNumber, withMaximalFill: boolean = false, ): MatchedFillResults { // Initialize empty fill results. const leftFillResults: FillResults = { makerAssetFilledAmount: new BigNumber(0), takerAssetFilledAmount: new BigNumber(0), makerFeePaid: new BigNumber(0), takerFeePaid: new BigNumber(0), protocolFeePaid: new BigNumber(0), }; const rightFillResults: FillResults = { makerAssetFilledAmount: new BigNumber(0), takerAssetFilledAmount: new BigNumber(0), makerFeePaid: new BigNumber(0), takerFeePaid: new BigNumber(0), protocolFeePaid: new BigNumber(0), }; let profitInLeftMakerAsset = new BigNumber(0); let profitInRightMakerAsset = new BigNumber(0); // Assert matchable if ( leftOrder.makerAssetAmount .times(rightOrder.makerAssetAmount) .lt(leftOrder.takerAssetAmount.times(rightOrder.takerAssetAmount)) ) { throw new ExchangeRevertErrors.NegativeSpreadError( orderHashUtils.getOrderHashHex(leftOrder), orderHashUtils.getOrderHashHex(rightOrder), ); } // Asset Transfer Amounts if (leftOrder.takerAssetAmount.gt(rightOrder.makerAssetAmount)) { leftFillResults.makerAssetFilledAmount = safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, rightOrder.makerAssetAmount, ); leftFillResults.takerAssetFilledAmount = rightOrder.makerAssetAmount; rightFillResults.makerAssetFilledAmount = rightOrder.makerAssetAmount; rightFillResults.takerAssetFilledAmount = rightOrder.takerAssetAmount; } else if (withMaximalFill && leftOrder.makerAssetAmount.lt(rightOrder.takerAssetAmount)) { leftFillResults.makerAssetFilledAmount = leftOrder.makerAssetAmount; leftFillResults.takerAssetFilledAmount = leftOrder.takerAssetAmount; rightFillResults.makerAssetFilledAmount = safeGetPartialAmountFloor( rightOrder.makerAssetAmount, rightOrder.takerAssetAmount, leftOrder.makerAssetAmount, ); rightFillResults.takerAssetFilledAmount = leftOrder.makerAssetAmount; } else if (!withMaximalFill && leftOrder.takerAssetAmount.lt(rightOrder.makerAssetAmount)) { leftFillResults.makerAssetFilledAmount = leftOrder.makerAssetAmount; leftFillResults.takerAssetFilledAmount = leftOrder.takerAssetAmount; rightFillResults.makerAssetFilledAmount = leftOrder.takerAssetAmount; rightFillResults.takerAssetFilledAmount = safeGetPartialAmountCeil( rightOrder.takerAssetAmount, rightOrder.makerAssetAmount, leftOrder.takerAssetAmount, ); } else { leftFillResults.makerAssetFilledAmount = leftOrder.makerAssetAmount; leftFillResults.takerAssetFilledAmount = leftOrder.takerAssetAmount; rightFillResults.makerAssetFilledAmount = rightOrder.makerAssetAmount; rightFillResults.takerAssetFilledAmount = rightOrder.takerAssetAmount; } // Profit profitInLeftMakerAsset = leftFillResults.makerAssetFilledAmount.minus(rightFillResults.makerAssetFilledAmount); profitInRightMakerAsset = rightFillResults.makerAssetFilledAmount.minus(leftFillResults.makerAssetFilledAmount); // Fees leftFillResults.makerFeePaid = safeGetPartialAmountFloor( leftFillResults.makerAssetFilledAmount, leftOrder.makerAssetAmount, leftOrder.makerFee, ); leftFillResults.takerFeePaid = safeGetPartialAmountFloor( leftFillResults.takerAssetFilledAmount, leftOrder.takerAssetAmount, leftOrder.takerFee, ); rightFillResults.makerFeePaid = safeGetPartialAmountFloor( rightFillResults.makerAssetFilledAmount, rightOrder.makerAssetAmount, rightOrder.makerFee, ); rightFillResults.takerFeePaid = safeGetPartialAmountFloor( rightFillResults.takerAssetFilledAmount, rightOrder.takerAssetAmount, rightOrder.takerFee, ); // Protocol Fee leftFillResults.protocolFeePaid = safeMul(protocolFeeMultiplier, gasPrice); rightFillResults.protocolFeePaid = safeMul(protocolFeeMultiplier, gasPrice); return { left: leftFillResults, right: rightFillResults, profitInLeftMakerAsset, profitInRightMakerAsset, }; } export const LibFractions = { add: (n1: BigNumber, d1: BigNumber, n2: BigNumber, d2: BigNumber): [BigNumber, BigNumber] => { if (n1.isZero()) { return [n2, d2]; } if (n2.isZero()) { return [n1, d1]; } const numerator = safeAdd(safeMul(n1, d2), safeMul(n2, d1)); const denominator = safeMul(d1, d2); return [numerator, denominator]; }, normalize: ( numerator: BigNumber, denominator: BigNumber, maxValue: BigNumber = new BigNumber(2).exponentiatedBy(127), ): [BigNumber, BigNumber] => { if (numerator.isGreaterThan(maxValue) || denominator.isGreaterThan(maxValue)) { let rescaleBase = numerator.isGreaterThanOrEqualTo(denominator) ? numerator : denominator; rescaleBase = safeDiv(rescaleBase, maxValue); return [safeDiv(numerator, rescaleBase), safeDiv(denominator, rescaleBase)]; } else { return [numerator, denominator]; } }, };
the_stack
import { QuotationInvoiceHeaders } from 'src/components/data/table-definitions/quotation_invoice_items'; import { CurrentlyViewedInvoiceQuotation, CustomerAddressShape, DiscountType, ProductNameType, QuotationInvoiceFormShape, QuotationInvoiceItemShape, RoundingType, } from 'src/store/types'; import { computed, ref } from 'vue'; import { store } from '../../store'; import { DateTime } from 'luxon'; import MultiFormatPicture from 'src/helpers/MultiFormatPicture'; import { snakeCase } from 'lodash'; import useDownloadBinary from '../useDownloadBinary'; export const currentInvoiceQuotation = computed({ get: () => // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access store.getters[ 'invoices_quotations/GET_CURRENTLY_VIEWED_INVOICE_QUOTATION' ] as CurrentlyViewedInvoiceQuotation, set: (value) => value, }); export const getCurrentInvoiceQuotationData = computed( () => ( currentInvoiceQuotationData: CurrentlyViewedInvoiceQuotation, tableColumns: QuotationInvoiceHeaders[] ): QuotationInvoiceFormShape => { const form: QuotationInvoiceFormShape = {} as QuotationInvoiceFormShape; try { const currentInvoiceQuotationDataNormalised = JSON.parse( JSON.stringify(currentInvoiceQuotationData) ) as CurrentlyViewedInvoiceQuotation; const items = (currentInvoiceQuotationDataNormalised?.items ?? []) .sort((a, b) => a.sort_order - b.sort_order) .map((item) => { const isRealProduct = item?.product !== null; const productIdColumnHeader = tableColumns.filter( (column) => column.name === 'productId' )[0]; if (isRealProduct) { productIdColumnHeader.options?.push({ label: item?.product?.name ?? '', value: item?.product?.id ?? '', }); } return { productId: isRealProduct ? { label: item?.product?.name ?? '', value: item?.product?.id ?? null, } : null, productName: !isRealProduct ? item.product_name : '', productNameType: isRealProduct ? ('real_product' as ProductNameType) : ('custom_product' as ProductNameType), description: item.description, qty: item.qty, UOM: item.unitOfMeasurement.name, collectionTypeId: item.collectionType.name, groupQty: item.group_qty, unitPrice: item.unit_price, unitDiscount: item.unit_discount, discountType: item.discount_type, customSerialNumber: item.custom_serial_number, }; }); form.items = items; form.additionalFees = currentInvoiceQuotationDataNormalised.additional_fees; form.date = currentInvoiceQuotationDataNormalised.date; form.code = currentInvoiceQuotationDataNormalised.code; form.customerId = { label: currentInvoiceQuotationDataNormalised?.customer?.customer_name ?? '', value: currentInvoiceQuotationDataNormalised?.customer?.id ?? '', }; form.customerBillingAddressId = { label: currentInvoiceQuotationDataNormalised?.billing_address ?.full_address ?? '', value: currentInvoiceQuotationDataNormalised?.billing_address?.id ?? '', }; form.customerShippingAddressId = { label: currentInvoiceQuotationDataNormalised?.shipping_address ?.full_address ?? '', value: currentInvoiceQuotationDataNormalised?.shipping_address?.id ?? '', }; form.introduction = currentInvoiceQuotationDataNormalised.introduction === 'undefined' ? '' : currentInvoiceQuotationDataNormalised.introduction; form.title = currentInvoiceQuotationDataNormalised.title; form.simpleQuantities = currentInvoiceQuotationDataNormalised.simple_quantities; form.amountsAreTaxInclusive = currentInvoiceQuotationDataNormalised.amounts_are_tax_inclusive; form.taxPercentage = currentInvoiceQuotationDataNormalised.tax_percentage; form.roundAmounts = currentInvoiceQuotationDataNormalised.round_amounts; form.roundAmountType = currentInvoiceQuotationDataNormalised.round_amount_type; form.showDiscounts = currentInvoiceQuotationDataNormalised.show_discounts; form.discountType = currentInvoiceQuotationDataNormalised.discount_type; form.setDiscountTypePerLine = currentInvoiceQuotationDataNormalised.set_discount_type_per_line; form.calculateTotals = currentInvoiceQuotationDataNormalised.calculate_totals; form.changeProductPrices = currentInvoiceQuotationDataNormalised.change_product_prices; form.numberOfDecimals = currentInvoiceQuotationDataNormalised.number_of_decimals; form.useThousandSeparator = currentInvoiceQuotationDataNormalised.use_thousand_separator; form.thousandSeparatorType = currentInvoiceQuotationDataNormalised.thousand_separator_type; form.notes = currentInvoiceQuotationDataNormalised?.notes === 'undefined' ? '' : currentInvoiceQuotationDataNormalised?.notes; form.showAdditionalSubtotalDiscount = currentInvoiceQuotationDataNormalised.show_additional_subtotal_discount; form.additionalDiscountType = currentInvoiceQuotationDataNormalised.additional_discount_type; form.additionalDiscountAmount = currentInvoiceQuotationDataNormalised.additional_discount_amount; form.showAdditionalFees = currentInvoiceQuotationDataNormalised.show_additional_fees; form.showImages = currentInvoiceQuotationDataNormalised.show_images; form.useCustomSerialNumbers = currentInvoiceQuotationDataNormalised.use_custom_serial_numbers; form.useEditor = currentInvoiceQuotationDataNormalised.use_editor; } catch (error) { console.log(error); } return form; } ); export const getRoundedTotal = function ( amount: string | number, roundingType: RoundingType, numberOfDecimals: number ) { let total: string | number = ''; switch (roundingType) { case 'none': total = Number(amount).toFixed(numberOfDecimals); break; case 'nearest': total = Math.round(amount as number); break; case 'down': total = Math.floor(amount as number); break; case 'up': total = Math.ceil(amount as number); break; } return total; }; type GetTotalArrayConfig = { items: QuotationInvoiceItemShape[]; roundAmountType: RoundingType; roundAmounts: boolean; numberOfDecimals: number; showDiscounts: boolean; discountType: DiscountType; roundedTotal: typeof getRoundedTotal; }; export const getTotalArray = function ({ items, roundAmountType, roundAmounts, numberOfDecimals, showDiscounts, discountType, roundedTotal, }: GetTotalArrayConfig): number[] { const totalArray: number[] = []; if (items && items.length) { items.forEach((item, index) => { const unitPrice = Number(item?.unitPrice ?? 0); const qty = Number(item?.qty ?? 0); //const thousandSeparator = form.thousandSeparatorType; if (showDiscounts) { const unitDiscount = Number(item?.unitDiscount ?? 0); let discountedPrice = 0; if (discountType === 'percentage') { discountedPrice = (1 - unitDiscount / 100) * unitPrice; } else { discountedPrice = unitPrice - unitDiscount; } if (roundAmounts) { totalArray[index] = Number( roundedTotal( qty * discountedPrice, roundAmountType, numberOfDecimals ) ); } else { totalArray[index] = qty * discountedPrice; } } else { // The effect is the same for when `roundAmounts` // is true or false totalArray[index] = Number( roundedTotal(qty * unitPrice, roundAmountType, numberOfDecimals) ); } }); } return totalArray; }; type GetLineDiscountArrayConfig = { items: QuotationInvoiceItemShape[]; roundingType: RoundingType; roundAmounts: boolean; numberOfDecimals: number; showDiscounts: boolean; discountType: DiscountType; roundedTotal: typeof getRoundedTotal; setDiscountTypePerLine: boolean; }; export const getLineDiscountArray = function ({ items, roundingType, numberOfDecimals, showDiscounts, discountType, roundAmounts, roundedTotal, setDiscountTypePerLine, }: GetLineDiscountArrayConfig): number[] { const discountArray: number[] = []; if (items && items.length) { items.forEach((item, index) => { const unitPrice = Number(item?.unitPrice ?? 0); const qty = Number(item?.qty ?? 0); //const thousandSeparator = form.thousandSeparatorType; if (showDiscounts) { const unitDiscount = Number(item?.unitDiscount ?? 0); let discount = 0; if (setDiscountTypePerLine) { const lineDiscountType = item.discountType; if (lineDiscountType === 'percentage') { discount = (unitDiscount / 100) * unitPrice; } else discount = unitDiscount; } else if (discountType === 'percentage') { discount = (unitDiscount / 100) * unitPrice; } else { discount = unitDiscount; } if (roundAmounts) { discountArray[index] = Number( roundedTotal(qty * discount, roundingType, numberOfDecimals) ); } else { discountArray[index] = qty * discount; } } else { discountArray[index] = 0; } }); } return discountArray; }; export const getTotalQuantities = function ( items: QuotationInvoiceItemShape[] ) { return computed(() => { return items .map((item) => Number(item.qty)) .reduce((prevQty, curQty) => prevQty + curQty, 0); }); }; export const getSubTotal = function ( itemTotals: number[], roundedTotal: typeof getRoundedTotal, roundAmountType: RoundingType, numberOfDecimals: number ) { return computed(() => { const total = itemTotals.reduce( (prevTotal, curTotal) => Number(prevTotal) + Number(curTotal), 0 ); return Number(roundedTotal(total, roundAmountType, numberOfDecimals)); }); }; export const discountTypeOptions = ref([ { label: 'Num', value: 'number' }, { label: '%', value: 'percentage' }, ]); export const roundTypeOptions = ref([ { label: 'None', value: 'none' }, { label: 'Nearest', value: 'nearest' }, { label: 'Down', value: 'down' }, { label: 'Up', value: 'up' }, ]); export const numberOfDecimalOptionValues = [0, 1, 2, 3, 4, 5, 6]; export const fullDate = function (date: string): string { // Date is in iso format return DateTime.fromISO(date).toLocaleString(DateTime.DATE_FULL); }; const getAddressObject = function (address: CustomerAddressShape) { return { streetAddress: address?.street_address, addressLine2: `${address?.city ?? ''} ${address?.postal_code ?? ''}`.trim(), addressLine3: `${address?.addressState?.name ?? ''}${ address?.addressCountry?.name && address?.addressState?.name ? ', ' + address?.addressCountry?.name : address?.addressCountry?.name ?? '' }`.trim(), }; }; export const getCustomerInformation = function ( data: CurrentlyViewedInvoiceQuotation ) { const isCorporateCustomer = data.customer.is_corporate; const customerName = isCorporateCustomer ? data.customer.company_name : data.customer.customer_name; const corporateCustomerHasRep = data.customer.corporate_has_rep; const shippingAddress = getAddressObject(data.shipping_address); const billingAddress = getAddressObject(data.billing_address); const individualCustomerOrRepDetails = { name: !isCorporateCustomer ? customerName : `${data.customer?.first_name ?? ''} ${data.customer?.last_name ?? ''}`, email: data.customer?.email ?? '', phoneNumber: data.customer?.phone_number ?? '', customerHasTitle: !!data.customer?.title?.name, title: data.customer?.title?.name ?? '', }; const corporateCustomerDetails = { name: data.customer?.company_name ?? '', email: data.customer?.company_email ?? '', phoneNumber: data.customer?.company_phone ?? '', }; const isIndividualCustomerOrRepAvailable = (isCorporateCustomer && corporateCustomerHasRep) || !isCorporateCustomer; const isBillingAddressAvailable = !!data.billing_address; const isShippingAddressAvailable = !!data.shipping_address; const customerTitle = data.customer?.title?.name ?? 'Sir/Madam'; const documentTitle = data.title && data.title !== 'undefined' ? data.title : ''; const documentIntroduction = data.introduction && data.introduction !== 'undefined' ? data.introduction : ''; const documentNotes = data.notes && data.notes !== 'undefined' ? data.notes : ''; return { isCorporateCustomer, customerName, corporateCustomerHasRep, shippingAddress, billingAddress, individualCustomerOrRepDetails, isIndividualCustomerOrRepAvailable, corporateCustomerDetails, isBillingAddressAvailable, isShippingAddressAvailable, customerTitle, documentTitle, documentIntroduction, documentNotes, }; }; export const getCompanyInformation = function ( data: CurrentlyViewedInvoiceQuotation ) { const documentCompany = { name: data.company.name, logoInitials: data.company.name.slice(0, 3).toLocaleUpperCase(), fullAddress: `${data.company?.address ?? ''}${ data.company?.city ? ' ' + data.company?.city + `${data.company.state?.name ? ',' : ''}` : '' }${ data.company.state?.name ? ' ' + data.company.state?.name + `${data.company.country?.name ? ',' : ''}` : '' }${ data.company.country?.name ? ' ' + data.company.country?.name : '' }`.trim(), phoneNumber: data.company?.phone_number, email: data.company.email, logoUrl: new MultiFormatPicture(data.company?.company_logo).imageUrls ?.original, }; return documentCompany; }; export const downloadInvoiceQuotation = async function ({ id, quotationData, }: { id: string; quotationData: CurrentlyViewedInvoiceQuotation; }) { const fileName = `${snakeCase(quotationData.title)}_${quotationData.id}`; await store .dispatch('invoices_quotations/DOWNLOAD_INVOICE_QUOTATION', id) .then( ({ arrayBuffer, contentType, }: { arrayBuffer: ArrayBuffer; contentType: string; }) => useDownloadBinary(fileName, arrayBuffer, contentType) ); };
the_stack
import { Template } from '@aws-cdk/assertions'; import { testDeprecated } from '@aws-cdk/cdk-build-tools'; import { Lazy, Stack, Token } from '@aws-cdk/core'; import { AccountPrincipal, Anyone, AnyPrincipal, ArnPrincipal, CanonicalUserPrincipal, CompositePrincipal, Effect, FederatedPrincipal, IPrincipal, PolicyDocument, PolicyStatement, PrincipalPolicyFragment, ServicePrincipal, Role, } from '../lib'; describe('IAM policy document', () => { test('the Permission class is a programming model for iam', () => { const stack = new Stack(); const p = new PolicyStatement(); p.addActions('sqs:SendMessage'); p.addActions('dynamodb:CreateTable', 'dynamodb:DeleteTable'); p.addResources('myQueue'); p.addResources('yourQueue'); p.addAllResources(); p.addAwsAccountPrincipal(`my${Token.asString({ account: 'account' })}name`); p.addAccountCondition('12221121221'); expect(stack.resolve(p.toStatementJson())).toEqual({ Action: ['sqs:SendMessage', 'dynamodb:CreateTable', 'dynamodb:DeleteTable'], Resource: ['myQueue', 'yourQueue', '*'], Effect: 'Allow', Principal: { AWS: { 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':iam::my', { account: 'account' }, 'name:root']], }, }, Condition: { StringEquals: { 'sts:ExternalId': '12221121221' } }, }); }); test('the PolicyDocument class is a dom for iam policy documents', () => { const stack = new Stack(); const doc = new PolicyDocument(); const p1 = new PolicyStatement(); p1.addActions('sqs:SendMessage'); p1.addNotResources('arn:aws:sqs:us-east-1:123456789012:forbidden_queue'); const p2 = new PolicyStatement(); p2.effect = Effect.DENY; p2.addActions('cloudformation:CreateStack'); const p3 = new PolicyStatement(); p3.effect = Effect.ALLOW; p3.addNotActions('cloudformation:UpdateTerminationProtection'); const p4 = new PolicyStatement(); p4.effect = Effect.DENY; p4.addNotPrincipals(new CanonicalUserPrincipal('OnlyAuthorizedUser')); doc.addStatements(p1); doc.addStatements(p2); doc.addStatements(p3); doc.addStatements(p4); expect(stack.resolve(doc)).toEqual({ Version: '2012-10-17', Statement: [{ Effect: 'Allow', Action: 'sqs:SendMessage', NotResource: 'arn:aws:sqs:us-east-1:123456789012:forbidden_queue' }, { Effect: 'Deny', Action: 'cloudformation:CreateStack' }, { Effect: 'Allow', NotAction: 'cloudformation:UpdateTerminationProtection' }, { Effect: 'Deny', NotPrincipal: { CanonicalUser: 'OnlyAuthorizedUser' } }], }); }); test('Cannot combine Actions and NotActions', () => { expect(() => { new PolicyStatement({ actions: ['abc:def'], notActions: ['abc:def'], }); }).toThrow(/Cannot add 'NotActions' to policy statement if 'Actions' have been added/); }); test('Throws with invalid actions', () => { expect(() => { new PolicyStatement({ actions: ['service:action', '*', 'service:acti*', 'in:val:id'], }); }).toThrow(/Action 'in:val:id' is invalid/); }); test('Throws with invalid not actions', () => { expect(() => { new PolicyStatement({ notActions: ['service:action', '*', 'service:acti*', 'in:val:id'], }); }).toThrow(/Action 'in:val:id' is invalid/); }); // https://github.com/aws/aws-cdk/issues/13479 test('Does not validate unresolved tokens', () => { const stack = new Stack(); const perm = new PolicyStatement({ actions: [`${Lazy.string({ produce: () => 'sqs:sendMessage' })}`], }); expect(stack.resolve(perm.toStatementJson())).toEqual({ Effect: 'Allow', Action: 'sqs:sendMessage', }); }); test('Cannot combine Resources and NotResources', () => { expect(() => { new PolicyStatement({ resources: ['abc'], notResources: ['def'], }); }).toThrow(/Cannot add 'NotResources' to policy statement if 'Resources' have been added/); }); test('Cannot add NotPrincipals when Principals exist', () => { const stmt = new PolicyStatement({ principals: [new CanonicalUserPrincipal('abc')], }); expect(() => { stmt.addNotPrincipals(new CanonicalUserPrincipal('def')); }).toThrow(/Cannot add 'NotPrincipals' to policy statement if 'Principals' have been added/); }); test('Cannot add Principals when NotPrincipals exist', () => { const stmt = new PolicyStatement({ notPrincipals: [new CanonicalUserPrincipal('abc')], }); expect(() => { stmt.addPrincipals(new CanonicalUserPrincipal('def')); }).toThrow(/Cannot add 'Principals' to policy statement if 'NotPrincipals' have been added/); }); test('Permission allows specifying multiple actions upon construction', () => { const stack = new Stack(); const perm = new PolicyStatement(); perm.addResources('MyResource'); perm.addActions('Action1', 'Action2', 'Action3'); expect(stack.resolve(perm.toStatementJson())).toEqual({ Effect: 'Allow', Action: ['Action1', 'Action2', 'Action3'], Resource: 'MyResource', }); }); test('PolicyDoc resolves to undefined if there are no permissions', () => { const stack = new Stack(); const p = new PolicyDocument(); expect(stack.resolve(p)).toBeUndefined(); }); test('canonicalUserPrincipal adds a principal to a policy with the passed canonical user id', () => { const stack = new Stack(); const p = new PolicyStatement(); const canoncialUser = 'averysuperduperlongstringfor'; p.addPrincipals(new CanonicalUserPrincipal(canoncialUser)); expect(stack.resolve(p.toStatementJson())).toEqual({ Effect: 'Allow', Principal: { CanonicalUser: canoncialUser, }, }); }); test('addAccountRootPrincipal adds a principal with the current account root', () => { const stack = new Stack(); const p = new PolicyStatement(); p.addAccountRootPrincipal(); expect(stack.resolve(p.toStatementJson())).toEqual({ Effect: 'Allow', Principal: { AWS: { 'Fn::Join': [ '', [ 'arn:', { Ref: 'AWS::Partition' }, ':iam::', { Ref: 'AWS::AccountId' }, ':root', ], ], }, }, }); }); test('addFederatedPrincipal adds a Federated principal with the passed value', () => { const stack = new Stack(); const p = new PolicyStatement(); p.addFederatedPrincipal('com.amazon.cognito', { StringEquals: { key: 'value' } }); expect(stack.resolve(p.toStatementJson())).toEqual({ Effect: 'Allow', Principal: { Federated: 'com.amazon.cognito', }, Condition: { StringEquals: { key: 'value' }, }, }); }); test('addAwsAccountPrincipal can be used multiple times', () => { const stack = new Stack(); const p = new PolicyStatement(); p.addAwsAccountPrincipal('1234'); p.addAwsAccountPrincipal('5678'); expect(stack.resolve(p.toStatementJson())).toEqual({ Effect: 'Allow', Principal: { AWS: [ { 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':iam::1234:root']] }, { 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':iam::5678:root']] }, ], }, }); }); describe('hasResource', () => { test('false if there are no resources', () => { expect(new PolicyStatement().hasResource).toEqual(false); }); test('true if there is one resource', () => { expect(new PolicyStatement({ resources: ['one-resource'] }).hasResource).toEqual(true); }); test('true for multiple resources', () => { const p = new PolicyStatement(); p.addResources('r1'); p.addResources('r2'); expect(p.hasResource).toEqual(true); }); }); describe('hasPrincipal', () => { test('false if there is no principal', () => { expect(new PolicyStatement().hasPrincipal).toEqual(false); }); test('true if there is a principal', () => { const p = new PolicyStatement(); p.addArnPrincipal('bla'); expect(p.hasPrincipal).toEqual(true); }); test('true if there is a notPrincipal', () => { const p = new PolicyStatement(); p.addNotPrincipals(new CanonicalUserPrincipal('test')); expect(p.hasPrincipal).toEqual(true); }); }); test('statementCount returns the number of statement in the policy document', () => { const p = new PolicyDocument(); expect(p.statementCount).toEqual(0); p.addStatements(new PolicyStatement({ actions: ['service:action1'] })); expect(p.statementCount).toEqual(1); p.addStatements(new PolicyStatement({ actions: ['service:action2'] })); expect(p.statementCount).toEqual(2); }); describe('{ AWS: "*" } principal', () => { test('is represented as `Anyone`', () => { const stack = new Stack(); const p = new PolicyDocument(); p.addStatements(new PolicyStatement({ principals: [new Anyone()] })); expect(stack.resolve(p)).toEqual({ Statement: [ { Effect: 'Allow', Principal: { AWS: '*' } }, ], Version: '2012-10-17', }); }); test('is represented as `AnyPrincipal`', () => { const stack = new Stack(); const p = new PolicyDocument(); p.addStatements(new PolicyStatement({ principals: [new AnyPrincipal()] })); expect(stack.resolve(p)).toEqual({ Statement: [ { Effect: 'Allow', Principal: { AWS: '*' } }, ], Version: '2012-10-17', }); }); test('is represented as `addAnyPrincipal`', () => { const stack = new Stack(); const p = new PolicyDocument(); const s = new PolicyStatement(); s.addAnyPrincipal(); p.addStatements(s); expect(stack.resolve(p)).toEqual({ Statement: [ { Effect: 'Allow', Principal: { AWS: '*' } }, ], Version: '2012-10-17', }); }); }); test('addResources() will not break a list-encoded Token', () => { const stack = new Stack(); const statement = new PolicyStatement(); statement.addActions(...Lazy.list({ produce: () => ['a', 'b', 'c'] })); statement.addResources(...Lazy.list({ produce: () => ['x', 'y', 'z'] })); expect(stack.resolve(statement.toStatementJson())).toEqual({ Effect: 'Allow', Action: ['a', 'b', 'c'], Resource: ['x', 'y', 'z'], }); }); test('addResources()/addActions() will not add duplicates', () => { const stack = new Stack(); const statement = new PolicyStatement(); statement.addActions('a'); statement.addActions('a'); statement.addResources('x'); statement.addResources('x'); expect(stack.resolve(statement.toStatementJson())).toEqual({ Effect: 'Allow', Action: ['a'], Resource: ['x'], }); }); test('addNotResources()/addNotActions() will not add duplicates', () => { const stack = new Stack(); const statement = new PolicyStatement(); statement.addNotActions('a'); statement.addNotActions('a'); statement.addNotResources('x'); statement.addNotResources('x'); expect(stack.resolve(statement.toStatementJson())).toEqual({ Effect: 'Allow', NotAction: ['a'], NotResource: ['x'], }); }); test('addCanonicalUserPrincipal can be used to add cannonical user principals', () => { const stack = new Stack(); const p = new PolicyDocument(); const s1 = new PolicyStatement(); s1.addCanonicalUserPrincipal('cannonical-user-1'); const s2 = new PolicyStatement(); s2.addPrincipals(new CanonicalUserPrincipal('cannonical-user-2')); p.addStatements(s1); p.addStatements(s2); expect(stack.resolve(p)).toEqual({ Statement: [ { Effect: 'Allow', Principal: { CanonicalUser: 'cannonical-user-1' } }, { Effect: 'Allow', Principal: { CanonicalUser: 'cannonical-user-2' } }, ], Version: '2012-10-17', }); }); test('addPrincipal correctly merges array in', () => { const stack = new Stack(); const arrayPrincipal: IPrincipal = { get grantPrincipal() { return this; }, assumeRoleAction: 'sts:AssumeRole', policyFragment: new PrincipalPolicyFragment({ AWS: ['foo', 'bar'] }), addToPolicy() { return false; }, addToPrincipalPolicy() { return { statementAdded: false }; }, }; const s = new PolicyStatement(); s.addAccountRootPrincipal(); s.addPrincipals(arrayPrincipal); expect(stack.resolve(s.toStatementJson())).toEqual({ Effect: 'Allow', Principal: { AWS: [ { 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':iam::', { Ref: 'AWS::AccountId' }, ':root']] }, 'foo', 'bar', ], }, }); }); // https://github.com/aws/aws-cdk/issues/1201 test('policy statements with multiple principal types can be created using multiple addPrincipal calls', () => { const stack = new Stack(); const s = new PolicyStatement(); s.addArnPrincipal('349494949494'); s.addServicePrincipal('test.service'); s.addResources('resource'); s.addActions('action'); expect(stack.resolve(s.toStatementJson())).toEqual({ Action: 'action', Effect: 'Allow', Principal: { AWS: '349494949494', Service: 'test.service' }, Resource: 'resource', }); }); describe('Service principals', () => { test('regional service principals resolve appropriately', () => { const stack = new Stack(undefined, undefined, { env: { region: 'cn-north-1' } }); const s = new PolicyStatement(); s.addActions('test:Action'); s.addServicePrincipal('codedeploy.amazonaws.com'); expect(stack.resolve(s.toStatementJson())).toEqual({ Effect: 'Allow', Action: 'test:Action', Principal: { Service: 'codedeploy.cn-north-1.amazonaws.com.cn' }, }); }); // Deprecated: 'region' parameter to ServicePrincipal shouldn't be used. testDeprecated('regional service principals resolve appropriately (with user-set region)', () => { const stack = new Stack(undefined, undefined, { env: { region: 'cn-northeast-1' } }); const s = new PolicyStatement(); s.addActions('test:Action'); s.addServicePrincipal('codedeploy.amazonaws.com', { region: 'cn-north-1' }); expect(stack.resolve(s.toStatementJson())).toEqual({ Effect: 'Allow', Action: 'test:Action', Principal: { Service: 'codedeploy.cn-north-1.amazonaws.com.cn' }, }); }); test('obscure service principals resolve to the user-provided value', () => { const stack = new Stack(undefined, undefined, { env: { region: 'cn-north-1' } }); const s = new PolicyStatement(); s.addActions('test:Action'); s.addServicePrincipal('test.service-principal.dev'); expect(stack.resolve(s.toStatementJson())).toEqual({ Effect: 'Allow', Action: 'test:Action', Principal: { Service: 'test.service-principal.dev' }, }); }); }); describe('CompositePrincipal can be used to represent a principal that has multiple types', () => { test('with a single principal', () => { const stack = new Stack(); const p = new CompositePrincipal(new ArnPrincipal('i:am:an:arn')); const statement = new PolicyStatement(); statement.addPrincipals(p); expect(stack.resolve(statement.toStatementJson())).toEqual({ Effect: 'Allow', Principal: { AWS: 'i:am:an:arn' } }); }); test('conditions are allowed in an assumerolepolicydocument', () => { const stack = new Stack(); new Role(stack, 'Role', { assumedBy: new CompositePrincipal( new ArnPrincipal('i:am'), new FederatedPrincipal('federated', { StringEquals: { 'aws:some-key': 'some-value' } }), ), }); Template.fromStack(stack).hasResourceProperties('AWS::IAM::Role', { AssumeRolePolicyDocument: { Statement: [ { Action: 'sts:AssumeRole', Effect: 'Allow', Principal: { AWS: 'i:am' }, }, { Action: 'sts:AssumeRole', Condition: { StringEquals: { 'aws:some-key': 'some-value' }, }, Effect: 'Allow', Principal: { Federated: 'federated' }, }, ], }, }); }); test('conditions are not allowed when used in a single statement', () => { expect(() => { new PolicyStatement({ actions: ['s3:test'], principals: [new CompositePrincipal( new ArnPrincipal('i:am'), new FederatedPrincipal('federated', { StringEquals: { 'aws:some-key': 'some-value' } }))], }); }).toThrow(/Components of a CompositePrincipal must not have conditions/); }); test('principals and conditions are a big nice merge', () => { const stack = new Stack(); // add via ctor const p = new CompositePrincipal( new ArnPrincipal('i:am:an:arn'), new ServicePrincipal('amazon.com')); // add via `addPrincipals` (with condition) p.addPrincipals( new Anyone(), new ServicePrincipal('another.service'), ); const statement = new PolicyStatement(); statement.addPrincipals(p); // add via policy statement statement.addArnPrincipal('aws-principal-3'); statement.addCondition('cond2', { boom: '123' }); expect(stack.resolve(statement.toStatementJson())).toEqual({ Condition: { cond2: { boom: '123' }, }, Effect: 'Allow', Principal: { AWS: ['i:am:an:arn', '*', 'aws-principal-3'], Service: ['amazon.com', 'another.service'], }, }); }); test('can mix types of assumeRoleAction in a single composite', () => { const stack = new Stack(); // WHEN new Role(stack, 'Role', { assumedBy: new CompositePrincipal( new ArnPrincipal('arn'), new FederatedPrincipal('fed', {}, 'sts:Boom')), }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::IAM::Role', { AssumeRolePolicyDocument: { Statement: [ { Action: 'sts:AssumeRole', Effect: 'Allow', Principal: { AWS: 'arn' }, }, { Action: 'sts:Boom', Effect: 'Allow', Principal: { Federated: 'fed' }, }, ], }, }); }); }); describe('PrincipalWithConditions can be used to add a principal with conditions', () => { test('includes conditions from both the wrapped principal and the wrapper', () => { const stack = new Stack(); const principalOpts = { conditions: { BinaryEquals: { 'principal-key': 'SGV5LCBmcmllbmQh', }, }, }; const p = new ServicePrincipal('s3.amazonaws.com', principalOpts) .withConditions({ StringEquals: { 'wrapper-key': ['val-1', 'val-2'] } }); const statement = new PolicyStatement(); statement.addPrincipals(p); expect(stack.resolve(statement.toStatementJson())).toEqual({ Condition: { BinaryEquals: { 'principal-key': 'SGV5LCBmcmllbmQh' }, StringEquals: { 'wrapper-key': ['val-1', 'val-2'] }, }, Effect: 'Allow', Principal: { Service: 's3.amazonaws.com', }, }); }); test('conditions from addCondition are merged with those from the principal', () => { const stack = new Stack(); const p = new AccountPrincipal('012345678900').withConditions({ StringEquals: { key: 'val' } }); const statement = new PolicyStatement(); statement.addPrincipals(p); statement.addCondition('Null', { 'banned-key': 'true' }); expect(stack.resolve(statement.toStatementJson())).toEqual({ Effect: 'Allow', Principal: { AWS: { 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':iam::012345678900:root']] } }, Condition: { StringEquals: { key: 'val' }, Null: { 'banned-key': 'true' } }, }); }); test('adding conditions via `withConditions` does not affect the original principal', () => { const originalPrincipal = new ArnPrincipal('iam:an:arn'); const principalWithConditions = originalPrincipal.withConditions({ StringEquals: { key: 'val' } }); expect(originalPrincipal.policyFragment.conditions).toEqual({}); expect(principalWithConditions.policyFragment.conditions).toEqual({ StringEquals: { key: 'val' } }); }); test('conditions are merged when operators conflict', () => { const p = new FederatedPrincipal('fed', { OperatorOne: { 'fed-key': 'fed-val' }, OperatorTwo: { 'fed-key': 'fed-val' }, OperatorThree: { 'fed-key': 'fed-val' }, }).withConditions({ OperatorTwo: { 'with-key': 'with-val' }, OperatorThree: { 'with-key': 'with-val' }, }); const statement = new PolicyStatement(); statement.addCondition('OperatorThree', { 'add-key': 'add-val' }); statement.addPrincipals(p); expect(statement.toStatementJson()).toEqual({ Effect: 'Allow', Principal: { Federated: 'fed' }, Condition: { OperatorOne: { 'fed-key': 'fed-val' }, OperatorTwo: { 'fed-key': 'fed-val', 'with-key': 'with-val' }, OperatorThree: { 'fed-key': 'fed-val', 'with-key': 'with-val', 'add-key': 'add-val' }, }, }); }); test('tokens can be used in conditions', () => { // GIVEN const stack = new Stack(); const statement = new PolicyStatement(); // WHEN const p = new ArnPrincipal('arn:of:principal').withConditions({ StringEquals: Lazy.any({ produce: () => ({ goo: 'zar' }) }), }); statement.addPrincipals(p); // THEN const resolved = stack.resolve(statement.toStatementJson()); expect(resolved).toEqual({ Condition: { StringEquals: { goo: 'zar', }, }, Effect: 'Allow', Principal: { AWS: 'arn:of:principal', }, }); }); test('conditions cannot be merged if they include tokens', () => { const p = new FederatedPrincipal('fed', { StringEquals: { foo: 'bar' }, }).withConditions({ StringEquals: Lazy.any({ produce: () => ({ goo: 'zar' }) }), }); const statement = new PolicyStatement(); expect(() => statement.addPrincipals(p)).toThrow(/multiple "StringEquals" conditions cannot be merged if one of them contains an unresolved token/); }); test('values passed to `withConditions` overwrite values from the wrapped principal ' + 'when keys conflict within an operator', () => { const p = new FederatedPrincipal('fed', { Operator: { key: 'p-val' }, }).withConditions({ Operator: { key: 'with-val' }, }); const statement = new PolicyStatement(); statement.addPrincipals(p); expect(statement.toStatementJson()).toEqual({ Effect: 'Allow', Principal: { Federated: 'fed' }, Condition: { Operator: { key: 'with-val' }, }, }); }); }); describe('duplicate statements', () => { test('without tokens', () => { // GIVEN const stack = new Stack(); const p = new PolicyDocument(); const statement = new PolicyStatement(); statement.addResources('resource1', 'resource2'); statement.addActions('action1', 'action2'); statement.addServicePrincipal('service'); statement.addConditions({ a: { b: 'c', }, d: { e: 'f', }, }); // WHEN p.addStatements(statement); p.addStatements(statement); p.addStatements(statement); // THEN expect(stack.resolve(p).Statement).toHaveLength(1); }); test('with tokens', () => { // GIVEN const stack = new Stack(); const p = new PolicyDocument(); const statement1 = new PolicyStatement(); statement1.addResources(Lazy.string({ produce: () => 'resource' })); statement1.addActions(Lazy.string({ produce: () => 'action' })); const statement2 = new PolicyStatement(); statement2.addResources(Lazy.string({ produce: () => 'resource' })); statement2.addActions(Lazy.string({ produce: () => 'action' })); // WHEN p.addStatements(statement1); p.addStatements(statement2); // THEN expect(stack.resolve(p).Statement).toHaveLength(1); }); }); test('autoAssignSids enables auto-assignment of a unique SID for each statement', () => { // GIVEN const doc = new PolicyDocument({ assignSids: true, }); // WHEN doc.addStatements(new PolicyStatement({ actions: ['service:action1'], resources: ['resource1'] })); doc.addStatements(new PolicyStatement({ actions: ['service:action1'], resources: ['resource1'] })); doc.addStatements(new PolicyStatement({ actions: ['service:action1'], resources: ['resource1'] })); doc.addStatements(new PolicyStatement({ actions: ['service:action1'], resources: ['resource1'] })); doc.addStatements(new PolicyStatement({ actions: ['service:action2'], resources: ['resource2'] })); // THEN const stack = new Stack(); expect(stack.resolve(doc)).toEqual({ Version: '2012-10-17', Statement: [ { Action: 'service:action1', Effect: 'Allow', Resource: 'resource1', Sid: '0' }, { Action: 'service:action2', Effect: 'Allow', Resource: 'resource2', Sid: '1' }, ], }); }); test('constructor args are equivalent to mutating in-place', () => { const stack = new Stack(); const s = new PolicyStatement(); s.addActions('service:action1', 'service:action2'); s.addAllResources(); s.addArnPrincipal('arn'); s.addCondition('key', { equals: 'value' }); const doc1 = new PolicyDocument(); doc1.addStatements(s); const doc2 = new PolicyDocument(); doc2.addStatements(new PolicyStatement({ actions: ['service:action1', 'service:action2'], resources: ['*'], principals: [new ArnPrincipal('arn')], conditions: { key: { equals: 'value' }, }, })); expect(stack.resolve(doc1)).toEqual(stack.resolve(doc2)); }); describe('fromJson', () => { test("throws error when Statement isn't an array", () => { expect(() => { PolicyDocument.fromJson({ Statement: 'asdf', }); }).toThrow(/Statement must be an array/); }); }); test('adding another condition with the same operator does not delete the original', () => { const stack = new Stack(); const p = new PolicyStatement(); p.addCondition('StringEquals', { 'kms:ViaService': 'service' }); p.addAccountCondition('12221121221'); expect(stack.resolve(p.toStatementJson())).toEqual({ Effect: 'Allow', Condition: { StringEquals: { 'kms:ViaService': 'service', 'sts:ExternalId': '12221121221' } }, }); }); test('validation error if policy statement has no actions', () => { const policyStatement = new PolicyStatement({ principals: [new AnyPrincipal()], }); // THEN const validationErrorsForResourcePolicy: string[] = policyStatement.validateForResourcePolicy(); // const validationErrorsForIdentityPolicy: string[] = policyStatement.validateForIdentityPolicy(); expect(validationErrorsForResourcePolicy).toEqual(['A PolicyStatement must specify at least one \'action\' or \'notAction\'.']); }); test('validation error if policy statement for resource-based policy has no principals specified', () => { const policyStatement = new PolicyStatement({ actions: ['*'], }); // THEN const validationErrors: string[] = policyStatement.validateForResourcePolicy(); expect(validationErrors).toEqual(['A PolicyStatement used in a resource-based policy must specify at least one IAM principal.']); }); });
the_stack
import { delay, IMap, RGB } from "./common"; import { KMeans, Vector } from "./lib/clustering"; import { hslToRgb, lab2rgb, rgb2lab, rgbToHsl } from "./lib/colorconversion"; import { ClusteringColorSpace, Settings } from "./settings"; import { Uint8Array2D } from "./structs/typedarrays"; import { Random } from "./random"; export class ColorMapResult { public imgColorIndices!: Uint8Array2D; public colorsByIndex!: RGB[]; public width!: number; public height!: number; } export class ColorReducer { /** * Creates a map of the various colors used */ public static createColorMap(kmeansImgData: ImageData) { const imgColorIndices = new Uint8Array2D(kmeansImgData.width, kmeansImgData.height); let colorIndex = 0; const colors: IMap<number> = {}; const colorsByIndex: RGB[] = []; let idx = 0; for (let j: number = 0; j < kmeansImgData.height; j++) { for (let i: number = 0; i < kmeansImgData.width; i++) { const r = kmeansImgData.data[idx++]; const g = kmeansImgData.data[idx++]; const b = kmeansImgData.data[idx++]; const a = kmeansImgData.data[idx++]; let currentColorIndex; const color = r + "," + g + "," + b; if (typeof colors[color] === "undefined") { currentColorIndex = colorIndex; colors[color] = colorIndex; colorsByIndex.push([r, g, b]); colorIndex++; } else { currentColorIndex = colors[color]; } imgColorIndices.set(i, j, currentColorIndex); } } const result = new ColorMapResult(); result.imgColorIndices = imgColorIndices; result.colorsByIndex = colorsByIndex; result.width = kmeansImgData.width; result.height = kmeansImgData.height; return result; } /** * Applies K-means clustering on the imgData to reduce the colors to * k clusters and then output the result to the given outputImgData */ public static async applyKMeansClustering(imgData: ImageData, outputImgData: ImageData, ctx: CanvasRenderingContext2D, settings: Settings, onUpdate: ((kmeans: KMeans) => void) | null = null) { const vectors: Vector[] = []; let idx = 0; let vIdx = 0; const bitsToChopOff = 2; // r,g,b gets rounded to every 4 values, 0,4,8,... // group by color, add points as 1D index to prevent Point object allocation const pointsByColor: IMap<number[]> = {}; for (let j: number = 0; j < imgData.height; j++) { for (let i: number = 0; i < imgData.width; i++) { let r = imgData.data[idx++]; let g = imgData.data[idx++]; let b = imgData.data[idx++]; const a = imgData.data[idx++]; // small performance boost: reduce bitness of colors by chopping off the last bits // this will group more colors with only slight variation in color together, reducing the size of the points r = r >> bitsToChopOff << bitsToChopOff; g = g >> bitsToChopOff << bitsToChopOff; b = b >> bitsToChopOff << bitsToChopOff; const color = `${r},${g},${b}`; if (!(color in pointsByColor)) { pointsByColor[color] = [j * imgData.width + i]; } else { pointsByColor[color].push(j * imgData.width + i); } } } for (const color of Object.keys(pointsByColor)) { const rgb: number[] = color.split(",").map((v) => parseInt(v)); // determine vector data based on color space conversion let data: number[]; if (settings.kMeansClusteringColorSpace === ClusteringColorSpace.RGB) { data = rgb; } else if (settings.kMeansClusteringColorSpace === ClusteringColorSpace.HSL) { data = rgbToHsl(rgb[0], rgb[1], rgb[2]); } else if (settings.kMeansClusteringColorSpace === ClusteringColorSpace.LAB) { data = rgb2lab(rgb); } else { data = rgb; } // determine the weight (#pointsOfColor / #totalpoints) of each color const weight = pointsByColor[color].length / (imgData.width * imgData.height); const vec = new Vector(data, weight); vec.tag = rgb; vectors[vIdx++] = vec; } const random = new Random(settings.randomSeed === 0 ? new Date().getTime() : settings.randomSeed); // vectors of all the unique colors are built, time to cluster them const kmeans = new KMeans(vectors, settings.kMeansNrOfClusters, random); let curTime = new Date().getTime(); kmeans.step(); while (kmeans.currentDeltaDistanceDifference > settings.kMeansMinDeltaDifference) { kmeans.step(); // update GUI every 500ms if (new Date().getTime() - curTime > 500) { curTime = new Date().getTime(); await delay(0); if (onUpdate != null) { ColorReducer.updateKmeansOutputImageData(kmeans, settings, pointsByColor, imgData, outputImgData, false); onUpdate(kmeans); } } } // update the output image data (because it will be used for further processing) ColorReducer.updateKmeansOutputImageData(kmeans, settings, pointsByColor, imgData, outputImgData, true); if (onUpdate != null) { onUpdate(kmeans); } } /** * Updates the image data from the current kmeans centroids and their respective associated colors (vectors) */ public static updateKmeansOutputImageData(kmeans: KMeans, settings: Settings, pointsByColor: IMap<number[]>, imgData: ImageData, outputImgData: ImageData, restrictToSpecifiedColors: boolean) { for (let c: number = 0; c < kmeans.centroids.length; c++) { // for each cluster centroid const centroid = kmeans.centroids[c]; // points per category are the different unique colors belonging to that cluster for (const v of kmeans.pointsPerCategory[c]) { // determine the rgb color value of the cluster centroid let rgb: number[]; if (settings.kMeansClusteringColorSpace === ClusteringColorSpace.RGB) { rgb = centroid.values; } else if (settings.kMeansClusteringColorSpace === ClusteringColorSpace.HSL) { const hsl = centroid.values; rgb = hslToRgb(hsl[0], hsl[1], hsl[2]); } else if (settings.kMeansClusteringColorSpace === ClusteringColorSpace.LAB) { const lab = centroid.values; rgb = lab2rgb(lab); } else { rgb = centroid.values; } // remove decimals rgb = rgb.map(v => Math.floor(v)); if (restrictToSpecifiedColors) { if (settings.kMeansColorRestrictions.length > 0) { // there are color restrictions, for each centroid find the color from the color restrictions that's the closest let minDistance = Number.MAX_VALUE; let closestRestrictedColor: RGB | string | null = null; for (const color of settings.kMeansColorRestrictions) { // RGB distance is not very good for the human eye perception, convert both to lab and then calculate the distance const centroidLab = rgb2lab(rgb); let restrictionLab: number[]; if (typeof color === "string") { restrictionLab = rgb2lab(settings.colorAliases[color]); } else { restrictionLab = rgb2lab(color); } const distance = Math.sqrt((centroidLab[0] - restrictionLab[0]) * (centroidLab[0] - restrictionLab[0]) + (centroidLab[1] - restrictionLab[1]) * (centroidLab[1] - restrictionLab[1]) + (centroidLab[2] - restrictionLab[2]) * (centroidLab[2] - restrictionLab[2])); if (distance < minDistance) { minDistance = distance; closestRestrictedColor = color; } } // use this color instead if (closestRestrictedColor !== null) { if (typeof closestRestrictedColor === "string") { rgb = settings.colorAliases[closestRestrictedColor]; } else { rgb = closestRestrictedColor; } } } } let pointRGB: number[] = v.tag; // replace all pixels of the old color by the new centroid color const pointColor = `${Math.floor(pointRGB[0])},${Math.floor(pointRGB[1])},${Math.floor(pointRGB[2])}`; for (const pt of pointsByColor[pointColor]) { const ptx = pt % imgData.width; const pty = Math.floor(pt / imgData.width); let dataOffset = (pty * imgData.width + ptx) * 4; outputImgData.data[dataOffset++] = rgb[0]; outputImgData.data[dataOffset++] = rgb[1]; outputImgData.data[dataOffset++] = rgb[2]; } } } } /** * Builds a distance matrix for each color to each other */ public static buildColorDistanceMatrix(colorsByIndex: RGB[]) { const colorDistances: number[][] = new Array(colorsByIndex.length); for (let j: number = 0; j < colorsByIndex.length; j++) { colorDistances[j] = new Array(colorDistances.length); } for (let j: number = 0; j < colorsByIndex.length; j++) { for (let i: number = j; i < colorsByIndex.length; i++) { const c1 = colorsByIndex[j]; const c2 = colorsByIndex[i]; const distance = Math.sqrt((c1[0] - c2[0]) * (c1[0] - c2[0]) + (c1[1] - c2[1]) * (c1[1] - c2[1]) + (c1[2] - c2[2]) * (c1[2] - c2[2])); colorDistances[i][j] = distance; colorDistances[j][i] = distance; } } return colorDistances; } public static async processNarrowPixelStripCleanup(colormapResult: ColorMapResult) { // build the color distance matrix, which describes the distance of each color to each other const colorDistances: number[][] = ColorReducer.buildColorDistanceMatrix(colormapResult.colorsByIndex); let count = 0; const imgColorIndices = colormapResult.imgColorIndices; for (let j: number = 1; j < colormapResult.height - 1; j++) { for (let i: number = 1; i < colormapResult.width - 1; i++) { const top = imgColorIndices.get(i, j - 1); const bottom = imgColorIndices.get(i, j + 1); const left = imgColorIndices.get(i - 1, j); const right = imgColorIndices.get(i + 1, j); const cur = imgColorIndices.get(i, j); if (cur !== top && cur !== bottom && cur !== left && cur !== right) { // single pixel } else if (cur !== top && cur !== bottom) { // check the color distance whether the top or bottom color is closer const topColorDistance = colorDistances[cur][top]; const bottomColorDistance = colorDistances[cur][bottom]; imgColorIndices.set(i, j, topColorDistance < bottomColorDistance ? top : bottom); count++; } else if (cur !== left && cur !== right) { // check the color distance whether the top or bottom color is closer const leftColorDistance = colorDistances[cur][left]; const rightColorDistance = colorDistances[cur][right]; imgColorIndices.set(i, j, leftColorDistance < rightColorDistance ? left : right); count++; } } } console.log(count + " pixels replaced to remove narrow pixel strips"); } }
the_stack
import $1 from "react"; import { HostComponent } from "../Renderer/shims/ReactNativeTypes"; import { PressEvent } from "../Types/CoreEventTypes"; import { ScrollEvent } from "../Types/CoreEventTypes"; import { EventSubscription } from "../vendor/emitter/EventEmitter"; import { KeyboardEvent } from "./Keyboard/Keyboard"; declare type State = /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { isTouching: boolean; lastMomentumScrollBeginTime: number; lastMomentumScrollEndTime: number; observedScrollSinceBecomingResponder: boolean; becameResponderWhileAnimating: boolean; }; declare var ScrollResponderMixin: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { _subscriptionKeyboardWillShow?: null | undefined | EventSubscription; _subscriptionKeyboardWillHide?: null | undefined | EventSubscription; _subscriptionKeyboardDidShow?: null | undefined | EventSubscription; _subscriptionKeyboardDidHide?: null | undefined | EventSubscription; scrollResponderMixinGetInitialState: () => State; /** * Invoke this from an `onScroll` event. */ scrollResponderHandleScrollShouldSetResponder: () => boolean; /** * Merely touch starting is not sufficient for a scroll view to become the * responder. Being the "responder" means that the very next touch move/end * event will result in an action/movement. * * Invoke this from an `onStartShouldSetResponder` event. * * `onStartShouldSetResponder` is used when the next move/end will trigger * some UI movement/action, but when you want to yield priority to views * nested inside of the view. * * There may be some cases where scroll views actually should return `true` * from `onStartShouldSetResponder`: Any time we are detecting a standard tap * that gives priority to nested views. * * - If a single tap on the scroll view triggers an action such as * recentering a map style view yet wants to give priority to interaction * views inside (such as dropped pins or labels), then we would return true * from this method when there is a single touch. * * - Similar to the previous case, if a two finger "tap" should trigger a * zoom, we would check the `touches` count, and if `>= 2`, we would return * true. * */ scrollResponderHandleStartShouldSetResponder: (e: PressEvent) => boolean; /** * There are times when the scroll view wants to become the responder * (meaning respond to the next immediate `touchStart/touchEnd`), in a way * that *doesn't* give priority to nested views (hence the capture phase): * * - Currently animating. * - Tapping anywhere that is not a text input, while the keyboard is * up (which should dismiss the keyboard). * * Invoke this from an `onStartShouldSetResponderCapture` event. */ scrollResponderHandleStartShouldSetResponderCapture: (e: PressEvent) => boolean; /** * Do we consider there to be a dismissible soft-keyboard open? */ scrollResponderKeyboardIsDismissible: () => boolean; /** * Invoke this from an `onResponderReject` event. * * Some other element is not yielding its role as responder. Normally, we'd * just disable the `UIScrollView`, but a touch has already began on it, the * `UIScrollView` will not accept being disabled after that. The easiest * solution for now is to accept the limitation of disallowing this * altogether. To improve this, find a way to disable the `UIScrollView` after * a touch has already started. */ scrollResponderHandleResponderReject: () => void; /** * We will allow the scroll view to give up its lock iff it acquired the lock * during an animation. This is a very useful default that happens to satisfy * many common user experiences. * * - Stop a scroll on the left edge, then turn that into an outer view's * backswipe. * - Stop a scroll mid-bounce at the top, continue pulling to have the outer * view dismiss. * - However, without catching the scroll view mid-bounce (while it is * motionless), if you drag far enough for the scroll view to become * responder (and therefore drag the scroll view a bit), any backswipe * navigation of a swipe gesture higher in the view hierarchy, should be * rejected. */ scrollResponderHandleTerminationRequest: () => boolean; /** * Invoke this from an `onTouchEnd` event. * * @param {PressEvent} e Event. */ scrollResponderHandleTouchEnd: (e: PressEvent) => void; /** * Invoke this from an `onTouchCancel` event. * * @param {PressEvent} e Event. */ scrollResponderHandleTouchCancel: (e: PressEvent) => void; /** * Invoke this from an `onResponderRelease` event. */ scrollResponderHandleResponderRelease: (e: PressEvent) => void; scrollResponderHandleScroll: (e: ScrollEvent) => void; /** * Invoke this from an `onResponderGrant` event. */ scrollResponderHandleResponderGrant: (e: ScrollEvent) => void; /** * Unfortunately, `onScrollBeginDrag` also fires when *stopping* the scroll * animation, and there's not an easy way to distinguish a drag vs. stopping * momentum. * * Invoke this from an `onScrollBeginDrag` event. */ scrollResponderHandleScrollBeginDrag: (e: ScrollEvent) => void; /** * Invoke this from an `onScrollEndDrag` event. */ scrollResponderHandleScrollEndDrag: (e: ScrollEvent) => void; /** * Invoke this from an `onMomentumScrollBegin` event. */ scrollResponderHandleMomentumScrollBegin: (e: ScrollEvent) => void; /** * Invoke this from an `onMomentumScrollEnd` event. */ scrollResponderHandleMomentumScrollEnd: (e: ScrollEvent) => void; /** * Invoke this from an `onTouchStart` event. * * Since we know that the `SimpleEventPlugin` occurs later in the plugin * order, after `ResponderEventPlugin`, we can detect that we were *not* * permitted to be the responder (presumably because a contained view became * responder). The `onResponderReject` won't fire in that case - it only * fires when a *current* responder rejects our request. * * @param {PressEvent} e Touch Start event. */ scrollResponderHandleTouchStart: (e: PressEvent) => void; /** * Invoke this from an `onTouchMove` event. * * Since we know that the `SimpleEventPlugin` occurs later in the plugin * order, after `ResponderEventPlugin`, we can detect that we were *not* * permitted to be the responder (presumably because a contained view became * responder). The `onResponderReject` won't fire in that case - it only * fires when a *current* responder rejects our request. * * @param {PressEvent} e Touch Start event. */ scrollResponderHandleTouchMove: (e: PressEvent) => void; /** * A helper function for this class that lets us quickly determine if the * view is currently animating. This is particularly useful to know when * a touch has just started or ended. */ scrollResponderIsAnimating: () => boolean; /** * Returns the node that represents native view that can be scrolled. * Components can pass what node to use by defining a `getScrollableNode` * function otherwise `this` is used. */ scrollResponderGetScrollableNode: () => null | undefined | number; /** * A helper function to scroll to a specific point in the ScrollView. * This is currently used to help focus child TextViews, but can also * be used to quickly scroll to any element we want to focus. Syntax: * * `scrollResponderScrollTo(options: {x: number = 0; y: number = 0; animated: boolean = true})` * * Note: The weird argument signature is due to the fact that, for historical reasons, * the function also accepts separate arguments as as alternative to the options object. * This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED. */ scrollResponderScrollTo: (x?: number | { x?: number; y?: number; animated?: boolean; }, y?: number, animated?: boolean) => void; /** * Scrolls to the end of the ScrollView, either immediately or with a smooth * animation. * * Example: * * `scrollResponderScrollToEnd({animated: true})` */ scrollResponderScrollToEnd: (options?: { animated?: boolean; }) => void; /** * A helper function to zoom to a specific rect in the scrollview. The argument has the shape * {x: number; y: number; width: number; height: number; animated: boolean = true} * * @platform ios */ scrollResponderZoomTo: (rect: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { x: number; y: number; width: number; height: number; animated?: boolean; }, animated?: boolean) => // deprecated, put this inside the rect argument instead void; /** * Displays the scroll indicators momentarily. */ scrollResponderFlashScrollIndicators: () => void; /** * This method should be used as the callback to onFocus in a TextInputs' * parent view. Note that any module using this mixin needs to return * the parent view's ref in getScrollViewRef() in order to use this method. * @param {number} nodeHandle The TextInput node handle * @param {number} additionalOffset The scroll view's bottom "contentInset". * Default is 0. * @param {bool} preventNegativeScrolling Whether to allow pulling the content * down to make it meet the keyboard's top. Default is false. */ scrollResponderScrollNativeHandleToKeyboard: <T>(nodeHandle: number | $1.ElementRef<HostComponent<T>>, additionalOffset?: number, preventNegativeScrollOffset?: boolean) => void; /** * The calculations performed here assume the scroll view takes up the entire * screen - even if has some content inset. We then measure the offsets of the * keyboard, and compensate both for the scroll view's "contentInset". * * @param {number} left Position of input w.r.t. table view. * @param {number} top Position of input w.r.t. table view. * @param {number} width Width of the text input. * @param {number} height Height of the text input. */ scrollResponderInputMeasureAndScrollToKeyboard: (left: number, top: number, width: number, height: number) => void; scrollResponderTextInputFocusError: (msg: string) => void; /** * `componentWillMount` is the closest thing to a standard "constructor" for * React components. * * The `keyboardWillShow` is called before input focus. */ UNSAFE_componentWillMount: () => void; componentWillUnmount: () => void; /** * Warning, this may be called several times for a single keyboard opening. * It's best to store the information in this method and then take any action * at a later point (either in `keyboardDidShow` or other). * * Here's the order that events occur in: * - focus * - willShow {startCoordinates, endCoordinates} several times * - didShow several times * - blur * - willHide {startCoordinates, endCoordinates} several times * - didHide several times * * The `ScrollResponder` module callbacks for each of these events. * Even though any user could have easily listened to keyboard events * themselves, using these `props` callbacks ensures that ordering of events * is consistent - and not dependent on the order that the keyboard events are * subscribed to. This matters when telling the scroll view to scroll to where * the keyboard is headed - the scroll responder better have been notified of * the keyboard destination before being instructed to scroll to where the * keyboard will be. Stick to the `ScrollResponder` callbacks, and everything * will work. * * WARNING: These callbacks will fire even if a keyboard is displayed in a * different navigation pane. Filter out the events to determine if they are * relevant to you. (For example, only if you receive these callbacks after * you had explicitly focused a node etc). */ scrollResponderKeyboardWillShow: (e: KeyboardEvent) => void; scrollResponderKeyboardWillHide: (e: KeyboardEvent) => void; scrollResponderKeyboardDidShow: (e: KeyboardEvent) => void; scrollResponderKeyboardDidHide: (e: KeyboardEvent) => void; }; declare var ScrollResponder: /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { Mixin: typeof ScrollResponderMixin; }; export type { State }; declare const $f2tExportDefault: typeof ScrollResponder; export default $f2tExportDefault;
the_stack
'use strict'; import 'jest-localstorage-mock'; import { render, unmountComponentAtNode } from 'react-dom'; import React, { createRef, forwardRef, useImperativeHandle } from 'react'; import { act } from 'react-dom/test-utils'; import { WalletProvider, WalletProviderProps } from '../WalletProvider'; import { Adapter, BaseWalletAdapter, WalletError, WalletName, WalletNotReadyError, WalletReadyState, } from '@solana/wallet-adapter-base'; import { PublicKey } from '@solana/web3.js'; import { useWallet, WalletContextState } from '../useWallet'; type TestRefType = { getWalletContextState(): WalletContextState; }; const TestComponent = forwardRef(function TestComponentImpl(props, ref) { const wallet = useWallet(); useImperativeHandle( ref, () => ({ getWalletContextState() { return wallet; }, }), [wallet] ); return null; }); describe('WalletProvider', () => { let container: HTMLDivElement | null; let ref: React.RefObject<TestRefType>; let fooWalletAdapter: MockWalletAdapter; let barWalletAdapter: MockWalletAdapter; let bazWalletAdapter: MockWalletAdapter; let adapters: Adapter[]; function renderTest(props: Omit<WalletProviderProps, 'children' | 'wallets'>) { act(() => { render( <WalletProvider {...props} wallets={adapters}> <TestComponent ref={ref} /> </WalletProvider>, container ); }); } abstract class MockWalletAdapter extends BaseWalletAdapter { connectionPromise: null | Promise<void> = null; disconnectionPromise: null | Promise<void> = null; connectedValue = false; get connected() { return this.connectedValue; } readyStateValue: WalletReadyState = WalletReadyState.Installed; get readyState() { return this.readyStateValue; } connecting = false; connect = jest.fn(async () => { this.connecting = true; if (this.connectionPromise) { await this.connectionPromise; } this.connecting = false; this.connectedValue = true; this.emit('connect', this.publicKey!); }); disconnect = jest.fn(async () => { this.connecting = false; if (this.disconnectionPromise) { await this.disconnectionPromise; } this.connectedValue = false; this.emit('disconnect'); }); sendTransaction = jest.fn(); } class FooWalletAdapter extends MockWalletAdapter { name = 'FooWallet' as WalletName; url = 'https://foowallet.com'; icon = 'foo.png'; publicKey = new PublicKey('Foo11111111111111111111111111111111111111111'); } class BarWalletAdapter extends MockWalletAdapter { name = 'BarWallet' as WalletName; url = 'https://barwallet.com'; icon = 'bar.png'; publicKey = new PublicKey('Bar11111111111111111111111111111111111111111'); } class BazWalletAdapter extends MockWalletAdapter { name = 'BazWallet' as WalletName; url = 'https://bazwallet.com'; icon = 'baz.png'; publicKey = new PublicKey('Baz11111111111111111111111111111111111111111'); } beforeEach(() => { localStorage.clear(); jest.resetAllMocks(); container = document.createElement('div'); document.body.appendChild(container); ref = createRef(); fooWalletAdapter = new FooWalletAdapter(); barWalletAdapter = new BarWalletAdapter(); bazWalletAdapter = new BazWalletAdapter(); adapters = [fooWalletAdapter, barWalletAdapter, bazWalletAdapter]; }); afterEach(() => { if (container) { unmountComponentAtNode(container); container.remove(); container = null; } }); describe('given a selected wallet', () => { beforeEach(async () => { fooWalletAdapter.readyStateValue = WalletReadyState.NotDetected; renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); expect(ref.current?.getWalletContextState().wallet?.readyState).toBe(WalletReadyState.NotDetected); }); describe('that then becomes ready', () => { beforeEach(() => { act(() => { fooWalletAdapter.readyStateValue = WalletReadyState.Installed; fooWalletAdapter.emit('readyStateChange', WalletReadyState.Installed); }); }); it('sets `ready` to true', () => { expect(ref.current?.getWalletContextState().wallet?.readyState).toBe(WalletReadyState.Installed); }); }); describe('when the wallet disconnects of its own accord', () => { beforeEach(() => { act(() => { fooWalletAdapter.disconnect(); }); }); it('should clear the stored wallet name', () => { expect(localStorage.removeItem).toHaveBeenCalled(); }); it('updates state tracking variables appropriately', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ wallet: null, connected: false, connecting: false, publicKey: null, }); }); }); describe('when the wallet disconnects as a consequence of the window unloading', () => { beforeEach(() => { act(() => { window.dispatchEvent(new Event('beforeunload')); fooWalletAdapter.disconnect(); }); }); it('should not clear the stored wallet name', () => { expect(localStorage.removeItem).not.toHaveBeenCalled(); }); }); }); describe('when there exists no stored wallet name', () => { beforeEach(() => { (localStorage.getItem as jest.Mock).mockReturnValue(null); }); it('loads no wallet into state', () => { renderTest({}); expect(ref.current?.getWalletContextState().wallet).toBeNull(); }); it('loads no public key into state', () => { renderTest({}); expect(ref.current?.getWalletContextState().publicKey).toBeNull(); }); }); describe('when there exists a stored wallet name', () => { beforeEach(() => { (localStorage.getItem as jest.Mock).mockReturnValue(JSON.stringify('FooWallet')); }); it('loads the corresponding adapter into state', () => { renderTest({}); expect(ref.current?.getWalletContextState().wallet?.adapter).toBeInstanceOf(FooWalletAdapter); }); it('loads the corresponding public key into state', () => { renderTest({}); expect(ref.current?.getWalletContextState().publicKey).toBe(fooWalletAdapter.publicKey); }); it('sets state tracking variables to defaults', () => { renderTest({}); expect(ref.current?.getWalletContextState()).toMatchObject({ connected: false, connecting: false, }); }); describe('and auto connect is disabled', () => { const props = { autoConnect: false }; beforeEach(() => { renderTest(props); }); it('`autoConnect` is `false` on state', () => { expect(ref.current?.getWalletContextState().autoConnect).toBe(false); }); it('does not call `connect` on the adapter', () => { expect(fooWalletAdapter.connect).not.toHaveBeenCalled(); }); }); describe('and auto connect is enabled', () => { const props = { autoConnect: true }; beforeEach(() => { fooWalletAdapter.readyStateValue = WalletReadyState.NotDetected; renderTest(props); }); it('`autoConnect` is `true` on state', () => { expect(ref.current?.getWalletContextState().autoConnect).toBe(true); }); describe('before the adapter is ready', () => { it('does not call `connect` on the adapter', () => { expect(fooWalletAdapter.connect).not.toHaveBeenCalled(); }); describe('once the adapter becomes ready', () => { beforeEach(async () => { await act(async () => { fooWalletAdapter.readyStateValue = WalletReadyState.Installed; fooWalletAdapter.emit('readyStateChange', WalletReadyState.Installed); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); it('calls `connect` on the adapter', () => { expect(fooWalletAdapter.connect).toHaveBeenCalledTimes(1); }); }); }); }); }); describe('custom error handler', () => { const errorToEmit = new WalletError(); let handleError: (error: WalletError) => void; beforeEach(async () => { handleError = jest.fn(); renderTest({ onError: handleError }); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); it('gets called in response to adapter errors', () => { act(() => { fooWalletAdapter.emit('error', errorToEmit); }); expect(handleError).toBeCalledWith(errorToEmit); }); it('does not get called if the window is unloading', () => { const errorToEmit = new WalletError(); act(() => { window.dispatchEvent(new Event('beforeunload')); fooWalletAdapter.emit('error', errorToEmit); }); expect(handleError).not.toBeCalled(); }); }); describe('connect()', () => { describe('given a wallet that is not ready', () => { beforeEach(async () => { window.open = jest.fn(); fooWalletAdapter.readyStateValue = WalletReadyState.NotDetected; renderTest({}); act(() => { ref.current?.getWalletContextState().select('FooWallet' as WalletName); }); expect(ref.current?.getWalletContextState().wallet?.readyState).toBe(WalletReadyState.NotDetected); act(() => { expect(ref.current?.getWalletContextState().connect).rejects.toThrow(); }); }); it('clears out the state', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ wallet: null, connected: false, connecting: false, publicKey: null, }); }); it("opens the wallet's URL in a new window", () => { expect(window.open).toBeCalledWith('https://foowallet.com', '_blank'); }); it('throws a `WalletNotReady` error', () => { act(() => { expect(ref.current?.getWalletContextState().connect()).rejects.toThrow(new WalletNotReadyError()); }); }); }); describe('given a wallet that is ready', () => { let commitConnection: () => void; beforeEach(async () => { renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); fooWalletAdapter.connectionPromise = new Promise<void>((resolve) => { commitConnection = resolve; }); act(() => { ref.current?.getWalletContextState().connect(); }); }); it('calls connect on the adapter', () => { expect(fooWalletAdapter.connect).toHaveBeenCalled(); }); it('updates state tracking variables appropriately', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ connected: false, connecting: true, }); }); describe('once connected', () => { beforeEach(() => { act(() => { commitConnection(); }); }); it('updates state tracking variables appropriately', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ connected: true, connecting: false, }); }); }); }); }); describe('disconnect()', () => { describe('when there is already a wallet connected', () => { let commitDisconnection: () => void; beforeEach(async () => { window.open = jest.fn(); renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); act(() => { ref.current?.getWalletContextState().connect(); }); fooWalletAdapter.disconnectionPromise = new Promise<void>((resolve) => { commitDisconnection = resolve; }); act(() => { ref.current?.getWalletContextState().disconnect(); }); }); it('updates state tracking variables appropriately', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ connected: true, }); }); describe('once disconnected', () => { beforeEach(() => { act(() => { commitDisconnection(); }); }); it('should clear the stored wallet name', () => { expect(localStorage.removeItem).toHaveBeenCalled(); }); it('clears out the state', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ wallet: null, connected: false, connecting: false, publicKey: null, }); }); }); }); }); describe('select()', () => { describe('when there is no wallet connected', () => { describe('and you select a wallet', () => { beforeEach(async () => { renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); it('sets the state tracking variables', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ wallet: { adapter: fooWalletAdapter, readyState: fooWalletAdapter.readyState }, connected: false, connecting: false, publicKey: fooWalletAdapter.publicKey, }); }); }); }); describe('when there is already a wallet selected', () => { let commitFooWalletDisconnection: () => void; beforeEach(async () => { fooWalletAdapter.disconnectionPromise = new Promise<void>((resolve) => { commitFooWalletDisconnection = resolve; }); renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); describe('and you select a different wallet', () => { beforeEach(async () => { await act(async () => { ref.current?.getWalletContextState().select('BarWallet' as WalletName); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); it('should disconnect the old wallet', () => { expect(fooWalletAdapter.disconnect).toHaveBeenCalled(); }); it('the adapter of the new wallet should be set in state', () => { expect(ref.current?.getWalletContextState().wallet?.adapter).toBe(barWalletAdapter); }); /** * Regression test: a race condition in the wallet name setter could result in the * wallet reverting back to an old value, depending on the cadence of the previous * wallets' disconnect operation. */ describe('then change your mind before the first one has disconnected', () => { beforeEach(async () => { await act(async () => { ref.current?.getWalletContextState().select('BazWallet' as WalletName); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); act(() => { commitFooWalletDisconnection(); }); }); it('the wallet you selected last should be set in state', () => { expect(ref.current?.getWalletContextState().wallet?.adapter).toBe(bazWalletAdapter); }); }); }); }); }); });
the_stack
import * as expect from "expect"; import * as simple from "simple-mock"; import { Metrics, timedIdentityClientFunctionCall, timedIntentFunctionCall, timedMatrixClientFunctionCall } from "../../src"; class InterceptedClass { public client: any; constructor(private metrics: Metrics, private interceptedFn: (i: number) => number) { this.client = { userId: 5678 }; } @timedMatrixClientFunctionCall() async matrixClientIntercepted(i: number): Promise<number> { return this.interceptedFn(i); } @timedIdentityClientFunctionCall() async identityClientIntercepted(i: number): Promise<number> { return this.interceptedFn(i); } @timedIntentFunctionCall() async intentIntercepted(i: number) : Promise<number> { return this.interceptedFn(i); } } // Not a fan of this but the promise with metrics chained isn't returned, just the original before the metrics were chained // I think this is deliberate so that metrics slow down any promises that later get chained // If we could return the promise with metrics chained this can go away. const waitingPromise = () => new Promise((resolve) => setTimeout(resolve, 10)); describe('decorators', () => { describe('timedMatrixClientFunctionCall', () => { it('should call the intercepted method with provided args', async () => { const amount = 1234; const interceptedFn = simple.stub().callFn((i: number) => { expect(i).toBe(amount); return -1; }); const interceptedClass = new InterceptedClass(new Metrics(), interceptedFn); await interceptedClass.matrixClientIntercepted(amount); expect(interceptedFn.callCount).toBe(1); }); it('should return the result of the intercepted method', async () => { const amount = 1234; const interceptedClass = new InterceptedClass(new Metrics(), (i) => amount); const result = await interceptedClass.matrixClientIntercepted(amount * 2); expect(result).toBe(amount); }); it('should expose errors from the intercepted method', async () => { const reason = "Bad things"; const interceptedClass = new InterceptedClass(new Metrics(), () => { throw new Error(reason); }); await expect(interceptedClass.matrixClientIntercepted(1234)).rejects.toThrow(reason); }); it('should call start on metrics with function name before calling intercepted method', async () => { const metrics = new Metrics(); simple.mock(metrics, "start"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.start.callCount).toBe(1); expect(metrics.start.lastCall.args[0]).toBe("matrix_client_function_call"); expect(metrics.start.lastCall.args[1]).toHaveProperty("functionName", "matrixClientIntercepted"); return -1; }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.matrixClientIntercepted(1234); }); it('should call end on metrics with function name after calling intercepted method', async () => { const metrics = new Metrics(); simple.mock(metrics, "end"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.end.callCount).toBe(0); return -1; }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.matrixClientIntercepted(1234).then(waitingPromise); expect(metrics.end.callCount).toBe(1); expect(metrics.end.lastCall.args[0]).toBe("matrix_client_function_call"); expect(metrics.end.lastCall.args[1]).toHaveProperty("functionName", "matrixClientIntercepted"); }); it('should increment the successful counter on returning a result', async () => { const metrics = new Metrics(); simple.mock(metrics, "increment"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.increment.callCount).toBe(0); return -1; }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.matrixClientIntercepted(1234).then(waitingPromise); expect(metrics.increment.callCount).toBe(1); expect(metrics.increment.lastCall.args[0]).toBe("matrix_client_successful_function_call"); expect(metrics.increment.lastCall.args[1]).toHaveProperty("functionName", "matrixClientIntercepted"); }); it('should increment the failure counter on throwing', async () => { const metrics = new Metrics(); simple.mock(metrics, "increment"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.increment.callCount).toBe(0); throw new Error("Bad things"); }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.matrixClientIntercepted(1234).catch(waitingPromise); expect(metrics.increment.callCount).toBe(1); expect(metrics.increment.lastCall.args[0]).toBe("matrix_client_failed_function_call"); expect(metrics.increment.lastCall.args[1]).toHaveProperty("functionName", "matrixClientIntercepted"); }); }); describe('timedIdentityClientFunctionCall', () => { it('should call the intercepted method with provided args', async () => { const amount = 1234; const interceptedFn = simple.stub().callFn((i: number) => { expect(i).toBe(amount); return -1; }); const interceptedClass = new InterceptedClass(new Metrics(), interceptedFn); await interceptedClass.identityClientIntercepted(amount); expect(interceptedFn.callCount).toBe(1); }); it('should return the result of the intercepted method', async () => { const amount = 1234; const interceptedClass = new InterceptedClass(new Metrics(), (i) => amount); const result = await interceptedClass.identityClientIntercepted(amount * 2); expect(result).toBe(amount); }); it('should expose errors from the intercepted method', async () => { const reason = "Bad things"; const interceptedClass = new InterceptedClass(new Metrics(), () => { throw new Error(reason); }); await expect(interceptedClass.identityClientIntercepted(1234)).rejects.toThrow(reason); }); it('should call start on metrics with function name before calling intercepted method', async () => { const metrics = new Metrics(); simple.mock(metrics, "start"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.start.callCount).toBe(1); expect(metrics.start.lastCall.args[0]).toBe("identity_client_function_call"); expect(metrics.start.lastCall.args[1]).toHaveProperty("functionName", "identityClientIntercepted"); return -1; }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.identityClientIntercepted(1234); }); it('should call end on metrics with function name after calling intercepted method', async () => { const metrics = new Metrics(); simple.mock(metrics, "end"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.end.callCount).toBe(0); return -1; }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.identityClientIntercepted(1234).then(waitingPromise); expect(metrics.end.callCount).toBe(1); expect(metrics.end.lastCall.args[0]).toBe("identity_client_function_call"); expect(metrics.end.lastCall.args[1]).toHaveProperty("functionName", "identityClientIntercepted"); }); it('should increment the successful counter on returning a result', async () => { const metrics = new Metrics(); simple.mock(metrics, "increment"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.increment.callCount).toBe(0); return -1; }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.identityClientIntercepted(1234).then(waitingPromise); expect(metrics.increment.callCount).toBe(1); expect(metrics.increment.lastCall.args[0]).toBe("identity_client_successful_function_call"); expect(metrics.increment.lastCall.args[1]).toHaveProperty("functionName", "identityClientIntercepted"); }); it('should increment the failure counter on throwing', async () => { const metrics = new Metrics(); simple.mock(metrics, "increment"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.increment.callCount).toBe(0); throw new Error("Bad things"); }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.identityClientIntercepted(1234).catch(waitingPromise); expect(metrics.increment.callCount).toBe(1); expect(metrics.increment.lastCall.args[0]).toBe("identity_client_failed_function_call"); expect(metrics.increment.lastCall.args[1]).toHaveProperty("functionName", "identityClientIntercepted"); }); }); describe('timedIntentFunctionCall', () => { it('should call the intercepted method with provided args', async () => { const amount = 1234; const interceptedFn = simple.stub().callFn((i: number) => { expect(i).toBe(amount); return -1; }); const interceptedClass = new InterceptedClass(new Metrics(), interceptedFn); await interceptedClass.intentIntercepted(amount); expect(interceptedFn.callCount).toBe(1); }); it('should return the result of the intercepted method', async () => { const amount = 1234; const interceptedClass = new InterceptedClass(new Metrics(), (i) => amount); const result = await interceptedClass.intentIntercepted(amount * 2); expect(result).toBe(amount); }); it('should expose errors from the intercepted method', async () => { const reason = "Bad things"; const interceptedClass = new InterceptedClass(new Metrics(), () => { throw new Error(reason); }); await expect(interceptedClass.intentIntercepted(1234)).rejects.toThrow(reason); }); it('should call start on metrics with function name before calling intercepted method', async () => { const metrics = new Metrics(); simple.mock(metrics, "start"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.start.callCount).toBe(1); expect(metrics.start.lastCall.args[0]).toBe("intent_function_call"); expect(metrics.start.lastCall.args[1]).toHaveProperty("functionName", "intentIntercepted"); return -1; }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.intentIntercepted(1234); }); it('should call end on metrics with function name after calling intercepted method', async () => { const metrics = new Metrics(); simple.mock(metrics, "end"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.end.callCount).toBe(0); return -1; }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.intentIntercepted(1234).then(waitingPromise); expect(metrics.end.callCount).toBe(1); expect(metrics.end.lastCall.args[0]).toBe("intent_function_call"); expect(metrics.end.lastCall.args[1]).toHaveProperty("functionName", "intentIntercepted"); }); it('should increment the successful counter on returning a result', async () => { const metrics = new Metrics(); simple.mock(metrics, "increment"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.increment.callCount).toBe(0); return -1; }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.intentIntercepted(1234).then(waitingPromise); expect(metrics.increment.callCount).toBe(1); expect(metrics.increment.lastCall.args[0]).toBe("intent_successful_function_call"); expect(metrics.increment.lastCall.args[1]).toHaveProperty("functionName", "intentIntercepted"); }); it('should increment the failure counter on throwing', async () => { const metrics = new Metrics(); simple.mock(metrics, "increment"); const interceptedFn = simple.stub().callFn((i: number) => { expect(metrics.increment.callCount).toBe(0); throw new Error("Bad things"); }); const interceptedClass = new InterceptedClass(metrics, interceptedFn); await interceptedClass.intentIntercepted(1234).catch(waitingPromise); expect(metrics.increment.callCount).toBe(1); expect(metrics.increment.lastCall.args[0]).toBe("intent_failed_function_call"); expect(metrics.increment.lastCall.args[1]).toHaveProperty("functionName", "intentIntercepted"); }); }); });
the_stack
import { ATN } from "antlr4ts/atn/ATN"; import { ATNDeserializer } from "antlr4ts/atn/ATNDeserializer"; import { FailedPredicateException } from "antlr4ts/FailedPredicateException"; import { NotNull } from "antlr4ts/Decorators"; import { NoViableAltException } from "antlr4ts/NoViableAltException"; import { Override } from "antlr4ts/Decorators"; import { Parser } from "antlr4ts/Parser"; import { ParserRuleContext } from "antlr4ts/ParserRuleContext"; import { ParserATNSimulator } from "antlr4ts/atn/ParserATNSimulator"; import { ParseTreeListener } from "antlr4ts/tree/ParseTreeListener"; import { ParseTreeVisitor } from "antlr4ts/tree/ParseTreeVisitor"; import { RecognitionException } from "antlr4ts/RecognitionException"; import { RuleContext } from "antlr4ts/RuleContext"; //import { RuleVersion } from "antlr4ts/RuleVersion"; import { TerminalNode } from "antlr4ts/tree/TerminalNode"; import { Token } from "antlr4ts/Token"; import { TokenStream } from "antlr4ts/TokenStream"; import { Vocabulary } from "antlr4ts/Vocabulary"; import { VocabularyImpl } from "antlr4ts/VocabularyImpl"; import * as Utils from "antlr4ts/misc/Utils"; import { QueryParserListener } from "./QueryParserListener"; import { QueryParserVisitor } from "./QueryParserVisitor"; export class QueryParser extends Parser { public static readonly ID = 1; public static readonly SINGULAR_PARAM_MARK = 2; public static readonly PLURAL_PARAM_MARK = 3; public static readonly COMMA = 4; public static readonly OB = 5; public static readonly CB = 6; public static readonly WORD = 7; public static readonly REQUIRED_MARK = 8; public static readonly SPECIAL = 9; public static readonly EOF_STATEMENT = 10; public static readonly WSL = 11; public static readonly STRING = 12; public static readonly RULE_input = 0; public static readonly RULE_query = 1; public static readonly RULE_param = 2; public static readonly RULE_ignored = 3; public static readonly RULE_scalarParam = 4; public static readonly RULE_pickParam = 5; public static readonly RULE_arrayPickParam = 6; public static readonly RULE_arrayParam = 7; public static readonly RULE_scalarParamName = 8; public static readonly RULE_paramName = 9; public static readonly RULE_pickKey = 10; // tslint:disable:no-trailing-whitespace public static readonly ruleNames: string[] = [ "input", "query", "param", "ignored", "scalarParam", "pickParam", "arrayPickParam", "arrayParam", "scalarParamName", "paramName", "pickKey", ]; private static readonly _LITERAL_NAMES: Array<string | undefined> = [ undefined, undefined, "'$'", "'$$'", "','", "'('", "')'", undefined, "'!'", undefined, "';'", ]; private static readonly _SYMBOLIC_NAMES: Array<string | undefined> = [ undefined, "ID", "SINGULAR_PARAM_MARK", "PLURAL_PARAM_MARK", "COMMA", "OB", "CB", "WORD", "REQUIRED_MARK", "SPECIAL", "EOF_STATEMENT", "WSL", "STRING", ]; public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(QueryParser._LITERAL_NAMES, QueryParser._SYMBOLIC_NAMES, []); // @Override // @NotNull public get vocabulary(): Vocabulary { return QueryParser.VOCABULARY; } // tslint:enable:no-trailing-whitespace // @Override public get grammarFileName(): string { return "QueryParser.g4"; } // @Override public get ruleNames(): string[] { return QueryParser.ruleNames; } // @Override public get serializedATN(): string { return QueryParser._serializedATN; } protected createFailedPredicateException(predicate?: string, message?: string): FailedPredicateException { return new FailedPredicateException(this, predicate, message); } constructor(input: TokenStream) { super(input); this._interp = new ParserATNSimulator(QueryParser._ATN, this); } // @RuleVersion(0) public input(): InputContext { let _localctx: InputContext = new InputContext(this._ctx, this.state); this.enterRule(_localctx, 0, QueryParser.RULE_input); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 22; this.query(); this.state = 24; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === QueryParser.EOF_STATEMENT) { { this.state = 23; this.match(QueryParser.EOF_STATEMENT); } } this.state = 26; this.match(QueryParser.EOF); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public query(): QueryContext { let _localctx: QueryContext = new QueryContext(this._ctx, this.state); this.enterRule(_localctx, 2, QueryParser.RULE_query); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 29; this._errHandler.sync(this); _la = this._input.LA(1); do { { { this.state = 28; this.ignored(); } } this.state = 31; this._errHandler.sync(this); _la = this._input.LA(1); } while ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << QueryParser.ID) | (1 << QueryParser.COMMA) | (1 << QueryParser.OB) | (1 << QueryParser.CB) | (1 << QueryParser.WORD) | (1 << QueryParser.REQUIRED_MARK) | (1 << QueryParser.SPECIAL) | (1 << QueryParser.STRING))) !== 0)); this.state = 42; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === QueryParser.SINGULAR_PARAM_MARK || _la === QueryParser.PLURAL_PARAM_MARK) { { { this.state = 33; this.param(); this.state = 37; this._errHandler.sync(this); _la = this._input.LA(1); while ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << QueryParser.ID) | (1 << QueryParser.COMMA) | (1 << QueryParser.OB) | (1 << QueryParser.CB) | (1 << QueryParser.WORD) | (1 << QueryParser.REQUIRED_MARK) | (1 << QueryParser.SPECIAL) | (1 << QueryParser.STRING))) !== 0)) { { { this.state = 34; this.ignored(); } } this.state = 39; this._errHandler.sync(this); _la = this._input.LA(1); } } } this.state = 44; this._errHandler.sync(this); _la = this._input.LA(1); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public param(): ParamContext { let _localctx: ParamContext = new ParamContext(this._ctx, this.state); this.enterRule(_localctx, 4, QueryParser.RULE_param); try { this.state = 49; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 4, this._ctx) ) { case 1: this.enterOuterAlt(_localctx, 1); { this.state = 45; this.pickParam(); } break; case 2: this.enterOuterAlt(_localctx, 2); { this.state = 46; this.arrayPickParam(); } break; case 3: this.enterOuterAlt(_localctx, 3); { this.state = 47; this.scalarParam(); } break; case 4: this.enterOuterAlt(_localctx, 4); { this.state = 48; this.arrayParam(); } break; } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public ignored(): IgnoredContext { let _localctx: IgnoredContext = new IgnoredContext(this._ctx, this.state); this.enterRule(_localctx, 6, QueryParser.RULE_ignored); let _la: number; try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 52; this._errHandler.sync(this); _alt = 1; do { switch (_alt) { case 1: { { this.state = 51; _la = this._input.LA(1); if (!((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << QueryParser.ID) | (1 << QueryParser.COMMA) | (1 << QueryParser.OB) | (1 << QueryParser.CB) | (1 << QueryParser.WORD) | (1 << QueryParser.REQUIRED_MARK) | (1 << QueryParser.SPECIAL) | (1 << QueryParser.STRING))) !== 0))) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } break; default: throw new NoViableAltException(this); } this.state = 54; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 5, this._ctx); } while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public scalarParam(): ScalarParamContext { let _localctx: ScalarParamContext = new ScalarParamContext(this._ctx, this.state); this.enterRule(_localctx, 8, QueryParser.RULE_scalarParam); try { this.enterOuterAlt(_localctx, 1); { this.state = 56; this.match(QueryParser.SINGULAR_PARAM_MARK); this.state = 57; this.scalarParamName(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public pickParam(): PickParamContext { let _localctx: PickParamContext = new PickParamContext(this._ctx, this.state); this.enterRule(_localctx, 10, QueryParser.RULE_pickParam); let _la: number; try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 59; this.match(QueryParser.SINGULAR_PARAM_MARK); this.state = 60; this.paramName(); this.state = 61; this.match(QueryParser.OB); this.state = 62; this.pickKey(); this.state = 67; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 6, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { if (_alt === 1) { { { this.state = 63; this.match(QueryParser.COMMA); this.state = 64; this.pickKey(); } } } this.state = 69; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 6, this._ctx); } this.state = 71; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === QueryParser.COMMA) { { this.state = 70; this.match(QueryParser.COMMA); } } this.state = 73; this.match(QueryParser.CB); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public arrayPickParam(): ArrayPickParamContext { let _localctx: ArrayPickParamContext = new ArrayPickParamContext(this._ctx, this.state); this.enterRule(_localctx, 12, QueryParser.RULE_arrayPickParam); let _la: number; try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 75; this.match(QueryParser.PLURAL_PARAM_MARK); this.state = 76; this.paramName(); this.state = 77; this.match(QueryParser.OB); this.state = 78; this.pickKey(); this.state = 83; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 8, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { if (_alt === 1) { { { this.state = 79; this.match(QueryParser.COMMA); this.state = 80; this.pickKey(); } } } this.state = 85; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 8, this._ctx); } this.state = 87; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === QueryParser.COMMA) { { this.state = 86; this.match(QueryParser.COMMA); } } this.state = 89; this.match(QueryParser.CB); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public arrayParam(): ArrayParamContext { let _localctx: ArrayParamContext = new ArrayParamContext(this._ctx, this.state); this.enterRule(_localctx, 14, QueryParser.RULE_arrayParam); try { this.enterOuterAlt(_localctx, 1); { this.state = 91; this.match(QueryParser.PLURAL_PARAM_MARK); this.state = 92; this.scalarParamName(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public scalarParamName(): ScalarParamNameContext { let _localctx: ScalarParamNameContext = new ScalarParamNameContext(this._ctx, this.state); this.enterRule(_localctx, 16, QueryParser.RULE_scalarParamName); try { this.enterOuterAlt(_localctx, 1); { this.state = 94; this.match(QueryParser.ID); this.state = 96; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 10, this._ctx) ) { case 1: { this.state = 95; this.match(QueryParser.REQUIRED_MARK); } break; } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public paramName(): ParamNameContext { let _localctx: ParamNameContext = new ParamNameContext(this._ctx, this.state); this.enterRule(_localctx, 18, QueryParser.RULE_paramName); try { this.enterOuterAlt(_localctx, 1); { this.state = 98; this.match(QueryParser.ID); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public pickKey(): PickKeyContext { let _localctx: PickKeyContext = new PickKeyContext(this._ctx, this.state); this.enterRule(_localctx, 20, QueryParser.RULE_pickKey); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 100; this.match(QueryParser.ID); this.state = 102; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === QueryParser.REQUIRED_MARK) { { this.state = 101; this.match(QueryParser.REQUIRED_MARK); } } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } public static readonly _serializedATN: string = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x03\x0Ek\x04\x02" + "\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04\x07" + "\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x03\x02\x03\x02" + "\x05\x02\x1B\n\x02\x03\x02\x03\x02\x03\x03\x06\x03 \n\x03\r\x03\x0E\x03" + "!\x03\x03\x03\x03\x07\x03&\n\x03\f\x03\x0E\x03)\v\x03\x07\x03+\n\x03\f" + "\x03\x0E\x03.\v\x03\x03\x04\x03\x04\x03\x04\x03\x04\x05\x044\n\x04\x03" + "\x05\x06\x057\n\x05\r\x05\x0E\x058\x03\x06\x03\x06\x03\x06\x03\x07\x03" + "\x07\x03\x07\x03\x07\x03\x07\x03\x07\x07\x07D\n\x07\f\x07\x0E\x07G\v\x07" + "\x03\x07\x05\x07J\n\x07\x03\x07\x03\x07\x03\b\x03\b\x03\b\x03\b\x03\b" + "\x03\b\x07\bT\n\b\f\b\x0E\bW\v\b\x03\b\x05\bZ\n\b\x03\b\x03\b\x03\t\x03" + "\t\x03\t\x03\n\x03\n\x05\nc\n\n\x03\v\x03\v\x03\f\x03\f\x05\fi\n\f\x03" + "\f\x02\x02\x02\r\x02\x02\x04\x02\x06\x02\b\x02\n\x02\f\x02\x0E\x02\x10" + "\x02\x12\x02\x14\x02\x16\x02\x02\x03\x05\x02\x03\x03\x06\v\x0E\x0E\x02" + "m\x02\x18\x03\x02\x02\x02\x04\x1F\x03\x02\x02\x02\x063\x03\x02\x02\x02" + "\b6\x03\x02\x02\x02\n:\x03\x02\x02\x02\f=\x03\x02\x02\x02\x0EM\x03\x02" + "\x02\x02\x10]\x03\x02\x02\x02\x12`\x03\x02\x02\x02\x14d\x03\x02\x02\x02" + "\x16f\x03\x02\x02\x02\x18\x1A\x05\x04\x03\x02\x19\x1B\x07\f\x02\x02\x1A" + "\x19\x03\x02\x02\x02\x1A\x1B\x03\x02\x02\x02\x1B\x1C\x03\x02\x02\x02\x1C" + "\x1D\x07\x02\x02\x03\x1D\x03\x03\x02\x02\x02\x1E \x05\b\x05\x02\x1F\x1E" + "\x03\x02\x02\x02 !\x03\x02\x02\x02!\x1F\x03\x02\x02\x02!\"\x03\x02\x02" + "\x02\",\x03\x02\x02\x02#\'\x05\x06\x04\x02$&\x05\b\x05\x02%$\x03\x02\x02" + "\x02&)\x03\x02\x02\x02\'%\x03\x02\x02\x02\'(\x03\x02\x02\x02(+\x03\x02" + "\x02\x02)\'\x03\x02\x02\x02*#\x03\x02\x02\x02+.\x03\x02\x02\x02,*\x03" + "\x02\x02\x02,-\x03\x02\x02\x02-\x05\x03\x02\x02\x02.,\x03\x02\x02\x02" + "/4\x05\f\x07\x0204\x05\x0E\b\x0214\x05\n\x06\x0224\x05\x10\t\x023/\x03" + "\x02\x02\x0230\x03\x02\x02\x0231\x03\x02\x02\x0232\x03\x02\x02\x024\x07" + "\x03\x02\x02\x0257\t\x02\x02\x0265\x03\x02\x02\x0278\x03\x02\x02\x028" + "6\x03\x02\x02\x0289\x03\x02\x02\x029\t\x03\x02\x02\x02:;\x07\x04\x02\x02" + ";<\x05\x12\n\x02<\v\x03\x02\x02\x02=>\x07\x04\x02\x02>?\x05\x14\v\x02" + "?@\x07\x07\x02\x02@E\x05\x16\f\x02AB\x07\x06\x02\x02BD\x05\x16\f\x02C" + "A\x03\x02\x02\x02DG\x03\x02\x02\x02EC\x03\x02\x02\x02EF\x03\x02\x02\x02" + "FI\x03\x02\x02\x02GE\x03\x02\x02\x02HJ\x07\x06\x02\x02IH\x03\x02\x02\x02" + "IJ\x03\x02\x02\x02JK\x03\x02\x02\x02KL\x07\b\x02\x02L\r\x03\x02\x02\x02" + "MN\x07\x05\x02\x02NO\x05\x14\v\x02OP\x07\x07\x02\x02PU\x05\x16\f\x02Q" + "R\x07\x06\x02\x02RT\x05\x16\f\x02SQ\x03\x02\x02\x02TW\x03\x02\x02\x02" + "US\x03\x02\x02\x02UV\x03\x02\x02\x02VY\x03\x02\x02\x02WU\x03\x02\x02\x02" + "XZ\x07\x06\x02\x02YX\x03\x02\x02\x02YZ\x03\x02\x02\x02Z[\x03\x02\x02\x02" + "[\\\x07\b\x02\x02\\\x0F\x03\x02\x02\x02]^\x07\x05\x02\x02^_\x05\x12\n" + "\x02_\x11\x03\x02\x02\x02`b\x07\x03\x02\x02ac\x07\n\x02\x02ba\x03\x02" + "\x02\x02bc\x03\x02\x02\x02c\x13\x03\x02\x02\x02de\x07\x03\x02\x02e\x15" + "\x03\x02\x02\x02fh\x07\x03\x02\x02gi\x07\n\x02\x02hg\x03\x02\x02\x02h" + "i\x03\x02\x02\x02i\x17\x03\x02\x02\x02\x0E\x1A!\',38EIUYbh"; public static __ATN: ATN; public static get _ATN(): ATN { if (!QueryParser.__ATN) { QueryParser.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(QueryParser._serializedATN)); } return QueryParser.__ATN; } } export class InputContext extends ParserRuleContext { public query(): QueryContext { return this.getRuleContext(0, QueryContext); } public EOF(): TerminalNode { return this.getToken(QueryParser.EOF, 0); } public EOF_STATEMENT(): TerminalNode | undefined { return this.tryGetToken(QueryParser.EOF_STATEMENT, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return QueryParser.RULE_input; } // @Override public enterRule(listener: QueryParserListener): void { if (listener.enterInput) { listener.enterInput(this); } } // @Override public exitRule(listener: QueryParserListener): void { if (listener.exitInput) { listener.exitInput(this); } } // @Override public accept<Result>(visitor: QueryParserVisitor<Result>): Result { if (visitor.visitInput) { return visitor.visitInput(this); } else { return visitor.visitChildren(this); } } } export class QueryContext extends ParserRuleContext { public ignored(): IgnoredContext[]; public ignored(i: number): IgnoredContext; public ignored(i?: number): IgnoredContext | IgnoredContext[] { if (i === undefined) { return this.getRuleContexts(IgnoredContext); } else { return this.getRuleContext(i, IgnoredContext); } } public param(): ParamContext[]; public param(i: number): ParamContext; public param(i?: number): ParamContext | ParamContext[] { if (i === undefined) { return this.getRuleContexts(ParamContext); } else { return this.getRuleContext(i, ParamContext); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return QueryParser.RULE_query; } // @Override public enterRule(listener: QueryParserListener): void { if (listener.enterQuery) { listener.enterQuery(this); } } // @Override public exitRule(listener: QueryParserListener): void { if (listener.exitQuery) { listener.exitQuery(this); } } // @Override public accept<Result>(visitor: QueryParserVisitor<Result>): Result { if (visitor.visitQuery) { return visitor.visitQuery(this); } else { return visitor.visitChildren(this); } } } export class ParamContext extends ParserRuleContext { public pickParam(): PickParamContext | undefined { return this.tryGetRuleContext(0, PickParamContext); } public arrayPickParam(): ArrayPickParamContext | undefined { return this.tryGetRuleContext(0, ArrayPickParamContext); } public scalarParam(): ScalarParamContext | undefined { return this.tryGetRuleContext(0, ScalarParamContext); } public arrayParam(): ArrayParamContext | undefined { return this.tryGetRuleContext(0, ArrayParamContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return QueryParser.RULE_param; } // @Override public enterRule(listener: QueryParserListener): void { if (listener.enterParam) { listener.enterParam(this); } } // @Override public exitRule(listener: QueryParserListener): void { if (listener.exitParam) { listener.exitParam(this); } } // @Override public accept<Result>(visitor: QueryParserVisitor<Result>): Result { if (visitor.visitParam) { return visitor.visitParam(this); } else { return visitor.visitChildren(this); } } } export class IgnoredContext extends ParserRuleContext { public ID(): TerminalNode[]; public ID(i: number): TerminalNode; public ID(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(QueryParser.ID); } else { return this.getToken(QueryParser.ID, i); } } public WORD(): TerminalNode[]; public WORD(i: number): TerminalNode; public WORD(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(QueryParser.WORD); } else { return this.getToken(QueryParser.WORD, i); } } public STRING(): TerminalNode[]; public STRING(i: number): TerminalNode; public STRING(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(QueryParser.STRING); } else { return this.getToken(QueryParser.STRING, i); } } public COMMA(): TerminalNode[]; public COMMA(i: number): TerminalNode; public COMMA(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(QueryParser.COMMA); } else { return this.getToken(QueryParser.COMMA, i); } } public OB(): TerminalNode[]; public OB(i: number): TerminalNode; public OB(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(QueryParser.OB); } else { return this.getToken(QueryParser.OB, i); } } public CB(): TerminalNode[]; public CB(i: number): TerminalNode; public CB(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(QueryParser.CB); } else { return this.getToken(QueryParser.CB, i); } } public SPECIAL(): TerminalNode[]; public SPECIAL(i: number): TerminalNode; public SPECIAL(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(QueryParser.SPECIAL); } else { return this.getToken(QueryParser.SPECIAL, i); } } public REQUIRED_MARK(): TerminalNode[]; public REQUIRED_MARK(i: number): TerminalNode; public REQUIRED_MARK(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(QueryParser.REQUIRED_MARK); } else { return this.getToken(QueryParser.REQUIRED_MARK, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return QueryParser.RULE_ignored; } // @Override public enterRule(listener: QueryParserListener): void { if (listener.enterIgnored) { listener.enterIgnored(this); } } // @Override public exitRule(listener: QueryParserListener): void { if (listener.exitIgnored) { listener.exitIgnored(this); } } // @Override public accept<Result>(visitor: QueryParserVisitor<Result>): Result { if (visitor.visitIgnored) { return visitor.visitIgnored(this); } else { return visitor.visitChildren(this); } } } export class ScalarParamContext extends ParserRuleContext { public SINGULAR_PARAM_MARK(): TerminalNode { return this.getToken(QueryParser.SINGULAR_PARAM_MARK, 0); } public scalarParamName(): ScalarParamNameContext { return this.getRuleContext(0, ScalarParamNameContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return QueryParser.RULE_scalarParam; } // @Override public enterRule(listener: QueryParserListener): void { if (listener.enterScalarParam) { listener.enterScalarParam(this); } } // @Override public exitRule(listener: QueryParserListener): void { if (listener.exitScalarParam) { listener.exitScalarParam(this); } } // @Override public accept<Result>(visitor: QueryParserVisitor<Result>): Result { if (visitor.visitScalarParam) { return visitor.visitScalarParam(this); } else { return visitor.visitChildren(this); } } } export class PickParamContext extends ParserRuleContext { public SINGULAR_PARAM_MARK(): TerminalNode { return this.getToken(QueryParser.SINGULAR_PARAM_MARK, 0); } public paramName(): ParamNameContext { return this.getRuleContext(0, ParamNameContext); } public OB(): TerminalNode { return this.getToken(QueryParser.OB, 0); } public pickKey(): PickKeyContext[]; public pickKey(i: number): PickKeyContext; public pickKey(i?: number): PickKeyContext | PickKeyContext[] { if (i === undefined) { return this.getRuleContexts(PickKeyContext); } else { return this.getRuleContext(i, PickKeyContext); } } public CB(): TerminalNode { return this.getToken(QueryParser.CB, 0); } public COMMA(): TerminalNode[]; public COMMA(i: number): TerminalNode; public COMMA(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(QueryParser.COMMA); } else { return this.getToken(QueryParser.COMMA, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return QueryParser.RULE_pickParam; } // @Override public enterRule(listener: QueryParserListener): void { if (listener.enterPickParam) { listener.enterPickParam(this); } } // @Override public exitRule(listener: QueryParserListener): void { if (listener.exitPickParam) { listener.exitPickParam(this); } } // @Override public accept<Result>(visitor: QueryParserVisitor<Result>): Result { if (visitor.visitPickParam) { return visitor.visitPickParam(this); } else { return visitor.visitChildren(this); } } } export class ArrayPickParamContext extends ParserRuleContext { public PLURAL_PARAM_MARK(): TerminalNode { return this.getToken(QueryParser.PLURAL_PARAM_MARK, 0); } public paramName(): ParamNameContext { return this.getRuleContext(0, ParamNameContext); } public OB(): TerminalNode { return this.getToken(QueryParser.OB, 0); } public pickKey(): PickKeyContext[]; public pickKey(i: number): PickKeyContext; public pickKey(i?: number): PickKeyContext | PickKeyContext[] { if (i === undefined) { return this.getRuleContexts(PickKeyContext); } else { return this.getRuleContext(i, PickKeyContext); } } public CB(): TerminalNode { return this.getToken(QueryParser.CB, 0); } public COMMA(): TerminalNode[]; public COMMA(i: number): TerminalNode; public COMMA(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(QueryParser.COMMA); } else { return this.getToken(QueryParser.COMMA, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return QueryParser.RULE_arrayPickParam; } // @Override public enterRule(listener: QueryParserListener): void { if (listener.enterArrayPickParam) { listener.enterArrayPickParam(this); } } // @Override public exitRule(listener: QueryParserListener): void { if (listener.exitArrayPickParam) { listener.exitArrayPickParam(this); } } // @Override public accept<Result>(visitor: QueryParserVisitor<Result>): Result { if (visitor.visitArrayPickParam) { return visitor.visitArrayPickParam(this); } else { return visitor.visitChildren(this); } } } export class ArrayParamContext extends ParserRuleContext { public PLURAL_PARAM_MARK(): TerminalNode { return this.getToken(QueryParser.PLURAL_PARAM_MARK, 0); } public scalarParamName(): ScalarParamNameContext { return this.getRuleContext(0, ScalarParamNameContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return QueryParser.RULE_arrayParam; } // @Override public enterRule(listener: QueryParserListener): void { if (listener.enterArrayParam) { listener.enterArrayParam(this); } } // @Override public exitRule(listener: QueryParserListener): void { if (listener.exitArrayParam) { listener.exitArrayParam(this); } } // @Override public accept<Result>(visitor: QueryParserVisitor<Result>): Result { if (visitor.visitArrayParam) { return visitor.visitArrayParam(this); } else { return visitor.visitChildren(this); } } } export class ScalarParamNameContext extends ParserRuleContext { public ID(): TerminalNode { return this.getToken(QueryParser.ID, 0); } public REQUIRED_MARK(): TerminalNode | undefined { return this.tryGetToken(QueryParser.REQUIRED_MARK, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return QueryParser.RULE_scalarParamName; } // @Override public enterRule(listener: QueryParserListener): void { if (listener.enterScalarParamName) { listener.enterScalarParamName(this); } } // @Override public exitRule(listener: QueryParserListener): void { if (listener.exitScalarParamName) { listener.exitScalarParamName(this); } } // @Override public accept<Result>(visitor: QueryParserVisitor<Result>): Result { if (visitor.visitScalarParamName) { return visitor.visitScalarParamName(this); } else { return visitor.visitChildren(this); } } } export class ParamNameContext extends ParserRuleContext { public ID(): TerminalNode { return this.getToken(QueryParser.ID, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return QueryParser.RULE_paramName; } // @Override public enterRule(listener: QueryParserListener): void { if (listener.enterParamName) { listener.enterParamName(this); } } // @Override public exitRule(listener: QueryParserListener): void { if (listener.exitParamName) { listener.exitParamName(this); } } // @Override public accept<Result>(visitor: QueryParserVisitor<Result>): Result { if (visitor.visitParamName) { return visitor.visitParamName(this); } else { return visitor.visitChildren(this); } } } export class PickKeyContext extends ParserRuleContext { public ID(): TerminalNode { return this.getToken(QueryParser.ID, 0); } public REQUIRED_MARK(): TerminalNode | undefined { return this.tryGetToken(QueryParser.REQUIRED_MARK, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return QueryParser.RULE_pickKey; } // @Override public enterRule(listener: QueryParserListener): void { if (listener.enterPickKey) { listener.enterPickKey(this); } } // @Override public exitRule(listener: QueryParserListener): void { if (listener.exitPickKey) { listener.exitPickKey(this); } } // @Override public accept<Result>(visitor: QueryParserVisitor<Result>): Result { if (visitor.visitPickKey) { return visitor.visitPickKey(this); } else { return visitor.visitChildren(this); } } }
the_stack
import { Inject, Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import { combineLatest, filter, first, map, pairwise, publishReplay, refCount, startWith, switchMap } from 'rxjs/operators'; import { AppMetadataTypes } from '../../../../cloud-foundry/src/actions/app-metadata.actions'; import { GetApplication, UpdateApplication, UpdateExistingApplication, } from '../../../../cloud-foundry/src/actions/application.actions'; import { CFAppState } from '../../../../cloud-foundry/src/cf-app-state'; import { applicationEntityType, domainEntityType, organizationEntityType, routeEntityType, serviceBindingEntityType, spaceEntityType, stackEntityType, } from '../../../../cloud-foundry/src/cf-entity-types'; import { APP_GUID, CF_GUID } from '../../../../core/src/shared/entity.tokens'; import { EntityService } from '../../../../store/src/entity-service'; import { ActionState, rootUpdatingKey } from '../../../../store/src/reducers/api-request-reducer/types'; import { getCurrentPageRequestInfo, PaginationObservables, } from '../../../../store/src/reducers/pagination-reducer/pagination-reducer.types'; import { endpointEntitiesSelector } from '../../../../store/src/selectors/endpoint.selectors'; import { APIResource, EntityInfo } from '../../../../store/src/types/api.types'; import { PaginationEntityState } from '../../../../store/src/types/pagination.types'; import { IApp, IAppSummary, IDomain, IOrganization, ISpace, IStack } from '../../cf-api.types'; import { cfEntityCatalog } from '../../cf-entity-catalog'; import { createEntityRelationKey } from '../../entity-relations/entity-relations.types'; import { ApplicationStateData, ApplicationStateService } from '../../shared/services/application-state.service'; import { AppStat } from '../../store/types/app-metadata.types'; import { ApplicationEnvVarsHelper, EnvVarStratosProject, } from './application/application-tabs-base/tabs/build-tab/application-env-vars.service'; import { getRoute, isTCPRoute } from './routes/routes.helper'; export function createGetApplicationAction(guid: string, endpointGuid: string) { return new GetApplication( guid, endpointGuid, [ createEntityRelationKey(applicationEntityType, routeEntityType), createEntityRelationKey(applicationEntityType, spaceEntityType), createEntityRelationKey(applicationEntityType, stackEntityType), createEntityRelationKey(applicationEntityType, serviceBindingEntityType), createEntityRelationKey(routeEntityType, domainEntityType), createEntityRelationKey(spaceEntityType, organizationEntityType), ] ); } export interface ApplicationData { fetching: boolean; app: APIResource<IApp>; stack: APIResource<IStack>; cf: any; } @Injectable() export class ApplicationService { public entityService: EntityService<APIResource<IApp>>; private appSummaryEntityService: EntityService<IAppSummary>; constructor( @Inject(CF_GUID) public cfGuid: string, @Inject(APP_GUID) public appGuid: string, private store: Store<CFAppState>, private appStateService: ApplicationStateService, private appEnvVarsService: ApplicationEnvVarsHelper, ) { this.entityService = cfEntityCatalog.application.store.getEntityService( appGuid, cfGuid, { includeRelations: createGetApplicationAction(appGuid, cfGuid).includeRelations, populateMissing: true } ); this.appSummaryEntityService = cfEntityCatalog.appSummary.store.getEntityService( appGuid, cfGuid ); this.constructCoreObservables(); this.constructAmalgamatedObservables(); this.constructStatusObservables(); } // NJ: This needs to be cleaned up. So much going on! /** * An observable based on the core application entity */ isFetchingApp$: Observable<boolean>; isUpdatingApp$: Observable<boolean>; isDeletingApp$: Observable<boolean>; isFetchingEnvVars$: Observable<boolean>; isUpdatingEnvVars$: Observable<boolean>; isFetchingStats$: Observable<boolean>; app$: Observable<EntityInfo<APIResource<IApp>>>; waitForAppEntity$: Observable<EntityInfo<APIResource<IApp>>>; appSummary$: Observable<EntityInfo<IAppSummary>>; appStats$: Observable<AppStat[]>; private appStatsFetching$: Observable<PaginationEntityState>; // Use isFetchingStats$ which is properly gated appEnvVars: PaginationObservables<APIResource>; appOrg$: Observable<APIResource<IOrganization>>; appSpace$: Observable<APIResource<ISpace>>; application$: Observable<ApplicationData>; applicationStratProject$: Observable<EnvVarStratosProject>; applicationState$: Observable<ApplicationStateData>; applicationUrl$: Observable<string>; applicationRunning$: Observable<boolean>; orgDomains$: Observable<APIResource<IDomain>[]>; /** * Fetch the current state of the app (given it's instances) as an object ready */ static getApplicationState( appStateService: ApplicationStateService, app: IApp, appGuid: string, cfGuid: string): Observable<ApplicationStateData> { return cfEntityCatalog.appStats.store.getPaginationMonitor(appGuid, cfGuid).currentPage$.pipe( map(appInstancesPages => { return appStateService.get(app, appInstancesPages); }) ).pipe(publishReplay(1), refCount()); } private constructCoreObservables() { // First set up all the base observables this.app$ = this.entityService.waitForEntity$; const moreWaiting$ = this.app$.pipe( filter(entityInfo => !!(entityInfo.entity && entityInfo.entity.entity && entityInfo.entity.entity.cfGuid)), map(entityInfo => entityInfo.entity.entity)); this.appSpace$ = moreWaiting$.pipe( first(), switchMap(app => { return cfEntityCatalog.space.store.getWithOrganization.getEntityService( app.space_guid, app.cfGuid, ).waitForEntity$.pipe( map(entityInfo => entityInfo.entity) ); }), publishReplay(1), refCount() ); this.appOrg$ = moreWaiting$.pipe( first(), switchMap(() => this.appSpace$), map(space => space.entity.organization), filter(org => !!org) ); this.isDeletingApp$ = this.entityService.isDeletingEntity$.pipe(publishReplay(1), refCount()); this.waitForAppEntity$ = this.entityService.waitForEntity$.pipe(publishReplay(1), refCount()); this.appSummary$ = this.waitForAppEntity$.pipe( switchMap(() => this.appSummaryEntityService.entityObs$), publishReplay(1), refCount() ); this.appEnvVars = this.appEnvVarsService.createEnvVarsObs(this.appGuid, this.cfGuid); } public getApplicationEnvVarsMonitor() { return cfEntityCatalog.appEnvVar.store.getEntityMonitor( this.appGuid ); } private constructAmalgamatedObservables() { // Assign/Amalgamate them to public properties (with mangling if required) const appStats = cfEntityCatalog.appStats.store.getPaginationService(this.appGuid, this.cfGuid); // This will fail to fetch the app stats if the current app is not running but we're // willing to do this to speed up the initial fetch for a running application. this.appStats$ = appStats.entities$; this.appStatsFetching$ = appStats.pagination$.pipe(publishReplay(1), refCount()); this.application$ = this.waitForAppEntity$.pipe( combineLatest(this.store.select(endpointEntitiesSelector)), filter(([entityInfo]) => { return !!entityInfo && !!entityInfo.entity && !!entityInfo.entity.entity && !!entityInfo.entity.entity.cfGuid; }), map(([{ entity, entityRequestInfo }, endpoints]): ApplicationData => { return { fetching: entityRequestInfo.fetching, app: entity, stack: entity.entity.stack, cf: endpoints[entity.entity.cfGuid], }; }), publishReplay(1), refCount()); this.applicationState$ = this.waitForAppEntity$.pipe( combineLatest(this.appStats$.pipe(startWith(null))), map(([appInfo, appStatsArray]: [EntityInfo, AppStat[]]) => { return this.appStateService.get(appInfo.entity.entity, appStatsArray || null); }), publishReplay(1), refCount()); this.applicationStratProject$ = this.appEnvVars.entities$.pipe(map(applicationEnvVars => { return this.appEnvVarsService.FetchStratosProject(applicationEnvVars[0].entity); }), publishReplay(1), refCount()); this.applicationRunning$ = this.application$.pipe( map(app => app ? app.app.entity.state === 'STARTED' : false) ); // In an ideal world we'd get domains inline with the application, however the inline path from app to org domains exceeds max cf depth // of 2 (app --> space --> org --> domains). this.orgDomains$ = this.appOrg$.pipe( switchMap(org => cfEntityCatalog.domain.store.getOrganizationDomains.getPaginationService(org.metadata.guid, this.cfGuid).entities$ ), publishReplay(1), refCount() ); } private constructStatusObservables() { this.isFetchingApp$ = this.entityService.isFetchingEntity$; this.isUpdatingApp$ = this.entityService.entityObs$.pipe(map(a => { const updatingRoot = a.entityRequestInfo.updating[rootUpdatingKey] || { busy: false }; const updatingSection = a.entityRequestInfo.updating[UpdateExistingApplication.updateKey] || { busy: false }; return !!updatingRoot.busy || !!updatingSection.busy; })); this.isFetchingEnvVars$ = this.appEnvVars.pagination$.pipe( map(ev => getCurrentPageRequestInfo(ev).busy), startWith(false), publishReplay(1), refCount()); this.isUpdatingEnvVars$ = this.appEnvVars.pagination$.pipe(map( ev => !!(getCurrentPageRequestInfo(ev).busy && ev.ids[ev.currentPage]) ), startWith(false), publishReplay(1), refCount()); this.isFetchingStats$ = this.appStatsFetching$.pipe(map( appStats => appStats ? getCurrentPageRequestInfo(appStats).busy : false ), startWith(false), publishReplay(1), refCount()); this.applicationUrl$ = this.appSummaryEntityService.entityObs$.pipe( map(({ entity }) => entity), filter(app => !!app), map(applicationSummary => { const routes = applicationSummary.routes ? applicationSummary.routes : []; const nonTCPRoutes = routes.filter(p => p && !isTCPRoute(p.port)); return nonTCPRoutes[0] || null; }), map(entRoute => !!entRoute && !!entRoute && !!entRoute.domain ? getRoute(entRoute.port, entRoute.host, entRoute.path, true, false, entRoute.domain.name) : null ) ); } isEntityComplete(value, requestInfo: { fetching: boolean, }): boolean { if (requestInfo) { return !requestInfo.fetching; } else { return !!value; } } /* * Update an application */ updateApplication( updatedApplication: UpdateApplication, updateEntities?: AppMetadataTypes[], existingApplication?: IApp): Observable<ActionState> { return cfEntityCatalog.application.api.update<ActionState>( this.appGuid, this.cfGuid, { ...updatedApplication }, existingApplication, updateEntities ).pipe( pairwise(), filter(([oldS, newS]) => oldS.busy && !newS.busy), map(([, newS]) => newS), first() ); } }
the_stack
import { ContractRoles } from "../core/classes/contract-roles"; import { SignatureDrop as SignatureDropContract } from "contracts"; import { BigNumber, BigNumberish, BytesLike, constants, ethers, utils, } from "ethers"; import { ContractMetadata } from "../core/classes/contract-metadata"; import { ContractRoyalty } from "../core/classes/contract-royalty"; import { ContractWrapper } from "../core/classes/contract-wrapper"; import { IStorage } from "../core/interfaces/IStorage"; import { NetworkOrSignerOrProvider, TransactionResult, TransactionResultWithId, } from "../core/types"; import { DropErc721ContractSchema } from "../schema/contracts/drop-erc721"; import { SDKOptions } from "../schema/sdk-options"; import { CommonNFTInput, NFTMetadata, NFTMetadataInput, NFTMetadataOwner, } from "../schema/tokens/common"; import { DEFAULT_QUERY_ALL_COUNT, QueryAllParams } from "../types/QueryParams"; import { DropSingleClaimConditions } from "../core/classes/drop-single-claim-conditions"; import { Erc721 } from "../core/classes/erc-721"; import { ContractPrimarySale } from "../core/classes/contract-sales"; import { prepareClaim } from "../common/claim-conditions"; import { ContractEncoder } from "../core/classes/contract-encoder"; import { Erc721Enumerable } from "../core/classes/erc-721-enumerable"; import { Erc721Supply } from "../core/classes/erc-721-supply"; import { GasCostEstimator } from "../core/classes/gas-cost-estimator"; import { ClaimVerification } from "../types"; import { ContractEvents } from "../core/classes/contract-events"; import { ContractPlatformFee } from "../core/classes/contract-platform-fee"; import { ContractInterceptor } from "../core/classes/contract-interceptor"; import { getRoleHash } from "../common"; import { TokensClaimedEvent, TokensLazyMintedEvent, } from "contracts/DropERC721"; import { ContractAnalytics } from "../core/classes/contract-analytics"; import { Erc721WithQuantitySignatureMinting } from "../core/classes/erc-721-with-quantity-signature-minting"; import { DelayedReveal } from "../core/index"; /** * Setup a collection of NFTs where when it comes to minting, you can authorize * some external party to mint tokens on your contract, and specify what exactly * will be minted by that external party.. * * @example * * ```javascript * import { ThirdwebSDK } from "@thirdweb-dev/sdk"; * * const sdk = new ThirdwebSDK("rinkeby"); * const contract = sdk.getSignatureDrop("{{contract_address}}"); * ``` * * @internal */ export class SignatureDrop extends Erc721<SignatureDropContract> { static contractType = "signature-drop" as const; static contractRoles = ["admin", "minter", "transfer"] as const; static contractAbi = require("../../abis/SignatureDrop.json"); /** * @internal */ static schema = DropErc721ContractSchema; public encoder: ContractEncoder<SignatureDropContract>; public estimator: GasCostEstimator<SignatureDropContract>; public metadata: ContractMetadata< SignatureDropContract, typeof SignatureDrop.schema >; public sales: ContractPrimarySale<SignatureDropContract>; public platformFees: ContractPlatformFee<SignatureDropContract>; public events: ContractEvents<SignatureDropContract>; public roles: ContractRoles< SignatureDropContract, typeof SignatureDrop.contractRoles[number] >; public analytics: ContractAnalytics<SignatureDropContract>; /** * @internal */ public interceptor: ContractInterceptor<SignatureDropContract>; /** * Configure royalties * @remarks Set your own royalties for the entire contract or per token * @example * ```javascript * // royalties on the whole contract * contract.royalties.setDefaultRoyaltyInfo({ * seller_fee_basis_points: 100, // 1% * fee_recipient: "0x..." * }); * // override royalty for a particular token * contract.royalties.setTokenRoyaltyInfo(tokenId, { * seller_fee_basis_points: 500, // 5% * fee_recipient: "0x..." * }); * ``` */ public royalties: ContractRoyalty< SignatureDropContract, typeof SignatureDrop.schema >; /** * Configure claim conditions * @remarks Define who can claim NFTs in the collection, when and how many. * @example * ```javascript * const presaleStartTime = new Date(); * const claimCondition = { * startTime: presaleStartTime, // start the presale now * maxQuantity: 2, // limit how many mints for this presale * price: 0.01, // presale price * snapshot: ['0x...', '0x...'], // limit minting to only certain addresses * }; * await contract.claimCondition.set(claimCondition); * ``` */ public claimCondition: DropSingleClaimConditions<SignatureDropContract>; /** * Delayed reveal * @remarks Create a batch of encrypted NFTs that can be revealed at a later time. * @example * ```javascript * // the real NFTs, these will be encrypted until you reveal them * const realNFTs = [{ * name: "Common NFT #1", * description: "Common NFT, one of many.", * image: fs.readFileSync("path/to/image.png"), * }, { * name: "Super Rare NFT #2", * description: "You got a Super Rare NFT!", * image: fs.readFileSync("path/to/image.png"), * }]; * // A placeholder NFT that people will get immediately in their wallet, and will be converted to the real NFT at reveal time * const placeholderNFT = { * name: "Hidden NFT", * description: "Will be revealed next week!" * }; * // Create and encrypt the NFTs * await contract.revealer.createDelayedRevealBatch( * placeholderNFT, * realNFTs, * "my secret password", * ); * // Whenever you're ready, reveal your NFTs at any time * const batchId = 0; // the batch to reveal * await contract.revealer.reveal(batchId, "my secret password"); * ``` */ public revealer: DelayedReveal<SignatureDropContract>; /** * Signature Minting * @remarks Generate dynamic NFTs with your own signature, and let others mint them using that signature. * @example * ```javascript * // see how to craft a payload to sign in the `contract.signature.generate()` documentation * const signedPayload = contract.signature.generate(payload); * * // now anyone can mint the NFT * const tx = contract.signature.mint(signedPayload); * const receipt = tx.receipt; // the mint transaction receipt * const mintedId = tx.id; // the id of the NFT minted * ``` */ public signature: Erc721WithQuantitySignatureMinting; private _query = this.query as Erc721Supply; private _owned = this._query.owned as Erc721Enumerable; constructor( network: NetworkOrSignerOrProvider, address: string, storage: IStorage, options: SDKOptions = {}, contractWrapper = new ContractWrapper<SignatureDropContract>( network, address, SignatureDrop.contractAbi, options, ), ) { super(contractWrapper, storage, options); this.metadata = new ContractMetadata( this.contractWrapper, SignatureDrop.schema, this.storage, ); this.roles = new ContractRoles( this.contractWrapper, SignatureDrop.contractRoles, ); this.royalties = new ContractRoyalty(this.contractWrapper, this.metadata); this.sales = new ContractPrimarySale(this.contractWrapper); this.analytics = new ContractAnalytics(this.contractWrapper); this.encoder = new ContractEncoder(this.contractWrapper); this.estimator = new GasCostEstimator(this.contractWrapper); this.events = new ContractEvents(this.contractWrapper); this.platformFees = new ContractPlatformFee(this.contractWrapper); this.interceptor = new ContractInterceptor(this.contractWrapper); this.revealer = new DelayedReveal(this, this.contractWrapper, this.storage); this.signature = new Erc721WithQuantitySignatureMinting( this.contractWrapper, this.roles, this.storage, ); this.claimCondition = new DropSingleClaimConditions( this.contractWrapper, this.metadata, this.storage, ); } /** ****************************** * READ FUNCTIONS *******************************/ /** * Get All Minted NFTs * * @remarks Get all the data associated with every NFT in this contract. * * By default, returns the first 100 NFTs, use queryParams to fetch more. * * @example * ```javascript * const nfts = await contract.getAll(); * console.log(nfts); * ``` * @param queryParams - optional filtering to only fetch a subset of results. * @returns The NFT metadata for all NFTs queried. */ public async getAll( queryParams?: QueryAllParams, ): Promise<NFTMetadataOwner[]> { return this._query.all(queryParams); } /** * Get Owned NFTs * * @remarks Get all the data associated with the NFTs owned by a specific wallet. * * @example * ```javascript * // Address of the wallet to get the NFTs of * const address = "{{wallet_address}}"; * const nfts = await contract.getOwned(address); * console.log(nfts); * ``` * @param walletAddress - the wallet address to query, defaults to the connected wallet * @returns The NFT metadata for all NFTs in the contract. */ public async getOwned(walletAddress?: string): Promise<NFTMetadataOwner[]> { return this._owned.all(walletAddress); } /** * {@inheritDoc Erc721Enumerable.tokendIds} */ public async getOwnedTokenIds(walletAddress?: string): Promise<BigNumber[]> { return this._owned.tokenIds(walletAddress); } /** * Get the total count NFTs in this drop contract, both claimed and unclaimed */ public async totalSupply() { const claimed = await this.totalClaimedSupply(); const unclaimed = await this.totalUnclaimedSupply(); return claimed.add(unclaimed); } /** * Get All Claimed NFTs * * @remarks Fetch all the NFTs (and their owners) that have been claimed in this Drop. * * * @example * ```javascript * const claimedNFTs = await contract.getAllClaimed(); * const firstOwner = claimedNFTs[0].owner; * ``` * * @param queryParams - optional filtering to only fetch a subset of results. * @returns The NFT metadata and their ownersfor all NFTs queried. */ public async getAllClaimed( queryParams?: QueryAllParams, ): Promise<NFTMetadataOwner[]> { const start = BigNumber.from(queryParams?.start || 0).toNumber(); const count = BigNumber.from( queryParams?.count || DEFAULT_QUERY_ALL_COUNT, ).toNumber(); const maxId = Math.min( (await this.contractWrapper.readContract.nextTokenIdToMint()).toNumber(), start + count, ); return await Promise.all( Array.from(Array(maxId).keys()).map((i) => this.get(i.toString())), ); } /** * Get All Unclaimed NFTs * * @remarks Fetch all the NFTs that have been not been claimed yet in this Drop. * * * @example * ```javascript * const unclaimedNFTs = await contract.getAllUnclaimed(); * const firstUnclaimedNFT = unclaimedNFTs[0].name; * ``` * * @param queryParams - optional filtering to only fetch a subset of results. * @returns The NFT metadata for all NFTs queried. */ public async getAllUnclaimed( queryParams?: QueryAllParams, ): Promise<NFTMetadata[]> { const start = BigNumber.from(queryParams?.start || 0).toNumber(); const count = BigNumber.from( queryParams?.count || DEFAULT_QUERY_ALL_COUNT, ).toNumber(); const firstTokenId = BigNumber.from( Math.max( ( await this.contractWrapper.readContract.nextTokenIdToMint() ).toNumber(), start, ), ); const maxId = BigNumber.from( Math.min( ( await this.contractWrapper.readContract.nextTokenIdToMint() ).toNumber(), firstTokenId.toNumber() + count, ), ); return await Promise.all( Array.from(Array(maxId.sub(firstTokenId).toNumber()).keys()).map((i) => this.getTokenMetadata(firstTokenId.add(i).toString()), ), ); } /** * Get the claimed supply * * @remarks Get the number of claimed NFTs in this Drop. * * * @example * ```javascript * const claimedNFTCount = await contract.totalClaimedSupply(); * console.log(`NFTs claimed so far: ${claimedNFTCount}`); * ``` * @returns the claimed supply */ public async totalClaimedSupply(): Promise<BigNumber> { const claimCondition = await this.contractWrapper.readContract.claimCondition(); return claimCondition.supplyClaimed; } /** * Get the unclaimed supply * * @remarks Get the number of unclaimed NFTs in this Drop. * * * @example * ```javascript * const unclaimedNFTCount = await contract.totalUnclaimedSupply(); * console.log(`NFTs left to claim: ${unclaimedNFTCount}`); * ``` * @returns the unclaimed supply */ public async totalUnclaimedSupply(): Promise<BigNumber> { const maxSupply = await this.contractWrapper.readContract.nextTokenIdToMint(); return maxSupply.sub(await this.totalClaimedSupply()); } /** * Get whether users can transfer NFTs from this contract */ public async isTransferRestricted(): Promise<boolean> { const anyoneCanTransfer = await this.contractWrapper.readContract.hasRole( getRoleHash("transfer"), constants.AddressZero, ); return !anyoneCanTransfer; } /** ****************************** * WRITE FUNCTIONS *******************************/ /** * Create a batch of unique NFTs to be claimed in the future * * @remarks Create batch allows you to create a batch of many unique NFTs in one transaction. * * @example * ```javascript * // Custom metadata of the NFTs to create * const metadatas = [{ * name: "Cool NFT", * description: "This is a cool NFT", * image: fs.readFileSync("path/to/image.png"), // This can be an image url or file * }, { * name: "Cool NFT", * description: "This is a cool NFT", * image: fs.readFileSync("path/to/image.png"), * }]; * * const results = await contract.createBatch(metadatas); // uploads and creates the NFTs on chain * const firstTokenId = results[0].id; // token id of the first created NFT * const firstNFT = await results[0].data(); // (optional) fetch details of the first created NFT * ``` * * @param metadatas - The metadata to include in the batch. */ public async createBatch( metadatas: NFTMetadataInput[], ): Promise<TransactionResultWithId<NFTMetadata>[]> { const startFileNumber = await this.contractWrapper.readContract.nextTokenIdToMint(); const batch = await this.storage.uploadMetadataBatch( metadatas.map((m) => CommonNFTInput.parse(m)), startFileNumber.toNumber(), this.contractWrapper.readContract.address, await this.contractWrapper.getSigner()?.getAddress(), ); const baseUri = batch.baseUri; const receipt = await this.contractWrapper.sendTransaction("lazyMint", [ batch.uris.length, baseUri.endsWith("/") ? baseUri : `${baseUri}/`, ethers.utils.toUtf8Bytes(""), ]); const event = this.contractWrapper.parseLogs<TokensLazyMintedEvent>( "TokensLazyMinted", receipt?.logs, ); const startingIndex = event[0].args.startTokenId; const endingIndex = event[0].args.endTokenId; const results = []; for (let id = startingIndex; id.lte(endingIndex); id = id.add(1)) { results.push({ id, receipt, data: () => this.getTokenMetadata(id), }); } return results; } /** * Claim unique NFTs to a specific Wallet * * @remarks Let the specified wallet claim NFTs. * * @example * ```javascript * const address = "{{wallet_address}}"; // address of the wallet you want to claim the NFTs * const quantity = 1; // how many unique NFTs you want to claim * * const tx = await contract.claimTo(address, quantity); * const receipt = tx.receipt; // the transaction receipt * const claimedTokenId = tx.id; // the id of the NFT claimed * const claimedNFT = await tx.data(); // (optional) get the claimed NFT metadata * ``` * * @param destinationAddress - Address you want to send the token to * @param quantity - Quantity of the tokens you want to claim * @param proofs - Array of proofs * * @returns - an array of results containing the id of the token claimed, the transaction receipt and a promise to optionally fetch the nft metadata */ public async claimTo( destinationAddress: string, quantity: BigNumberish, proofs: BytesLike[] = [utils.hexZeroPad([0], 32)], ): Promise<TransactionResultWithId<NFTMetadataOwner>[]> { const claimVerification = await this.prepareClaim(quantity, proofs); const receipt = await this.contractWrapper.sendTransaction( "claim", [ destinationAddress, quantity, claimVerification.currencyAddress, claimVerification.price, { proof: claimVerification.proofs, maxQuantityInAllowlist: claimVerification.maxQuantityPerTransaction, }, ethers.utils.toUtf8Bytes(""), ], claimVerification.overrides, ); const event = this.contractWrapper.parseLogs<TokensClaimedEvent>( "TokensClaimed", receipt?.logs, ); const startingIndex: BigNumber = event[0].args.startTokenId; const endingIndex = startingIndex.add(quantity); const results = []; for (let id = startingIndex; id.lt(endingIndex); id = id.add(1)) { results.push({ id, receipt, data: () => this.get(id), }); } return results; } /** * Claim NFTs to the connected wallet. * * @remarks See {@link NFTDrop.claimTo} * * @returns - an array of results containing the id of the token claimed, the transaction receipt and a promise to optionally fetch the nft metadata */ public async claim( quantity: BigNumberish, proofs: BytesLike[] = [utils.hexZeroPad([0], 32)], ): Promise<TransactionResultWithId<NFTMetadataOwner>[]> { return this.claimTo( await this.contractWrapper.getSignerAddress(), quantity, proofs, ); } /** * Burn a single NFT * @param tokenId - the token Id to burn */ public async burn(tokenId: BigNumberish): Promise<TransactionResult> { return { receipt: await this.contractWrapper.sendTransaction("burn", [tokenId]), }; } /** ****************************** * PRIVATE FUNCTIONS *******************************/ /** * Returns proofs and the overrides required for the transaction. * * @returns - `overrides` and `proofs` as an object. */ private async prepareClaim( quantity: BigNumberish, proofs: BytesLike[] = [utils.hexZeroPad([0], 32)], ): Promise<ClaimVerification> { return prepareClaim( quantity, await this.claimCondition.get(), (await this.metadata.get()).merkle, 0, this.contractWrapper, this.storage, proofs, ); } }
the_stack
declare namespace Polymer { /** * Use `Polymer.PaperInputBehavior` to implement inputs with `<paper-input-container>`. This * behavior is implemented by `<paper-input>`. It exposes a number of properties from * `<paper-input-container>` and `<input is="iron-input">` and they should be bound in your * template. * * The input element can be accessed by the `inputElement` property if you need to access * properties or methods that are not exposed. */ interface PaperInputBehavior extends Polymer.IronControlState, Polymer.IronA11yKeysBehavior { /** * Set to true to disable this input. If you're using PaperInputBehavior to * implement your own paper-input-like element, bind this to * both the `<paper-input-container>`'s and the input's `disabled` property. */ disabled: boolean|null|undefined; keyBindings: object; /** * The label for this input. If you're using PaperInputBehavior to * implement your own paper-input-like element, bind this to * `<label>`'s content and `hidden` property, e.g. * `<label hidden$="[[!label]]">[[label]]</label>` in your `template` */ label: string|null|undefined; /** * The value for this input. If you're using PaperInputBehavior to * implement your own paper-input-like element, bind this to * the `<iron-input>`'s `bindValue` * property, or the value property of your input that is `notify:true`. */ value: string|null|undefined; /** * Returns true if the value is invalid. If you're using PaperInputBehavior to * implement your own paper-input-like element, bind this to both the * `<paper-input-container>`'s and the input's `invalid` property. * * If `autoValidate` is true, the `invalid` attribute is managed automatically, * which can clobber attempts to manage it manually. */ invalid: boolean|null|undefined; /** * Set this to specify the pattern allowed by `preventInvalidInput`. If * you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `allowedPattern` * property. */ allowedPattern: string|null|undefined; /** * The type of the input. The supported types are the * [native input's types](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_<input>_types). * If you're using PaperInputBehavior to implement your own paper-input-like element, * bind this to the (Polymer 1) `<input is="iron-input">`'s or (Polymer 2) * `<iron-input>`'s `type` property. */ type: string|null|undefined; /** * The datalist of the input (if any). This should match the id of an existing `<datalist>`. * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `list` property. */ list: string|null|undefined; /** * A pattern to validate the `input` with. If you're using PaperInputBehavior to * implement your own paper-input-like element, bind this to * the `<input is="iron-input">`'s `pattern` property. */ pattern: string|null|undefined; /** * Set to true to mark the input as required. If you're using PaperInputBehavior to * implement your own paper-input-like element, bind this to * the `<input is="iron-input">`'s `required` property. */ required: boolean|null|undefined; /** * The error message to display when the input is invalid. If you're using * PaperInputBehavior to implement your own paper-input-like element, * bind this to the `<paper-input-error>`'s content, if using. */ errorMessage: string|null|undefined; /** * Set to true to show a character counter. */ charCounter: boolean|null|undefined; /** * Set to true to disable the floating label. If you're using PaperInputBehavior to * implement your own paper-input-like element, bind this to * the `<paper-input-container>`'s `noLabelFloat` property. */ noLabelFloat: boolean|null|undefined; /** * Set to true to always float the label. If you're using PaperInputBehavior to * implement your own paper-input-like element, bind this to * the `<paper-input-container>`'s `alwaysFloatLabel` property. */ alwaysFloatLabel: boolean|null|undefined; /** * Set to true to auto-validate the input value. If you're using PaperInputBehavior to * implement your own paper-input-like element, bind this to * the `<paper-input-container>`'s `autoValidate` property. */ autoValidate: boolean|null|undefined; /** * Name of the validator to use. If you're using PaperInputBehavior to * implement your own paper-input-like element, bind this to * the `<input is="iron-input">`'s `validator` property. */ validator: string|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `autocomplete` property. */ autocomplete: string|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `autofocus` property. */ autofocus: boolean|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `inputmode` property. */ inputmode: string|null|undefined; /** * The minimum length of the input value. * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `minlength` property. */ minlength: number|null|undefined; /** * The maximum length of the input value. * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `maxlength` property. */ maxlength: number|null|undefined; /** * The minimum (numeric or date-time) input value. * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `min` property. */ min: string|null|undefined; /** * The maximum (numeric or date-time) input value. * Can be a String (e.g. `"2000-01-01"`) or a Number (e.g. `2`). * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `max` property. */ max: string|null|undefined; /** * Limits the numeric or date-time increments. * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `step` property. */ step: string|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `name` property. */ name: string|null|undefined; /** * A placeholder string in addition to the label. If this is set, the label will always float. */ placeholder: string|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `readonly` property. */ readonly: boolean|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `size` property. */ size: number|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `autocapitalize` property. */ autocapitalize: string|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `autocorrect` property. */ autocorrect: string|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `autosave` property, * used with type=search. */ autosave: string|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `results` property, * used with type=search. */ results: number|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the `<input is="iron-input">`'s `accept` property, * used with type=file. */ accept: string|null|undefined; /** * If you're using PaperInputBehavior to implement your own paper-input-like * element, bind this to the`<input is="iron-input">`'s `multiple` property, * used with type=file. */ multiple: boolean|null|undefined; /** * Returns a reference to the input element. */ readonly inputElement: HTMLElement; /** * Returns a reference to the focusable element. */ readonly _focusableElement: HTMLElement; /** * Forward focus to inputElement. Overriden from IronControlState. */ _focusBlurHandler(event: any): void; attached(): void; created(): void; _appendStringWithSpace(str: any, more: any): any; _onAddonAttached(event: any): void; /** * Validates the input element and sets an error style if needed. */ validate(): boolean; /** * Handler that is called when a shift+tab keypress is detected by the menu. * * @param event A key combination event. */ _onShiftTabDown(event: CustomEvent|null): void; /** * If `autoValidate` is true, then validates the element. */ _handleAutoValidate(): void; /** * Restores the cursor to its original position after updating the value. * * @param newValue The value that should be saved. */ updateValueAndPreserveCaret(newValue: string): void; _computeAlwaysFloatLabel(alwaysFloatLabel: any, placeholder: any): any; _updateAriaLabelledBy(): void; _generateInputId(): void; _onChange(event: any): void; _autofocusChanged(): void; } const PaperInputBehavior: object; }
the_stack
'use strict'; import * as vscode from 'vscode'; import * as fs from 'fs'; import { Delayer } from './delayer'; import * as callATD from './callATD'; let DEBUG: boolean = false; interface SpellSettings { language: string, ignoreWordsList: string[]; mistakeTypeToStatus: {}[]; languageIDs: string[]; ignoreRegExp: string[]; } interface SpellProblem { error: string; preContext: string; startLine: number; startChar: number; endLine: number; endChar: number; type: string; message: string; suggestions: string[]; } interface Map<V> { [key: string]: V; } let problems: SpellProblem[] = []; let settings: SpellSettings; let diagnosticMap = {}; let spellDiagnostics: vscode.DiagnosticCollection; let CONFIGFOLDER = "/.vscode"; let CONFIGFILE = "/spell.json"; let statusBarItem: vscode.StatusBarItem; let IsDisabled: boolean = false; enum upgradeAction { Stop, Search } interface UpgradeMessageItem extends vscode.MessageItem { id: upgradeAction; } export default class SpellProvider implements vscode.CodeActionProvider { private validationDelayer: Map<Delayer<void>> = Object.create(null); // key is the URI of the document private static addToDictionaryCmdId: string = 'SpellProvider.addToDictionary'; private static fixOnSuggestionCmdId: string = 'SpellProvider.fixOnSuggestion'; private static changeLanguageCmdId: string = 'SpellProvider.changeLanguage'; private addToDictionaryCmd: vscode.Disposable; private fixOnSuggestionCmd: vscode.Disposable; private changeLanguageCmd: vscode.Disposable; public activate(context: vscode.ExtensionContext) { if (DEBUG) console.log("Spell and Grammar checker active..."); const config = vscode.workspace.getConfiguration('spell'); if (config.get("StopAsking", false)) { // do nothing } else { vscode.window.showWarningMessage<UpgradeMessageItem>( 'The Spell Checker Extension no longer works - please uninstall it and install another one.', { title: "Show Suggested Replacement", id: upgradeAction.Search }, { title: "Don't Ask Again", id: upgradeAction.Stop, isCloseAffordance: true } ).then(selection => { switch (selection && selection.id) { case upgradeAction.Search: var open = require('open'); open('https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker'); break; case upgradeAction.Stop: config.update('StopAsking', true, true); console.log("Wrote setting..."); break; } }); } let subscriptions: vscode.Disposable[] = context.subscriptions; let toggleCmd: vscode.Disposable; vscode.commands.registerCommand("toggleSpell", this.toggleSpell.bind(this)); statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); statusBarItem.command = "toggleSpell"; statusBarItem.tooltip = "Toggle Spell Checker On/Off for supported files"; statusBarItem.show(); settings = this.readSettings(); this.addToDictionaryCmd = vscode.commands.registerCommand(SpellProvider.addToDictionaryCmdId, this.addToDictionary.bind(this)); this.fixOnSuggestionCmd = vscode.commands.registerCommand(SpellProvider.fixOnSuggestionCmdId, this.fixOnSuggestion.bind(this)); this.changeLanguageCmd = vscode.commands.registerCommand(SpellProvider.changeLanguageCmdId, this.changeLanguage.bind(this)); subscriptions.push(this); spellDiagnostics = vscode.languages.createDiagnosticCollection('Spell'); vscode.workspace.onDidOpenTextDocument(this.TriggerDiagnostics, this, subscriptions) vscode.workspace.onDidChangeTextDocument(this.TriggerDiffDiagnostics, this, subscriptions) vscode.workspace.onDidSaveTextDocument(this.TriggerDiagnostics, this, subscriptions) vscode.workspace.onDidCloseTextDocument((textDocument) => { spellDiagnostics.delete(textDocument.uri); }, null, subscriptions); if (vscode.window.activeTextEditor) { this.TriggerDiagnostics(vscode.window.activeTextEditor.document); } for (let i = 0; i < settings.languageIDs.length; i++) { if (DEBUG) console.log("Code Actons Registering for: " + settings.languageIDs[i]); vscode.languages.registerCodeActionsProvider(settings.languageIDs[i], this); } } public toggleSpell() { if (IsDisabled) { IsDisabled = false; if (vscode.window.activeTextEditor) { this.TriggerDiagnostics(vscode.window.activeTextEditor.document); } } else { IsDisabled = true; if (DEBUG) console.log("Clearing diagnostics as Spell was disabled.") spellDiagnostics.clear(); } this.updateStatus(); } public updateStatus() { if (IsDisabled) { statusBarItem.text = `$(book) Spell Disabled [${settings.language}]`; statusBarItem.color = "orange"; } else { statusBarItem.text = `$(book) Spell Enabled [${settings.language}]`; statusBarItem.color = "white"; } } public dispose(): void { spellDiagnostics.clear(); spellDiagnostics.dispose(); statusBarItem.dispose(); this.addToDictionaryCmd.dispose(); this.fixOnSuggestionCmd.dispose(); this.changeLanguageCmd.dispose(); } public provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext, token: vscode.CancellationToken): vscode.Command[] { let diagnostic: vscode.Diagnostic = context.diagnostics[0]; let match: string[] = diagnostic.message.match(/\[([a-zA-Z0-9\ ]+)\]\ \-/); let error: string = ''; // should always be true if (match.length >= 2) error = match[1]; if (error.length == 0) return undefined; // Get suggestions from suggestion string match = diagnostic.message.match(/\[([a-zA-Z0-9,\ ]+)\]$/); let suggestionstring: string = ''; let commands: vscode.Command[] = []; // Add each suggestion if (match && match.length >= 2) { suggestionstring = match[1]; let suggestions: string[] = suggestionstring.split(/\,\ /g); // Add suggestions to command list suggestions.forEach(function (suggestion) { commands.push({ title: 'Replace with \'' + suggestion + '\'', command: SpellProvider.fixOnSuggestionCmdId, arguments: [document, diagnostic, error, suggestion] }); }); } // Add ignore command commands.push({ title: 'Add \'' + error + '\' to ignore list', command: SpellProvider.addToDictionaryCmdId, arguments: [document, error] }); return commands; } // Itterate through the errors and populate the diagnostics - this has a delayer to lower the traffic private TriggerDiagnostics(document: vscode.TextDocument) { // Do nothing if the doc type is not one we should test if (settings.languageIDs.indexOf(document.languageId) === -1) { // if(DEBUG) console.log("Hiding status due to language ID [" + document.languageId + "]"); // //statusBarItem.hide(); return; } else { this.updateStatus(); // statusBarItem.show(); } if (IsDisabled) return; let d = this.validationDelayer[document.uri.toString()]; if (!d) { d = new Delayer<any>(150); this.validationDelayer[document.uri.toString()] = d; } d.trigger(() => { this.CreateDiagnostics(document); delete this.validationDelayer[document.uri.toString()]; }); } // NOT GOOD :( private TriggerDiffDiagnostics(event: vscode.TextDocumentChangeEvent) { this.TriggerDiagnostics(event.document); } // Itterate through the errors and populate the diagnostics private CreateDiagnostics(document: vscode.TextDocument) { let diagnostics: vscode.Diagnostic[] = []; let docToCheck = document.getText(); if (DEBUG) console.log("Starting new check on: " + document.fileName + " [" + document.languageId + "]"); problems = []; // removeUnwantedText before processing the spell checker ignores a lot of chars so removing them aids in problem matching docToCheck = this.removeUnwantedText(docToCheck); docToCheck = docToCheck.replace(/[\"!#$%&()*+,.\/:;<=>?@\[\]\\^_{|}]/g, " "); this.spellcheckDocument(docToCheck, (problems) => { for (let x = 0; x < problems.length; x++) { let problem = problems[x]; if (settings.ignoreWordsList.indexOf(problem.error) === -1) { if (this.convertSeverity(problem.type) !== -1) { let lineRange = new vscode.Range(problem.startLine, problem.startChar, problem.endLine, problem.endChar); let loc = new vscode.Location(document.uri, lineRange); let diag = new vscode.Diagnostic(lineRange, problem.message, this.convertSeverity(problem.type)); diagnostics.push(diag); } } } spellDiagnostics.set(document.uri, diagnostics); diagnosticMap[document.uri.toString()] = diagnostics; }); } private addToDictionary(document: vscode.TextDocument, word: string): any { if (DEBUG) console.log("Attempting to add to dictionary: " + word) // only add if it's not already there if (settings.ignoreWordsList.indexOf(word) === -1) { if (DEBUG) console.log("Word is not found in current dictionary -> adding") settings.ignoreWordsList.push(word); this.writeSettings(); } this.TriggerDiagnostics(document); } private writeSettings(): void { try { fs.mkdirSync(vscode.workspace.rootPath + CONFIGFOLDER); if (DEBUG) console.log("Created new settings folder: " + CONFIGFOLDER); vscode.window.showInformationMessage("SPELL: Created a new settings file: " + CONFIGFOLDER + CONFIGFILE) } catch (e) { if (DEBUG) console.log("Folder for settings existed: " + CONFIGFOLDER); } fs.writeFileSync(vscode.workspace.rootPath + CONFIGFOLDER + CONFIGFILE, JSON.stringify(settings, null, 2)); if (DEBUG) console.log("Settings written to: " + CONFIGFILE); } private fixOnSuggestion(document: vscode.TextDocument, diagnostic: vscode.Diagnostic, error: string, suggestion: string): any { if (DEBUG) console.log("Attempting to fix file:" + document.uri.toString()); let docError: string = document.getText(diagnostic.range); if (error == docError) { // Remove diagnostic from list let diagnostics: vscode.Diagnostic[] = diagnosticMap[document.uri.toString()]; let index: number = diagnostics.indexOf(diagnostic); diagnostics.splice(index, 1); // Update with new diagnostics diagnosticMap[document.uri.toString()] = diagnostics; spellDiagnostics.set(document.uri, diagnostics); // Insert the new text let edit = new vscode.WorkspaceEdit(); edit.replace(document.uri, diagnostic.range, suggestion); return vscode.workspace.applyEdit(edit); } else { vscode.window.showErrorMessage('The suggestion was not applied because it is out of date.'); } } private readSettings(): SpellSettings { let cfg: any = readJsonFile(vscode.workspace.rootPath + CONFIGFOLDER + CONFIGFILE); function readJsonFile(file): any { let cfg; try { cfg = JSON.parse(fs.readFileSync(file).toString()); if (DEBUG) console.log("Settings read from: " + file) } catch (err) { if (DEBUG) console.log("Default Settings") cfg = JSON.parse('{\ "version": "0.1.0", \ "language": "en", \ "ignoreWordsList": [], \ "mistakeTypeToStatus": { \ "Passive voice": "Hint", \ "Spelling": "Error", \ "Complex Expression": "Disable", \ "Hidden Verbs": "Information", \ "Hyphen Required": "Disable", \ "Redundant Expression": "Disable", \ "Did you mean...": "Disable", \ "Repeated Word": "Warning", \ "Missing apostrophe": "Warning", \ "Cliches": "Disable", \ "Missing Word": "Disable", \ "Make I uppercase": "Warning" \ },\ "languageIDs": ["markdown","plaintext"],\ "ignoreRegExp": [ \ "/\\\\(.*\\\\.(jpg|jpeg|png|md|gif|JPG|JPEG|PNG|MD|GIF)\\\\)/g", \ "/((http|https|ftp|git)\\\\S*)/g" \ ]\ }'); } //gracefully handle new fields if (cfg.languageIDs === undefined) cfg.languageIDs = ["markdown"]; if (cfg.language === undefined) cfg.language = "en"; if (cfg.ignoreRegExp === undefined) cfg.ignoreRegExp = []; return cfg; } return { language: cfg.language, ignoreWordsList: cfg.ignoreWordsList, mistakeTypeToStatus: cfg.mistakeTypeToStatus, languageIDs: cfg.languageIDs, ignoreRegExp: cfg.ignoreRegExp } } private convertSeverity(mistakeType: string): number { let mistakeTypeToStatus: {}[] = settings.mistakeTypeToStatus; switch (mistakeTypeToStatus[mistakeType]) { case "Warning": return vscode.DiagnosticSeverity.Warning; case "Information": return vscode.DiagnosticSeverity.Information; case "Error": return vscode.DiagnosticSeverity.Error; case "Hint": return vscode.DiagnosticSeverity.Hint; default: return -1; // used for 'Disabled' or no setting } } // ATD does not return a line number and results are not in order - most code is about 'guessing' a line number private spellcheckDocument(content: string, cb: (report: SpellProblem[]) => void): void { let problemMessage: string; let detectedErrors: any = {}; callATD.check(settings.language, content, function (error, docProblems) { if (error != null) console.log(error); if (docProblems != null) { for (let i = 0; i < docProblems.length; i++) { let problem = docProblems[i]; let problemTXT = problem.string; let problemPreContext: string = (typeof problem.precontext !== "object") ? problem.precontext + " " : ""; let problemWithPreContent: string = problemPreContext + problemTXT; let problemSuggestions: string[] = []; let startPosInFile: number = -1; // Check to see if this error has been seen before for improved uniqueness if (detectedErrors[problemWithPreContent] > 0) { startPosInFile = nthOccurrence(content, problemTXT, problemPreContext, detectedErrors[problemWithPreContent] + 1); } else { startPosInFile = nthOccurrence(content, problemTXT, problemPreContext, 1); } if (startPosInFile !== -1) { let linesToMistake: String[] = content.substring(0, startPosInFile).split('\n'); let numberOfLinesToMistake: number = linesToMistake.length - 1; if (!detectedErrors[problemWithPreContent]) detectedErrors[problemWithPreContent] = 1; else ++detectedErrors[problemWithPreContent]; // make the suggestions an array even if only one is returned if (String(problem.suggestions) !== "undefined") { if (Array.isArray(problem.suggestions.option)) problemSuggestions = problem.suggestions.option; else problemSuggestions = [problem.suggestions.option]; } problems.push({ error: problemTXT, preContext: problemPreContext, startLine: numberOfLinesToMistake, startChar: linesToMistake[numberOfLinesToMistake].length, endLine: numberOfLinesToMistake, endChar: linesToMistake[numberOfLinesToMistake].length + problemTXT.length, type: problem.description, message: problem.description + " [" + problemTXT + "] - suggest [" + problemSuggestions.join(", ") + "]", suggestions: problemSuggestions }); } } cb(problems); } }); function nthOccurrence(content, problem, preContext, occuranceNo) { let firstIndex = -1; let regex = new RegExp(preContext + "[ ]*" + problem, "g"); let m = regex.exec(content); if (m !== null) { let matchTXT = m[0]; // adjust for any precontent and padding firstIndex = m.index + m[0].match(/^\s*/)[0].length; if (preContext !== "") { let regex2 = new RegExp(preContext + "[ ]*", "g"); let m2 = regex2.exec(matchTXT); firstIndex += m2[0].length; } } let lengthUpToFirstIndex = firstIndex + 1; if (occuranceNo == 1) { return firstIndex; } else { let stringAfterFirstOccurrence = content.slice(lengthUpToFirstIndex); let nextOccurrence = nthOccurrence(stringAfterFirstOccurrence, problem, preContext, occuranceNo - 1); if (nextOccurrence === -1) { return -1; } else { return lengthUpToFirstIndex + nextOccurrence; } } } } private removeUnwantedText(content: string): string { let match; let expressions = settings.ignoreRegExp; for (let x = 0; x < expressions.length; x++) { // Convert the JSON of regExp Strings into a real RegExp let flags = expressions[x].replace(/.*\/([gimy]*)$/, '$1'); let pattern = expressions[x].replace(new RegExp('^/(.*?)/' + flags + '$'), '$1'); pattern = pattern.replace(/\\\\/g, "\\"); let regex = new RegExp(pattern, flags); if (DEBUG) console.log("Ignoreing [" + expressions[x] + "]"); match = content.match(regex); if (match !== null) { if (DEBUG) console.log("Found [" + match.length + "] matches for removal"); // look for a multi line match and build enough lines into the replacement for (let i = 0; i < match.length; i++) { let spaces: string; let lines = match[i].split("\n").length; if (lines > 1) { spaces = new Array(lines).join("\n"); } else { spaces = new Array(match[i].length + 1).join(" "); } content = content.replace(match[i], spaces); } } } return content; } public changeLanguage() { let items: vscode.QuickPickItem[] = []; items.push({ label: getLanguageDescription("en"), description: "en" }); items.push({ label: getLanguageDescription("fr"), description: "fr" }); items.push({ label: getLanguageDescription("de"), description: "de" }); items.push({ label: getLanguageDescription("pt"), description: "pt" }); items.push({ label: getLanguageDescription("es"), description: "es" }); let index: number; for (let i = 0; i < items.length; i++) { let element = items[i]; if (element.description == settings.language) { index = i; break; } } items.splice(index, 1); // replace the text with the selection vscode.window.showQuickPick(items).then((selection) => { if (!selection) return; settings.language = selection.description; if (DEBUG) console.log("Attempting to change to: " + settings.language); this.writeSettings(); vscode.window.showInformationMessage("To start checking in " + getLanguageDescription(settings.language) + " reload window by pressing 'F1' + 'Reload Window'.") }); function getLanguageDescription(initial: string): string { switch (initial) { case "en": return "English"; case "fr": return "French"; case "de": return "German"; case "pt": return "Portuguese"; case "es": return "Spanish"; default: return "English"; } } } }
the_stack
import callbackQueue from 'callback-queue'; import SKU from 'tf2-sku'; import pluralize from 'pluralize'; import request from '@nicklason/request-retry'; import async from 'async'; import Bot = require('./Bot'); import log from '../lib/logger'; import { exponentialBackoff } from '../lib/helpers'; import { Entry } from './Pricelist'; import moment from 'moment'; export = class Listings { private readonly bot: Bot; private checkingAllListings = false; private removingAllListings = false; private cancelCheckingListings = false; private autoRelistEnabled = false; private autoRelistTimeout; private templates: { buy: string; sell: string } = { buy: process.env.BPTF_DETAILS_BUY || 'I am buying your %name% for %price%, I have %current_stock% / %max_stock%.', sell: process.env.BPTF_DETAILS_SELL || 'I am selling my %name% for %price%, I am selling %amount_trade%.' }; constructor(bot: Bot) { this.bot = bot; } setupAutorelist(): void { if (process.env.AUTOBUMP !== 'true' || process.env.DISABLE_LISTINGS === 'true') { // Autobump is not enabled return; } // Autobump is enabled, add heartbeat listener this.bot.listingManager.removeListener('heartbeat', this.checkAccountInfo.bind(this)); this.bot.listingManager.on('heartbeat', this.checkAccountInfo.bind(this)); // Get account info this.checkAccountInfo(); } private enableAutoRelist(): void { if (this.autoRelistEnabled || process.env.DISABLE_LISTINGS === 'true') { return; } log.debug('Enabled autorelist'); this.autoRelistEnabled = true; clearTimeout(this.autoRelistTimeout); const doneWait = (): void => { async.eachSeries( [ (callback): void => { this.redoListings().asCallback(callback); }, (callback): void => { this.waitForListings().asCallback(callback); } ], (item, callback) => { if (this.bot.botManager.isStopping()) { return; } item(callback); }, () => { log.debug('Done relisting'); if (this.autoRelistEnabled) { log.debug('Waiting 30 minutes before relisting again'); this.autoRelistTimeout = setTimeout(doneWait, 30 * 60 * 1000); } } ); }; this.autoRelistTimeout = setTimeout(doneWait, 30 * 60 * 1000); } private checkAccountInfo(): void { log.debug('Checking account info'); this.getAccountInfo().asCallback((err, info) => { if (err) { log.warn('Failed to get account info from backpack.tf: ', err); return; } if (this.autoRelistEnabled && info.premium === 1) { log.warn('Disabling autorelist! - Your account is premium, no need to forcefully bump listings'); this.disableAutoRelist(); } else if (!this.autoRelistEnabled && info.premium !== 1) { log.warn( 'Enabling autorelist! - Consider paying for backpack.tf premium instead of forcefully bumping listings: https://backpack.tf/donate' ); this.enableAutoRelist(); } }); } private disableAutoRelist(): void { clearTimeout(this.autoRelistTimeout); this.autoRelistEnabled = false; log.debug('Disabled autorelist'); } private getAccountInfo(): Promise<any> { return new Promise((resolve, reject) => { const steamID64 = this.bot.manager.steamID.getSteamID64(); const options = { url: 'https://backpack.tf/api/users/info/v1', method: 'GET', qs: { key: process.env.BPTF_API_KEY, steamids: steamID64 }, gzip: true, json: true }; request(options, function(err, reponse, body) { if (err) { return reject(err); } return resolve(body.users[steamID64]); }); }); } checkBySKU(sku: string, data?: Entry | null): void { if (process.env.DISABLE_LISTINGS === 'true') { return; } const item = SKU.fromString(sku); const match = data && data.enabled === false ? null : this.bot.pricelist.getPrice(sku, true); let hasBuyListing = item.paintkit !== null; let hasSellListing = false; const amountCanBuy = this.bot.inventoryManager.amountCanTrade(sku, true); const amountCanSell = this.bot.inventoryManager.amountCanTrade(sku, false); this.bot.listingManager.findListings(sku).forEach(listing => { if (listing.intent === 1 && hasSellListing) { // Alrready have a sell listing, remove the listing listing.remove(); return; } if (listing.intent === 0) { hasBuyListing = true; } else if (listing.intent === 1) { hasSellListing = true; } if (match === null || (match.intent !== 2 && match.intent !== listing.intent)) { // We are not trading the item, remove the listing listing.remove(); } else if ((listing.intent === 0 && amountCanBuy <= 0) || (listing.intent === 1 && amountCanSell <= 0)) { // We are not buying / selling more, remove the listing listing.remove(); } else { const newDetails = this.getDetails(listing.intent, match); if (listing.details !== newDetails) { // Listing details don't match, update listing with new details and price const currencies = match[listing.intent === 0 ? 'buy' : 'sell']; listing.update({ time: match.time || moment().unix(), details: newDetails, currencies: currencies }); } } }); if (match !== null && match.enabled === true) { const assetids = this.bot.inventoryManager.getInventory().findBySKU(sku, true); // TODO: Check if we are already making a listing for same type of item + intent if (!hasBuyListing && amountCanBuy > 0) { // We have no buy order and we can buy more items, create buy listing this.bot.listingManager.createListing({ time: match.time || moment().unix(), sku: sku, intent: 0, details: this.getDetails(0, match), currencies: match.buy }); } if (!hasSellListing && amountCanSell > 0) { // We have no sell order and we can sell items, create sell listing this.bot.listingManager.createListing({ time: match.time || moment().unix(), id: assetids[assetids.length - 1], intent: 1, details: this.getDetails(1, match), currencies: match.sell }); } } } checkAll(): Promise<void> { return new Promise(resolve => { if (process.env.DISABLE_LISTINGS === 'true') { return resolve(); } log.debug('Checking all'); const doneRemovingAll = (): void => { const next = callbackQueue.add('checkAllListings', function() { resolve(); }); if (next === false) { return; } this.checkingAllListings = true; const inventory = this.bot.inventoryManager.getInventory(); const pricelist = this.bot.pricelist.getPrices().sort((a, b) => { return inventory.findBySKU(b.sku).length - inventory.findBySKU(a.sku).length; }); log.debug('Checking listings for ' + pluralize('item', pricelist.length, true) + '...'); this.recursiveCheckPricelist(pricelist).asCallback(() => { log.debug('Done checking all'); // Done checking all listings this.checkingAllListings = false; next(); }); }; if (!this.removingAllListings) { doneRemovingAll(); return; } callbackQueue.add('removeAllListings', () => { doneRemovingAll(); }); }); } private recursiveCheckPricelist(pricelist: Entry[]): Promise<void> { return new Promise(resolve => { let index = 0; const iteration = (): void => { if (pricelist.length <= index || this.cancelCheckingListings) { this.cancelCheckingListings = false; return resolve(); } setImmediate(() => { this.checkBySKU(pricelist[index].sku, pricelist[index]); index++; iteration(); }); }; iteration(); }); } removeAll(): Promise<void> { return new Promise((resolve, reject) => { if (this.checkingAllListings) { this.cancelCheckingListings = true; } log.debug('Removing all listings'); // Ensures that we don't to remove listings multiple times const next = callbackQueue.add('removeAllListings', function(err) { if (err) { return reject(err); } return resolve(null); }); if (next === false) { // Function was already called return; } this.removeAllListings().asCallback(next); }); } private removeAllListings(): Promise<void> { return new Promise((resolve, reject) => { this.removingAllListings = true; // Clear create queue this.bot.listingManager.actions.create = []; // Wait for backpack.tf to finish creating / removing listings this.waitForListings().then(() => { if (this.bot.listingManager.listings.length === 0) { log.debug('We have no listings'); this.removingAllListings = false; return resolve(); } log.debug('Removing all listings...'); // Remove all current listings this.bot.listingManager.listings.forEach(listing => listing.remove()); // Clear timeout clearTimeout(this.bot.listingManager._timeout); // Remove listings this.bot.listingManager._processActions(err => { if (err) { return reject(err); } // The request might fail, if it does we will try again return resolve(this.removeAllListings()); }); }); }); } redoListings(): Promise<void> { return this.removeAll().then(() => { return this.checkAll(); }); } waitForListings(): Promise<void> { return new Promise((resolve, reject) => { let checks = 0; const check = (): void => { checks++; log.debug('Checking listings...'); const prevCount = this.bot.listingManager.listings.length; this.bot.listingManager.getListings(err => { if (err) { return reject(err); } if (this.bot.listingManager.listings.length !== prevCount) { log.debug( 'Count changed: ' + this.bot.listingManager.listings.length + ' listed, ' + prevCount + ' previously' ); setTimeout(() => { check(); }, exponentialBackoff(checks)); } else { log.debug("Count didn't change"); return resolve(); } }); }; check(); }); } private getDetails(intent: 0 | 1, entry: Entry): string { const buying = intent === 0; const key = buying ? 'buy' : 'sell'; const details = this.templates[key] .replace(/%price%/g, entry[key].toString()) .replace(/%name%/g, entry.name) .replace(/%max_stock%/g, entry.max.toString()) .replace( /%current_stock%/g, this.bot.inventoryManager .getInventory() .getAmount(entry.sku) .toString() ) .replace(/%amount_trade%/g, this.bot.inventoryManager.amountCanTrade(entry.sku, buying).toString()); return details; } };
the_stack
import * as React from 'react'; import { useTranslation } from 'react-i18next'; import { useLocation, useHistory } from 'react-router-dom'; import { CommandBar, ChoiceGroup, IChoiceGroupOption, Checkbox } from '@fluentui/react'; import { ResourceKeys } from '../../../../../localization/resourceKeys'; import { getDeviceIdFromQueryString } from '../../../../shared/utils/queryStringHelper'; import { CANCEL, SAVE } from '../../../../constants/iconNames'; import { SynchronizationStatus } from '../../../../api/models/synchronizationStatus'; import { ROUTE_PARAMS } from '../../../../constants/routes'; import { MaskedCopyableTextField } from '../../../../shared/components/maskedCopyableTextField'; import { HeaderView } from '../../../../shared/components/headerView'; import { DeviceAuthenticationType } from '../../../../api/models/deviceAuthenticationType'; import { validateThumbprint, validateKey, validateModuleIdentityName, processThumbprint } from '../../../../shared/utils/utils'; import { useAsyncSagaReducer } from '../../../../shared/hooks/useAsyncSagaReducer'; import { addModuleIdentityReducer } from '../reducer'; import { addModuleIdentitySaga } from '../saga'; import { addModuleStateInitial } from '../state'; import { addModuleIdentityAction } from '../actions'; import '../../../../css/_deviceDetail.scss'; const initialKeyValue = { error: '', thumbprint: '', thumbprintError: '', value: '' }; export const AddModuleIdentity: React.FC = () => { const { t } = useTranslation(); const { search, pathname } = useLocation(); const history = useHistory(); const deviceId = getDeviceIdFromQueryString(search); const [ localState, dispatch ] = useAsyncSagaReducer(addModuleIdentityReducer, addModuleIdentitySaga, addModuleStateInitial(), 'addModuleState'); const { synchronizationStatus } = localState; const [ authenticationType, setAuthenticationType ] = React.useState(DeviceAuthenticationType.SymmetricKey); const [ autoGenerateKeys, setautoGenerateKeys ] = React.useState<boolean>(true); const [ module, setModule ] = React.useState<{ id: string, error: string }>({ id: '', error: ''}); const [ primaryKey, setPrimaryKey ] = React.useState(initialKeyValue); const [ secondaryKey, setSecondaryKey ] = React.useState(initialKeyValue); React.useEffect(() => { if (synchronizationStatus === SynchronizationStatus.upserted) { // only when module identity has been added successfully would navigate to module list view navigateToModuleList(); } }, [synchronizationStatus]); const showCommandBar = () => { return ( <CommandBar className="command" items={[ { ariaLabel: t(ResourceKeys.moduleIdentity.command.save), disabled: disableSaveButton(), iconProps: {iconName: SAVE}, key: SAVE, name: t(ResourceKeys.moduleIdentity.command.save), onClick: handleSave }, { ariaLabel: t(ResourceKeys.moduleIdentity.command.cancel), iconProps: {iconName: CANCEL}, key: CANCEL, name: t(ResourceKeys.moduleIdentity.command.cancel), onClick: navigateToModuleList } ]} /> ); }; const showModuleId = () => { return ( <MaskedCopyableTextField ariaLabel={t(ResourceKeys.moduleIdentity.moduleId)} label={t(ResourceKeys.moduleIdentity.moduleId)} value={module.id} required={true} onTextChange={changeModuleIdentityName} allowMask={false} readOnly={false} error={!!module.error ? t(module.error) : ''} labelCallout={t(ResourceKeys.moduleIdentity.moduleIdTooltip)} setFocus={true} /> ); }; const getAuthType = () => { return ( <ChoiceGroup label={t(ResourceKeys.moduleIdentity.authenticationType.text)} selectedKey={authenticationType} onChange={changeAuthenticationType} options={ [ { key: DeviceAuthenticationType.SymmetricKey, text: t(ResourceKeys.moduleIdentity.authenticationType.symmetricKey.type) }, { key: DeviceAuthenticationType.SelfSigned, text: t(ResourceKeys.moduleIdentity.authenticationType.selfSigned.type) }, { key: DeviceAuthenticationType.CACertificate, text: t(ResourceKeys.moduleIdentity.authenticationType.ca.type) } ] } required={true} /> ); }; const renderSymmetricKeySection = () => { return ( <> <MaskedCopyableTextField ariaLabel={t(ResourceKeys.moduleIdentity.authenticationType.symmetricKey.primaryKey)} label={t(ResourceKeys.moduleIdentity.authenticationType.symmetricKey.primaryKey)} value={primaryKey.value} required={true} onTextChange={changePrimaryKey} allowMask={true} readOnly={false} error={!!primaryKey.error ? t(primaryKey.error) : ''} labelCallout={t(ResourceKeys.moduleIdentity.authenticationType.symmetricKey.primaryKeyTooltip)} /> <MaskedCopyableTextField ariaLabel={t(ResourceKeys.moduleIdentity.authenticationType.symmetricKey.secondaryKey)} label={t(ResourceKeys.moduleIdentity.authenticationType.symmetricKey.secondaryKey)} value={secondaryKey.value} required={true} onTextChange={changeSecondaryKey} allowMask={true} readOnly={false} error={!!secondaryKey.error ? t(secondaryKey.error) : ''} labelCallout={t(ResourceKeys.moduleIdentity.authenticationType.symmetricKey.secondaryKeyTooltip)} /> </> ); }; const renderSelfSignedSection = () => { return ( <> <MaskedCopyableTextField ariaLabel={t(ResourceKeys.moduleIdentity.authenticationType.selfSigned.primaryThumbprint)} label={t(ResourceKeys.moduleIdentity.authenticationType.selfSigned.primaryThumbprint)} value={primaryKey.thumbprint} required={true} onTextChange={changePrimaryThumbprint} allowMask={true} readOnly={false} error={!!primaryKey.thumbprintError ? t(primaryKey.thumbprintError) : ''} labelCallout={t(ResourceKeys.moduleIdentity.authenticationType.selfSigned.primaryThumbprintTooltip)} /> <MaskedCopyableTextField ariaLabel={t(ResourceKeys.moduleIdentity.authenticationType.selfSigned.secondaryThumbprint)} label={t(ResourceKeys.moduleIdentity.authenticationType.selfSigned.secondaryThumbprint)} value={secondaryKey.thumbprint} required={true} onTextChange={changeSecondaryThumbprint} allowMask={true} readOnly={false} error={!!secondaryKey.thumbprintError ? t(secondaryKey.thumbprintError) : ''} labelCallout={t(ResourceKeys.moduleIdentity.authenticationType.selfSigned.secondaryThumbprintTooltip)} /> </> ); }; const showAuthentication = () => { return ( <div className="authentication"> {getAuthType()} {authenticationType === DeviceAuthenticationType.SymmetricKey && <> <Checkbox className="autoGenerateButton" label={t(ResourceKeys.moduleIdentity.authenticationType.symmetricKey.autoGenerate)} checked={autoGenerateKeys} onChange={changeAutoGenerateKeys} /> {!autoGenerateKeys && renderSymmetricKeySection() } </> } {authenticationType === DeviceAuthenticationType.SelfSigned && renderSelfSignedSection() } </div> ); }; const handleSave = () => { dispatch(addModuleIdentityAction.started({ authentication: { symmetricKey: authenticationType === DeviceAuthenticationType.SymmetricKey ? { primaryKey: autoGenerateKeys ? null : primaryKey.value, secondaryKey: autoGenerateKeys ? null : secondaryKey.value } : null, type: authenticationType.toString(), x509Thumbprint: authenticationType === DeviceAuthenticationType.SelfSigned ? { primaryThumbprint: processThumbprint(primaryKey.thumbprint), secondaryThumbprint: processThumbprint(secondaryKey.thumbprint) } : null, }, deviceId, moduleId: module.id })); }; const navigateToModuleList = () => { const path = pathname.replace(/\/add\/.*/, ``); history.push(`${path}/?${ROUTE_PARAMS.DEVICE_ID}=${encodeURIComponent(deviceId)}`); }; const disableSaveButton = () => { if (!module.id || !validateModuleIdentityName(module.id)) { return true; } if (authenticationType === DeviceAuthenticationType.SymmetricKey) { return !isSymmetricKeyValid(); } if (authenticationType === DeviceAuthenticationType.SelfSigned) { return !isSelfSignedThumbprintValid(); } return false; }; const isSymmetricKeyValid = () => { if (!autoGenerateKeys) { return primaryKey.value && secondaryKey.value && validateKey(primaryKey.value) && validateKey(secondaryKey.value); } return true; }; const isSelfSignedThumbprintValid = () => { return primaryKey.thumbprint && secondaryKey.thumbprint && validateThumbprint(primaryKey.thumbprint) && validateThumbprint(secondaryKey.thumbprint); }; const changeModuleIdentityName = (newValue?: string) => { const moduleIdError = getModuleIdentityNameValidationMessage(newValue); setModule({ error: moduleIdError, id: newValue }); }; const changeAuthenticationType = (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, option?: IChoiceGroupOption) => { setAuthenticationType(option.key as DeviceAuthenticationType); }; const changeAutoGenerateKeys = (ev?: React.FormEvent<HTMLElement | HTMLInputElement>, checked?: boolean) => { setautoGenerateKeys(checked); if (checked) { setPrimaryKey(initialKeyValue); setSecondaryKey(initialKeyValue); } }; const changePrimaryKey = (newValue?: string) => { const primaryKeyError = getSymmetricKeyValidationMessage(newValue); setPrimaryKey({ ...primaryKey, error: primaryKeyError, value: newValue }); }; const changeSecondaryKey = (newValue?: string) => { const secondaryKeyError = getSymmetricKeyValidationMessage(newValue); setSecondaryKey({ ...secondaryKey, error: secondaryKeyError, value: newValue }); }; const changePrimaryThumbprint = (newValue?: string) => { const primaryThumbprintError = getThumbprintValidationMessage(newValue); setPrimaryKey({ ...primaryKey, thumbprint: newValue, thumbprintError: primaryThumbprintError }); }; const changeSecondaryThumbprint = (newValue?: string) => { const secondaryThumbprintError = getThumbprintValidationMessage(newValue); setSecondaryKey({ ...secondaryKey, thumbprint: newValue, thumbprintError: secondaryThumbprintError }); }; const getThumbprintValidationMessage = (value: string) => { return validateThumbprint(value) ? '' : ResourceKeys.moduleIdentity.validation.invalidThumbprint; }; const getModuleIdentityNameValidationMessage = (value: string) => { return validateModuleIdentityName(value) ? '' : ResourceKeys.moduleIdentity.validation.invalidModuleIdentityName; }; const getSymmetricKeyValidationMessage = (value: string): string => { return autoGenerateKeys ? '' : validateKey(value) ? '' : ResourceKeys.moduleIdentity.validation.invalidKey; }; return ( <> {showCommandBar()} <HeaderView headerText={ResourceKeys.moduleIdentity.headerText} /> <div className="device-detail"> {showModuleId()} {showAuthentication()} </div> </> ); };
the_stack
import React from 'react'; import { CellMeasurerCache, SortDirection, SortDirectionType, Table } from 'react-virtualized'; import memoize from 'lodash/memoize'; import { styleSheetDataTable as styleSheet } from './styles'; import sortData from './helpers/sortData'; import expandData from './helpers/expandData'; import { indexData } from './helpers/indexData'; import { DataTableProps, DefaultDataTableProps, ExpandedRow, IndexedParentRow, ParentRow, RowStyles, } from './types'; import ColumnLabels from './ColumnLabels'; import TableHeader from './TableHeader'; import renderDataColumns from './columns/renderDataColumns'; import renderExpandableColumn from './columns/renderExpandableColumn'; import withStyles, { WithStylesProps } from '../../composers/withStyles'; import { getRowColor, getHeight, getKeys } from './helpers'; import { HEIGHT_TO_PX } from './constants'; export type DataTableState = { expandedRows: Set<number>; sortBy: string; sortDirection: SortDirectionType; }; /** A dynamic and responsive table for displaying tabular data. */ export class DataTable extends React.Component<DataTableProps & WithStylesProps, DataTableState> { static defaultProps: Pick<DataTableProps, DefaultDataTableProps> = { autoHeight: false, columnHeaderHeight: undefined, columnLabelCase: '', columnMetadata: {}, columnToLabel: {}, data: [], defaultDynamicRowHeight: 16, dynamicRowHeight: false, expandable: false, filterData: (data: IndexedParentRow[]) => data, height: 400, keys: [], minimumDynamicRowHeight: undefined, onRowClick: () => {}, overscanRowCount: 2, renderers: {}, rowHeight: 'regular', showAllRows: false, showColumnDividers: false, showRowDividers: false, sortByOverride: '', sortCallback: () => {}, sortDirectionOverride: SortDirection.ASC, sortOverride: false, tableHeaderHeight: undefined, tableHeaderLabel: '', width: 0, zebra: false, }; state: DataTableState = { expandedRows: new Set(), sortBy: this.props.sortByOverride || '', sortDirection: this.props.sortDirectionOverride!, }; timeoutId: number = 0; constructor(props: DataTableProps & WithStylesProps) { super(props); if (this.props.dataTableRef) { this.props.dataTableRef(this); } } keys = getKeys(this.props.keys!, this.props.data!); private getRowStyle = (expandedDataList: ExpandedRow[]) => ({ index, }: { index: number; }): RowStyles => ({ background: getRowColor( expandedDataList[index], index, this.props.zebra || false, this.props.theme, ), display: 'flex', flexDirection: 'row', alignItems: 'center', borderBottom: this.props.showRowDividers ? '1px solid' : '', borderColor: this.props.theme!.color.core.neutral[1], outline: 'none', }); private getData = memoize( ( data: ParentRow[], sortBy: string, sortDirection: SortDirectionType, sortByCacheKey?: string, // used only in the memoize cache key below ): IndexedParentRow[] => { const { sortByValue } = this.props; const indexedData = indexData(data); const sortedData = sortData(indexedData, this.keys, sortBy, sortDirection, sortByValue); return sortedData; }, (...args) => JSON.stringify(args), ); componentDidUpdate(prevProps: DataTableProps, prevState: DataTableState) { const { dynamicRowHeight, data, filterData, width, height, sortByCacheKey } = this.props; const { sortBy, sortDirection } = this.state; const dimensionsChanged = width !== prevProps.width || height !== prevProps.height; const sortChanged = sortByCacheKey !== prevProps.sortByCacheKey; const sortedData: IndexedParentRow[] = this.getData( data!, sortBy, sortDirection, sortByCacheKey, ); const filteredData = filterData!(sortedData); const oldFilteredData = prevProps.filterData!(sortedData); const filteredDataChanged = filteredData.length > 0 && (filteredData.length !== oldFilteredData.length || filteredData.some( (x: IndexedParentRow, i: number) => x.metadata.originalIndex !== oldFilteredData[i].metadata.originalIndex, )); if (this.props.data !== prevProps.data) { this.keys = getKeys(this.props.keys!, this.props.data!); this.setState({ expandedRows: new Set(), }); } else if (dynamicRowHeight && (filteredDataChanged || dimensionsChanged || sortChanged)) { // We need to make sure the cache is cleared before React tries to re-render. if (!this.timeoutId) { this.timeoutId = window.setTimeout(() => { this.cache.clearAll(); this.forceUpdate(); this.timeoutId = 0; }); } } } componentWillUnmount() { if (this.timeoutId) window.clearTimeout(this.timeoutId); } private getTableHeight = (expandedDataList: ExpandedRow[]): number => { const { height, rowHeight, showAllRows, dynamicRowHeight } = this.props; // @ts-ignore _rowHeightCache is missing from DataTable types // eslint-disable-next-line no-underscore-dangle const rowHeights: { [key: number]: number } = this.cache._rowHeightCache; if (showAllRows) { if (dynamicRowHeight) { if (Object.values(rowHeights).length > 0) { const totalHeight = Object.values(rowHeights).reduce( (sum: number, measuredRowHeight: number) => sum + measuredRowHeight, 0, ); return totalHeight + this.getColumnHeaderHeight(); } this.forceUpdate(); } else { return expandedDataList.length * getHeight(rowHeight) + this.getColumnHeaderHeight(); } } return height || 0; }; private getColumnHeaderHeight = () => { const { columnHeaderHeight, rowHeight } = this.props; return getHeight(rowHeight, columnHeaderHeight); }; private shouldRenderTableHeader = () => { return !!this.props.tableHeaderLabel; }; private sort = ({ sortBy, sortDirection, }: { sortBy: string; sortDirection: SortDirectionType; }): void => { this.cache.clearAll(); const { sortOverride, sortCallback } = this.props; if (sortOverride && sortCallback) { sortCallback(sortBy, sortDirection); } else { this.setState({ sortBy, sortDirection, }); } }; private expandRow = (newExpandedRowOriginalIndex: number) => ( event: React.SyntheticEvent<EventTarget>, ) => { const { dynamicRowHeight } = this.props; event.stopPropagation(); this.setState(({ expandedRows }) => { const newExpandedRows = new Set(expandedRows); if (expandedRows.has(newExpandedRowOriginalIndex)) { newExpandedRows.delete(newExpandedRowOriginalIndex); } else { newExpandedRows.add(newExpandedRowOriginalIndex); } return { expandedRows: newExpandedRows, }; }); if (dynamicRowHeight) { // We need to make sure the cache is cleared before React tries to re-render. if (!this.timeoutId) { this.timeoutId = window.setTimeout(() => { this.cache.clearAll(); this.forceUpdate(); this.timeoutId = 0; }); } } }; private handleRowClick = ({ rowData }: { rowData: ExpandedRow }) => this.props.onRowClick && this.props.onRowClick(rowData); renderTableHeader(parentWidth: number) { const { rowHeight, tableHeaderLabel, tableHeaderHeight } = this.props; return ( <TableHeader tableHeaderLabel={tableHeaderLabel} height={getHeight(rowHeight, tableHeaderHeight)} width={this.props.width ? Math.min(this.props.width, parentWidth) : parentWidth} /> ); } rowGetter = (expandedDataList: ExpandedRow[]) => ({ index }: { index: number }) => expandedDataList[index]; public cache = new CellMeasurerCache({ fixedHeight: false, fixedWidth: true, defaultHeight: this.props.defaultDynamicRowHeight, minHeight: this.props.minimumDynamicRowHeight, }); render() { const { autoHeight, cx, data, dynamicRowHeight, expandable, filterData, height, overscanRowCount, propagateRef, rowHeight, sortByCacheKey, styles, tableHeaderHeight, showAllRows, width, } = this.props; const { expandedRows, sortBy, sortDirection } = this.state; const sortedData: IndexedParentRow[] = this.getData( data!, sortBy, sortDirection, sortByCacheKey, ); const filteredData = filterData!(sortedData); const expandedData = expandData(filteredData, expandedRows, sortBy, this.keys, sortDirection); const tableHeight = autoHeight ? (height || 0) - (this.shouldRenderTableHeader() ? getHeight(rowHeight, tableHeaderHeight) : 0) : this.getTableHeight(expandedData); return ( <> {this.shouldRenderTableHeader() && this.renderTableHeader(width!)} <div className={cx(styles.table_container, { width })}> <Table ref={propagateRef} height={tableHeight} width={width!} rowCount={expandedData.length} rowGetter={this.rowGetter(expandedData)} sort={this.sort} sortBy={sortBy} sortDirection={sortDirection} headerHeight={this.getColumnHeaderHeight()} headerRowRenderer={ColumnLabels(this.props)} rowHeight={dynamicRowHeight ? this.cache.rowHeight : HEIGHT_TO_PX[rowHeight!]} rowStyle={this.getRowStyle(expandedData)} overscanRowCount={ dynamicRowHeight && showAllRows ? expandedData.length : overscanRowCount! } onRowClick={this.handleRowClick} > {expandable && renderExpandableColumn(cx, styles, expandedRows, this.expandRow)} {renderDataColumns(this.keys, this.cache, this.props)} </Table> </div> </> ); } } export default withStyles(styleSheet, { passThemeProp: true, })(DataTable);
the_stack
import { asyncExec, Rect, initalPropsOf } from './utils'; import { BitmapDescriptor, CameraPosition, CameraUpdate, CancelableCallback, CircleOptions, ComputeDistanceResult, ErrorCodes, GroundOverlayOptions, HuaweiMap, HuaweiMapOptions, InfoWindowAdapter, LatLng, LatLngBounds, LocationSource, MapEvent, MapType, MarkerOptions, Point, PolygonOptions, PolylineOptions, Projection, RepetitiveTile, SnapshotResult, TileOverlayOptions, TileType, UiSettings, URLTile, VisibleRegion } from './interfaces'; import { Circle, CircleImpl } from './circle'; import { Marker, MarkerImpl } from './marker'; import { GroundOverlay, GroundOverlayImpl } from './groundOverlay'; import { TileOverlay, TileOverlayImpl } from './tileOverlay'; import { Polygon, PolygonImpl } from './polygon'; import { Polyline, PolylineImpl } from './polyline'; export { Polyline, ButtCap, CustomCap, RoundCap, SquareCap, Cap } from './polyline'; export { Polygon } from './polygon'; export { Circle } from './circle'; export { TileOverlay } from './tileOverlay'; export { GroundOverlay } from './groundOverlay'; export { Marker } from './marker'; export { AnimationSet, RotateAnimation, AlphaAnimation, ScaleAnimation, TranslateAnimation, InterpolatorType, ErrorCodes, CameraMoveStartedReason, Color, MapType, MapEvent, JointType, Hue, PatternItemType, HuaweiMap, CameraUpdate, Tile, URLTile, RepetitiveTile, TileType, AnimationConstant } from './interfaces'; export const maps: Map<number, HuaweiMap> = new Map<number, HuaweiMapImpl>(); export function sync(mapId: number, mapDiv: string, components: any) { if (!maps.has(mapId)) { const huaweiMap: HuaweiMap = new HuaweiMapImpl(mapDiv, mapId); maps.set(mapId, huaweiMap); } const map = maps.get(mapId); const hashMap = (<HuaweiMapImpl>map).components; for (let i = 0; i < components.length; i++) { if (hashMap.has(components[i]['_id'])) continue; let obj = null; let id: string = components[i]['_id']; if (components[i]['_type'] === "circle") obj = new CircleImpl(mapDiv, mapId, id); else if (components[i]['_type'] === 'marker') obj = new MarkerImpl(mapDiv, mapId, id); else if (components[i]['_type'] === 'polygon') obj = new PolygonImpl(mapDiv, mapId, id); else if (components[i]['_type'] === 'polyline') obj = new PolylineImpl(mapDiv, mapId, id); else if (components[i]['_type'] === 'groundOverlay') obj = new GroundOverlayImpl(mapDiv, mapId, id); else if (components[i]['_type'] === 'tileOverlay') obj = new TileOverlayImpl(mapDiv, mapId, id); hashMap.set(components[i]['_id'], obj); } } export async function getMap(divId: string, huaweiMapOptions: HuaweiMapOptions): Promise<HuaweiMap> { const mapElement = document.getElementById(divId); if (!mapElement) return Promise.reject(ErrorCodes.toString(ErrorCodes.NO_DOM_ELEMENT_FOUND)); const initialProps = initalPropsOf(mapElement); const mapId = await asyncExec('HMSMap', 'initMap', [divId, { 'mapOptions': huaweiMapOptions, 'initialProps': initialProps }]); const huaweiMap: HuaweiMap = new HuaweiMapImpl(divId, mapId); maps.set(huaweiMap.getId(), huaweiMap); return huaweiMap; } export async function showMap(divId: string): Promise<HuaweiMap> { if (!document.getElementById(divId)) return Promise.reject(ErrorCodes.toString(ErrorCodes.NO_DOM_ELEMENT_FOUND)); const mapId = await asyncExec("HMSMap", "showMap", [divId]); const currentMap: HuaweiMap | undefined = maps.get(mapId); if (currentMap == undefined) return Promise.reject(ErrorCodes.toString(ErrorCodes.NO_DOM_ELEMENT_FOUND)); currentMap.startOverlayInterval(); currentMap.startObserver(); return currentMap; } export async function hasPermission(): Promise<boolean> { const json = await asyncExec("HMSMap", "hasPermission", []); return json.result; } export async function requestPermission(): Promise<void> { return asyncExec("HMSMap", "requestPermission", []); } export async function computeDistanceBetween(from: LatLng, to: LatLng): Promise<ComputeDistanceResult> { return asyncExec("HMSMap", "computeDistanceBetween", [{ "from": from, "to": to }]); } export async function setApiKey(apiKey: string): Promise<void> { return asyncExec("HMSMap", "setApiKey", [{ "apiKey": apiKey }]); } export function disableLogger(): Promise<void> { return asyncExec('HMSMap', 'disableLogger', []); } export function enableLogger(): Promise<void> { return asyncExec('HMSMap', 'enableLogger', []); } async function forceUpdateXAndY(x: number, y: number, mapDivId: string): Promise<void> { return asyncExec("HMSMap", "forceUpdateXAndY", [mapDivId, x, y]); } async function forceUpdateWidthAndHeight(width: number, height: number, mapDivId: string): Promise<void> { return asyncExec("HMSMap", "forceUpdateWidthAndHeight", [mapDivId, width, height]); } interface OverlapState { rect: Rect; visited: boolean; count: number; } class MapOverlayCache { private readonly mapDivId: string; private readonly mapElement: HTMLElement; private lastRectsRecord: Map<string, OverlapState> = new Map(); private rects: Map<string, OverlapState> = new Map(); private interval: number = -1; constructor(mapDivId: string, mapElement: HTMLElement) { this.mapDivId = mapDivId; this.mapElement = mapElement; } private syncWithJava() { /** * Find and send the Rect information of added/updated/deleted HTML Elements which intersects with map. */ let diffToAdd = []; let diffToDelete = []; for (let [key, value] of this.rects) { if(!this.lastRectsRecord.has(key)) { diffToAdd.push(value.rect); } else { this.lastRectsRecord.delete(key); } } for (let [key, value] of this.lastRectsRecord) { diffToDelete.push(value.rect); } if(diffToAdd.length>0 || diffToDelete.length>0){ asyncExec("HMSMap", "updateOverlappingHTMLElements", [this.mapDivId, diffToAdd, diffToDelete]); } this.lastRectsRecord.clear(); this.lastRectsRecord = new Map(this.rects); } private mapOverlayInterval() { this.fillCacheRecursively(document.body); this.refreshCache(); this.syncWithJava(); } private refreshCache() { for(let [key, value] of this.rects) { if(!value.visited) { this.removeRect(key, value); } else { value.visited = false; this.rects.set(key, value); } } } private removeRect(key: string, value: OverlapState) { if(value.count > 1) { value.count--; this.rects.set(key, value); } else { this.rects.delete(key); } } private fillCacheRecursively(element: HTMLElement) { for(let i=0; i < element.children.length; i++) { this.fillCacheRecursively(<HTMLElement>element.children[i]); } if(element.id === this.mapDivId) return; const curr: Rect = Rect.fromDomRect(element.getBoundingClientRect()); const map: Rect = Rect.fromDomRect(this.mapElement.getBoundingClientRect()); if(map.intersects(curr) && this.isAboveMap(element)) { let val = this.rects.get(curr.hashCode()); if (val == undefined) { this.rects.set(curr.hashCode(), {rect: curr, visited: true, count: 1}); } else { val.count = val.visited ? val.count+1 : 1; val.visited = true; this.rects.set(curr.hashCode(), val); } } } private isAboveMap(element: HTMLElement): boolean { const isParentOfMap = element.compareDocumentPosition(this.mapElement) & Node.DOCUMENT_POSITION_CONTAINED_BY; const elemZIndex = window.getComputedStyle(element).zIndex; if( !Boolean(isParentOfMap) && !isNaN(parseInt(elemZIndex)) && parseInt(elemZIndex) > 0) return true; const isMapCreatedBefore = element.compareDocumentPosition(this.mapElement) & Node.DOCUMENT_POSITION_PRECEDING; return Boolean(isMapCreatedBefore); } startInterval(){ this.interval = setInterval(() => this.mapOverlayInterval(), 100); } stopInterval(){ if(this.interval !== -1) clearInterval(this.interval); } } class MapDomChangeListener { private readonly mapDivId: string; private readonly mapElement: HTMLElement; private mapDomChangeObserver: MutationObserver; private mapDivRectCache: DOMRect; constructor(mapDivId: string, mapElement: HTMLElement) { this.mapDivId = mapDivId; this.mapElement = mapElement; this.mapDivRectCache = this.mapElement.getBoundingClientRect(); this.mapDomChangeObserver = this.createObserver(); } private addWindowResizeListener() { window.onresize = () => {this.updateWidthAndHeight()}; } private removeWindowResizeListener() { window.onresize = null; } private createObserver(): MutationObserver { return new MutationObserver(mutations => { this.updateXAndY(); this.updateWidthAndHeight(); }); } startListener() { this.mapDomChangeObserver.observe(document.body, { attributes: true, childList: true, subtree: true }); this.addWindowResizeListener(); } stopListener() { this.mapDomChangeObserver.disconnect(); this.removeWindowResizeListener(); } private updateWidthAndHeight() { const width = parseInt(window.getComputedStyle(this.mapElement, null).getPropertyValue('width')); const height = parseInt(window.getComputedStyle(this.mapElement, null).getPropertyValue('height')); if(this.mapDivRectCache.width != width || this.mapDivRectCache.height != height) { forceUpdateWidthAndHeight(width, height, this.mapDivId).then(() => { this.mapDivRectCache.width = width; this.mapDivRectCache.height = height; }); } } private updateXAndY() { const mapRect = this.mapElement.getBoundingClientRect(); const x = mapRect.x; const y = mapRect.y; if(this.mapDivRectCache.x != x || this.mapDivRectCache.y != y) { forceUpdateXAndY(x, y, this.mapDivId).then(() => { this.mapDivRectCache.x = x; this.mapDivRectCache.y = y; }); } } } class HuaweiMapImpl implements HuaweiMap { public readonly components: Map<string, any> = new Map<string, any>(); private readonly id: number; private readonly divId: string; private readonly uiSettings: UiSettings; private readonly projection: Projection; private readonly mapElement: HTMLElement; private readonly overlay: MapOverlayCache; private readonly mapListener: MapDomChangeListener; constructor(divId: string, mapId: number) { console.log(`Huawei map constructed with the div id ${divId} :: and the props ${mapId}`); this.id = mapId; this.divId = divId; this.projection = new ProjectionImpl(divId); this.uiSettings = new UiSettingsImpl(divId); const tempElement: HTMLElement | null = document.getElementById(this.divId); if (tempElement == null) throw Error(`Specified map div could not find: ${divId}`); this.mapElement = tempElement; this.overlay = new MapOverlayCache(divId, this.mapElement); this.mapListener = new MapDomChangeListener(divId, this.mapElement); this.startOverlayInterval(); this.startObserver(); } startOverlayInterval(): void { this.overlay.startInterval(); } startObserver(): void { this.mapListener.startListener(); } // IONIC FRAMEWORK SCROLL EVENT scroll(): void { if (this.mapElement == null) return; const mapRect = this.mapElement.getBoundingClientRect(); forceUpdateXAndY(mapRect.x, mapRect.y, this.divId); } syncDimensions(): void { if (this.mapElement == null) return; const width = parseInt(window.getComputedStyle(this.mapElement, null).getPropertyValue('width')); const height = parseInt(window.getComputedStyle(this.mapElement, null).getPropertyValue('height')); forceUpdateWidthAndHeight(width, height, this.divId); } async destroyMap(): Promise<void> { this.components.clear(); maps.delete(this.id); this.overlay.stopInterval(); this.mapListener.stopListener(); return asyncExec("HMSMap", "destroyMap", [this.divId]); } async hideMap(): Promise<void> { this.overlay.stopInterval(); this.mapListener.startListener(); return asyncExec("HMSMap", "hideMap", [this.divId]); } async on(event: MapEvent, callback: (val: any) => void): Promise<void> { const fixedFunctionNameForJavaScript: string = `${event}_${this.id}`; const fixedFunctionNameForJava: string = `set${event[0].toUpperCase()}${event.substr(1)}Listener`; return asyncExec('HMSMap', 'mapOptions', [this.divId, 'setListener', fixedFunctionNameForJava, { 'content': callback.toString() }]) .then(value => { window.subscribeHMSEvent(fixedFunctionNameForJavaScript, callback); }).catch(err => console.log(err)); } async setMapPointersEnabled(mapPointersEnabled: boolean): Promise<void> { return asyncExec('HMSMap', 'setMapPointersEnabled', [this.divId, mapPointersEnabled]); } async isMapPointersEnabled(): Promise<boolean> { const json = await asyncExec('HMSMap', 'isMapPointersEnabled', [this.divId]); return json.result; } async addCircle(circleOptions: CircleOptions): Promise<Circle> { if (!circleOptions["center"]) return Promise.reject(ErrorCodes.toString(ErrorCodes.CENTER_PROPERTY_MUST_DEFINED)); const componentId = await asyncExec('HMSMap', 'addComponent', [this.divId, "CIRCLE", circleOptions]); const circle: Circle = new CircleImpl(this.divId, this.id, componentId); this.components.set(circle.getId(), circle); return circle; } async addMarker(markerOptions: MarkerOptions): Promise<Marker> { if (!markerOptions["position"]) return Promise.reject(ErrorCodes.toString(ErrorCodes.POSITION_PROPERTY_MUST_DEFINED)); const componentId = await asyncExec('HMSMap', 'addComponent', [this.divId, "MARKER", markerOptions]); const marker: Marker = new MarkerImpl(this.divId, this.id, componentId); this.components.set(marker.getId(), marker); return marker; } async addGroundOverlay(groundOverlayOptions: GroundOverlayOptions): Promise<GroundOverlay> { if (!groundOverlayOptions["position"]) return Promise.reject(ErrorCodes.toString(ErrorCodes.POSITION_PROPERTY_MUST_DEFINED)); const componentId = await asyncExec('HMSMap', 'addComponent', [this.divId, "GROUND_OVERLAY", groundOverlayOptions]); const groundOverlay: GroundOverlay = new GroundOverlayImpl(this.divId, this.id, componentId); this.components.set(groundOverlay.getId(), groundOverlay); return groundOverlay; } async addTileOverlay(tileOverlayOptions: TileOverlayOptions): Promise<TileOverlay> { const componentId = await asyncExec('HMSMap', 'addComponent', [this.divId, "TILE_OVERLAY", tileOverlayOptions]); const tileOverlay: TileOverlay = new TileOverlayImpl(this.divId, this.id, componentId); this.components.set(tileOverlay.getId(), tileOverlay); return tileOverlay; } async addPolygon(polygonOptions: PolygonOptions): Promise<Polygon> { if (!polygonOptions["points"]) return Promise.reject(ErrorCodes.toString(ErrorCodes.POINTS_PROPERTY_MUST_DEFINED)); const componentId = await asyncExec('HMSMap', 'addComponent', [this.divId, "POLYGON", polygonOptions]); const polygon: Polygon = new PolygonImpl(this.divId, this.id, componentId); this.components.set(polygon.getId(), polygon); return polygon; } async addPolyline(polylineOptions: PolylineOptions): Promise<Polyline> { if (!polylineOptions["points"]) return Promise.reject(ErrorCodes.toString(ErrorCodes.POINTS_PROPERTY_MUST_DEFINED)); const componentId = await asyncExec('HMSMap', 'addComponent', [this.divId, "POLYLINE", polylineOptions]); const polyline: Polyline = new PolylineImpl(this.divId, this.id, componentId); this.components.set(polyline.getId(), polyline); return polyline; } animateCamera(cameraUpdate: CameraUpdate): Promise<void>; animateCamera(cameraUpdate: CameraUpdate, cancelableCallback: CancelableCallback): Promise<void>; animateCamera(cameraUpdate: CameraUpdate, cancelableCallback?: CancelableCallback, durationMs?: number): Promise<void> { const onFinishEventForJavascript = `${MapEvent.ON_CANCELABLE_CALLBACK_FINISH}_${this.id}`; const onCancelEventForJavascript = `${MapEvent.ON_CANCELABLE_CALLBACK_CANCEL}_${this.id}`; const props: any = {}; if (cancelableCallback != undefined) { window.subscribeHMSEvent(onFinishEventForJavascript, cancelableCallback.onFinish); window.subscribeHMSEvent(onCancelEventForJavascript, cancelableCallback.onCancel); if (cancelableCallback.onFinish != undefined) props["isOnFinish"] = true; if (cancelableCallback.onCancel != undefined) props["isOnCancel"] = true; if (durationMs) props["duration"] = durationMs; } return (<CameraUpdateImpl>cameraUpdate).animateCamera(this.divId, props); } moveCamera(cameraUpdate: CameraUpdate): Promise<void> { return (<CameraUpdateImpl>cameraUpdate).moveCamera(this.divId); } clear(): Promise<void> { this.components.clear(); return this.getHuaweiMapOptions('clear'); } resetMinMaxZoomPreference(): Promise<void> { return this.getHuaweiMapOptions('resetMinMaxZoomPreference'); } stopAnimation(): Promise<void> { return this.getHuaweiMapOptions('stopAnimation'); } getCameraPosition(): Promise<CameraPosition> { return this.getHuaweiMapOptions('getCameraPosition'); } getMapType(): Promise<MapType> { return this.getHuaweiMapOptions('getMapType'); } getMaxZoomLevel(): Promise<number> { return this.getHuaweiMapOptions('getMaxZoomLevel'); } getMinZoomLevel(): Promise<number> { return this.getHuaweiMapOptions('getMinZoomLevel'); } getProjection() { return this.projection; } getUiSettings(): UiSettings { return this.uiSettings; } isBuildingsEnabled(): Promise<boolean> { return this.getHuaweiMapOptions('isBuildingsEnabled'); } isMyLocationEnabled(): Promise<boolean> { return this.getHuaweiMapOptions('isMyLocationEnabled'); } isTrafficEnabled(): Promise<boolean> { return this.getHuaweiMapOptions('isTrafficEnabled'); } isIndoorEnabled(): Promise<boolean> { return this.getHuaweiMapOptions('isIndoorEnabled'); } setBuildingsEnabled(buildingsEnabled: boolean): Promise<void> { return this.setHuaweiMapOptions('setBuildingsEnabled', { 'buildingsEnabled': buildingsEnabled }); } setContentDescription(contentDescription: string): Promise<void> { return this.setHuaweiMapOptions('setContentDescription', { 'contentDescription': contentDescription }); } setInfoWindowAdapter(infoWindowAdapter: InfoWindowAdapter): Promise<void> { return this.setHuaweiMapOptions('setInfoWindowAdapter', { 'infoWindowAdapter': infoWindowAdapter }) } setLatLngBoundsForCameraTarget(latLngBounds: LatLngBounds): Promise<void> { return this.setHuaweiMapOptions('setLatLngBoundsForCameraTarget', { 'latLngBounds': latLngBounds }); } setLocationSource(locationSource: LocationSource): Promise<void> { return this.setHuaweiMapOptions('setLocationSource', { 'locationSource': locationSource }); } setMapStyle(mapStyle: MapStyleOptions): Promise<void> { return this.setHuaweiMapOptions('setMapStyle', { 'mapStyle': mapStyle.getResourceName() }); } setMapType(mapType: MapType): Promise<void> { return this.setHuaweiMapOptions('setMapType', { 'mapType': mapType }); } setMarkersClustering(markersClustering: boolean): Promise<void> { return this.setHuaweiMapOptions('setMarkersClustering', { 'markersClustering': markersClustering }); } setMaxZoomPreference(maxZoomPreference: number): Promise<void> { return this.setHuaweiMapOptions('setMaxZoomPreference', { 'maxZoomPreference': maxZoomPreference }); } setMinZoomPreference(minZoomPreference: number): Promise<void> { return this.setHuaweiMapOptions('setMinZoomPreference', { 'minZoomPreference': minZoomPreference }); } setMyLocationEnabled(myLocationEnabled: boolean): Promise<void> { return this.setHuaweiMapOptions('setMyLocationEnabled', { 'myLocationEnabled': myLocationEnabled }); } setPadding(left: number, top: number, right: number, bottom: number): Promise<void> { return this.setHuaweiMapOptions('setPadding', { 'left': left, 'top': top, 'right': right, 'bottom': bottom }); } setTrafficEnabled(trafficEnabled: boolean): Promise<void> { return this.setHuaweiMapOptions('setTrafficEnabled', { 'trafficEnabled': trafficEnabled }); } setPointToCenter(x: number, y: number): Promise<void> { return this.setHuaweiMapOptions('setPointToCenter', { 'x': x, 'y': y }); } getComponent(key: string): any { return this.components.get(key); } getId(): number { return this.id; } snapshot(onReadyCallback: (snapshot: SnapshotResult) => void): Promise<void> { const eventName = `${MapEvent.ON_SNAPSHOT_READY_CALLBACK}_${this.id}`; window.subscribeHMSEvent(eventName, onReadyCallback); return this.getHuaweiMapOptions('snapshot'); } // INTERNAL INTERNAL INTERNAL removeComponent(key: string): void { if (this.components.has(key)) { this.components.get(key).remove(); this.components.delete(key); } else { throw ErrorCodes.toString(ErrorCodes.NO_COMPONENT_EXISTS_GIVEN_ID); } } private setHuaweiMapOptions(func: string, props: any): Promise<void> { return asyncExec("HMSMap", "mapOptions", [this.divId, 'setHuaweiMapOptions', func, props]); } private async getHuaweiMapOptions(func: string): Promise<any> { const result = await asyncExec("HMSMap", "mapOptions", [this.divId, 'getHuaweiMapOptions', func, {}]); return result.value; } } class UiSettingsImpl implements UiSettings { private readonly mapDivId: string; constructor(mapDivId: string) { this.mapDivId = mapDivId; } isCompassEnabled(): Promise<boolean> { return this.getUiSettings('isCompassEnabled'); } isIndoorLevelPickerEnabled(): Promise<boolean> { return this.getUiSettings('isIndoorLevelPickerEnabled'); } isMapToolbarEnabled(): Promise<boolean> { return this.getUiSettings('isMapToolbarEnabled'); } isMyLocationButtonEnabled(): Promise<boolean> { return this.getUiSettings('isMyLocationButtonEnabled'); } isRotateGesturesEnabled(): Promise<boolean> { return this.getUiSettings('isRotateGesturesEnabled'); } isScrollGesturesEnabled(): Promise<boolean> { return this.getUiSettings('isScrollGesturesEnabled'); } isScrollGesturesEnabledDuringRotateOrZoom(): Promise<boolean> { return this.getUiSettings('isScrollGesturesEnabledDuringRotateOrZoom'); } isTiltGesturesEnabled(): Promise<boolean> { return this.getUiSettings('isTiltGesturesEnabled'); } isZoomControlsEnabled(): Promise<boolean> { return this.getUiSettings('isZoomControlsEnabled'); } isZoomGesturesEnabled(): Promise<boolean> { return this.getUiSettings('isZoomGesturesEnabled'); } setAllGesturesEnabled(allGesturesEnabled: boolean): Promise<void> { return this.setUiSettings('setAllGesturesEnabled', { 'allGesturesEnabled': allGesturesEnabled }); } setCompassEnabled(compassEnabled: boolean): Promise<void> { return this.setUiSettings('setCompassEnabled', { 'compassEnabled': compassEnabled }); } setIndoorLevelPickerEnabled(indoorLevelPickerEnabled: boolean): Promise<void> { return this.setUiSettings('setIndoorLevelPickerEnabled', { 'indoorLevelPickerEnabled': indoorLevelPickerEnabled }); } setMapToolbarEnabled(mapToolbarEnabled: boolean): Promise<void> { return this.setUiSettings('setMapToolbarEnabled', { 'mapToolbarEnabled': mapToolbarEnabled }); } setMyLocationButtonEnabled(myLocationButtonEnabled: boolean): Promise<void> { return this.setUiSettings('setMyLocationButtonEnabled', { 'myLocationButtonEnabled': myLocationButtonEnabled }); } setRotateGesturesEnabled(rotateGesturesEnabled: boolean): Promise<void> { return this.setUiSettings("setRotateGesturesEnabled", { 'rotateGesturesEnabled': rotateGesturesEnabled }); } setScrollGesturesEnabled(scrollGesturesEnabled: boolean): Promise<void> { return this.setUiSettings('setScrollGesturesEnabled', { 'scrollGesturesEnabled': scrollGesturesEnabled }); } setScrollGesturesEnabledDuringRotateOrZoom(scrollGesturesEnabledDuringRotateOrZoom: boolean): Promise<void> { return this.setUiSettings('setScrollGesturesEnabledDuringRotateOrZoom', { 'scrollGesturesEnabledDuringRotateOrZoom': scrollGesturesEnabledDuringRotateOrZoom }); } setTiltGesturesEnabled(tiltGesturesEnabled: boolean): Promise<void> { return this.setUiSettings('setTiltGesturesEnabled', { 'tiltGesturesEnabled': tiltGesturesEnabled }); } setZoomControlsEnabled(zoomControlsEnabled: boolean): Promise<void> { return this.setUiSettings('setZoomControlsEnabled', { 'zoomControlsEnabled': zoomControlsEnabled }); } setZoomGesturesEnabled(zoomGesturesEnabled: boolean): Promise<void> { return this.setUiSettings('setZoomGesturesEnabled', { 'zoomGesturesEnabled': zoomGesturesEnabled }); } setGestureScaleByMapCenter(gestureScaleByMapCenterEnabled: boolean): Promise<void> { return this.setUiSettings('setGestureScaleByMapCenter', { 'gestureScaleByMapCenterEnabled': gestureScaleByMapCenterEnabled }); } setMarkerClusterColor(markerClusterColor: number): Promise<void> { return this.setUiSettings('setMarkerClusterColor', { 'markerClusterColor': markerClusterColor }); } setMarkerClusterIcon(markerClusterIcon: BitmapDescriptor): Promise<void> { return this.setUiSettings('setMarkerClusterIcon', { 'markerClusterIcon': markerClusterIcon }); } setMarkerClusterTextColor(markerClusterTextColor: number): Promise<void> { return this.setUiSettings('setMarkerClusterTextColor', { 'markerClusterTextColor': markerClusterTextColor }); } private setUiSettings(func: string, props: any): Promise<void> { return asyncExec('HMSMap', 'mapOptions', [this.mapDivId, 'setUiSettings', func, props]); } private async getUiSettings(func: string) { const result = await asyncExec("HMSMap", "mapOptions", [this.mapDivId, 'getUiSettings', func, {}]); return result.value; } } class CameraUpdateImpl implements CameraUpdate { props: any; event: string = ""; moveCamera(mapId: string): Promise<any> { return asyncExec('HMSMap', 'mapOptions', [mapId, "moveCamera", this.event, this.props]); } animateCamera(mapId: string, props: any): Promise<any> { return asyncExec('HMSMap', 'mapOptions', [mapId, "animateCamera", this.event, { ...this.props, ...props }]); } } export class CameraUpdateFactory { private constructor() { } static newCameraPosition(cameraPosition: CameraPosition): CameraUpdate { return this.constructCameraUpdateImpl("newCameraPosition", { 'cameraPosition': cameraPosition }); } static newLatLng(latLng: LatLng): CameraUpdate { return this.constructCameraUpdateImpl("newLatLng", { 'latLng': latLng }); } static newLatLngBounds(latLngBounds: LatLngBounds, padding: number): CameraUpdate; static newLatLngBounds(latLngBounds: LatLngBounds, padding: number, width?: number, height?: number): CameraUpdate { let props: any = {}; props['bounds'] = latLngBounds; props['padding'] = padding; if (width && height) { props['width'] = width; props['height'] = height; } return this.constructCameraUpdateImpl("newLatLngBounds", props); } static newLatLngZoom(latLng: LatLng, zoom: number): CameraUpdate { return this.constructCameraUpdateImpl("newLatLngZoom", { "latLng": latLng, "zoom": zoom }); } static scrollBy(xPixel: number, yPixel: number): CameraUpdate { return this.constructCameraUpdateImpl("scrollBy", { 'xPixel': xPixel, 'yPixel': yPixel }); } static zoomBy(amount: number): CameraUpdate; static zoomBy(amount: number, focus?: Point): CameraUpdate { let props: any = {}; props['amount'] = amount; if (focus) props['focus'] = focus; return this.constructCameraUpdateImpl("zoomBy", props); } static zoomIn(): CameraUpdate { return this.constructCameraUpdateImpl("zoomIn", {}); } static zoomOut(): CameraUpdate { return this.constructCameraUpdateImpl("zoomOut", {}); } static zoomTo(zoom: number): CameraUpdate { return this.constructCameraUpdateImpl("zoomTo", { "zoom": zoom }); } private static constructCameraUpdateImpl(event: string, props: any): CameraUpdateImpl { let cameraUpdate = new CameraUpdateImpl(); cameraUpdate.event = event; cameraUpdate.props = props; return cameraUpdate; } } class ProjectionImpl implements Projection { private readonly divId: string; constructor(divId: string) { this.divId = divId; } fromScreenLocation(point: Point): Promise<LatLng> { return asyncExec("HMSMap", "mapOptions", [this.divId, "projections", "fromScreenLocation", { "point": point }]); } getVisibleRegion(): Promise<VisibleRegion> { return asyncExec("HMSMap", "mapOptions", [this.divId, "projections", "getVisibleRegion", {}]); } toScreenLocation(latLng: LatLng): Promise<Point> { return asyncExec("HMSMap", "mapOptions", [this.divId, "projections", "toScreenLocation", { "latLng": latLng }]); } } export class MapStyleOptions { private readonly resourceName: string; private constructor(resourceName: string) { this.resourceName = resourceName; } public static loadRawResourceStyle(resourceName: string): MapStyleOptions { return new MapStyleOptions(resourceName); } getResourceName(): string { return this.resourceName; } }
the_stack
import { expect } from 'chai'; import { simulate } from 'simulate-event'; import { Platform } from '@phosphor/domutils'; import { FocusTracker, Widget } from '@phosphor/widgets'; describe('@phosphor/widgets', () => { let _trackers: FocusTracker<Widget>[] = []; let _widgets: Widget[] = []; function createTracker(): FocusTracker<Widget> { let tracker = new FocusTracker<Widget>(); _trackers.push(tracker); return tracker; } function createWidget(): Widget { let widget = new Widget(); widget.node.tabIndex = -1; Widget.attach(widget, document.body); _widgets.push(widget); return widget; } function focusWidget(widget: Widget): void { widget.node.focus(); if (Platform.IS_IE) { // Ensure we get a synchronous event on IE for testing. simulate(widget.node, 'focus'); } } function blurWidget(widget: Widget): void { widget.node.blur(); if (Platform.IS_IE) { // Ensure we get a synchronous event on IE for testing. simulate(widget.node, 'blur'); } } afterEach(() => { while (_trackers.length > 0) { _trackers.pop()!.dispose(); } while (_widgets.length > 0) { _widgets.pop()!.dispose(); } }); describe('FocusTracker', () => { describe('#constructor()', () => { it('should create a FocusTracker', () => { let tracker = new FocusTracker<Widget>(); expect(tracker).to.be.an.instanceof(FocusTracker); }); }); describe('#dispose()', () => { it('should dispose of the resources held by the tracker', () => { let tracker = new FocusTracker<Widget>(); tracker.add(createWidget()); tracker.dispose(); expect(tracker.widgets.length).to.equal(0); }); it('should be a no-op if already disposed', () => { let tracker = new FocusTracker<Widget>(); tracker.dispose(); tracker.dispose(); expect(tracker.isDisposed).to.equal(true); }); }); describe('#currentChanged', () => { it('should be emitted when the current widget has changed', () => { let tracker = createTracker(); let widget0 = createWidget(); let widget1 = createWidget(); tracker.add(widget0); tracker.add(widget1); focusWidget(widget0); let emitArgs: FocusTracker.IChangedArgs<Widget> | null = null; tracker.currentChanged.connect((sender, args) => { emitArgs = args; }); focusWidget(widget1); expect(emitArgs).to.not.equal(null); expect(emitArgs!.oldValue).to.equal(widget0); expect(emitArgs!.newValue).to.equal(widget1); }); it('should not be emitted when the current widget does not change', () => { let tracker = createTracker(); let widget = createWidget(); focusWidget(widget); tracker.add(widget); let emitArgs: FocusTracker.IChangedArgs<Widget> | null = null; tracker.currentChanged.connect((sender, args) => { emitArgs = args; }); blurWidget(widget); focusWidget(widget); expect(emitArgs).to.equal(null); }); }); describe('#activeChanged', () => { it('should be emitted when the active widget has changed', () => { let tracker = createTracker(); let widget0 = createWidget(); let widget1 = createWidget(); tracker.add(widget0); tracker.add(widget1); focusWidget(widget0); let emitArgs: FocusTracker.IChangedArgs<Widget> | null = null; tracker.activeChanged.connect((sender, args) => { emitArgs = args; }); focusWidget(widget1); expect(emitArgs).to.not.equal(null); expect(emitArgs!.oldValue).to.equal(widget0); expect(emitArgs!.newValue).to.equal(widget1); }); it('should be emitted when the active widget is set to null', () => { let tracker = createTracker(); let widget = createWidget(); focusWidget(widget); tracker.add(widget); let emitArgs: FocusTracker.IChangedArgs<Widget> | null = null; tracker.activeChanged.connect((sender, args) => { emitArgs = args; }); blurWidget(widget); expect(emitArgs).to.not.equal(null); expect(emitArgs!.oldValue).to.equal(widget); expect(emitArgs!.newValue).to.equal(null); }); }); describe('#isDisposed', () => { it('should indicate whether the tracker is disposed', () => { let tracker = new FocusTracker<Widget>(); expect(tracker.isDisposed).to.equal(false); tracker.dispose(); expect(tracker.isDisposed).to.equal(true); }); }); describe('#currentWidget', () => { it('should get the current widget in the tracker', () => { let tracker = createTracker(); let widget = createWidget(); focusWidget(widget); tracker.add(widget); expect(tracker.currentWidget).to.equal(widget); }); it('should not be updated when the current widget loses focus', () => { let tracker = createTracker(); let widget = createWidget(); focusWidget(widget); tracker.add(widget); expect(tracker.currentWidget).to.equal(widget); blurWidget(widget); expect(tracker.currentWidget).to.equal(widget); }); it('should be set to the widget that gained focus', () => { let tracker = createTracker(); let widget0 = createWidget(); let widget1 = createWidget(); focusWidget(widget0); tracker.add(widget0); tracker.add(widget1); expect(tracker.currentWidget).to.equal(widget0); focusWidget(widget1); expect(tracker.currentWidget).to.equal(widget1); }); it('should revert to the previous widget if the current widget is removed', () => { let tracker = createTracker(); let widget0 = createWidget(); let widget1 = createWidget(); focusWidget(widget0); tracker.add(widget0); tracker.add(widget1); focusWidget(widget1); expect(tracker.currentWidget).to.equal(widget1); widget1.dispose(); expect(tracker.currentWidget).to.equal(widget0); }); it('should be `null` if there is no current widget', () => { let tracker = createTracker(); expect(tracker.currentWidget).to.equal(null); let widget = createWidget(); focusWidget(widget); tracker.add(widget); expect(tracker.currentWidget).to.equal(widget); widget.dispose(); expect(tracker.currentWidget).to.equal(null); }); }); describe('#activeWidget', () => { it('should get the active widget in the tracker', () => { let tracker = createTracker(); let widget = createWidget(); focusWidget(widget); tracker.add(widget); expect(tracker.activeWidget).to.equal(widget); }); it('should be set to `null` when the active widget loses focus', () => { let tracker = createTracker(); let widget = createWidget(); focusWidget(widget); tracker.add(widget); expect(tracker.activeWidget).to.equal(widget); blurWidget(widget); expect(tracker.activeWidget).to.equal(null); }); it('should be set to the widget that gained focus', () => { let tracker = createTracker(); let widget0 = createWidget(); let widget1 = createWidget(); focusWidget(widget0); tracker.add(widget0); tracker.add(widget1); expect(tracker.activeWidget).to.equal(widget0); focusWidget(widget1); expect(tracker.activeWidget).to.equal(widget1); }); it('should be `null` if there is no active widget', () => { let tracker = createTracker(); expect(tracker.currentWidget).to.equal(null); let widget = createWidget(); focusWidget(widget); tracker.add(widget); expect(tracker.activeWidget).to.equal(widget); widget.dispose(); expect(tracker.activeWidget).to.equal(null); }); }); describe('#widgets', () => { it('should be a read-only sequence of the widgets being tracked', () => { let tracker = createTracker(); expect(tracker.widgets.length).to.equal(0); let widget = createWidget(); tracker.add(widget); expect(tracker.widgets.length).to.equal(1); expect(tracker.widgets[0]).to.equal(widget); }); }); describe('#focusNumber()', () => { it('should get the focus number for a particular widget in the tracker', () => { let tracker = createTracker(); let widget = createWidget(); focusWidget(widget); tracker.add(widget); expect(tracker.focusNumber(widget)).to.equal(0); }); it('should give the highest number for the currentWidget', () => { let tracker = createTracker(); let widget0 = createWidget(); let widget1 = createWidget(); focusWidget(widget0); tracker.add(widget0); tracker.add(widget1); focusWidget(widget1); expect(tracker.focusNumber(widget1)).to.equal(1); expect(tracker.focusNumber(widget0)).to.equal(0); focusWidget(widget0); expect(tracker.focusNumber(widget0)).to.equal(2); }); it('should start a widget with a focus number of `-1`', () => { let tracker = createTracker(); let widget = createWidget(); tracker.add(widget); expect(tracker.focusNumber(widget)).to.equal(-1); }); it('should update when a widget gains focus', () => { let tracker = createTracker(); let widget0 = createWidget(); let widget1 = createWidget(); focusWidget(widget0); tracker.add(widget0); tracker.add(widget1); focusWidget(widget1); expect(tracker.focusNumber(widget0)).to.equal(0); focusWidget(widget0); expect(tracker.focusNumber(widget0)).to.equal(2); }); }); describe('#has()', () => { it('should test whether the focus tracker contains a given widget', () => { let tracker = createTracker(); let widget = createWidget(); expect(tracker.has(widget)).to.equal(false); tracker.add(widget); expect(tracker.has(widget)).to.equal(true); }); }); describe('#add()', () => { it('should add a widget to the focus tracker', () => { let tracker = createTracker(); let widget = createWidget(); tracker.add(widget); expect(tracker.has(widget)).to.equal(true); }); it('should make the widget the currentWidget if focused', () => { let tracker = createTracker(); let widget = createWidget(); focusWidget(widget); tracker.add(widget); expect(tracker.currentWidget).to.equal(widget); }); it('should remove the widget from the tracker after it has been disposed', () => { let tracker = createTracker(); let widget = createWidget(); tracker.add(widget); widget.dispose(); expect(tracker.has(widget)).to.equal(false); }); it('should be a no-op if the widget is already tracked', () => { let tracker = createTracker(); let widget = createWidget(); tracker.add(widget); tracker.add(widget); expect(tracker.has(widget)).to.equal(true); }); }); describe('#remove()', () => { it('should remove a widget from the focus tracker', () => { let tracker = createTracker(); let widget = createWidget(); tracker.add(widget); tracker.remove(widget); expect(tracker.has(widget)).to.equal(false); }); it('should set the currentWidget to the previous one if the widget is the currentWidget', () => { let tracker = createTracker(); let widget0 = createWidget(); let widget1 = createWidget(); let widget2 = createWidget(); focusWidget(widget0); tracker.add(widget0); tracker.add(widget1); tracker.add(widget2); focusWidget(widget1); focusWidget(widget2); tracker.remove(widget2); expect(tracker.currentWidget).to.equal(widget1); }); it('should be a no-op if the widget is not tracked', () => { let tracker = createTracker(); let widget = createWidget(); tracker.remove(widget); expect(tracker.has(widget)).to.equal(false); }); }); }); });
the_stack
const globalWindow = window type Options = { tab: string indentOn: RegExp spellcheck: boolean catchTab: boolean preserveIdent: boolean addClosing: boolean history: boolean window: typeof window } type HistoryRecord = { html: string pos: Position } export type Position = { start: number end: number dir?: '->' | '<-' } export type CodeJar = ReturnType<typeof CodeJar> export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: Position) => void, opt: Partial<Options> = {}) { const options: Options = { tab: '\t', indentOn: /{$/, spellcheck: false, catchTab: true, preserveIdent: true, addClosing: true, history: true, window: globalWindow, ...opt } const window = options.window const document = window.document let listeners: [string, any][] = [] let history: HistoryRecord[] = [] let at = -1 let focus = false let callback: (code: string) => void | undefined let prev: string // code content prior keydown event editor.setAttribute('contenteditable', 'plaintext-only') editor.setAttribute('spellcheck', options.spellcheck ? 'true' : 'false') editor.style.outline = 'none' editor.style.overflowWrap = 'break-word' editor.style.overflowY = 'auto' editor.style.whiteSpace = 'pre-wrap' let isLegacy = false // true if plaintext-only is not supported highlight(editor) if (editor.contentEditable !== 'plaintext-only') isLegacy = true if (isLegacy) editor.setAttribute('contenteditable', 'true') const debounceHighlight = debounce(() => { const pos = save() highlight(editor, pos) restore(pos) }, 30) let recording = false const shouldRecord = (event: KeyboardEvent): boolean => { return !isUndo(event) && !isRedo(event) && event.key !== 'Meta' && event.key !== 'Control' && event.key !== 'Alt' && !event.key.startsWith('Arrow') } const debounceRecordHistory = debounce((event: KeyboardEvent) => { if (shouldRecord(event)) { recordHistory() recording = false } }, 300) const on = <K extends keyof HTMLElementEventMap>(type: K, fn: (event: HTMLElementEventMap[K]) => void) => { listeners.push([type, fn]) editor.addEventListener(type, fn) } on('keydown', event => { if (event.defaultPrevented) return prev = toString() if (options.preserveIdent) handleNewLine(event) else legacyNewLineFix(event) if (options.catchTab) handleTabCharacters(event) if (options.addClosing) handleSelfClosingCharacters(event) if (options.history) { handleUndoRedo(event) if (shouldRecord(event) && !recording) { recordHistory() recording = true } } if (isLegacy) restore(save()) }) on('keyup', event => { if (event.defaultPrevented) return if (event.isComposing) return if (prev !== toString()) debounceHighlight() debounceRecordHistory(event) if (callback) callback(toString()) }) on('focus', _event => { focus = true }) on('blur', _event => { focus = false }) on('paste', event => { recordHistory() handlePaste(event) recordHistory() if (callback) callback(toString()) }) function save(): Position { const s = getSelection() const pos: Position = {start: 0, end: 0, dir: undefined} let {anchorNode, anchorOffset, focusNode, focusOffset} = s if (!anchorNode || !focusNode) throw 'error1' // Selection anchor and focus are expected to be text nodes, // so normalize them. if (anchorNode.nodeType === Node.ELEMENT_NODE) { const node = document.createTextNode('') anchorNode.insertBefore(node, anchorNode.childNodes[anchorOffset]) anchorNode = node anchorOffset = 0 } if (focusNode.nodeType === Node.ELEMENT_NODE) { const node = document.createTextNode('') focusNode.insertBefore(node, focusNode.childNodes[focusOffset]) focusNode = node focusOffset = 0 } visit(editor, el => { if (el === anchorNode && el === focusNode) { pos.start += anchorOffset pos.end += focusOffset pos.dir = anchorOffset <= focusOffset ? '->' : '<-' return 'stop' } if (el === anchorNode) { pos.start += anchorOffset if (!pos.dir) { pos.dir = '->' } else { return 'stop' } } else if (el === focusNode) { pos.end += focusOffset if (!pos.dir) { pos.dir = '<-' } else { return 'stop' } } if (el.nodeType === Node.TEXT_NODE) { if (pos.dir != '->') pos.start += el.nodeValue!.length if (pos.dir != '<-') pos.end += el.nodeValue!.length } }) // collapse empty text nodes editor.normalize() return pos } function restore(pos: Position) { const s = getSelection() let startNode: Node | undefined, startOffset = 0 let endNode: Node | undefined, endOffset = 0 if (!pos.dir) pos.dir = '->' if (pos.start < 0) pos.start = 0 if (pos.end < 0) pos.end = 0 // Flip start and end if the direction reversed if (pos.dir == '<-') { const {start, end} = pos pos.start = end pos.end = start } let current = 0 visit(editor, el => { if (el.nodeType !== Node.TEXT_NODE) return const len = (el.nodeValue || '').length if (current + len > pos.start) { if (!startNode) { startNode = el startOffset = pos.start - current } if (current + len > pos.end) { endNode = el endOffset = pos.end - current return 'stop' } } current += len }) if (!startNode) startNode = editor, startOffset = editor.childNodes.length if (!endNode) endNode = editor, endOffset = editor.childNodes.length // Flip back the selection if (pos.dir == '<-') { [startNode, startOffset, endNode, endOffset] = [endNode, endOffset, startNode, startOffset] } s.setBaseAndExtent(startNode, startOffset, endNode, endOffset) } function beforeCursor() { const s = getSelection() const r0 = s.getRangeAt(0) const r = document.createRange() r.selectNodeContents(editor) r.setEnd(r0.startContainer, r0.startOffset) return r.toString() } function afterCursor() { const s = getSelection() const r0 = s.getRangeAt(0) const r = document.createRange() r.selectNodeContents(editor) r.setStart(r0.endContainer, r0.endOffset) return r.toString() } function handleNewLine(event: KeyboardEvent) { if (event.key === 'Enter') { const before = beforeCursor() const after = afterCursor() let [padding] = findPadding(before) let newLinePadding = padding // If last symbol is "{" ident new line // Allow user defines indent rule if (options.indentOn.test(before)) { newLinePadding += options.tab } // Preserve padding if (newLinePadding.length > 0) { preventDefault(event) event.stopPropagation() insert('\n' + newLinePadding) } else { legacyNewLineFix(event) } // Place adjacent "}" on next line if (newLinePadding !== padding && after[0] === '}') { const pos = save() insert('\n' + padding) restore(pos) } } } function legacyNewLineFix(event: KeyboardEvent) { // Firefox does not support plaintext-only mode // and puts <div><br></div> on Enter. Let's help. if (isLegacy && event.key === 'Enter') { preventDefault(event) event.stopPropagation() if (afterCursor() == '') { insert('\n ') const pos = save() pos.start = --pos.end restore(pos) } else { insert('\n') } } } function handleSelfClosingCharacters(event: KeyboardEvent) { const open = `([{'"` const close = `)]}'"` const codeAfter = afterCursor() const codeBefore = beforeCursor() const escapeCharacter = codeBefore.substr(codeBefore.length - 1) === '\\' const charAfter = codeAfter.substr(0, 1) if (close.includes(event.key) && !escapeCharacter && charAfter === event.key) { // We already have closing char next to cursor. // Move one char to right. const pos = save() preventDefault(event) pos.start = ++pos.end restore(pos) } else if ( open.includes(event.key) && !escapeCharacter && (`"'`.includes(event.key) || ['', ' ', '\n'].includes(charAfter)) ) { preventDefault(event) const pos = save() const wrapText = pos.start == pos.end ? '' : getSelection().toString() const text = event.key + wrapText + close[open.indexOf(event.key)] insert(text) pos.start++ pos.end++ restore(pos) } } function handleTabCharacters(event: KeyboardEvent) { if (event.key === 'Tab') { preventDefault(event) if (event.shiftKey) { const before = beforeCursor() let [padding, start,] = findPadding(before) if (padding.length > 0) { const pos = save() // Remove full length tab or just remaining padding const len = Math.min(options.tab.length, padding.length) restore({start, end: start + len}) document.execCommand('delete') pos.start -= len pos.end -= len restore(pos) } } else { insert(options.tab) } } } function handleUndoRedo(event: KeyboardEvent) { if (isUndo(event)) { preventDefault(event) at-- const record = history[at] if (record) { editor.innerHTML = record.html restore(record.pos) } if (at < 0) at = 0 } if (isRedo(event)) { preventDefault(event) at++ const record = history[at] if (record) { editor.innerHTML = record.html restore(record.pos) } if (at >= history.length) at-- } } function recordHistory() { if (!focus) return const html = editor.innerHTML const pos = save() const lastRecord = history[at] if (lastRecord) { if (lastRecord.html === html && lastRecord.pos.start === pos.start && lastRecord.pos.end === pos.end) return } at++ history[at] = {html, pos} history.splice(at + 1) const maxHistory = 300 if (at > maxHistory) { at = maxHistory history.splice(0, 1) } } function handlePaste(event: ClipboardEvent) { preventDefault(event) const text = ((event as any).originalEvent || event) .clipboardData .getData('text/plain') .replace(/\r/g, '') const pos = save() insert(text) highlight(editor) restore({start: pos.start + text.length, end: pos.start + text.length}) } function visit(editor: HTMLElement, visitor: (el: Node) => 'stop' | undefined) { const queue: Node[] = [] if (editor.firstChild) queue.push(editor.firstChild) let el = queue.pop() while (el) { if (visitor(el) === 'stop') break if (el.nextSibling) queue.push(el.nextSibling) if (el.firstChild) queue.push(el.firstChild) el = queue.pop() } } function isCtrl(event: KeyboardEvent) { return event.metaKey || event.ctrlKey } function isUndo(event: KeyboardEvent) { return isCtrl(event) && !event.shiftKey && event.code === 'KeyZ' } function isRedo(event: KeyboardEvent) { return isCtrl(event) && event.shiftKey && event.code === 'KeyZ' } function insert(text: string) { text = text .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;') document.execCommand('insertHTML', false, text) } function debounce(cb: any, wait: number) { let timeout = 0 return (...args: any) => { clearTimeout(timeout) timeout = window.setTimeout(() => cb(...args), wait) } } function findPadding(text: string): [string, number, number] { // Find beginning of previous line. let i = text.length - 1 while (i >= 0 && text[i] !== '\n') i-- i++ // Find padding of the line. let j = i while (j < text.length && /[ \t]/.test(text[j])) j++ return [text.substring(i, j) || '', i, j] } function toString() { return editor.textContent || '' } function preventDefault(event: Event) { event.preventDefault() } function getSelection() { if (editor.parentNode?.nodeType == Node.DOCUMENT_FRAGMENT_NODE) { return (editor.parentNode as Document).getSelection()! } return window.getSelection()! } return { updateOptions(newOptions: Partial<Options>) { Object.assign(options, newOptions) }, updateCode(code: string) { editor.textContent = code highlight(editor) }, onUpdate(cb: (code: string) => void) { callback = cb }, toString, save, restore, recordHistory, destroy() { for (let [type, fn] of listeners) { editor.removeEventListener(type, fn) } }, } }
the_stack
* @module Editing */ import { BentleyStatus, CompressedId64Set, DbResult, Id64String, IModelStatus } from "@itwin/core-bentley"; import { Matrix3d, Matrix3dProps, Point3d, PointString3d, Range3d, Range3dProps, Transform, TransformProps, XYZProps, YawPitchRollAngles, } from "@itwin/core-geometry"; import { GeometricElement, IModelDb } from "@itwin/core-backend"; import { BRepEntity, ColorDefProps, DynamicGraphicsRequest3dProps, EcefLocation, EcefLocationProps, ElementGeometry, ElementGeometryDataEntry, ElementGeometryFunction, ElementGeometryInfo, ElementGeometryRequest, ElementGeometryUpdate, FilePropertyProps, GeometricElementProps, GeometryPartProps, GeometryStreamBuilder, IModelError, Placement3dProps, } from "@itwin/core-common"; import { BasicManipulationCommandIpc, editorBuiltInCmdIds, ElementGeometryCacheFilter, ElementGeometryResultOptions, ElementGeometryResultProps, FlatBufferGeometricElementData, FlatBufferGeometryFilter, FlatBufferGeometryPartData, LocateSubEntityProps, OffsetFacesProps, SolidModelingCommandIpc, SubEntityAppearanceProps, SubEntityGeometryProps, SubEntityLocationProps, SubEntityProps, } from "@itwin/editor-common"; import { EditCommand } from "./EditCommand"; /** @alpha */ export class BasicManipulationCommand extends EditCommand implements BasicManipulationCommandIpc { public static override commandId = editorBuiltInCmdIds.cmdBasicManipulation; public constructor(iModel: IModelDb, protected _str: string) { super(iModel); } public async deleteElements(ids: CompressedId64Set): Promise<IModelStatus> { for (const id of CompressedId64Set.iterable(ids)) this.iModel.elements.deleteElement(id); return IModelStatus.Success; } public async transformPlacement(ids: CompressedId64Set, transProps: TransformProps): Promise<IModelStatus> { const transform = Transform.fromJSON(transProps); for (const id of CompressedId64Set.iterable(ids)) { const element = this.iModel.elements.getElement<GeometricElement>(id); if (!element.placement.isValid) continue; // Ignore assembly parents w/o geometry, etc... element.placement.multiplyTransform(transform); this.iModel.elements.updateElement(element); } return IModelStatus.Success; } public async rotatePlacement(ids: CompressedId64Set, matrixProps: Matrix3dProps, aboutCenter: boolean): Promise<IModelStatus> { const matrix = Matrix3d.fromJSON(matrixProps); for (const id of CompressedId64Set.iterable(ids)) { const element = this.iModel.elements.getElement<GeometricElement>(id); if (!element.placement.isValid) continue; // Ignore assembly parents w/o geometry, etc... const fixedPoint = aboutCenter ? element.placement.calculateRange().center : Point3d.createFrom(element.placement.origin); const transform = Transform.createFixedPointAndMatrix(fixedPoint, matrix); element.placement.multiplyTransform(transform); this.iModel.elements.updateElement(element); } return IModelStatus.Success; } public async insertGeometricElement(props: GeometricElementProps, data?: FlatBufferGeometricElementData): Promise<Id64String> { const newElem = this.iModel.elements.createElement(props); const newId = this.iModel.elements.insertElement(newElem); if (undefined === data) return newId; const updateProps: ElementGeometryUpdate = { elementId: newId, entryArray: data.entryArray, isWorld: data.isWorld, viewIndependent: data.viewIndependent, }; const status = this.iModel.elementGeometryUpdate(updateProps); if (DbResult.BE_SQLITE_OK !== status) { this.iModel.elements.deleteElement(newId); // clean up element... throw new IModelError(status, "Error updating element geometry"); } return newId; } public async insertGeometryPart(props: GeometryPartProps, data?: FlatBufferGeometryPartData): Promise<Id64String> { if (undefined === props.geom && undefined !== data) { const builder = new GeometryStreamBuilder(); builder.appendGeometry(PointString3d.create(Point3d.createZero())); props.geom = builder.geometryStream; // can't insert a DgnGeometryPart without geometry... } const newElem = this.iModel.elements.createElement(props); const newId = this.iModel.elements.insertElement(newElem); if (undefined === data) return newId; const updateProps: ElementGeometryUpdate = { elementId: newId, entryArray: data.entryArray, is2dPart: data.is2dPart, }; const status = this.iModel.elementGeometryUpdate(updateProps); if (DbResult.BE_SQLITE_OK !== status) { this.iModel.elements.deleteElement(newId); // clean up element... throw new IModelError(status, "Error updating part geometry"); } return newId; } public async updateGeometricElement(propsOrId: GeometricElementProps | Id64String, data?: FlatBufferGeometricElementData): Promise<void> { let props: GeometricElementProps; if (typeof propsOrId === "string") { if (undefined === data) throw new IModelError(DbResult.BE_SQLITE_ERROR, "Flatbuffer data required for update by id"); props = this.iModel.elements.getElement<GeometricElement>(propsOrId); } else { props = propsOrId; } if (undefined === props.id) throw new IModelError(DbResult.BE_SQLITE_ERROR, "Element id required for update"); this.iModel.elements.updateElement(props); if (undefined === data) return; const updateProps: ElementGeometryUpdate = { elementId: props.id, entryArray: data.entryArray, isWorld: data.isWorld, viewIndependent: data.viewIndependent, }; const status = this.iModel.elementGeometryUpdate(updateProps); if (DbResult.BE_SQLITE_OK !== status) { throw new IModelError(status, "Error updating element geometry"); } } public async requestElementGeometry(elementId: Id64String, filter?: FlatBufferGeometryFilter): Promise<ElementGeometryInfo | undefined> { let accepted: ElementGeometryInfo | undefined; const onGeometry: ElementGeometryFunction = (info: ElementGeometryInfo): void => { accepted = info; if (undefined !== filter) { let numDisplayable = 0; for (const entry of info.entryArray) { if (!ElementGeometry.isDisplayableEntry(entry)) continue; numDisplayable++; if (filter.maxDisplayable && numDisplayable > filter.maxDisplayable) { accepted = undefined; break; } if (filter.reject && filter.reject.some((opcode) => entry.opcode === opcode)) { accepted = undefined; break; } if (filter.accept && !filter.accept.some((opcode) => entry.opcode === opcode)) { accepted = undefined; break; } if (undefined === filter.geometry) continue; let entityType; if (filter.geometry.curves && !(filter.geometry.surfaces || filter.geometry.solids)) entityType = ElementGeometry.isCurve(entry) ? BRepEntity.Type.Wire : undefined; // skip surface/solid opcodes... else entityType = ElementGeometry.getBRepEntityType(entry); switch (entityType) { case BRepEntity.Type.Wire: if (!filter.geometry.curves) accepted = undefined; break; case BRepEntity.Type.Sheet: if (!filter.geometry.surfaces) accepted = undefined; break; case BRepEntity.Type.Solid: if (!filter.geometry.solids) accepted = undefined; break; default: accepted = undefined; break; } if (undefined === accepted) break; } } }; const requestProps: ElementGeometryRequest = { onGeometry, elementId, }; if (DbResult.BE_SQLITE_OK !== this.iModel.elementGeometryRequest(requestProps)) return undefined; return accepted; } public async updateProjectExtents(extents: Range3dProps): Promise<void> { const newExtents = new Range3d(); newExtents.setFromJSON(extents); if (newExtents.isNull) throw new IModelError(DbResult.BE_SQLITE_ERROR, "Invalid project extents"); this.iModel.updateProjectExtents(newExtents); // Set source from calculated to user so connectors preserve the change. const unitsProps: FilePropertyProps = { name: "Units", namespace: "dgn_Db" }; const unitsStr = this.iModel.queryFilePropertyString(unitsProps); if (undefined !== unitsStr) { const unitsVal = JSON.parse(unitsStr); const calculated = 1; if (calculated !== unitsVal.extentsSource) { unitsVal.extentsSource = calculated; this.iModel.saveFileProperty(unitsProps, JSON.stringify(unitsVal)); } } } public async updateEcefLocation(ecefLocation: EcefLocationProps): Promise<void> { // Clear GCS that caller already determined was invalid... this.iModel.deleteFileProperty({ name: "DgnGCS", namespace: "dgn_Db" }); const newEcefLocation = new EcefLocation(ecefLocation); this.iModel.updateEcefLocation(newEcefLocation); } } interface ElementGeometryCacheRequestProps { id?: Id64String; } interface ElementGeometryCacheResponseProps { status: BentleyStatus; numGeom?: number; numPart?: number; numSolid?: number; numSurface?: number; numCurve?: number; numOther?: number; } interface SubEntityGeometryResponseProps { /** The face, edge, or vertex geometry */ geometry: ElementGeometryDataEntry; /** The face or edge range box for the sub-entity geometry stored as 6 values for low/high */ range?: Float64Array; /** Category id for geometry. */ category?: Id64String; /** SubCategory id for geometry. */ subCategory?: Id64String; /** Material id for geometry. */ material?: Id64String; /** color of geometry. */ color?: ColorDefProps; /** transparency of geometry. */ transparency?: number; /** weight of geometry. */ weight?: number; } type SubEntityGeometryFunction = (info: SubEntityGeometryResponseProps) => void; type ClosestFaceFunction = (info: SubEntityLocationProps) => void; type LocateSubEntityFunction = (info: SubEntityLocationProps[]) => void; interface SubEntityGeometryRequestProps { /** Sub-entity to return geometry for */ subEntity: SubEntityProps; /** Callback for result */ onResult: SubEntityGeometryFunction; } interface ClosestFaceRequestProps { /** Space point */ point: XYZProps; /** Optional direction for choosing face from edge or vertex hit... */ direction?: XYZProps; /** Callback for result */ onResult: ClosestFaceFunction; } interface LocateSubEntityRequestProps { /** Space point for boresite origin */ point: XYZProps; /** Vector for bosite direction */ direction: XYZProps; /** The maximum number of faces, edges, and vertices to return */ options: LocateSubEntityProps; /** Callback for result */ onResult: LocateSubEntityFunction; } interface ElementGeometryCacheOperationRequestProps { /** Target element id, tool element ids supplied by operations between elements... */ id: Id64String; /** Callback for result when element's geometry stream is requested in flatbuffer or graphic formats */ onGeometry?: ElementGeometryFunction; onSubEntityGeometry?: SubEntityGeometryRequestProps; onLocateSubEntity?: LocateSubEntityRequestProps; onClosestFace?: ClosestFaceRequestProps; onOffsetFaces?: OffsetFacesProps; } /** @alpha */ export class SolidModelingCommand extends BasicManipulationCommand implements SolidModelingCommandIpc { public static override commandId = editorBuiltInCmdIds.cmdSolidModeling; private async updateElementGeometryCache(props: ElementGeometryCacheRequestProps): Promise<ElementGeometryCacheResponseProps> { return this.iModel.nativeDb.updateElementGeometryCache(props); } public async createElementGeometryCache(id: Id64String, filter?: ElementGeometryCacheFilter): Promise<boolean> { const result = await this.updateElementGeometryCache({ id }); if (BentleyStatus.SUCCESS !== result.status) return false; if (undefined === filter) return true; if (filter.minGeom && (undefined === result.numGeom || filter.minGeom > result.numGeom)) return false; if (filter.maxGeom && (undefined === result.numGeom || filter.maxGeom < result.numGeom)) return false; if (!filter.parts && (result.numPart ?? 0 > 0)) return false; if (!filter.curves && (result.numCurve ?? 0 > 0)) return false; if (!filter.surfaces && (result.numSurface ?? 0 > 0)) return false; if (!filter.solids && (result.numSolid ?? 0 > 0)) return false; if (!filter.other && (result.numOther ?? 0 > 0)) return false; return true; } public async clearElementGeometryCache(): Promise<void> { await this.updateElementGeometryCache({}); } private requestSubEntityGeometry(id: Id64String, subEntity: SubEntityProps): SubEntityGeometryResponseProps | undefined { let accepted: SubEntityGeometryResponseProps | undefined; const onResult: SubEntityGeometryFunction = (info: SubEntityGeometryResponseProps): void => { accepted = info; }; const opProps: SubEntityGeometryRequestProps = { subEntity, onResult }; const props: ElementGeometryCacheOperationRequestProps = { id, onSubEntityGeometry: opProps }; this.iModel.nativeDb.elementGeometryCacheOperation(props); return accepted; } public async getSubEntityGeometry(id: Id64String, subEntity: SubEntityProps, opts: Omit<ElementGeometryResultOptions, "writeChanges" | "insertProps">): Promise<SubEntityGeometryProps | undefined> { const geometryProps = this.requestSubEntityGeometry(id, subEntity); if (undefined === geometryProps?.geometry || undefined === geometryProps?.category) return undefined; const resultProps: SubEntityGeometryProps = {}; if (opts.wantGeometry) resultProps.geometry = geometryProps.geometry; if (opts.wantRange) resultProps.range = (geometryProps?.range ? ElementGeometry.toElementAlignedBox3d(geometryProps?.range) : undefined); if (opts.wantAppearance) { const appearance: SubEntityAppearanceProps = { category: geometryProps.category }; appearance.subCategory = geometryProps.subCategory; appearance.material = geometryProps.material; appearance.color = geometryProps.color; appearance.transparency = geometryProps.transparency; appearance.weight = geometryProps.weight; resultProps.appearance = appearance; } if (!opts.wantGraphic) return resultProps; const requestId = opts.requestId ? opts.requestId : `SubEntity:${id}-${subEntity.id}`; const toleranceLog10 = (opts.chordTolerance ? Math.floor(Math.log10(opts.chordTolerance)) : -2); const requestProps: DynamicGraphicsRequest3dProps = { id: requestId, modelId: this.iModel.iModelId, toleranceLog10, type: "3d", placement: { origin: Point3d.createZero(), angles: YawPitchRollAngles.createDegrees(0, 0, 0) }, categoryId: geometryProps.category, geometry: { format: "flatbuffer", data: [geometryProps.geometry] }, }; resultProps.graphic = await this.iModel.generateElementGraphics(requestProps); return resultProps; } public async locateSubEntities(id: Id64String, point: XYZProps, direction: XYZProps, options: LocateSubEntityProps): Promise<SubEntityLocationProps[] | undefined> { let accepted: SubEntityLocationProps[] | undefined; const onResult: LocateSubEntityFunction = (info: SubEntityLocationProps[]): void => { accepted = info; }; const opProps: LocateSubEntityRequestProps = { point, direction, options, onResult }; const props: ElementGeometryCacheOperationRequestProps = { id, onLocateSubEntity: opProps }; this.iModel.nativeDb.elementGeometryCacheOperation(props); return accepted; } public async getClosestFace(id: Id64String, point: XYZProps, direction?: XYZProps): Promise<SubEntityLocationProps | undefined> { let accepted: SubEntityLocationProps | undefined; const onResult: ClosestFaceFunction = (info: SubEntityLocationProps): void => { accepted = info; }; const opProps: ClosestFaceRequestProps = { point, direction, onResult }; const props: ElementGeometryCacheOperationRequestProps = { id, onClosestFace: opProps }; this.iModel.nativeDb.elementGeometryCacheOperation(props); return accepted; } private async getElementGeometryResults(id: Id64String, info: ElementGeometryInfo, opts: ElementGeometryResultOptions): Promise<ElementGeometryResultProps | undefined> { if (0 === info.entryArray.length || undefined === info.categoryId || undefined === info.bbox) return undefined; const resultProps: ElementGeometryResultProps = {}; if (opts.wantGeometry) resultProps.geometry = info; if (opts.wantRange) resultProps.range = ElementGeometry.toElementAlignedBox3d(info.bbox); if (opts.wantAppearance) resultProps.categoryId = info.categoryId; if (!(opts.wantGraphic || opts.writeChanges)) return resultProps; let placement: Placement3dProps; const sourceToWorld = (undefined === info?.sourceToWorld ? undefined : ElementGeometry.toTransform(info.sourceToWorld)); if (undefined === sourceToWorld) { placement = { origin: Point3d.createZero(), angles: YawPitchRollAngles.createDegrees(0, 0, 0) }; } else { const origin = sourceToWorld.getOrigin(); const angles = new YawPitchRollAngles(); YawPitchRollAngles.createFromMatrix3d(sourceToWorld.matrix, angles); placement = { origin, angles }; } if (opts.writeChanges) { if (opts.insertProps) { opts.insertProps.placement = placement; // entryArray is local to this placement... delete opts.insertProps.geom; // Ignore geometry if present... resultProps.elementId = await this.insertGeometricElement(opts.insertProps, { entryArray: info.entryArray }); } else { await this.updateGeometricElement(id, { entryArray: info.entryArray }); resultProps.elementId = id; } } if (!opts.wantGraphic) return resultProps; const requestId = opts.requestId ? opts.requestId : `EGCacheOp:${id}`; const toleranceLog10 = (opts.chordTolerance ? Math.floor(Math.log10(opts.chordTolerance)) : -2); const requestProps: DynamicGraphicsRequest3dProps = { id: requestId, modelId: this.iModel.iModelId, toleranceLog10, type: "3d", placement, categoryId: info.categoryId, geometry: { format: "flatbuffer", data: info.entryArray }, }; resultProps.graphic = await this.iModel.generateElementGraphics(requestProps); return resultProps; } public async offsetFaces(id: Id64String, params: OffsetFacesProps, opts: ElementGeometryResultOptions): Promise<ElementGeometryResultProps | undefined> { let accepted: ElementGeometryInfo | undefined; const onResult: ElementGeometryFunction = (info: ElementGeometryInfo): void => { accepted = info; }; const props: ElementGeometryCacheOperationRequestProps = { id, onOffsetFaces: params, onGeometry: onResult }; this.iModel.nativeDb.elementGeometryCacheOperation(props); if (undefined === accepted) return undefined; return this.getElementGeometryResults(id, accepted, opts); } }
the_stack
import ComponentRepository from '../core/ComponentRepository'; import Component from '../core/Component'; import EntityRepository from '../core/EntityRepository'; import {WellKnownComponentTIDs} from './WellKnownComponentTIDs'; import Matrix44 from '../math/Matrix44'; import SceneGraphComponent from './SceneGraphComponent'; import {ProcessStage} from '../definitions/ProcessStage'; import MutableVector3 from '../math/MutableVector3'; import MutableQuaternion from '../math/MutableQuaternion'; import {MathUtil} from '../math/MathUtil'; import MutableVector4 from '../math/MutableVector4'; import MutableMatrix44 from '../math/MutableMatrix44'; import { ComponentTID, ComponentSID, EntityUID, Index, } from '../../types/CommonTypes'; import {ShaderSemantics} from '../definitions/ShaderSemantics'; import GlobalDataRepository from '../core/GlobalDataRepository'; import Config from '../core/Config'; import {BoneDataType} from '../definitions/BoneDataType'; import { IMatrix44 } from '../math/IMatrix'; export default class SkeletalComponent extends Component { public _jointIndices: Index[] = []; private __joints: SceneGraphComponent[] = []; public _inverseBindMatrices: Matrix44[] = []; public _bindShapeMatrix?: Matrix44; private __jointMatrices?: number[]; public jointsHierarchy?: SceneGraphComponent; public isSkinning = true; public isOptimizingMode = true; private static __tmpVec3_0 = MutableVector3.zero(); private static __tmpVec3_1 = MutableVector3.zero(); private static __tmp_mat4 = MutableMatrix44.identity(); private static __tmp_q: MutableQuaternion = new MutableQuaternion(0, 0, 0, 1); private static __identityMat = MutableMatrix44.identity(); private __qArray = new Float32Array(0); private __tsArray = new Float32Array(0); private __tqArray = new Float32Array(0); private __sqArray = new Float32Array(0); private __qtsArray = new Float32Array(0); private __qtsInfo = MutableVector4.dummy(); private __matArray = new Float32Array(0); private __worldMatrix = MutableMatrix44.identity(); private __isWorldMatrixVanilla = true; private static __globalDataRepository = GlobalDataRepository.getInstance(); private static __tookGlobalDataNum = 0; constructor( entityUid: EntityUID, componentSid: ComponentSID, entityRepository: EntityRepository ) { super(entityUid, componentSid, entityRepository); if (SkeletalComponent.__tookGlobalDataNum < Config.maxSkeletonNumber) { if (Config.boneDataType === BoneDataType.Mat44x1) { SkeletalComponent.__globalDataRepository.takeOne( ShaderSemantics.BoneMatrix ); } else if (Config.boneDataType === BoneDataType.Vec4x2) { SkeletalComponent.__globalDataRepository.takeOne( ShaderSemantics.BoneTranslatePackedQuat ); SkeletalComponent.__globalDataRepository.takeOne( ShaderSemantics.BoneScalePackedQuat ); } else if (Config.boneDataType === BoneDataType.Vec4x2Old) { SkeletalComponent.__globalDataRepository.takeOne( ShaderSemantics.BoneQuaternion ); SkeletalComponent.__globalDataRepository.takeOne( ShaderSemantics.BoneTranslateScale ); } else if (Config.boneDataType === BoneDataType.Vec4x1) { SkeletalComponent.__globalDataRepository.takeOne( ShaderSemantics.BoneTranslateScale ); SkeletalComponent.__globalDataRepository.takeOne( ShaderSemantics.BoneCompressedChunk ); } SkeletalComponent.__tookGlobalDataNum++; } else { console.warn( 'The actual number of Skeleton generated exceeds Config.maxSkeletonNumber.' ); } this.moveStageTo(ProcessStage.Logic); } static get componentTID(): ComponentTID { return WellKnownComponentTIDs.SkeletalComponentTID; } set joints(joints: SceneGraphComponent[]) { this.__joints = joints; let index = 0; if (this.componentSID < Config.maxSkeletonNumber) { index = this.componentSID; } if (Config.boneDataType === BoneDataType.Mat44x1) { this.__matArray = SkeletalComponent.__globalDataRepository.getValue( ShaderSemantics.BoneMatrix, index )._v; } else if (Config.boneDataType === BoneDataType.Vec4x2) { this.__tqArray = SkeletalComponent.__globalDataRepository.getValue( ShaderSemantics.BoneTranslatePackedQuat, index )._v; this.__sqArray = SkeletalComponent.__globalDataRepository.getValue( ShaderSemantics.BoneScalePackedQuat, index )._v; } else if (Config.boneDataType === BoneDataType.Vec4x2Old) { this.__qArray = SkeletalComponent.__globalDataRepository.getValue( ShaderSemantics.BoneQuaternion, index )._v; this.__tsArray = SkeletalComponent.__globalDataRepository.getValue( ShaderSemantics.BoneTranslateScale, index )._v; } else if (Config.boneDataType === BoneDataType.Vec4x1) { this.__tsArray = SkeletalComponent.__globalDataRepository.getValue( ShaderSemantics.BoneTranslateScale, index )._v; this.__qtsArray = SkeletalComponent.__globalDataRepository.getValue( ShaderSemantics.BoneCompressedChunk, index )._v; this.__qtsInfo = SkeletalComponent.__globalDataRepository.getValue( ShaderSemantics.BoneCompressedInfo, 0 ); } } get rootJointWorldMatrixInner() { return this.jointsHierarchy?.worldMatrixInner; } get jointMatrices() { return this.__jointMatrices; } get jointQuaternionArray() { return this.__qArray; } get jointTranslateScaleArray() { return this.__tsArray; } get jointTranslatePackedQuat() { return this.__tqArray; } get jointScalePackedQuat() { return this.__sqArray; } get jointMatricesArray() { return this.__matArray; } get jointCompressedChunk() { return this.__qtsArray; } get jointCompressedInfo() { return this.__qtsInfo; } get worldMatrix() { return this.__worldMatrix.clone(); } get worldMatrixInner() { return this.__worldMatrix; } get isWorldMatrixUpdated() { return !this.__isWorldMatrixVanilla; } $logic() { if (!this.isSkinning) { return; } for (let i = 0; i < this.__joints.length; i++) { const joint = this.__joints[i]; let m; if (joint.isVisible) { const globalJointTransform = joint.worldMatrixInner; const inverseBindMatrix = this._inverseBindMatrices[i]; MutableMatrix44.multiplyTo( globalJointTransform, inverseBindMatrix, SkeletalComponent.__tmp_mat4 ); if (this._bindShapeMatrix) { SkeletalComponent.__tmp_mat4.multiply(this._bindShapeMatrix); // only for glTF1 } m = SkeletalComponent.__tmp_mat4; } else { m = SkeletalComponent.__identityMat; } if (i===0) { this.__worldMatrix.copyComponents(m); } this.__isWorldMatrixVanilla = false; if ( Config.boneDataType === BoneDataType.Mat44x1 || Config.boneDataType === BoneDataType.Vec4x1 ) { this.__copyToMatArray(m, i); } if (Config.boneDataType !== BoneDataType.Mat44x1) { const scaleVec = SkeletalComponent.__tmpVec3_0.setComponents( Math.hypot(m.m00, m.m01, m.m02), Math.hypot(m.m10, m.m11, m.m12), Math.hypot(m.m20, m.m21, m.m22) ); m.m00 /= scaleVec.x; m.m01 /= scaleVec.x; m.m02 /= scaleVec.x; m.m10 /= scaleVec.y; m.m11 /= scaleVec.y; m.m12 /= scaleVec.y; m.m20 /= scaleVec.z; m.m21 /= scaleVec.z; m.m22 /= scaleVec.z; const q = SkeletalComponent.__tmp_q.fromMatrix(m); if ( Config.boneDataType === BoneDataType.Vec4x2Old || Config.boneDataType === BoneDataType.Vec4x1 ) { let maxScale = 1; if (Math.abs(scaleVec.x) > Math.abs(scaleVec.y)) { if (Math.abs(scaleVec.x) > Math.abs(scaleVec.z)) { maxScale = scaleVec.x; } else { maxScale = scaleVec.z; } } else { if (Math.abs(scaleVec.y) > Math.abs(scaleVec.z)) { maxScale = scaleVec.y; } else { maxScale = scaleVec.z; } } this.__tsArray[i * 4 + 3] = maxScale; } if (Config.boneDataType === BoneDataType.Vec4x2) { const vec2QPacked = MathUtil.packNormalizedVec4ToVec2( q.x, q.y, q.z, q.w, Math.pow(2, 12) ); this.__tqArray[i * 4 + 0] = m.m03; this.__tqArray[i * 4 + 1] = m.m13; this.__tqArray[i * 4 + 2] = m.m23; this.__sqArray[i * 4 + 0] = scaleVec.x; this.__sqArray[i * 4 + 1] = scaleVec.y; this.__sqArray[i * 4 + 2] = scaleVec.z; this.__tqArray[i * 4 + 3] = vec2QPacked[0]; this.__sqArray[i * 4 + 3] = vec2QPacked[1]; } else if (Config.boneDataType === BoneDataType.Vec4x2Old) { this.__tsArray[i * 4 + 0] = m.m03; // m.getTranslate().x this.__tsArray[i * 4 + 1] = m.m13; // m.getTranslate().y this.__tsArray[i * 4 + 2] = m.m23; // m.getTranslate().z this.__qArray[i * 4 + 0] = q.x; this.__qArray[i * 4 + 1] = q.y; this.__qArray[i * 4 + 2] = q.z; this.__qArray[i * 4 + 3] = q.w; } if (Config.boneDataType === BoneDataType.Vec4x1) { // pack quaternion this.__tsArray[i * 4 + 0] = m.m03; // m.getTranslate().x this.__tsArray[i * 4 + 1] = m.m13; // m.getTranslate().y this.__tsArray[i * 4 + 2] = m.m23; // m.getTranslate().z const vec2QPacked = MathUtil.packNormalizedVec4ToVec2( q.x, q.y, q.z, q.w, Math.pow(2, 12) ); this.__qtsArray[i * 4 + 0] = vec2QPacked[0]; this.__qtsArray[i * 4 + 1] = vec2QPacked[1]; // q.normalize(); } } } if (Config.boneDataType === BoneDataType.Vec4x1) { // const maxScale = Math.max(...scales); let maxAbsX = 1; let maxAbsY = 1; let maxAbsZ = 1; for (let i = 0; i < this.__joints.length; i++) { const absX = Math.abs(this.__tsArray[i * 4 + 0]); if (absX > maxAbsX) { maxAbsX = absX; } const absY = Math.abs(this.__tsArray[i * 4 + 1]); if (absY > maxAbsY) { maxAbsY = absY; } const absZ = Math.abs(this.__tsArray[i * 4 + 2]); if (absZ > maxAbsZ) { maxAbsZ = absZ; } } this.__qtsInfo.x = maxAbsX; this.__qtsInfo.y = maxAbsY; this.__qtsInfo.z = maxAbsZ; this.__qtsInfo.w = 1; for (let i = 0; i < this.__joints.length; i++) { // pack normalized XYZ and Uniform Scale const x = this.__tsArray[i * 4 + 0]; const y = this.__tsArray[i * 4 + 1]; const z = this.__tsArray[i * 4 + 2]; const scale = this.__tsArray[i * 4 + 3]; const normalizedX = x / maxAbsX; const normalizedY = y / maxAbsY; const normalizedZ = z / maxAbsZ; const normalizedW = scale; const vec2TPacked = MathUtil.packNormalizedVec4ToVec2( normalizedX, normalizedY, normalizedZ, normalizedW, Math.pow(2, 12) ); this.__qtsArray[i * 4 + 2] = vec2TPacked[0]; this.__qtsArray[i * 4 + 3] = vec2TPacked[1]; } } } private __copyToMatArray(m: IMatrix44, i: Index) { this.__matArray[i * 16 + 0] = m._v[0]; this.__matArray[i * 16 + 1] = m._v[1]; this.__matArray[i * 16 + 2] = m._v[2]; this.__matArray[i * 16 + 3] = m._v[3]; this.__matArray[i * 16 + 4] = m._v[4]; this.__matArray[i * 16 + 5] = m._v[5]; this.__matArray[i * 16 + 6] = m._v[6]; this.__matArray[i * 16 + 7] = m._v[7]; this.__matArray[i * 16 + 8] = m._v[8]; this.__matArray[i * 16 + 9] = m._v[9]; this.__matArray[i * 16 + 10] = m._v[10]; this.__matArray[i * 16 + 11] = m._v[11]; this.__matArray[i * 16 + 12] = m._v[12]; this.__matArray[i * 16 + 13] = m._v[13]; this.__matArray[i * 16 + 14] = m._v[14]; this.__matArray[i * 16 + 15] = m._v[15]; } } ComponentRepository.registerComponentClass(SkeletalComponent);
the_stack
import tl = require('azure-pipelines-task-lib/task'); import jsonPath = require('JSONPath'); import webClient = require('azure-pipelines-tasks-azure-arm-rest-v2/webClient'); import { AzureEndpoint } from 'azure-pipelines-tasks-azure-arm-rest-v2/azureModels'; import { ServiceClient } from 'azure-pipelines-tasks-azure-arm-rest-v2/AzureServiceClient'; import { ToError } from 'azure-pipelines-tasks-azure-arm-rest-v2/AzureServiceClientBase'; import { uploadFileToSasUrl } from './azure-storage'; import https = require('https'); import { parse } from 'webdeployment-common-v2/ParameterParserUtility'; export const SourceType = { JAR: "Jar", SOURCE_DIRECTORY: "Source", DOT_NET_CORE_ZIP: "NetCoreZip" } class UploadTarget { private _sasUrl: string; private _relativePath: string; constructor(sasUrl: string, relativePath: string) { this._sasUrl = sasUrl; this._relativePath = relativePath; } public get sasUrl(): string { return this._sasUrl; } public get relativePath(): string { return this._relativePath; } } const ASYNC_OPERATION_HEADER = 'azure-asyncoperation'; export class AzureSpringCloud { private _resourceId: string; private _client: ServiceClient; constructor(endpoint: AzureEndpoint, resourceId: string) { tl.debug('Initializeing service client'); this._client = new ServiceClient(endpoint.applicationTokenCredentials, endpoint.subscriptionID, 30); this._resourceId = resourceId; tl.debug('Finished initializeing service client'); } /** * Encapsulates sending of Azure API requests. * @param method * @param url * @param body */ protected sendRequest(method: string, url: string, body?: any): Promise<webClient.WebResponse> { var httpRequest = new webClient.WebRequest(); httpRequest.method = method; httpRequest.uri = url; if (body) httpRequest.body = body; tl.debug(`Sending ${method} request to ${url}`); return this._client.beginRequest(httpRequest); } /** * Deploys an artifact to an Azure Spring Cloud deployment * @param artifactToUpload * @param appName * @param deploymentName * @param createDeployment If true, a new deployment will be created or the prior one will be completely overriden. If false, only the changes to the prior deployment will be applied. * @param jvmOptions * @param environmentVariables */ public async deploy(artifactToUpload: string, sourceType: string, appName: string, deploymentName: string, createDeployment: boolean, runtime?: string, jvmOptions?: string, environmentVariables?: string, dotNetCoreMainEntryPath?: string, version?: string): Promise<void> { //Get deployment URL tl.debug('Starting deployment.'); try { const deploymentTarget = await this.getUploadTarget(appName); await uploadFileToSasUrl(deploymentTarget.sasUrl, artifactToUpload); const deploymentUpdateRequestBody = this.prepareDeploymentUpdateRequestBody(deploymentTarget.relativePath, sourceType, runtime, jvmOptions, environmentVariables, dotNetCoreMainEntryPath, version); await this.applyDeploymentModifications(appName, deploymentName, deploymentUpdateRequestBody, createDeployment); } catch (error) { throw error; } } public async setActiveDeployment(appName: string, deploymentName: string) { console.log(`Setting active deployment on app ${appName} to ${deploymentName}`); const requestUri = this._client.getRequestUri(`${this._resourceId}/apps/{appName}`, { '{appName}': appName, '{deploymentName}': deploymentName }, null, '2020-07-01'); const requestBody = JSON.stringify( { properties: { activeDeploymentName: deploymentName } } ); const response = await this.sendRequest('PATCH', requestUri, requestBody); console.log('Response:'); console.log(response.body); let expectedStatusCodes: number[] = [200, 202]; if (!expectedStatusCodes.includes(response.statusCode)) { tl.error('Error code: ' + response.statusCode); tl.error(response.statusMessage); throw Error(response.statusCode + ":" + response.statusMessage); } else { tl.debug('App update initiated.') //If the operation is asynchronous, block pending its conclusion. var operationStatusUrl = response.headers[ASYNC_OPERATION_HEADER]; if (operationStatusUrl) { tl.debug('Awaiting operation completion.'); try { await this.awaitOperationCompletion(operationStatusUrl); } catch (error) { tl.debug('Error in awaiting operation completion'); throw error; } } else { tl.debug('Received async status code with no async operation. Headers: '); tl.debug(JSON.stringify(response.headers)); } } } protected async getAllDeploymentInfo(appName: String): Promise<Object> { tl.debug(`Finding deployments for app ${appName}`) const requestUri = this._client.getRequestUri(`${this._resourceId}/apps/{appName}/deployments`, { '{appName}': appName }, null, '2020-07-01'); try { const response = await this.sendRequest('GET', requestUri); if (response.statusCode == 404) { tl.debug('404 when querying deployment names'); throw Error(tl.loc('NoDeploymentsExist')); } if (response.statusCode != 200) { tl.error(`${tl.loc('UnableToGetDeploymentInformation')} ${tl.loc('StatusCode')}: ${response.statusCode}`); throw ToError(response); } else { tl.debug('Found deployments.'); return response.body; } } catch (error) { throw (error); } } /** * Returns the currently inactive deployment, or `undefined` if none exists. * @param appName */ public async getInactiveDeploymentName(appName: string): Promise<string> { const allDeploymentsData = await this.getAllDeploymentInfo(appName); const inactiveDeploymentName = jsonPath.eval(allDeploymentsData, '$.value[?(@.properties.active == false)].name')[0]; tl.debug(`Inactive deployment name: ${inactiveDeploymentName}`); return inactiveDeploymentName; } /** * Returns all deployment names for an app. * @param appName */ public async getAllDeploymentNames(appName: string): Promise<string[]> { const allDeploymentsData = await this.getAllDeploymentInfo(appName); const deploymentNames = jsonPath.eval(allDeploymentsData, '$.value[*].name') tl.debug('Found deployment names: ' + deploymentNames); return deploymentNames; } protected async getUploadTarget(appName: string): Promise<UploadTarget> { tl.debug('Obtaining upload target.'); const requestUri = this._client.getRequestUri(`${this._resourceId}/apps/{appName}/getResourceUploadUrl`, { '{appName}': appName }, null, '2020-07-01'); const response = await this.sendRequest('POST', requestUri, null); if (response.statusCode != 200) { console.error('Error code: ' + response.statusCode); console.error(response.statusMessage); throw ToError(response); } return new UploadTarget(response.body.uploadUrl, response.body.relativePath); } /** * Prepares a body for a deployment update request. */ private prepareDeploymentUpdateRequestBody(resourcePath: string, sourceType: string, runtime?: string, jvmOptions?: string, environmentVariables?: string, dotNetCoreMainEntryPath?: string, version?: string) { //Populate optional deployment settings var deploymentSettings = {}; if (runtime) { deploymentSettings['runtimeVersion'] = runtime; } if (jvmOptions) { tl.debug("JVM Options modified."); deploymentSettings['jvmOptions'] = jvmOptions; } if (dotNetCoreMainEntryPath) { tl.debug('.Net Core Entry path specified'); deploymentSettings['netCoreMainEntryPath'] = dotNetCoreMainEntryPath; } if (environmentVariables) { tl.debug("Environment variables modified."); const parsedEnvVariables = parse(environmentVariables); //Parsed pairs come back as {"key1":{"value":"val1"},"key2":{"value":"val 2"}} var transformedEnvironmentVariables = {}; Object.keys(parsedEnvVariables).forEach(key => { transformedEnvironmentVariables[key] = parsedEnvVariables[key]['value']; }); tl.debug('Environment Variables: ' + JSON.stringify(transformedEnvironmentVariables)); deploymentSettings['environmentVariables'] = transformedEnvironmentVariables; } //Populate source settings var sourceSettings = { relativePath: resourcePath, type: sourceType }; if (version) { sourceSettings['version'] = version; } //Build update request body return { properties: { source: sourceSettings, deploymentSettings: deploymentSettings } }; } /** * Creates/Updates deployment settings. * @param appName The name of the app to create/update * @param deploymentName The name of the deployment to create/update * @param deploymentUpdateRequestBody JSON specifying all deployment properties * @param createDeployment Whether or not a new deployment should be created. */ private async applyDeploymentModifications(appName: string, deploymentName: string, deploymentUpdateRequestBody, createDeployment: boolean) { console.log(`${createDeployment ? 'Creating' : 'Updating'} ${appName}, deployment ${deploymentName}...`); let method = createDeployment ? 'PUT' : 'PATCH'; let requestUri = this._client.getRequestUri(`${this._resourceId}/apps/{appName}/deployments/{deploymentName}`, { '{appName}': appName, '{deploymentName}': deploymentName }, null, '2020-07-01'); // Send the request try { var response = await this.sendRequest(method, requestUri, JSON.stringify(deploymentUpdateRequestBody)); } catch (error) { tl.debug('Error when sending app update request'); throw (error); } console.log(response.body); let expectedStatusCodes: number[] = createDeployment ? [201, 202] : [202]; if (!expectedStatusCodes.includes(response.statusCode)) { console.error(`${tl.loc('StatusCode')}: ${response.statusCode}`); console.error(response.statusMessage); throw ToError(response); } else { tl.debug('App update initiated.') //If the operation is asynchronous, block pending its conclusion. var operationStatusUrl = response.headers[ASYNC_OPERATION_HEADER]; if (operationStatusUrl) { tl.debug('Awaiting operation completion.'); try { await this.awaitOperationCompletion(operationStatusUrl); } catch (error) { tl.debug('Error in awaiting operation completion'); throw error; } finally { //A build log is available on the deployment when uploading a folder. Let's display it. if (deploymentUpdateRequestBody.properties.source.sourceType == SourceType.SOURCE_DIRECTORY) await this.printDeploymentLog(appName, deploymentName); } } else { tl.debug('Received async status code with no async operation. Headers: '); tl.debug(JSON.stringify(response.headers)); } } } /** * Obtains the build/deployment log for a deployment and prints it to the console. * @param appName * @param deploymentName */ async printDeploymentLog(appName: string, deploymentName: string) { let logUrlRequestUri = this._client.getRequestUri(this._resourceId + '/apps/{appName}/deployments/{deploymentName}/getLogFileUrl', { '{appName}': appName, '{deploymentName}': deploymentName }, null, "2020-07-01"); var logUrl: string; try { var logUrlResponse = await this.sendRequest('POST', logUrlRequestUri); var logUrlResponseBody = logUrlResponse.body; logUrl = logUrlResponseBody.url; } catch (error) { tl.warning('Unable to get deployment log URL: ' + error); return; } //Can't use the regular client as the presence of an Authorization header results in errors. https.get(logUrl, response => { var downloadedLog = ''; //another chunk of data has been received, so append it to `str` response.on('data', function (chunk) { downloadedLog += chunk; }); //the whole response has been received, so we just print it out here response.on('end', function () { console.log('========================================================'); console.log(' ' + tl.loc('DeploymentLog')); console.log('========================================================'); console.log(downloadedLog); }); }).end(); } /** * Awaits the completion of an operation marked by a return of status code 200 from the status URL. * @param operationStatusUrl The status URL of the Azure operation */ async awaitOperationCompletion(operationStatusUrl: string) { tl.debug('Checking operation status at ' + operationStatusUrl); var statusCode = 202; var message = ''; var response: webClient.WebResponse; //A potentially infinite loop, but tasks can have timeouts.throw (`${response.body.error.code}`) while (statusCode == 202) { //Sleep for a 1.5 seconds await new Promise(r => setTimeout(r, 1500)); //Get status response = await this.sendRequest('GET', operationStatusUrl); statusCode = response.statusCode; message = response.statusMessage; tl.debug(`${statusCode}: ${message}`); } switch (statusCode) { case 202: { tl.error(tl.loc(('OperationTimedOut'))); break; } case 200: { var responseError = response.body.error; if (responseError) { throw Error(`${responseError.message} [${responseError.code}]`) } break; } default: { throw Error(tl.loc('OperationFailed', statusCode, message)); } } } /** * Deletes a deployment of the app. * @param appName * @param deploymentName */ public async deleteDeployment(appName: string, deploymentName: string) { console.log(`Deleting deployment ${deploymentName} from app ${appName}`); let requestUri = this._client.getRequestUri(`${this._resourceId}/apps/{appName}/deployments/{deploymentName}`, { '{appName}': appName, '{deploymentName}': deploymentName }, null, '2020-07-01'); var response = await this.sendRequest('DELETE', requestUri); if (response.statusCode != 200) { console.error(`${tl.loc('UnableToDeleteDeployment')} ${tl.loc('StatusCode')}: ${response.statusCode}`); console.error(response.statusMessage); throw Error(tl.loc('UnableToDeleteDeployment')); } } /** * Retrieves the private test endpoint(s) for the deployment. * Returns null if private endpoint is disabled. */ public async getTestEndpoint(appName: string, deploymentName: string): Promise<string> { tl.debug(`Retrieving private endpoint for deployment ${deploymentName} from app ${appName}`); let requestUri = this._client.getRequestUri(`${this._resourceId}/listTestKeys`, {}, null, '2020-07-01'); try { var response: webClient.WebResponse = await this.sendRequest('POST', requestUri); if (!response.body.enabled) { tl.warning(tl.loc('PrivateTestEndpointNotEnabled')); return null; } else { tl.debug('Private endpoint returned.'); return `${response.body.primaryTestEndpoint}/${encodeURIComponent(appName)}/${encodeURIComponent(deploymentName)}` } } catch (error) { tl.error(tl.loc('UnableToRetrieveTestEndpointKeys')); throw (error); } } }
the_stack
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Inject, Injectable } from '@angular/core'; import { MemoizedSelector, select, Store } from '@ngrx/store'; import { combineLatest as observableCombineLatest, Observable } from 'rxjs'; import { distinctUntilChanged, filter, map, mergeMap, startWith, switchMap, take, tap } from 'rxjs/operators'; import { compareArraysUsingIds, PAGINATED_RELATIONS_TO_ITEMS_OPERATOR, relationsToItems } from '../../item-page/simple/item-types/shared/item-relationships-utils'; import { AppState, keySelector } from '../../app.reducer'; import { hasValue, hasValueOperator, isNotEmpty, isNotEmptyOperator } from '../../shared/empty.util'; import { ReorderableRelationship } from '../../shared/form/builder/ds-dynamic-form-ui/existing-metadata-list-element/existing-metadata-list-element.component'; import { RemoveNameVariantAction, SetNameVariantAction } from '../../shared/form/builder/ds-dynamic-form-ui/relation-lookup-modal/name-variant.actions'; import { NameVariantListState } from '../../shared/form/builder/ds-dynamic-form-ui/relation-lookup-modal/name-variant.reducer'; import { NotificationsService } from '../../shared/notifications/notifications.service'; import { followLink, FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; import { dataService } from '../cache/builders/build-decorators'; import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; import { RequestParam } from '../cache/models/request-param.model'; import { ObjectCacheService } from '../cache/object-cache.service'; import { CoreState } from '../core.reducers'; import { HttpOptions } from '../dspace-rest/dspace-rest.service'; import { HALEndpointService } from '../shared/hal-endpoint.service'; import { RelationshipType } from '../shared/item-relationships/relationship-type.model'; import { Relationship } from '../shared/item-relationships/relationship.model'; import { RELATIONSHIP } from '../shared/item-relationships/relationship.resource-type'; import { Item } from '../shared/item.model'; import { sendRequest, getFirstCompletedRemoteData, getFirstSucceededRemoteData, getFirstSucceededRemoteDataPayload, getRemoteDataPayload } from '../shared/operators'; import { DataService } from './data.service'; import { DefaultChangeAnalyzer } from './default-change-analyzer.service'; import { ItemDataService } from './item-data.service'; import { PaginatedList } from './paginated-list.model'; import { RemoteData } from './remote-data'; import { DeleteRequest, FindListOptions, PostRequest, RestRequest } from './request.models'; import { RequestService } from './request.service'; import { RequestEntryState } from './request.reducer'; import { NoContent } from '../shared/NoContent.model'; const relationshipListsStateSelector = (state: AppState) => state.relationshipLists; const relationshipListStateSelector = (listID: string): MemoizedSelector<AppState, NameVariantListState> => { return keySelector<NameVariantListState>(listID, relationshipListsStateSelector); }; const relationshipStateSelector = (listID: string, itemID: string): MemoizedSelector<AppState, string> => { return keySelector<string>(itemID, relationshipListStateSelector(listID)); }; /** * Return true if the Item in the payload of the source observable matches * the given Item by UUID * * @param itemCheck the Item to compare with */ const compareItemsByUUID = (itemCheck: Item) => (source: Observable<RemoteData<Item>>): Observable<boolean> => source.pipe( getFirstSucceededRemoteDataPayload(), map((item: Item) => item.uuid === itemCheck.uuid) ); /** * The service handling all relationship requests */ @Injectable() @dataService(RELATIONSHIP) export class RelationshipService extends DataService<Relationship> { protected linkPath = 'relationships'; protected responseMsToLive = 15 * 60 * 1000; constructor(protected itemService: ItemDataService, protected requestService: RequestService, protected rdbService: RemoteDataBuildService, protected store: Store<CoreState>, protected halService: HALEndpointService, protected objectCache: ObjectCacheService, protected notificationsService: NotificationsService, protected http: HttpClient, protected comparator: DefaultChangeAnalyzer<Relationship>, protected appStore: Store<AppState>, @Inject(PAGINATED_RELATIONS_TO_ITEMS_OPERATOR) private paginatedRelationsToItems: (thisId: string) => (source: Observable<RemoteData<PaginatedList<Relationship>>>) => Observable<RemoteData<PaginatedList<Item>>>) { super(); } /** * Get the endpoint for a relationship by ID * @param uuid */ getRelationshipEndpoint(uuid: string) { return this.getBrowseEndpoint().pipe( map((href: string) => `${href}/${uuid}`) ); } /** * Send a delete request for a relationship by ID * @param id */ deleteRelationship(id: string, copyVirtualMetadata: string): Observable<RemoteData<NoContent>> { return this.getRelationshipEndpoint(id).pipe( isNotEmptyOperator(), take(1), distinctUntilChanged(), map((endpointURL: string) => new DeleteRequest(this.requestService.generateRequestId(), endpointURL + '?copyVirtualMetadata=' + copyVirtualMetadata) ), sendRequest(this.requestService), switchMap((restRequest: RestRequest) => this.rdbService.buildFromRequestUUID(restRequest.uuid)), getFirstCompletedRemoteData(), tap(() => this.refreshRelationshipItemsInCacheByRelationship(id)), ); } /** * Method to create a new relationship * @param typeId The identifier of the relationship type * @param item1 The first item of the relationship * @param item2 The second item of the relationship * @param leftwardValue The leftward value of the relationship * @param rightwardValue The rightward value of the relationship */ addRelationship(typeId: string, item1: Item, item2: Item, leftwardValue?: string, rightwardValue?: string): Observable<RemoteData<Relationship>> { const options: HttpOptions = Object.create({}); let headers = new HttpHeaders(); headers = headers.append('Content-Type', 'text/uri-list'); options.headers = headers; return this.halService.getEndpoint(this.linkPath).pipe( isNotEmptyOperator(), take(1), map((endpointUrl: string) => `${endpointUrl}?relationshipType=${typeId}`), map((endpointUrl: string) => isNotEmpty(leftwardValue) ? `${endpointUrl}&leftwardValue=${leftwardValue}` : endpointUrl), map((endpointUrl: string) => isNotEmpty(rightwardValue) ? `${endpointUrl}&rightwardValue=${rightwardValue}` : endpointUrl), map((endpointURL: string) => new PostRequest(this.requestService.generateRequestId(), endpointURL, `${item1.self} \n ${item2.self}`, options)), sendRequest(this.requestService), switchMap((restRequest: RestRequest) => this.rdbService.buildFromRequestUUID(restRequest.uuid)), getFirstCompletedRemoteData(), tap(() => this.refreshRelationshipItemsInCache(item1)), tap(() => this.refreshRelationshipItemsInCache(item2)), ) as Observable<RemoteData<Relationship>>; } /** * Method to remove two items of a relationship from the cache using the identifier of the relationship * @param relationshipId The identifier of the relationship */ private refreshRelationshipItemsInCacheByRelationship(relationshipId: string) { this.findById(relationshipId, true, false, followLink('leftItem'), followLink('rightItem')).pipe( getFirstSucceededRemoteData(), getRemoteDataPayload(), switchMap((rel: Relationship) => observableCombineLatest( rel.leftItem.pipe(getFirstSucceededRemoteData(), getRemoteDataPayload()), rel.rightItem.pipe(getFirstSucceededRemoteData(), getRemoteDataPayload()) ) ), take(1) ).subscribe(([item1, item2]) => { this.refreshRelationshipItemsInCache(item1); this.refreshRelationshipItemsInCache(item2); }); } /** * Method to remove an item that's part of a relationship from the cache * @param item The item to remove from the cache */ public refreshRelationshipItemsInCache(item) { this.objectCache.remove(item._links.self.href); this.requestService.removeByHrefSubstring(item.uuid); observableCombineLatest([ this.objectCache.hasByHref$(item._links.self.href), this.requestService.hasByHref$(item.self) ]).pipe( filter(([existsInOC, existsInRC]) => !existsInOC && !existsInRC), take(1), ).subscribe(() => this.itemService.findByHref(item._links.self.href, false)); } /** * Get an item's relationships in the form of an array * * @param item The {@link Item} to get {@link Relationship}s for * @param linksToFollow List of {@link FollowLinkConfig} that indicate which {@link HALLink}s * should be automatically resolved */ getItemRelationshipsArray(item: Item, ...linksToFollow: FollowLinkConfig<Relationship>[]): Observable<Relationship[]> { return this.findAllByHref(item._links.relationships.href, undefined, true, false, ...linksToFollow).pipe( getFirstSucceededRemoteData(), getRemoteDataPayload(), map((rels: PaginatedList<Relationship>) => rels.page), hasValueOperator(), distinctUntilChanged(compareArraysUsingIds()), ); } /** * Get an array of the labels of an item’s unique relationship types * The array doesn't contain any duplicate labels * @param item */ getRelationshipTypeLabelsByItem(item: Item): Observable<string[]> { return this.getItemRelationshipsArray(item, followLink('leftItem'), followLink('rightItem'), followLink('relationshipType')).pipe( switchMap((relationships: Relationship[]) => observableCombineLatest(relationships.map((relationship: Relationship) => this.getRelationshipTypeLabelByRelationshipAndItem(relationship, item)))), map((labels: string[]) => Array.from(new Set(labels))) ); } private getRelationshipTypeLabelByRelationshipAndItem(relationship: Relationship, item: Item): Observable<string> { return relationship.leftItem.pipe( getFirstSucceededRemoteData(), map((itemRD: RemoteData<Item>) => itemRD.payload), switchMap((otherItem: Item) => relationship.relationshipType.pipe( getFirstSucceededRemoteData(), map((relationshipTypeRD) => relationshipTypeRD.payload), map((relationshipType: RelationshipType) => { if (otherItem.uuid === item.uuid) { return relationshipType.leftwardType; } else { return relationshipType.rightwardType; } }) ) )); } /** * Resolve a given item's relationships into related items and return the items as an array * @param item */ getRelatedItems(item: Item): Observable<Item[]> { return this.getItemRelationshipsArray( item, followLink('leftItem'), followLink('rightItem'), followLink('relationshipType') ).pipe( relationsToItems(item.uuid) ); } /** * Resolve a given item's relationships into related items, filtered by a relationship label * and return the items as an array * @param item * @param label * @param options */ getRelatedItemsByLabel(item: Item, label: string, options?: FindListOptions): Observable<RemoteData<PaginatedList<Item>>> { return this.getItemRelationshipsByLabel(item, label, options, true, true, followLink('leftItem'), followLink('rightItem'), followLink('relationshipType')).pipe(this.paginatedRelationsToItems(item.uuid)); } /** * Resolve a given item's relationships by label * This should move to the REST API. * * @param item * @param label * @param options * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved */ getItemRelationshipsByLabel(item: Item, label: string, options?: FindListOptions, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<Relationship>[]): Observable<RemoteData<PaginatedList<Relationship>>> { let findListOptions = new FindListOptions(); if (options) { findListOptions = Object.assign(new FindListOptions(), options); } const searchParams = [new RequestParam('label', label), new RequestParam('dso', item.id)]; if (findListOptions.searchParams) { findListOptions.searchParams = [...findListOptions.searchParams, ...searchParams]; } else { findListOptions.searchParams = searchParams; } return this.searchBy('byLabel', findListOptions, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } /** * Method for fetching an item's relationships, but filtered by related item IDs (essentially performing a reverse lookup) * Only relationships where leftItem or rightItem's ID is present in the list provided will be returned * @param item * @param uuids */ getRelationshipsByRelatedItemIds(item: Item, uuids: string[]): Observable<Relationship[]> { return this.getItemRelationshipsArray(item, followLink('leftItem'), followLink('rightItem')).pipe( switchMap((relationships: Relationship[]) => { return observableCombineLatest(relationships.map((relationship: Relationship) => { const isLeftItem$ = this.isItemInUUIDArray(relationship.leftItem, uuids); const isRightItem$ = this.isItemInUUIDArray(relationship.rightItem, uuids); return observableCombineLatest([isLeftItem$, isRightItem$]).pipe( filter(([isLeftItem, isRightItem]) => isLeftItem || isRightItem), map(() => relationship), startWith(undefined) ); })); }), map((relationships: Relationship[]) => relationships.filter(((relationship) => hasValue(relationship)))), ); } private isItemInUUIDArray(itemRD$: Observable<RemoteData<Item>>, uuids: string[]) { return itemRD$.pipe( getFirstSucceededRemoteData(), map((itemRD: RemoteData<Item>) => itemRD.payload), map((item: Item) => uuids.includes(item.uuid)) ); } /** * Method to retrieve a relationship based on two items and a relationship type label * @param item1 The first item in the relationship * @param item2 The second item in the relationship * @param label The rightward or leftward type of the relationship */ getRelationshipByItemsAndLabel(item1: Item, item2: Item, label: string, options?: FindListOptions): Observable<Relationship> { return this.getItemRelationshipsByLabel( item1, label, options, true, false, followLink('relationshipType'), followLink('leftItem'), followLink('rightItem') ).pipe( getFirstSucceededRemoteData(), // the mergemap below will emit all elements of the list as separate events mergeMap((relationshipListRD: RemoteData<PaginatedList<Relationship>>) => relationshipListRD.payload.page), mergeMap((relationship: Relationship) => { return observableCombineLatest([ this.itemService.findByHref(relationship._links.leftItem.href).pipe(compareItemsByUUID(item2)), this.itemService.findByHref(relationship._links.rightItem.href).pipe(compareItemsByUUID(item2)) ]).pipe( map(([isLeftItem, isRightItem]) => isLeftItem || isRightItem), map((isMatch) => isMatch ? relationship : undefined) ); }), filter((relationship) => hasValue(relationship)), take(1) ); } /** * Method to set the name variant for specific list and item * @param listID The list for which to save the name variant * @param itemID The item ID for which to save the name variant * @param nameVariant The name variant to save */ public setNameVariant(listID: string, itemID: string, nameVariant: string) { this.appStore.dispatch(new SetNameVariantAction(listID, itemID, nameVariant)); } /** * Method to retrieve the name variant for a specific list and item * @param listID The list for which to retrieve the name variant * @param itemID The item ID for which to retrieve the name variant */ public getNameVariant(listID: string, itemID: string): Observable<string> { return this.appStore.pipe( select(relationshipStateSelector(listID, itemID)) ); } /** * Method to remove the name variant for specific list and item * @param listID The list for which to remove the name variant * @param itemID The item ID for which to remove the name variant */ public removeNameVariant(listID: string, itemID: string) { this.appStore.dispatch(new RemoveNameVariantAction(listID, itemID)); } /** * Method to retrieve all name variants for a single list * @param listID The id of the list */ public getNameVariantsByListID(listID: string) { return this.appStore.pipe(select(relationshipListStateSelector(listID))); } /** * Method to update the name variant on the server * @param item1 The first item of the relationship * @param item2 The second item of the relationship * @param relationshipLabel The leftward or rightward type of the relationship * @param nameVariant The name variant to set for the matching relationship */ public updateNameVariant(item1: Item, item2: Item, relationshipLabel: string, nameVariant: string): Observable<RemoteData<Relationship>> { return this.getRelationshipByItemsAndLabel(item1, item2, relationshipLabel) .pipe( switchMap((relation: Relationship) => relation.relationshipType.pipe( getFirstSucceededRemoteData(), getRemoteDataPayload(), map((type) => { return { relation, type }; }) ) ), switchMap((relationshipAndType: { relation: Relationship, type: RelationshipType }) => { const { relation, type } = relationshipAndType; let updatedRelationship; if (relationshipLabel === type.leftwardType) { updatedRelationship = Object.assign(new Relationship(), relation, { rightwardValue: nameVariant }); } else { updatedRelationship = Object.assign(new Relationship(), relation, { leftwardValue: nameVariant }); } return this.update(updatedRelationship); }), ); } /** * Check whether a given item is the left item of a given relationship, as an observable boolean * @param relationship the relationship for which to check whether the given item is the left item * @param item the item for which to check whether it is the left item of the given relationship */ public isLeftItem(relationship: Relationship, item: Item): Observable<boolean> { return relationship.leftItem.pipe( getFirstSucceededRemoteData(), getRemoteDataPayload(), filter((leftItem: Item) => hasValue(leftItem) && isNotEmpty(leftItem.uuid)), map((leftItem) => leftItem.uuid === item.uuid) ); } /** * Method to update the the right or left place of a relationship * The useLeftItem field in the reorderable relationship determines which place should be updated * @param reoRel */ public updatePlace(reoRel: ReorderableRelationship): Observable<RemoteData<Relationship>> { let updatedRelationship; if (reoRel.useLeftItem) { updatedRelationship = Object.assign(new Relationship(), reoRel.relationship, { rightPlace: reoRel.newIndex }); } else { updatedRelationship = Object.assign(new Relationship(), reoRel.relationship, { leftPlace: reoRel.newIndex }); } const update$ = this.update(updatedRelationship); update$.pipe( filter((relationshipRD: RemoteData<Relationship>) => relationshipRD.state === RequestEntryState.ResponsePending), take(1), ).subscribe((relationshipRD: RemoteData<Relationship>) => { if (relationshipRD.state === RequestEntryState.ResponsePending) { this.refreshRelationshipItemsInCacheByRelationship(reoRel.relationship.id); } }); return update$; } /** * Patch isn't supported on the relationship endpoint, so use put instead. * * @param object the {@link Relationship} to update */ update(object: Relationship): Observable<RemoteData<Relationship>> { return this.put(object); } /** * Patch isn't supported on the relationship endpoint, so use put instead. * * @param typeId the relationship type id to apply as a filter to the returned relationships * @param itemUuid The uuid of the item to be checked on the side defined by relationshipLabel * @param relationshipLabel the name of the relation as defined from the side of the itemUuid * @param arrayOfItemIds The uuid of the items to be found on the other side of returned relationships */ searchByItemsAndType(typeId: string,itemUuid: string,relationshipLabel: string, arrayOfItemIds: string[] ): Observable<RemoteData<PaginatedList<Relationship>>> { const searchParams = [ { fieldName: 'typeId', fieldValue: typeId }, { fieldName: 'focusItem', fieldValue: itemUuid }, { fieldName: 'relationshipLabel', fieldValue: relationshipLabel }, { fieldName: 'size', fieldValue: arrayOfItemIds.length }, { fieldName: 'embed', fieldValue: 'leftItem' }, { fieldName: 'embed', fieldValue: 'rightItem' }, ]; arrayOfItemIds.forEach( (itemId) => { searchParams.push( { fieldName: 'relatedItem', fieldValue: itemId }, ); }); return this.searchBy( 'byItemsAndType', { searchParams: searchParams }) as Observable<RemoteData<PaginatedList<Relationship>>>; } }
the_stack
import * as THREE from 'three'; import { mat4InvertCompat } from '../utils/mat4InvertCompat'; import { getWorldQuaternionLite } from '../utils/math'; import { Matrix4InverseCache } from '../utils/Matrix4InverseCache'; import { VRMSpringBoneColliderMesh } from './VRMSpringBoneColliderGroup'; import { VRMSpringBoneParameters } from './VRMSpringBoneParameters'; // based on // http://rocketjump.skr.jp/unity3d/109/ // https://github.com/dwango/UniVRM/blob/master/Scripts/SpringBone/VRMSpringBone.cs const IDENTITY_MATRIX4 = Object.freeze(new THREE.Matrix4()); const IDENTITY_QUATERNION = Object.freeze(new THREE.Quaternion()); // 計算中の一時保存用変数(一度インスタンスを作ったらあとは使い回す) const _v3A = new THREE.Vector3(); const _v3B = new THREE.Vector3(); const _v3C = new THREE.Vector3(); const _quatA = new THREE.Quaternion(); const _matA = new THREE.Matrix4(); const _matB = new THREE.Matrix4(); /** * A class represents a single spring bone of a VRM. * It should be managed by a [[VRMSpringBoneManager]]. */ export class VRMSpringBone { /** * Radius of the bone, will be used for collision. */ public radius: number; /** * Stiffness force of the bone. Increasing the value = faster convergence (feels "harder"). * On UniVRM, its range on GUI is between `0.0` and `4.0` . */ public stiffnessForce: number; /** * Power of the gravity against this bone. * The "power" used in here is very far from scientific physics term... */ public gravityPower: number; /** * Direction of the gravity against this bone. * Usually it should be normalized. */ public gravityDir: THREE.Vector3; /** * Drag force of the bone. Increasing the value = less oscillation (feels "heavier"). * On UniVRM, its range on GUI is between `0.0` and `1.0` . */ public dragForce: number; /** * Collider groups attached to this bone. */ public colliders: VRMSpringBoneColliderMesh[]; /** * An Object3D attached to this bone. */ public readonly bone: THREE.Object3D; /** * Current position of child tail, in world unit. Will be used for verlet integration. */ protected _currentTail = new THREE.Vector3(); /** * Previous position of child tail, in world unit. Will be used for verlet integration. */ protected _prevTail = new THREE.Vector3(); /** * Next position of child tail, in world unit. Will be used for verlet integration. * Actually used only in [[update]] and it's kind of temporary variable. */ protected _nextTail = new THREE.Vector3(); /** * Initial axis of the bone, in local unit. */ protected _boneAxis = new THREE.Vector3(); /** * Length of the bone in relative space unit. Will be used for normalization in update loop. * It's same as local unit length unless there are scale transformation in world matrix. */ protected _centerSpaceBoneLength: number; /** * Position of this bone in relative space, kind of a temporary variable. */ protected _centerSpacePosition = new THREE.Vector3(); /** * This springbone will be calculated based on the space relative from this object. * If this is `null`, springbone will be calculated in world space. */ protected _center: THREE.Object3D | null = null; public get center(): THREE.Object3D | null { return this._center; } public set center(center: THREE.Object3D | null) { // convert tails to world space this._getMatrixCenterToWorld(_matA); this._currentTail.applyMatrix4(_matA); this._prevTail.applyMatrix4(_matA); this._nextTail.applyMatrix4(_matA); // uninstall inverse cache if (this._center?.userData.inverseCacheProxy) { (this._center.userData.inverseCacheProxy as Matrix4InverseCache).revert(); delete this._center.userData.inverseCacheProxy; } // change the center this._center = center; // install inverse cache if (this._center) { if (!this._center.userData.inverseCacheProxy) { this._center.userData.inverseCacheProxy = new Matrix4InverseCache(this._center.matrixWorld); } } // convert tails to center space this._getMatrixWorldToCenter(_matA); this._currentTail.applyMatrix4(_matA); this._prevTail.applyMatrix4(_matA); this._nextTail.applyMatrix4(_matA); // convert center space dependant state _matA.multiply(this.bone.matrixWorld); // 🔥 ?? this._centerSpacePosition.setFromMatrixPosition(_matA); this._centerSpaceBoneLength = _v3A .copy(this._initialLocalChildPosition) .applyMatrix4(_matA) .sub(this._centerSpacePosition) .length(); } /** * Rotation of parent bone, in world unit. * We should update this constantly in [[update]]. */ private _parentWorldRotation = new THREE.Quaternion(); /** * Initial state of the local matrix of the bone. */ private _initialLocalMatrix = new THREE.Matrix4(); /** * Initial state of the rotation of the bone. */ private _initialLocalRotation = new THREE.Quaternion(); /** * Initial state of the position of its child. */ private _initialLocalChildPosition = new THREE.Vector3(); /** * Create a new VRMSpringBone. * * @param bone An Object3D that will be attached to this bone * @param params Several parameters related to behavior of the spring bone */ constructor(bone: THREE.Object3D, params: VRMSpringBoneParameters = {}) { this.bone = bone; // uniVRMでの parent this.bone.matrixAutoUpdate = false; // updateにより計算されるのでthree.js内での自動処理は不要 this.radius = params.radius ?? 0.02; this.stiffnessForce = params.stiffnessForce ?? 1.0; this.gravityDir = params.gravityDir ? new THREE.Vector3().copy(params.gravityDir) : new THREE.Vector3().set(0.0, -1.0, 0.0); this.gravityPower = params.gravityPower ?? 0.0; this.dragForce = params.dragForce ?? 0.4; this.colliders = params.colliders ?? []; this._centerSpacePosition.setFromMatrixPosition(this.bone.matrixWorld); this._initialLocalMatrix.copy(this.bone.matrix); this._initialLocalRotation.copy(this.bone.quaternion); if (this.bone.children.length === 0) { // 末端のボーン。子ボーンがいないため「自分の少し先」が子ボーンということにする // https://github.com/dwango/UniVRM/blob/master/Assets/VRM/UniVRM/Scripts/SpringBone/VRMSpringBone.cs#L246 this._initialLocalChildPosition.copy(this.bone.position).normalize().multiplyScalar(0.07); // magic number! derives from original source } else { const firstChild = this.bone.children[0]; this._initialLocalChildPosition.copy(firstChild.position); } this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)); this._prevTail.copy(this._currentTail); this._nextTail.copy(this._currentTail); this._boneAxis.copy(this._initialLocalChildPosition).normalize(); this._centerSpaceBoneLength = _v3A .copy(this._initialLocalChildPosition) .applyMatrix4(this.bone.matrixWorld) .sub(this._centerSpacePosition) .length(); this.center = params.center ?? null; } /** * Reset the state of this bone. * You might want to call [[VRMSpringBoneManager.reset]] instead. */ public reset(): void { this.bone.quaternion.copy(this._initialLocalRotation); // We need to update its matrixWorld manually, since we tweaked the bone by our hand this.bone.updateMatrix(); this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(), this.bone.matrix); this._centerSpacePosition.setFromMatrixPosition(this.bone.matrixWorld); // Apply updated position to tail states this.bone.localToWorld(this._currentTail.copy(this._initialLocalChildPosition)); this._prevTail.copy(this._currentTail); this._nextTail.copy(this._currentTail); } /** * Update the state of this bone. * You might want to call [[VRMSpringBoneManager.update]] instead. * * @param delta deltaTime */ public update(delta: number): void { if (delta <= 0) return; // 親スプリングボーンの姿勢は常に変化している。 // それに基づいて処理直前に自分のworldMatrixを更新しておく this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(), this.bone.matrix); if (this.bone.parent) { // SpringBoneは親から順に処理されていくため、 // 親のmatrixWorldは最新状態の前提でworldMatrixからquaternionを取り出す。 // 制限はあるけれど、計算は少ないのでgetWorldQuaternionではなくこの方法を取る。 getWorldQuaternionLite(this.bone.parent, this._parentWorldRotation); } else { this._parentWorldRotation.copy(IDENTITY_QUATERNION); } // Get bone position in center space this._getMatrixWorldToCenter(_matA); _matA.multiply(this.bone.matrixWorld); // 🔥 ?? this._centerSpacePosition.setFromMatrixPosition(_matA); // Get parent position in center space this._getMatrixWorldToCenter(_matB); _matB.multiply(this._getParentMatrixWorld()); // several parameters const stiffness = this.stiffnessForce * delta; const external = _v3B.copy(this.gravityDir).multiplyScalar(this.gravityPower * delta); // verlet積分で次の位置を計算 this._nextTail .copy(this._currentTail) .add( _v3A .copy(this._currentTail) .sub(this._prevTail) .multiplyScalar(1 - this.dragForce), ) // 前フレームの移動を継続する(減衰もあるよ) .add( _v3A .copy(this._boneAxis) .applyMatrix4(this._initialLocalMatrix) .applyMatrix4(_matB) .sub(this._centerSpacePosition) .normalize() .multiplyScalar(stiffness), ) // 親の回転による子ボーンの移動目標 .add(external); // 外力による移動量 // normalize bone length this._nextTail .sub(this._centerSpacePosition) .normalize() .multiplyScalar(this._centerSpaceBoneLength) .add(this._centerSpacePosition); // Collisionで移動 this._collision(this._nextTail); this._prevTail.copy(this._currentTail); this._currentTail.copy(this._nextTail); // Apply rotation, convert vector3 thing into actual quaternion // Original UniVRM is doing world unit calculus at here but we're gonna do this on local unit // since Three.js is not good at world coordination stuff const initialCenterSpaceMatrixInv = mat4InvertCompat(_matA.copy(_matB.multiply(this._initialLocalMatrix))); const applyRotation = _quatA.setFromUnitVectors( this._boneAxis, _v3A.copy(this._nextTail).applyMatrix4(initialCenterSpaceMatrixInv).normalize(), ); this.bone.quaternion.copy(this._initialLocalRotation).multiply(applyRotation); // We need to update its matrixWorld manually, since we tweaked the bone by our hand this.bone.updateMatrix(); this.bone.matrixWorld.multiplyMatrices(this._getParentMatrixWorld(), this.bone.matrix); } /** * Do collision math against every colliders attached to this bone. * * @param tail The tail you want to process */ private _collision(tail: THREE.Vector3): void { this.colliders.forEach((collider) => { this._getMatrixWorldToCenter(_matA); _matA.multiply(collider.matrixWorld); const colliderCenterSpacePosition = _v3A.setFromMatrixPosition(_matA); const colliderRadius = collider.geometry.boundingSphere!.radius; // the bounding sphere is guaranteed to be exist by VRMSpringBoneImporter._createColliderMesh const r = this.radius + colliderRadius; if (tail.distanceToSquared(colliderCenterSpacePosition) <= r * r) { // ヒット。Colliderの半径方向に押し出す const normal = _v3B.subVectors(tail, colliderCenterSpacePosition).normalize(); const posFromCollider = _v3C.addVectors(colliderCenterSpacePosition, normal.multiplyScalar(r)); // normalize bone length tail.copy( posFromCollider .sub(this._centerSpacePosition) .normalize() .multiplyScalar(this._centerSpaceBoneLength) .add(this._centerSpacePosition), ); } }); } /** * Create a matrix that converts center space into world space. * @param target Target matrix */ private _getMatrixCenterToWorld(target: THREE.Matrix4): THREE.Matrix4 { if (this._center) { target.copy(this._center.matrixWorld); } else { target.identity(); } return target; } /** * Create a matrix that converts world space into center space. * @param target Target matrix */ private _getMatrixWorldToCenter(target: THREE.Matrix4): THREE.Matrix4 { if (this._center) { target.copy((this._center.userData.inverseCacheProxy as Matrix4InverseCache).inverse); } else { target.identity(); } return target; } /** * Returns the world matrix of its parent object. */ private _getParentMatrixWorld(): THREE.Matrix4 { return this.bone.parent ? this.bone.parent.matrixWorld : IDENTITY_MATRIX4; } }
the_stack
import * as d3 from "d3"; import { buildNetworkDAG, topologicalSort } from "../model/build_network"; import { generateJulia, generatePython } from "../model/code_generation"; import { changeDataset } from "../model/data"; import { download, graphToJson } from "../model/export_model"; import { setupPlots, setupTestResults, showPredictions } from "../model/graphs"; import { train } from "../model/mnist_model"; import { model } from "../model/params_object"; import { loadStateIfPossible, storeNetworkInUrl } from "../model/save_state_url"; import { clearError, displayError } from "./error"; import { blankTemplate, defaultTemplate, resnetTemplate } from "./model_templates"; import { Activation, Relu, Sigmoid, Tanh } from "./shapes/activation"; import { ActivationLayer } from "./shapes/activationlayer"; import { Draggable } from "./shapes/draggable"; import { Layer } from "./shapes/layer"; import { Add } from "./shapes/layers/add"; import { BatchNorm } from "./shapes/layers/batchnorm"; import { Concatenate } from "./shapes/layers/concatenate"; import { Conv2D } from "./shapes/layers/convolutional"; import { Dense } from "./shapes/layers/dense"; import { Dropout } from "./shapes/layers/dropout"; import { Flatten } from "./shapes/layers/flatten"; import { Input } from "./shapes/layers/input"; import { MaxPooling2D } from "./shapes/layers/maxpooling"; import { Output } from "./shapes/layers/output"; import { TextBox } from "./shapes/textbox"; import { WireGuide } from "./shapes/wireguide"; import { copyTextToClipboard } from "./utils"; import { windowProperties } from "./window"; export interface IDraggableData { draggable: Draggable[]; input: Input; output: Output; } export let svgData: IDraggableData = { draggable: [], input: null, output: null, }; document.addEventListener("DOMContentLoaded", () => { // This function runs when the DOM is ready, i.e. when the document has been parsed setupPlots(); setupTestResults(); setupOptionOnClicks(); setupIndividualOnClicks(); const categoryElements = document.getElementsByClassName("categoryTitle") as HTMLCollectionOf<HTMLElement>; for (const elmt of categoryElements) { makeCollapsable(elmt); } window.addEventListener("resize", resizeMiddleSVG); window.addEventListener("resize", setupPlots); resizeMiddleSVG(); window.onkeyup = (event: KeyboardEvent) => { switch (event.key) { case "Escape": if (windowProperties.selectedElement) { windowProperties.selectedElement.unselect(); windowProperties.selectedElement = null; } break; case "Delete": if (document.getElementsByClassName("focusParam").length === 0) { deleteSelected(); } break; case "Backspace": if (document.getElementsByClassName("focusParam").length === 0) { deleteSelected(); } break; case "Enter": break; } }; windowProperties.wireGuide = new WireGuide(); windowProperties.shapeTextBox = new TextBox(); d3.select("#svg").on("mousemove", () => { if (windowProperties.selectedElement instanceof Layer) { windowProperties.wireGuide.moveToMouse(); } }); svgData = loadStateIfPossible(); // Select the input block when we load the page svgData.input.select(); }); function addOnClickToOptions(categoryId: string, func: (optionValue: string, element: HTMLElement) => void): void { for (const element of document.getElementById(categoryId).getElementsByClassName("option")) { element.addEventListener("click", () => { func(element.getAttribute("data-optionValue"), element as HTMLElement); }); } } function setupOptionOnClicks(): void { addOnClickToOptions("tabselector", (tabType) => switchTab(tabType)); addOnClickToOptions("layers", (layerType) => appendItem(layerType)); addOnClickToOptions("activations", (activationType) => appendItem(activationType)); addOnClickToOptions("templates", (templateType) => createTemplate(templateType)); addOnClickToOptions("educationLayers", (articleType) => { document.getElementById("education" + articleType).scrollIntoView(true); }); addOnClickToOptions("educationStory", (articleType) => { document.getElementById("education" + articleType).scrollIntoView(true); }); addOnClickToOptions("classes", (_, element) => { selectOption("classes", element); if (model.architecture != null) { showPredictions(); } }); addOnClickToOptions("optimizers", (optimizerType, element) => { selectOption("optimizers", element); model.params.optimizer = optimizerType; }); addOnClickToOptions("losses", (lossType, element) => { selectOption("losses", element); model.params.loss = lossType; }); } function selectOption(optionCategoryId: string, optionElement: HTMLElement): void { for (const option of document.getElementById(optionCategoryId).getElementsByClassName("option")) { option.classList.remove("selected"); } optionElement.classList.add("selected"); } function createTemplate(template: string): void { switch (template) { case "blank": blankTemplate(svgData); break; case "default": defaultTemplate(svgData); break; case "resnet": resnetTemplate(svgData); break; } } function appendItem(itemType: string): void { const item: Draggable = new ({ add: Add, batchnorm: BatchNorm, concatenate: Concatenate, conv2D: Conv2D, dense: Dense, dropout: Dropout, flatten: Flatten, maxPooling2D: MaxPooling2D, relu: Relu, sigmoid: Sigmoid, tanh: Tanh, } as any)[itemType](); svgData.draggable.push(item); } function setupIndividualOnClicks(): void { document.getElementById("exportPython").addEventListener("click", () => { changeDataset(svgData.input.getParams().dataset); const filename = svgData.input.getParams().dataset + "_model.py"; download(generatePython(topologicalSort(svgData.input)), filename); }); document.getElementById("exportJulia").addEventListener("click", () => { changeDataset(svgData.input.getParams().dataset); if (svgData.input.getParams().dataset === "cifar") { displayError(new Error("Julia Export does not support CIFAR10, use MNIST instead.")); } else { const filename = svgData.input.getParams().dataset + "_model.jl"; download(generateJulia(topologicalSort(svgData.input)), filename); } }); document.getElementById("copyModel").addEventListener("click", () => { changeDataset(svgData.input.getParams().dataset); // TODO change dataset should happen when the dataset changes const state = graphToJson(svgData); const baseUrl: string = window.location.href; const urlParam: string = storeNetworkInUrl(state); copyTextToClipboard(baseUrl + "#" + urlParam); }); document.getElementById("train").addEventListener("click", trainOnClick); document.getElementById("informationEducation").addEventListener("click", () => { document.getElementById("informationOverlay").style.display = "none"; switchTab("education"); }); document.getElementById("informationOverlay").addEventListener("click", () => { document.getElementById("informationOverlay").style.display = "none"; }); document.getElementById("x").addEventListener("click", () => clearError()); document.getElementById("svg").addEventListener("click", (event) => { // Only click if there is a selected element, and the clicked element is an SVG Element, and its id is "svg" // It does this to prevent unselecting if we click on a layer block or other svg shape if (windowProperties.selectedElement && event.target instanceof SVGElement && event.target.id === "svg") { windowProperties.selectedElement.unselect(); windowProperties.selectedElement = null; } }); } function deleteSelected(): void { if (windowProperties.selectedElement) { windowProperties.selectedElement.delete(); windowProperties.selectedElement = null; } } async function trainOnClick(): Promise<void> { // Only train if not already training const training = document.getElementById("train"); if (!training.classList.contains("train-active")) { clearError(); changeDataset(svgData.input.getParams().dataset); // TODO change dataset should happen when the dataset changes // Grab hyperparameters setModelHyperparameters(); const trainingBox = document.getElementById("ti_training"); trainingBox.children[1].innerHTML = "Yes"; training.innerHTML = "Training"; training.classList.add("train-active"); try { model.architecture = buildNetworkDAG(svgData.input); await train(); } catch (error) { displayError(error); } finally { training.innerHTML = "Train"; training.classList.remove("train-active"); trainingBox.children[1].innerHTML = "No"; } } } function resizeMiddleSVG(): void { const originalSVGWidth = 1000; const svgWidth = document.getElementById("middle").clientWidth; const svgHeight = document.getElementById("middle").clientHeight; const ratio = svgWidth / originalSVGWidth; const xTranslate = (svgWidth - originalSVGWidth) / 2; const yTranslate = Math.max(0, (svgHeight * ratio - svgHeight) / 2); // Modify initialization heights for random locations for layers/activations so they don't appear above the svg const yOffsetDelta = yTranslate / ratio - windowProperties.svgYOffset; ActivationLayer.defaultInitialLocation.y += yOffsetDelta; Activation.defaultLocation.y += yOffsetDelta; windowProperties.svgYOffset = yTranslate / ratio; windowProperties.svgTransformRatio = ratio; document.getElementById("svg").setAttribute("transform", `translate(${xTranslate}, 0) scale(${ratio}, ${ratio}) `); // Call crop position on each draggable to ensure it is within the new canvas boundary if (svgData.input != null) { svgData.input.cropPosition(); svgData.input.moveAction(); } if (svgData.output != null) { svgData.output.cropPosition(); svgData.output.moveAction(); } svgData.draggable.forEach((elem) => { elem.cropPosition(); elem.moveAction(); }); } function toggleExpanderTriangle(categoryTitle: Element): void { categoryTitle.getElementsByClassName("expander")[0].classList.toggle("expanded"); } function makeCollapsable(elmt: Element): void { elmt.addEventListener("click", () => { toggleExpanderTriangle(elmt); const arr = Array.prototype.slice.call(elmt.parentElement.children).slice(1); if (elmt.getAttribute("data-expanded") === "false") { for (const sib of arr) { if (sib.id !== "defaultparambox") { sib.style.display = "block"; } } elmt.setAttribute("data-expanded", "true"); } else { for (const sib of arr) { sib.style.display = "none"; } elmt.setAttribute("data-expanded", "false"); } }); } /** * Takes the hyperparemeters from the html and assigns them to the global model */ export function setModelHyperparameters(): void { let temp: number = 0; const hyperparams = document.getElementsByClassName("hyperparamvalue"); for (const hp of hyperparams) { const name: string = hp.id; temp = Number(( document.getElementById(name) as HTMLInputElement).value); if (temp < 0 || temp == null) { const error: Error = Error("Hyperparameters should be positive numbers."); displayError(error); return; } switch (name) { case "learningRate": model.params.learningRate = temp; break; case "epochs": model.params.epochs = Math.trunc(temp); break; case "batchSize": model.params.batchSize = Math.trunc(temp); break; } } } export function tabSelected(): string { if (document.getElementById("networkTab").style.display !== "none") { return "networkTab"; } else if (document.getElementById("progressTab").style.display !== "none") { return "progressTab"; } else if (document.getElementById("visualizationTab").style.display !== "none") { return "visualizationTab"; } else if (document.getElementById("educationTab").style.display !== "none") { return "educationTab"; } else { throw new Error("No tab selection found"); } } function switchTab(tabType: string): void { // Hide all tabs document.getElementById("networkTab").style.display = "none"; document.getElementById("progressTab").style.display = "none"; document.getElementById("visualizationTab").style.display = "none"; document.getElementById("educationTab").style.display = "none"; // Hide all menus document.getElementById("networkMenu").style.display = "none"; document.getElementById("progressMenu").style.display = "none"; document.getElementById("visualizationMenu").style.display = "none"; document.getElementById("educationMenu").style.display = "none"; // Hide all paramshells document.getElementById("networkParamshell").style.display = "none"; document.getElementById("progressParamshell").style.display = "none"; document.getElementById("visualizationParamshell").style.display = "none"; document.getElementById("educationParamshell").style.display = "none"; // Unselect all tabs document.getElementById("network").classList.remove("tab-selected"); document.getElementById("progress").classList.remove("tab-selected"); document.getElementById("visualization").classList.remove("tab-selected"); document.getElementById("education").classList.remove("tab-selected"); // Display only the selected tab document.getElementById(tabType + "Tab").style.display = null; document.getElementById(tabType).classList.add("tab-selected"); document.getElementById(tabType + "Menu").style.display = null; document.getElementById(tabType + "Paramshell").style.display = null; document.getElementById("paramshell").style.display = null; document.getElementById("menu").style.display = null; // document.getElementById("menu_expander").style.display = null; switch (tabType) { case "network": resizeMiddleSVG(); break; case "progress": setupPlots(); break; case "visualization": showPredictions(); break; case "education": document.getElementById("paramshell").style.display = "none"; break; } // Give border radius to top and bottom neighbors if (document.getElementsByClassName("top_neighbor_tab-selected").length > 0) { document.getElementsByClassName("top_neighbor_tab-selected")[0].classList .remove("top_neighbor_tab-selected"); document.getElementsByClassName("bottom_neighbor_tab-selected")[0].classList .remove("bottom_neighbor_tab-selected"); } const tabMapping = ["blanktab", "network", "progress", "visualization", "middleblanktab", "education", "bottomblanktab"]; const index = tabMapping.indexOf(tabType); document.getElementById(tabMapping[index - 1]).classList.add("top_neighbor_tab-selected"); document.getElementById(tabMapping[index + 1]).classList.add("bottom_neighbor_tab-selected"); }
the_stack
import * as vscode from 'vscode'; import * as uri from 'vscode-uri'; import { MarkdownEngine } from '../markdownEngine'; import { Slugifier } from '../slugify'; import { TableOfContents, TocEntry } from '../tableOfContents'; import { Disposable } from '../util/dispose'; import { MdWorkspaceContents, SkinnyTextDocument } from '../workspaceContents'; import { InternalHref, MdLink, MdLinkProvider } from './documentLinkProvider'; import { MdWorkspaceCache } from './workspaceCache'; /** * A link in a markdown file. */ export interface MdLinkReference { readonly kind: 'link'; readonly isTriggerLocation: boolean; readonly isDefinition: boolean; readonly location: vscode.Location; readonly link: MdLink; } /** * A header in a markdown file. */ export interface MdHeaderReference { readonly kind: 'header'; readonly isTriggerLocation: boolean; readonly isDefinition: boolean; /** * The range of the header. * * In `# a b c #` this would be the range of `# a b c #` */ readonly location: vscode.Location; /** * The text of the header. * * In `# a b c #` this would be `a b c` */ readonly headerText: string; /** * The range of the header text itself. * * In `# a b c #` this would be the range of `a b c` */ readonly headerTextLocation: vscode.Location; } export type MdReference = MdLinkReference | MdHeaderReference; export class MdReferencesProvider extends Disposable implements vscode.ReferenceProvider { private readonly _linkCache: MdWorkspaceCache<readonly MdLink[]>; public constructor( private readonly linkProvider: MdLinkProvider, private readonly workspaceContents: MdWorkspaceContents, private readonly engine: MarkdownEngine, private readonly slugifier: Slugifier, ) { super(); this._linkCache = this._register(new MdWorkspaceCache(workspaceContents, doc => linkProvider.getAllLinks(doc))); } async provideReferences(document: SkinnyTextDocument, position: vscode.Position, context: vscode.ReferenceContext, token: vscode.CancellationToken): Promise<vscode.Location[] | undefined> { const allRefs = await this.getAllReferencesAtPosition(document, position, token); return allRefs .filter(ref => context.includeDeclaration || !ref.isDefinition) .map(ref => ref.location); } public async getAllReferencesAtPosition(document: SkinnyTextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise<MdReference[]> { const toc = await TableOfContents.create(this.engine, document); if (token.isCancellationRequested) { return []; } const header = toc.entries.find(entry => entry.line === position.line); if (header) { return this.getReferencesToHeader(document, header); } else { return this.getReferencesToLinkAtPosition(document, position, token); } } private async getReferencesToHeader(document: SkinnyTextDocument, header: TocEntry): Promise<MdReference[]> { const links = (await this._linkCache.getAll()).flat(); const references: MdReference[] = []; references.push({ kind: 'header', isTriggerLocation: true, isDefinition: true, location: header.headerLocation, headerText: header.text, headerTextLocation: header.headerTextLocation }); for (const link of links) { if (link.href.kind === 'internal' && this.looksLikeLinkToDoc(link.href, document.uri) && this.slugifier.fromHeading(link.href.fragment).value === header.slug.value ) { references.push({ kind: 'link', isTriggerLocation: false, isDefinition: false, link, location: new vscode.Location(link.source.resource, link.source.hrefRange), }); } } return references; } private async getReferencesToLinkAtPosition(document: SkinnyTextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise<MdReference[]> { const docLinks = await this.linkProvider.getAllLinks(document); for (const link of docLinks) { if (link.kind === 'definition') { // We could be in either the ref name or the definition if (link.ref.range.contains(position)) { return Array.from(this.getReferencesToLinkReference(docLinks, link.ref.text, { resource: document.uri, range: link.ref.range })); } else if (link.source.hrefRange.contains(position)) { return this.getReferencesToLink(link, position, token); } } else { if (link.source.hrefRange.contains(position)) { return this.getReferencesToLink(link, position, token); } } } return []; } private async getReferencesToLink(sourceLink: MdLink, triggerPosition: vscode.Position, token: vscode.CancellationToken): Promise<MdReference[]> { const allLinksInWorkspace = (await this._linkCache.getAll()).flat(); if (token.isCancellationRequested) { return []; } if (sourceLink.href.kind === 'reference') { return Array.from(this.getReferencesToLinkReference(allLinksInWorkspace, sourceLink.href.ref, { resource: sourceLink.source.resource, range: sourceLink.source.hrefRange })); } if (sourceLink.href.kind === 'external') { const references: MdReference[] = []; for (const link of allLinksInWorkspace) { if (link.href.kind === 'external' && link.href.uri.toString() === sourceLink.href.uri.toString()) { const isTriggerLocation = sourceLink.source.resource.fsPath === link.source.resource.fsPath && sourceLink.source.hrefRange.isEqual(link.source.hrefRange); references.push({ kind: 'link', isTriggerLocation, isDefinition: false, link, location: new vscode.Location(link.source.resource, link.source.hrefRange), }); } } return references; } const targetDoc = await tryFindMdDocumentForLink(sourceLink.href, this.workspaceContents); if (token.isCancellationRequested) { return []; } const references: MdReference[] = []; if (targetDoc && sourceLink.href.fragment && sourceLink.source.fragmentRange?.contains(triggerPosition)) { const toc = await TableOfContents.create(this.engine, targetDoc); const entry = toc.lookup(sourceLink.href.fragment); if (entry) { references.push({ kind: 'header', isTriggerLocation: false, isDefinition: true, location: entry.headerLocation, headerText: entry.text, headerTextLocation: entry.headerTextLocation }); } for (const link of allLinksInWorkspace) { if (link.href.kind !== 'internal' || !this.looksLikeLinkToDoc(link.href, targetDoc.uri)) { continue; } if (this.slugifier.fromHeading(link.href.fragment).equals(this.slugifier.fromHeading(sourceLink.href.fragment))) { const isTriggerLocation = sourceLink.source.resource.fsPath === link.source.resource.fsPath && sourceLink.source.hrefRange.isEqual(link.source.hrefRange); references.push({ kind: 'link', isTriggerLocation, isDefinition: false, link, location: new vscode.Location(link.source.resource, link.source.hrefRange), }); } } } else { // Triggered on a link without a fragment so we only require matching the file and ignore fragments references.push(...this.findAllLinksToFile(targetDoc?.uri ?? sourceLink.href.path, allLinksInWorkspace, sourceLink)); } return references; } private looksLikeLinkToDoc(href: InternalHref, targetDoc: vscode.Uri) { return href.path.fsPath === targetDoc.fsPath || uri.Utils.extname(href.path) === '' && href.path.with({ path: href.path.path + '.md' }).fsPath === targetDoc.fsPath; } public async getAllReferencesToFile(resource: vscode.Uri, _token: vscode.CancellationToken): Promise<MdReference[]> { const allLinksInWorkspace = (await this._linkCache.getAll()).flat(); return Array.from(this.findAllLinksToFile(resource, allLinksInWorkspace, undefined)); } private * findAllLinksToFile(resource: vscode.Uri, allLinksInWorkspace: readonly MdLink[], sourceLink: MdLink | undefined): Iterable<MdReference> { for (const link of allLinksInWorkspace) { if (link.href.kind !== 'internal' || !this.looksLikeLinkToDoc(link.href, resource)) { continue; } // Exclude cases where the file is implicitly referencing itself if (link.source.text.startsWith('#') && link.source.resource.fsPath === resource.fsPath) { continue; } const isTriggerLocation = !!sourceLink && sourceLink.source.resource.fsPath === link.source.resource.fsPath && sourceLink.source.hrefRange.isEqual(link.source.hrefRange); const pathRange = this.getPathRange(link); yield { kind: 'link', isTriggerLocation, isDefinition: false, link, location: new vscode.Location(link.source.resource, pathRange), }; } } private * getReferencesToLinkReference(allLinks: Iterable<MdLink>, refToFind: string, from: { resource: vscode.Uri; range: vscode.Range }): Iterable<MdReference> { for (const link of allLinks) { let ref: string; if (link.kind === 'definition') { ref = link.ref.text; } else if (link.href.kind === 'reference') { ref = link.href.ref; } else { continue; } if (ref === refToFind && link.source.resource.fsPath === from.resource.fsPath) { const isTriggerLocation = from.resource.fsPath === link.source.resource.fsPath && ( (link.href.kind === 'reference' && from.range.isEqual(link.source.hrefRange)) || (link.kind === 'definition' && from.range.isEqual(link.ref.range))); const pathRange = this.getPathRange(link); yield { kind: 'link', isTriggerLocation, isDefinition: link.kind === 'definition', link, location: new vscode.Location(from.resource, pathRange), }; } } } /** * Get just the range of the file path, dropping the fragment */ private getPathRange(link: MdLink): vscode.Range { return link.source.fragmentRange ? link.source.hrefRange.with(undefined, link.source.fragmentRange.start.translate(0, -1)) : link.source.hrefRange; } } export async function tryFindMdDocumentForLink(href: InternalHref, workspaceContents: MdWorkspaceContents): Promise<SkinnyTextDocument | undefined> { const targetDoc = await workspaceContents.getMarkdownDocument(href.path); if (targetDoc) { return targetDoc; } // We don't think the file exists. If it doesn't already have an extension, try tacking on a `.md` and using that instead if (uri.Utils.extname(href.path) === '') { const dotMdResource = href.path.with({ path: href.path.path + '.md' }); return workspaceContents.getMarkdownDocument(dotMdResource); } return undefined; }
the_stack
import { IgxGridModule, IgxGridComponent } from './public_api'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { TestBed, fakeAsync, tick } from '@angular/core/testing'; import { configureTestSuite } from '../../test-utils/configure-suite'; import { DebugElement } from '@angular/core'; import { GridFunctions, GridSummaryFunctions } from '../../test-utils/grid-functions.spec'; import { IgxAddRowComponent, IgxGridRowEditingTransactionComponent } from '../../test-utils/grid-samples.spec'; import { By } from '@angular/platform-browser'; import { IgxActionStripComponent } from '../../action-strip/action-strip.component'; import { IgxActionStripModule } from '../../action-strip/action-strip.module'; import { DefaultGridMasterDetailComponent } from './grid.master-detail.spec'; import { ColumnLayoutTestComponent } from './grid.multi-row-layout.spec'; import { UIInteractions, wait } from '../../test-utils/ui-interactions.spec'; import { IgxStringFilteringOperand } from '../../data-operations/filtering-condition'; import { SortingDirection } from '../../data-operations/sorting-expression.interface'; import { DefaultSortingStrategy } from '../../data-operations/sorting-strategy'; import { TransactionType } from '../../services/public_api'; import { IgxGridRowComponent } from './grid-row.component'; import { takeUntil, first } from 'rxjs/operators'; import { Subject } from 'rxjs'; const DEBOUNCETIME = 30; describe('IgxGrid - Row Adding #grid', () => { const GRID_ROW = 'igx-grid-row'; const DISPLAY_CONTAINER = 'igx-display-container'; const SUMMARY_ROW = 'igx-grid-summary-row'; const GRID_THEAD_ITEM = '.igx-grid-thead__item'; let fixture; let grid: IgxGridComponent; let gridContent: DebugElement; let actionStrip: IgxActionStripComponent; const endTransition = () => { // transition end needs to be simulated const animationElem = fixture.nativeElement.querySelector('.igx-grid__tr--inner'); const endEvent = new AnimationEvent('animationend'); animationElem.dispatchEvent(endEvent); }; configureTestSuite((() => { TestBed.configureTestingModule({ declarations: [ IgxAddRowComponent, ColumnLayoutTestComponent, DefaultGridMasterDetailComponent, IgxGridRowEditingTransactionComponent ], imports: [ NoopAnimationsModule, IgxActionStripModule, IgxGridModule] }); })); describe('General tests', () => { beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(IgxAddRowComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; gridContent = GridFunctions.getGridContent(fixture); actionStrip = fixture.componentInstance.actionStrip; })); it('Should be able to enter add row mode on action strip click', () => { const row = grid.rowList.first; actionStrip.show(row); fixture.detectChanges(); const addRowIcon = fixture.debugElement.queryAll(By.css(`igx-grid-editing-actions igx-icon`))[1]; addRowIcon.parent.triggerEventHandler('click', new Event('click')); fixture.detectChanges(); const addRow = grid.gridAPI.get_row_by_index(1); expect(addRow.addRowUI).toBeTrue(); }); it('Should be able to enter add row mode through the exposed API method.', () => { const rows = grid.rowList.toArray(); rows[0].beginAddRow(); fixture.detectChanges(); endTransition(); let addRow = grid.gridAPI.get_row_by_index(1); expect(addRow.addRowUI).toBeTrue(); UIInteractions.triggerEventHandlerKeyDown('escape', gridContent); fixture.detectChanges(); addRow = grid.gridAPI.get_row_by_index(1); expect(addRow.addRowUI).toBeFalse(); rows[1].beginAddRow(); fixture.detectChanges(); addRow = grid.gridAPI.get_row_by_index(2); expect(addRow.addRowUI).toBeTrue(); }); xit('Should display the banner above the row if there is no room underneath it', () => { fixture.componentInstance.paging = true; fixture.detectChanges(); grid.notifyChanges(true); fixture.detectChanges(); grid.paginator.perPage = 7; fixture.detectChanges(); const lastRow = grid.rowList.last; const lastRowIndex = lastRow.index; actionStrip.show(lastRow); fixture.detectChanges(); const addRowIcon = fixture.debugElement.queryAll(By.css(`igx-grid-editing-actions igx-icon`))[1]; addRowIcon.parent.triggerEventHandler('click', new Event('click')); fixture.detectChanges(); endTransition(); const addRow = grid.gridAPI.get_row_by_index(lastRowIndex + 1); // expect(addRow.addRow).toBeTrue(); const banner = GridFunctions.getRowEditingOverlay(fixture); fixture.detectChanges(); const bannerBottom = banner.getBoundingClientRect().bottom; const addRowTop = addRow.nativeElement.getBoundingClientRect().top; // The banner appears above the row expect(bannerBottom).toBeLessThanOrEqual(addRowTop); // No much space between the row and the banner expect(addRowTop - bannerBottom).toBeLessThan(2); }); it('Should be able to enter add row mode on Alt + plus key.', () => { GridFunctions.focusFirstCell(fixture, grid); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('+', gridContent, true, false, false); fixture.detectChanges(); const addRow = grid.gridAPI.get_row_by_index(1); expect(addRow.addRowUI).toBeTrue(); }); it('Should not be able to enter add row mode on Alt + Shift + plus key.', () => { GridFunctions.focusFirstCell(fixture, grid); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('+', gridContent, true, true, false); fixture.detectChanges(); const banner = GridFunctions.getRowEditingOverlay(fixture); expect(banner).toBeNull(); expect(grid.gridAPI.get_row_by_index(1).addRowUI).toBeFalse(); }); it('Should not be able to enter add row mode when rowEditing is disabled', () => { grid.rowEditable = false; fixture.detectChanges(); grid.rowList.first.beginAddRow(); fixture.detectChanges(); const banner = GridFunctions.getRowEditingOverlay(fixture); expect(banner).toBeNull(); expect(grid.gridAPI.get_row_by_index(1).addRowUI).toBeFalse(); }); it('Should allow adding row from pinned row.', () => { let row = grid.gridAPI.get_row_by_index(0); row.pin(); fixture.detectChanges(); expect(grid.pinnedRecords.length).toBe(1); row = grid.gridAPI.get_row_by_index(0); row.beginAddRow(); fixture.detectChanges(); endTransition(); // add row should be pinned const addRow = grid.gridAPI.get_row_by_index(1) as IgxGridRowComponent; expect(addRow.addRowUI).toBe(true); expect(grid.pinnedRows[1]).toBe(addRow); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); // added record should be pinned. expect(grid.pinnedRecords.length).toBe(2); expect(grid.pinnedRecords[1]).toBe(grid.data[grid.data.length - 1]); }); it('Should allow adding row from ghost row.', () => { const row = grid.getRowByIndex(0); row.pin(); fixture.detectChanges(); expect(grid.pinnedRecords.length).toBe(1); const ghostRow = grid.gridAPI.get_row_by_index(1); ghostRow.beginAddRow(); fixture.detectChanges(); endTransition(); // add row should be unpinned const addRow = grid.gridAPI.get_row_by_index(2); expect(addRow.addRowUI).toBe(true); expect(grid.pinnedRows.length).toBe(1); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); // added record should be unpinned. expect(grid.pinnedRecords.length).toBe(1); expect(grid.unpinnedRecords[grid.unpinnedRecords.length - 1]).toBe(grid.data[grid.data.length - 1]); }); it('should navigate to added row on snackbar button click.', async () => { const rows = grid.rowList.toArray(); const dataCount = grid.data.length; rows[0].beginAddRow(); fixture.detectChanges(); endTransition(); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); // check row is in data expect(grid.data.length).toBe(dataCount + 1); const addedRec = grid.data[grid.data.length - 1]; grid.addRowSnackbar.triggerAction(); fixture.detectChanges(); await wait(100); fixture.detectChanges(); // check added row is rendered and is in view const row = grid.gridAPI.get_row_by_key(addedRec[grid.primaryKey]); expect(row).not.toBeNull(); const gridOffsets = grid.tbody.nativeElement.getBoundingClientRect(); const rowOffsets = row.nativeElement.getBoundingClientRect(); expect(rowOffsets.top >= gridOffsets.top && rowOffsets.bottom <= gridOffsets.bottom).toBeTruthy(); }); it('should navigate to added row on snackbar button click when row is not in current view.', async () => { fixture.componentInstance.paging = true; fixture.detectChanges(); grid.paginator.perPage = 5; grid.markForCheck(); fixture.detectChanges(); const rows = grid.rowList.toArray(); const dataCount = grid.data.length; rows[0].beginAddRow(); fixture.detectChanges(); endTransition(); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); // check row is in data expect(grid.data.length).toBe(dataCount + 1); const addedRec = grid.data[grid.data.length - 1]; grid.addRowSnackbar.triggerAction(); fixture.detectChanges(); await wait(100); fixture.detectChanges(); // check page is correct expect(grid.paginator.page).toBe(5); // check added row is rendered and is in view const row = grid.gridAPI.get_row_by_key(addedRec[grid.primaryKey]); expect(row).not.toBeNull(); const gridOffsets = grid.tbody.nativeElement.getBoundingClientRect(); const rowOffsets = row.nativeElement.getBoundingClientRect(); expect(rowOffsets.top >= gridOffsets.top && rowOffsets.bottom <= gridOffsets.bottom).toBeTruthy(); }); it('Should generate correct row ID based on the primary column type', () => { const column = grid.columns.find(col => col.field === grid.primaryKey); const type = column.dataType; const row = grid.gridAPI.get_row_by_index(0); row.beginAddRow(); fixture.detectChanges(); const newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeTrue(); const cell = newRow.cells.find(c => c.column === column); expect(typeof(cell.value)).toBe(type); }); it('should allow setting a different display time for snackbar', async () => { grid.snackbarDisplayTime = 50; fixture.detectChanges(); const row = grid.gridAPI.get_row_by_index(0); row.beginAddRow(); fixture.detectChanges(); endTransition(); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); expect(grid.addRowSnackbar.isVisible).toBe(true); // should hide after 50ms await wait(51); fixture.detectChanges(); expect(grid.addRowSnackbar.isVisible).toBe(false); }); it('Should set templated banner text when adding row', () => { const rows = grid.rowList.toArray(); rows[0].beginAddRow(); fixture.detectChanges(); endTransition(); const addRow = grid.gridAPI.get_row_by_index(1); expect(addRow.addRowUI).toBeTrue(); expect(GridFunctions.getRowEditingBannerText(fixture)).toEqual('Adding Row'); }); }); describe('Add row events tests:', () => { const $destroyer = new Subject<boolean>(); beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(IgxAddRowComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; gridContent = GridFunctions.getGridContent(fixture); })); afterEach(fakeAsync(() => { $destroyer.next(true); })); it('Should emit all events in the correct order', () => { spyOn(grid.rowEditEnter, 'emit').and.callThrough(); spyOn(grid.cellEditEnter, 'emit').and.callThrough(); spyOn(grid.cellEdit, 'emit').and.callThrough(); spyOn(grid.cellEditDone, 'emit').and.callThrough(); spyOn(grid.cellEditExit, 'emit').and.callThrough(); spyOn(grid.rowEdit, 'emit').and.callThrough(); spyOn(grid.rowEditDone, 'emit').and.callThrough(); spyOn(grid.rowEditExit, 'emit').and.callThrough(); grid.rowEditEnter.pipe(takeUntil($destroyer)).subscribe(() => { expect(grid.rowEditEnter.emit).toHaveBeenCalledTimes(1); expect(grid.cellEditEnter.emit).not.toHaveBeenCalled(); }); grid.cellEditEnter.pipe(takeUntil($destroyer)).subscribe(() => { expect(grid.rowEditEnter.emit).toHaveBeenCalledTimes(1); expect(grid.cellEditEnter.emit).toHaveBeenCalledTimes(1); expect(grid.cellEdit.emit).not.toHaveBeenCalled(); }); grid.cellEdit.pipe(takeUntil($destroyer)).subscribe(() => { expect(grid.cellEditEnter.emit).toHaveBeenCalledTimes(1); expect(grid.cellEdit.emit).toHaveBeenCalledTimes(1); expect(grid.cellEditDone.emit).not.toHaveBeenCalled(); }); grid.cellEditDone.pipe(takeUntil($destroyer)).subscribe(() => { expect(grid.cellEdit.emit).toHaveBeenCalledTimes(1); expect(grid.cellEditDone.emit).toHaveBeenCalledTimes(1); expect(grid.cellEditExit.emit).not.toHaveBeenCalled(); }); grid.cellEditExit.pipe(takeUntil($destroyer)).subscribe(() => { expect(grid.cellEditDone.emit).toHaveBeenCalledTimes(1); expect(grid.cellEditExit.emit).toHaveBeenCalledTimes(1); expect(grid.rowEdit.emit).not.toHaveBeenCalled(); }); grid.rowEdit.pipe(takeUntil($destroyer)).subscribe(() => { expect(grid.cellEditExit.emit).toHaveBeenCalledTimes(1); expect(grid.rowEdit.emit).toHaveBeenCalledTimes(1); expect(grid.rowEditDone.emit).not.toHaveBeenCalled(); }); grid.rowEditDone.pipe(takeUntil($destroyer)).subscribe(() => { expect(grid.rowEdit.emit).toHaveBeenCalledTimes(1); expect(grid.rowEditDone.emit).toHaveBeenCalledTimes(1); expect(grid.rowEditExit.emit).not.toHaveBeenCalled(); }); grid.rowEditExit.pipe(takeUntil($destroyer)).subscribe(() => { expect(grid.rowEditDone.emit).toHaveBeenCalledTimes(1); expect(grid.rowEditExit.emit).toHaveBeenCalledTimes(1); }); grid.rowList.first.beginAddRow(); fixture.detectChanges(); endTransition(); const cell = grid.gridAPI.get_cell_by_index(1, 'CompanyName'); const cellInput = cell.nativeElement.querySelector('[igxinput]'); UIInteractions.setInputElementValue(cellInput, 'aaa'); fixture.detectChanges(); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); }); it('Should emit all grid editing events as per row editing specification', () => { spyOn(grid.cellEditEnter, 'emit').and.callThrough(); spyOn(grid.cellEditDone, 'emit').and.callThrough(); spyOn(grid.rowEditEnter, 'emit').and.callThrough(); spyOn(grid.rowEditDone, 'emit').and.callThrough(); const row = grid.gridAPI.get_row_by_index(0); row.beginAddRow(); fixture.detectChanges(); endTransition(); const newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeTrue(); expect(grid.cellEditEnter.emit).toHaveBeenCalled(); expect(grid.rowEditEnter.emit).toHaveBeenCalled(); const cell = grid.gridAPI.get_cell_by_index(1, 'CompanyName'); const cellInput = cell.nativeElement.querySelector('[igxinput]'); UIInteractions.setInputElementValue(cellInput, 'aaa'); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('enter', gridContent); fixture.detectChanges(); expect(grid.cellEditDone.emit).toHaveBeenCalled(); expect(grid.rowEditDone.emit).toHaveBeenCalled(); }); it('Should not enter add mode when rowEditEnter is canceled', () => { grid.rowEditEnter.pipe(takeUntil($destroyer)).subscribe((evt) => { evt.cancel = true; }); grid.rowList.first.beginAddRow(); fixture.detectChanges(); endTransition(); expect(grid.gridAPI.get_row_by_index(1).addRowUI).toBeFalse(); }); it('Should enter add mode but close it when cellEditEnter is canceled', () => { let canceled = true; grid.cellEditEnter.pipe(first()).subscribe((evt) => { evt.cancel = canceled; }); grid.rowList.first.beginAddRow(); fixture.detectChanges(); expect(grid.gridAPI.get_row_by_index(1).addRowUI).toBeTrue(); expect(grid.crudService.cellInEditMode).toEqual(false); grid.gridAPI.crudService.endEdit(false); fixture.detectChanges(); canceled = false; grid.rowList.first.beginAddRow(); fixture.detectChanges(); expect(grid.gridAPI.get_row_by_index(1).addRowUI).toBeTrue(); }); it('Should scroll and start adding a row as the first one when using the public API method', async () => { await wait(DEBOUNCETIME); fixture.detectChanges(); grid.navigateTo(20, 0); await wait(DEBOUNCETIME); fixture.detectChanges(); grid.beginAddRowById(null); await wait(DEBOUNCETIME); fixture.detectChanges(); expect(grid.gridAPI.get_row_by_index(0).addRowUI).toBeTrue(); }); xit('Should scroll and start adding a row as for a row that is not in view', async () => { await wait(DEBOUNCETIME); fixture.detectChanges(); grid.beginAddRowById('FAMIA'); await wait(DEBOUNCETIME); fixture.detectChanges(); expect(grid.gridAPI.get_row_by_index(8).addRowUI).toBeTrue(); }); }); describe('Exit add row mode tests', () => { beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(IgxAddRowComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; gridContent = GridFunctions.getGridContent(fixture); actionStrip = fixture.componentInstance.actionStrip; })); it('Should exit add row mode and commit on clicking DONE button in the overlay', () => { const dataLength = grid.data.length; const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); let newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeTrue(); const doneButtonElement = GridFunctions.getRowEditingDoneButton(fixture); doneButtonElement.click(); fixture.detectChanges(); newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeFalse(); expect(grid.data.length).toBe(dataLength + 1); }); it('Should exit add row mode and discard on clicking CANCEL button in the overlay', async () => { const dataLength = grid.data.length; const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); let newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeTrue(); const cancelButtonElement = GridFunctions.getRowEditingCancelButton(fixture); cancelButtonElement.click(); fixture.detectChanges(); await wait(100); fixture.detectChanges(); newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeFalse(); expect(grid.data.length).toBe(dataLength); }); it('Should exit add row mode and discard on ESC KEYDOWN', () => { const dataLength = grid.data.length; const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); let newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeTrue(); UIInteractions.triggerEventHandlerKeyDown('escape', gridContent); fixture.detectChanges(); newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeFalse(); expect(grid.data.length).toBe(dataLength); }); it('Should exit add row mode and commit on ENTER KEYDOWN.', () => { const dataLength = grid.data.length; const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); let newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeTrue(); UIInteractions.triggerEventHandlerKeyDown('enter', gridContent); fixture.detectChanges(); newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeFalse(); expect(grid.data.length).toBe(dataLength + 1); }); it('Should correctly scroll all rows after closing the add row', async () => { grid.width = '400px'; fixture.detectChanges(); const dataLength = grid.data.length; const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); let newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeTrue(); const cancelButtonElement = GridFunctions.getRowEditingCancelButton(fixture); cancelButtonElement.click(); fixture.detectChanges(); await wait(100); fixture.detectChanges(); newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeFalse(); expect(grid.data.length).toBe(dataLength); (grid as any).scrollTo(0, grid.columnList.length - 1); await wait(100); fixture.detectChanges(); // All rows should be scrolled, from their forOf directive. If not then the `_horizontalForOfs` in the grid is outdated. const gridRows = fixture.debugElement.queryAll(By.css(GRID_ROW)); gridRows.forEach(item => { const displayContainer = item.query(By.css(DISPLAY_CONTAINER)); expect(displayContainer.nativeElement.style.left).not.toBe('0px'); }); }); }); describe('Row Adding - Paging tests', () => { beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(IgxAddRowComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; gridContent = GridFunctions.getGridContent(fixture); })); it('Should preserve the changes after page navigation', () => { const dataLength = grid.data.length; fixture.componentInstance.paging = true; fixture.detectChanges(); grid.perPage = 5; fixture.detectChanges(); const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); GridFunctions.navigateToLastPage(grid.nativeElement); fixture.detectChanges(); expect(grid.data.length).toBe(dataLength); }); it('Should save changes when changing page count', () => { const dataLength = grid.data.length; fixture.componentInstance.paging = true; fixture.detectChanges(); grid.perPage = 5; fixture.detectChanges(); const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); const select = GridFunctions.getGridPageSelectElement(fixture); select.click(); fixture.detectChanges(); const selectList = fixture.debugElement.query(By.css('.igx-drop-down__list-scroll')); selectList.children[2].nativeElement.click(); fixture.detectChanges(); expect(grid.data.length).toBe(dataLength); }); }); describe('Row Adding - Filtering tests', () => { beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(IgxAddRowComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; gridContent = GridFunctions.getGridContent(fixture); actionStrip = fixture.componentInstance.actionStrip; })); it('Should exit add row mode on filter applied and discard', () => { spyOn(grid.gridAPI.crudService, 'endEdit').and.callThrough(); const dataLength = grid.data.length; const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); grid.filter('CompanyName', 'al', IgxStringFilteringOperand.instance().condition('contains'), true); fixture.detectChanges(); expect(grid.gridAPI.crudService.endEdit).toHaveBeenCalled(); expect(grid.data.length).toBe(dataLength); }); it('Filtering should consider newly added rows', () => { grid.filter('CompanyName', 'al', IgxStringFilteringOperand.instance().condition('contains'), true); fixture.detectChanges(); expect(grid.dataView.length).toBe(4); const row = grid.gridAPI.get_row_by_index(0); row.beginAddRow(); fixture.detectChanges(); endTransition(); const newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeTrue(); const cell = grid.gridAPI.get_cell_by_index(1, 'CompanyName'); const cellInput = cell.nativeElement.querySelector('[igxinput]'); UIInteractions.setInputElementValue(cellInput, 'Alan'); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); expect(grid.dataView.length).toBe(5); }); it('Should not show the action strip "Show" button if added row is filtered out', () => { grid.filter('CompanyName', 'al', IgxStringFilteringOperand.instance().condition('contains'), true); fixture.detectChanges(); const row = grid.gridAPI.get_row_by_index(0); row.beginAddRow(); fixture.detectChanges(); endTransition(); const newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeTrue(); const cell = grid.gridAPI.get_cell_by_index(1, 'CompanyName'); const cellInput = cell.nativeElement.querySelector('[igxinput]'); UIInteractions.setInputElementValue(cellInput, 'Xuary'); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); expect(grid.dataView.length).toBe(4); expect(grid.addRowSnackbar.actionText).toBe(''); }); }); describe('Row Adding - Sorting tests', () => { beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(IgxAddRowComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; gridContent = GridFunctions.getGridContent(fixture); actionStrip = fixture.componentInstance.actionStrip; })); it('Should exit add row mode and discard on sorting', () => { spyOn(grid.gridAPI.crudService, 'endEdit').and.callThrough(); const dataLength = grid.data.length; const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); grid.sort({ fieldName: 'CompanyName', dir: SortingDirection.Asc, ignoreCase: true, strategy: DefaultSortingStrategy.instance() }); fixture.detectChanges(); expect(grid.data.length).toBe(dataLength); expect(grid.gridAPI.crudService.endEdit).toHaveBeenCalled(); }); it('Sorting should consider newly added rows', () => { grid.sort({ fieldName: 'CompanyName', dir: SortingDirection.Asc, ignoreCase: true, strategy: DefaultSortingStrategy.instance() }); fixture.detectChanges(); const row = grid.gridAPI.get_row_by_index(0); row.beginAddRow(); fixture.detectChanges(); endTransition(); const newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeTrue(); const cell = grid.gridAPI.get_cell_by_index(1, 'CompanyName'); const cellInput = cell.nativeElement.querySelector('[igxinput]'); UIInteractions.setInputElementValue(cellInput, 'Azua'); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); expect(grid.getCellByColumn(4, 'CompanyName').value).toBe('Azua'); }); }); describe('Row Adding - Master detail view', () => { beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(DefaultGridMasterDetailComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; gridContent = GridFunctions.getGridContent(fixture); })); it('Should collapse expanded detail view before spawning add row UI', () => { grid.rowEditable = true; fixture.detectChanges(); const row = grid.rowList.first; grid.expandRow(row.rowID); fixture.detectChanges(); expect(row.expanded).toBeTrue(); row.beginAddRow(); fixture.detectChanges(); expect(row.expanded).toBeFalse(); expect(grid.gridAPI.get_row_by_index(1).addRowUI).toBeTrue(); }); }); describe('Row Adding - MRL tests', () => { beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(ColumnLayoutTestComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; })); it('Should render adding row with correct multi row layout', () => { grid.rowEditable = true; fixture.detectChanges(); const gridFirstRow = grid.rowList.first; const firstRowCells = gridFirstRow.cells.toArray(); // const headerCells = grid.headerGroups.first.children.toArray(); const headerCells = grid.headerGroupsList[0].children.toArray(); // headers are aligned to cells GridFunctions.verifyLayoutHeadersAreAligned(headerCells, firstRowCells); gridFirstRow.beginAddRow(); fixture.detectChanges(); const newRow = grid.gridAPI.get_row_by_index(1); expect(newRow.addRowUI).toBeTrue(); const newRowCells = newRow.cells.toArray(); GridFunctions.verifyLayoutHeadersAreAligned(headerCells, newRowCells); }); }); describe('Row Adding - Group by', () => { beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(IgxAddRowComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; gridContent = GridFunctions.getGridContent(fixture); })); it(`Should show the action strip "Show" button if added row is in collapsed group 4and on click should expand the group and scroll to the correct added row`, () => { grid.groupBy({ fieldName: 'CompanyName', dir: SortingDirection.Asc, ignoreCase: true, strategy: DefaultSortingStrategy.instance() }); fixture.detectChanges(); let groupRows = grid.groupsRowList.toArray(); grid.toggleGroup(groupRows[2].groupRow); fixture.detectChanges(); expect(groupRows[2].expanded).toBeFalse(); const row = grid.gridAPI.get_row_by_index(1); row.beginAddRow(); fixture.detectChanges(); endTransition(); const cell = grid.gridAPI.get_cell_by_index(2, 'CompanyName'); const cellInput = cell.nativeElement.querySelector('[igxinput]'); UIInteractions.setInputElementValue(cellInput, 'Antonio Moreno Taquería'); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); const addedRec = grid.data[grid.data.length - 1]; expect(grid.addRowSnackbar.actionText).toBe('SHOW'); grid.addRowSnackbar.triggerAction(); fixture.detectChanges(); const row2 = grid.getRowByKey(addedRec[grid.primaryKey]); groupRows = grid.groupsRowList.toArray(); expect(row2).not.toBeNull(); expect(groupRows[2].expanded).toBeTrue(); expect(groupRows[2].groupRow.records.length).toEqual(2); expect(groupRows[2].groupRow.records[1]).toBe(row2.data); }); }); describe('Row Adding - Summaries', () => { beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(IgxAddRowComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; gridContent = GridFunctions.getGridContent(fixture); })); it('Should update summaries after adding new row', () => { grid.getColumnByName('ID').hasSummary = true; fixture.detectChanges(); let summaryRow = fixture.debugElement.query(By.css(SUMMARY_ROW)); GridSummaryFunctions.verifyColumnSummaries(summaryRow, 0, ['Count'], ['27']); grid.rowList.first.beginAddRow(); fixture.detectChanges(); endTransition(); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); summaryRow = fixture.debugElement.query(By.css(SUMMARY_ROW)); GridSummaryFunctions.verifyColumnSummaries(summaryRow, 0, ['Count'], ['28']); }); }); describe('Row Adding - Column manipulations', () => { beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(IgxAddRowComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; gridContent = GridFunctions.getGridContent(fixture); })); it('Should exit add row mode when moving a column', () => { spyOn(grid.gridAPI.crudService, 'endEdit').and.callThrough(); const dataLength = grid.data.length; const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); expect(grid.gridAPI.get_row_by_index(1).addRowUI).toBeTrue(); expect(grid.rowEditingOverlay.collapsed).toEqual(false); grid.moveColumn(grid.columns[1], grid.columns[2]); fixture.detectChanges(); expect(grid.gridAPI.crudService.endEdit).toHaveBeenCalled(); expect(grid.data.length).toBe(dataLength); expect(grid.rowEditingOverlay.collapsed).toEqual(true); }); it('Should exit add row mode when pinning/unpinning a column', () => { spyOn(grid.gridAPI.crudService, 'endEdit').and.callThrough(); const dataLength = grid.data.length; const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); expect(grid.gridAPI.get_row_by_index(1).addRowUI).toBeTrue(); expect(grid.rowEditingOverlay.collapsed).toEqual(false); grid.pinColumn('CompanyName'); fixture.detectChanges(); expect(grid.gridAPI.crudService.endEdit).toHaveBeenCalled(); expect(grid.data.length).toBe(dataLength); expect(grid.rowEditingOverlay.collapsed).toEqual(true); row.beginAddRow(); fixture.detectChanges(); endTransition(); grid.unpinColumn('CompanyName'); fixture.detectChanges(); expect(grid.gridAPI.crudService.endEdit).toHaveBeenCalled(); expect(grid.data.length).toBe(dataLength); expect(grid.rowEditingOverlay.collapsed).toEqual(true); }); it('Should exit add row mode when resizing a column', async () => { spyOn(grid.gridAPI.crudService, 'endEdit').and.callThrough(); fixture.detectChanges(); const dataLength = grid.data.length; const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); expect(grid.gridAPI.get_row_by_index(1).addRowUI).toBeTrue(); expect(grid.rowEditingOverlay.collapsed).toEqual(false); const headers: DebugElement[] = fixture.debugElement.queryAll(By.css(GRID_THEAD_ITEM)); const headerResArea = headers[2].children[3].nativeElement; UIInteractions.simulateMouseEvent('mousedown', headerResArea, 400, 0); await wait(200); fixture.detectChanges(); const resizer = GridFunctions.getResizer(fixture).nativeElement; expect(resizer).toBeDefined(); UIInteractions.simulateMouseEvent('mousemove', resizer, 450, 0); UIInteractions.simulateMouseEvent('mouseup', resizer, 450, 0); fixture.detectChanges(); expect(grid.gridAPI.crudService.endEdit).toHaveBeenCalled(); expect(grid.data.length).toBe(dataLength); expect(grid.rowEditingOverlay.collapsed).toEqual(false); }); it('Should exit add row mode when hiding a column', () => { spyOn(grid.gridAPI.crudService, 'endEdit').and.callThrough(); const dataLength = grid.data.length; const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); expect(grid.gridAPI.get_row_by_index(1).addRowUI).toBeTrue(); expect(grid.rowEditingOverlay.collapsed).toEqual(false); const column = grid.columnList.filter(c => c.field === 'ContactName')[0]; column.hidden = true; fixture.detectChanges(); expect(grid.gridAPI.crudService.endEdit).toHaveBeenCalled(); expect(grid.data.length).toBe(dataLength); expect(grid.rowEditingOverlay.collapsed).toEqual(true); }); }); describe('Row Adding - Transactions', () => { beforeEach(fakeAsync(/** height/width setter rAF */() => { fixture = TestBed.createComponent(IgxGridRowEditingTransactionComponent); fixture.detectChanges(); grid = fixture.componentInstance.grid; gridContent = GridFunctions.getGridContent(fixture); })); it('Should create ADD transaction when adding a new row', () => { const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); const states = grid.transactions.getAggregatedChanges(true); expect(states.length).toEqual(1); expect(states[0].type).toEqual(TransactionType.ADD); }); it('All updates on uncommitted add row should be merged into one ADD transaction', () => { const row = grid.rowList.first; row.beginAddRow(); fixture.detectChanges(); endTransition(); grid.gridAPI.crudService.endEdit(true); fixture.detectChanges(); let states = grid.transactions.getAggregatedChanges(true); expect(states.length).toEqual(1); expect(states[0].type).toEqual(TransactionType.ADD); const cell = grid.getCellByColumn(grid.dataView.length - 1, 'ProductName'); cell.update('aaa'); fixture.detectChanges(); states = grid.transactions.getAggregatedChanges(true); expect(states.length).toEqual(1); expect(states[0].type).toEqual(TransactionType.ADD); expect(states[0].newValue['ProductName']).toEqual('aaa'); }); }); });
the_stack
import { CheckboxGroupPO } from '../pages/checkbox-group.po'; import { checkIfDisabled, checkLabels } from '../../helper/assertion-helper'; import { countriesArr, errorTooltipMessage, europeanCountriesArr, fourFruitsArr, hobbiesArr, itemsArr, markingsStyle, phonesArr, programmingLanguagesArr, reptilesArr, seasonsArr, seasonsOutputLabel, sportsArr, threeFruitsArr, currencies, purchasedItemsArr, engineeringErrorMessage, workExpierenceErrorMessage, graduationErrorMessage, qualificationCheckboxesArr, subjectsArr } from '../fixtures/appData/checkbox-group-page-content'; import { click, clickNextElement, executeScriptBeforeTagAttr, getAttributeByName, getElementArrayLength, getText, getTextArr, isElementDisplayed, mouseHoverElement, refreshPage, scrollIntoView } from '../../driver/wdio'; describe('Checkbox group test suite', () => { const checkboxGroupPage = new CheckboxGroupPO(); const { stringValueCheckboxesArr, stringValueCheckboxLabelArr, stringValuecheckboxGroupLabelsArr, stringValuecheckboxGroupsArr, stringValueoutputLabelsArr, winterCheckbox, objectValueCheckboxesArr, objectValueCheckboxLabelArr, objectValuecheckboxGroupLabelsArr, objectValuecheckboxGroupsArr, projectedValueCheckboxesArr, projectedValueCheckboxLabelArr, projectedValuecheckboxGroupLabelsArr, projectedValuecheckboxGroupsArr, formValidationCheckboxesArr, formValidationCheckboxLabelArr, formValidationcheckboxGroupLabelsArr, formValidationcheckboxGroupsArr, errorTooltip, sectiontitle, objectValueoutputLabelsArr, projectValueoutputLabelsArr, formvalidationValueoutputLabelsArr } = checkboxGroupPage; beforeAll(() => { checkboxGroupPage.open(); }, 1); afterEach(() => { refreshPage(); }, 1); describe('Checkbox Group created with List of Values.', () => { // TODO: Need to revise this one and consider using nexElement method it('should check that each checkbox has label', () => { const checkboxCount = getElementArrayLength(stringValueCheckboxesArr); const checkboxLabelCount = getElementArrayLength(stringValueCheckboxLabelArr); expect(checkboxCount).toEqual(checkboxLabelCount); }); it('should check checkbox markings are centered', () => { const checkboxMarkDisplayStyle = executeScriptBeforeTagAttr(winterCheckbox, 'display'); expect(checkboxMarkDisplayStyle).toContain(markingsStyle); }); it('should check reactive inline checkboxes', () => { checkLabels(stringValueCheckboxLabelArr, seasonsArr, 0, 4); checkCheckboxSelecting( stringValueCheckboxesArr, stringValueCheckboxLabelArr, stringValueoutputLabelsArr, 0, 0, 4, seasonsArr ); }); it('should check reactive pre-selection based on value passed checkboxes', () => { checkLabels(stringValueCheckboxLabelArr, phonesArr, 4, 8); checkCheckboxSelecting( stringValueCheckboxesArr, stringValueCheckboxLabelArr, stringValueoutputLabelsArr, 1, 4, 8, phonesArr ); }); it('should check reactive pre-selection based on value passed from formGroup checkboxes', () => { checkLabels(stringValueCheckboxLabelArr, sportsArr, 8, 12); checkCheckboxSelecting( stringValueCheckboxesArr, stringValueCheckboxLabelArr, stringValueoutputLabelsArr, 2, 8, 12, sportsArr ); }); it('should check reactive disabled checkboxes', () => { checkLabels(stringValueCheckboxLabelArr, sportsArr, 12, 16); for (let i = 12; 16 > i; i++) { checkIfDisabled(stringValueCheckboxesArr, 'aria-disabled', 'true', i); } }); it('should check template inline checkboxes', () => { checkLabels(stringValueCheckboxLabelArr, seasonsArr, 19, 23); checkCheckboxSelecting( stringValueCheckboxesArr, stringValueCheckboxLabelArr, stringValueoutputLabelsArr, 4, 19, 23, seasonsArr ); }); it('should check template pre-selection based on value passed checkboxes', () => { checkLabels(stringValueCheckboxLabelArr, sportsArr, 23, 27); checkCheckboxSelecting( stringValueCheckboxesArr, stringValueCheckboxLabelArr, stringValueoutputLabelsArr, 5, 23, 27, sportsArr ); }); it('should check reactive disabled checkboxes', () => { checkLabels(stringValueCheckboxLabelArr, sportsArr, 27, 31); for (let i = 27; 31 > i; i++) { checkIfDisabled(stringValueCheckboxesArr, 'aria-disabled', 'true', i); } }); }); describe('Checkbox Group created From List of Objects.', () => { it('should check that each checkbox has label', () => { const checkboxCount = getElementArrayLength(objectValueCheckboxesArr); const checkboxLabelCount = getElementArrayLength(objectValueCheckboxLabelArr); expect(checkboxCount).toEqual(checkboxLabelCount); }); it('should check reactive inline checkboxes2', () => { checkLabels(objectValueCheckboxLabelArr, programmingLanguagesArr, 0, 4); checkCheckboxSelecting( objectValueCheckboxesArr, objectValueCheckboxLabelArr, objectValueoutputLabelsArr, 0, 0, 4, programmingLanguagesArr ); checkIfDisabled(objectValueCheckboxesArr, 'aria-disabled', 'true', 1); checkIfDisabled(objectValueCheckboxesArr, 'aria-disabled', 'true', 3); }); it('should check reactive pre-selection based on value passed checkboxes', () => { checkLabels(objectValueCheckboxLabelArr, countriesArr, 4, 7); checkCheckboxSelecting( objectValueCheckboxesArr, objectValueCheckboxLabelArr, objectValueoutputLabelsArr, 1, 4, 7, countriesArr ); }); it('should check reactive pre-selection based on value passed from formGroup checkboxes', () => { checkLabels(objectValueCheckboxLabelArr, countriesArr, 7, 10); checkCheckboxSelecting( objectValueCheckboxesArr, objectValueCheckboxLabelArr, objectValueoutputLabelsArr, 2, 7, 10, currencies ); }); it('should check reactive lookup key and display key usages checkboxes', () => { checkLabels(objectValueCheckboxLabelArr, itemsArr, 10, 13); checkCheckboxSelecting( objectValueCheckboxesArr, objectValueCheckboxLabelArr, objectValueoutputLabelsArr, 3, 10, 13, purchasedItemsArr ); }); it('should check reactive disabled checkboxes', () => { checkLabels(objectValueCheckboxLabelArr, countriesArr, 13, 16); for (let i = 13; 16 > i; i++) { checkIfDisabled(objectValueCheckboxesArr, 'aria-disabled', 'true', i); } }); it('should check template inline checkboxes', () => { checkLabels(objectValueCheckboxLabelArr, programmingLanguagesArr, 16, 20); checkCheckboxSelecting( objectValueCheckboxesArr, objectValueCheckboxLabelArr, objectValueoutputLabelsArr, 4, 16, 20, programmingLanguagesArr ); checkIfDisabled(objectValueCheckboxesArr, 'aria-disabled', 'true', 17); checkIfDisabled(objectValueCheckboxesArr, 'aria-disabled', 'true', 19); }); it('should check template pre-selection based on value passed checkboxes', () => { checkLabels(objectValueCheckboxLabelArr, countriesArr, 20, 23); checkCheckboxSelecting( objectValueCheckboxesArr, objectValueCheckboxLabelArr, objectValueoutputLabelsArr, 5, 20, 23, currencies ); }); it('should check template lookup key and display key usages checkboxes', () => { checkLabels(objectValueCheckboxLabelArr, itemsArr, 23, 26); checkCheckboxSelecting( objectValueCheckboxesArr, objectValueCheckboxLabelArr, objectValueoutputLabelsArr, 6, 23, 26, purchasedItemsArr ); }); it('should check reactive disabled checkboxes', () => { checkLabels(objectValueCheckboxLabelArr, countriesArr, 26, 29); for (let i = 26; 29 > i; i++) { checkIfDisabled(objectValueCheckboxesArr, 'aria-disabled', 'true', i); } }); }); describe('Checkbox Group created From content projected Checkboxes.', () => { it('should check that each checkbox has label', () => { const checkboxCount = getElementArrayLength(projectedValueCheckboxesArr); const checkboxLabelCount = getElementArrayLength(projectedValueCheckboxLabelArr); expect(checkboxCount).toEqual(checkboxLabelCount); }); it('should check reactive checkboxes', () => { checkLabels(projectedValueCheckboxLabelArr, fourFruitsArr, 0, 4); checkCheckboxSelecting( projectedValueCheckboxesArr, projectedValueCheckboxLabelArr, projectValueoutputLabelsArr, 0, 0, 4, fourFruitsArr ); checkIfDisabled(projectedValueCheckboxesArr, 'aria-disabled', 'true', 0); checkIfDisabled(projectedValueCheckboxesArr, 'aria-disabled', 'true', 2); }); it('should check reactive pre-selection based on value passed checkboxes', () => { checkLabels(projectedValueCheckboxLabelArr, hobbiesArr, 4, 8); checkCheckboxSelecting( projectedValueCheckboxesArr, projectedValueCheckboxLabelArr, projectValueoutputLabelsArr, 1, 4, 8, hobbiesArr ); }); it('should check reactive pre-selection based on value passed from formGroup checkboxes', () => { checkLabels(projectedValueCheckboxLabelArr, europeanCountriesArr, 8, 12); checkCheckboxSelecting( projectedValueCheckboxesArr, projectedValueCheckboxLabelArr, projectValueoutputLabelsArr, 2, 8, 12, europeanCountriesArr ); }); it('should check reactive disabled checkboxes', () => { checkLabels(projectedValueCheckboxLabelArr, europeanCountriesArr, 12, 16); for (let i = 12; 16 > i; i++) { checkIfDisabled(projectedValueCheckboxesArr, 'aria-disabled', 'true', i); } }); it('should check template inline checkboxes 555', () => { checkLabels(projectedValueCheckboxLabelArr, subjectsArr, 16, 20); checkIfDisabled(projectedValueCheckboxesArr, 'aria-disabled', 'true', 16); checkIfDisabled(projectedValueCheckboxesArr, 'aria-disabled', 'true', 19); checkCheckboxSelecting( projectedValueCheckboxesArr, projectedValueCheckboxLabelArr, projectValueoutputLabelsArr, 3, 16, 20, subjectsArr ); }); it('should check template pre-selection based on value passed checkboxes', () => { checkLabels(projectedValueCheckboxLabelArr, reptilesArr, 20, 24); checkCheckboxSelecting( projectedValueCheckboxesArr, projectedValueCheckboxLabelArr, projectValueoutputLabelsArr, 4, 20, 24, reptilesArr ); }); it('should check template disabled checkboxes', () => { checkLabels(projectedValueCheckboxLabelArr, europeanCountriesArr, 24, 28); for (let i = 24; 28 > i; i++) { checkIfDisabled(projectedValueCheckboxesArr, 'aria-disabled', 'true', i); } }); }); describe('Checkbox Group handling of Form Validation and Error Message Display.', () => { it('should check that each checkbox has label', () => { const checkboxCount = getElementArrayLength(formValidationCheckboxesArr); const checkboxLabelCount = getElementArrayLength(formValidationCheckboxLabelArr); expect(checkboxCount).toEqual(checkboxLabelCount); }); it('should check Checkbox group created from passed checkboxes and value is required', () => { scrollIntoView(formValidationCheckboxesArr, 1); clickNextElement(formValidationCheckboxesArr, 1); mouseHoverElement(formValidationCheckboxesArr, 0); expect(isElementDisplayed(errorTooltip)).toBe(true); expect(getText(errorTooltip)).toEqual(errorTooltipMessage); checkLabels(formValidationCheckboxLabelArr, threeFruitsArr, 0, 3); checkCheckboxSelecting( formValidationCheckboxesArr, formValidationCheckboxLabelArr, formvalidationValueoutputLabelsArr, 0, 0, 3, threeFruitsArr ); }); it('should check Checkbox group created from list of values and value is required', () => { // get checkbox error color and tooltip scrollIntoView(formValidationCheckboxesArr, 4); clickNextElement(formValidationCheckboxesArr, 4); // click twice to mark and unmark box to get error state clickNextElement(formValidationCheckboxesArr, 4); // needed for getting the tooltip in next line mouseHoverElement(formValidationCheckboxesArr, 3); expect(isElementDisplayed(errorTooltip)).toBe(true); expect(getText(errorTooltip)).toEqual(errorTooltipMessage); checkLabels(formValidationCheckboxLabelArr, threeFruitsArr, 3, 6); checkCheckboxSelecting( formValidationCheckboxesArr, formValidationCheckboxLabelArr, formvalidationValueoutputLabelsArr, 1, 3, 6, threeFruitsArr ); }); it('should check Checkbox group created from list of values and value is required', () => { // get checkbox error color and tooltip scrollIntoView(formValidationCheckboxesArr, 6); clickNextElement(formValidationCheckboxesArr, 6); // click twice to mark and unmark box to get error state clickNextElement(formValidationCheckboxesArr, 6); expect(isElementDisplayed(errorTooltip)).toBe(true); mouseHoverElement(formValidationCheckboxesArr, 6); expect(isElementDisplayed(errorTooltip)).toBe(true); checkLabels(formValidationCheckboxLabelArr, qualificationCheckboxesArr, 6, 9); expect(getTextArr(formValidationCheckboxLabelArr, 6, 9)).toEqual(qualificationCheckboxesArr); checkIfDisabled(formValidationCheckboxesArr, 'aria-disabled', 'true', 10); checkIfDisabled(formValidationCheckboxesArr, 'aria-disabled', 'true', 12); }); it('should check error messages in Checkbox group created from list of values and value is required', () => { scrollIntoView(formValidationCheckboxesArr, 8); clickNextElement(formValidationCheckboxesArr, 8); clickNextElement(formValidationCheckboxesArr, 8); expect(getText(errorTooltip)).toEqual(workExpierenceErrorMessage); clickNextElement(formValidationCheckboxesArr, 7); clickNextElement(formValidationCheckboxesArr, 7); expect(getText(errorTooltip)).toEqual(engineeringErrorMessage); clickNextElement(formValidationCheckboxesArr, 6); clickNextElement(formValidationCheckboxesArr, 6); expect(getText(errorTooltip)).toEqual(graduationErrorMessage); }); it('should check selecting checkboxes created from list of SelectItem Objects and value is required', () => { checkCheckboxSelecting( formValidationCheckboxesArr, formValidationCheckboxLabelArr, formvalidationValueoutputLabelsArr, 2, 9, 12, programmingLanguagesArr ); }); }); describe('check example orientation', () => { it('should check LTR orientation', () => { checkboxGroupPage.checkRtlSwitch(); }); }); xdescribe('Check visual regression', () => { it('should check examples visual regression', () => { checkboxGroupPage.saveExampleBaselineScreenshot(); expect(checkboxGroupPage.compareWithBaseline()).toBeLessThan(5); }); }); }); function checkCheckboxSelecting( checkboxesArray: string, labelsArray: string, outputLabel: string, outputLabelIndex: number, start: number, end: number, expectedOutputLabelsArr: string[] ): void { let j = 0; for (let i = start; i < end; i++) { scrollIntoView(checkboxesArray, start); if (getAttributeByName(checkboxesArray, 'aria-disabled', i) !== 'true') { if ( getText(outputLabel, outputLabelIndex) .toLocaleLowerCase() .includes(expectedOutputLabelsArr[j].toLocaleLowerCase()) ) { click(labelsArray, i); expect(getText(outputLabel, outputLabelIndex).toLocaleLowerCase()).not.toContain( expectedOutputLabelsArr[j].toLocaleLowerCase() ); } else if ( !getText(outputLabel, outputLabelIndex) .toLocaleLowerCase() .includes(expectedOutputLabelsArr[j].toLocaleLowerCase()) ) { click(labelsArray, i); expect(getText(outputLabel, outputLabelIndex).toLocaleLowerCase()).toContain( expectedOutputLabelsArr[j].toLocaleLowerCase() ); } } j++; } }
the_stack
'use strict'; import { NativeModules, Platform } from "react-native"; import { CustomEvent } from "./CustomEvent"; import { TagGroupEditor, TagGroupOperation } from "./TagGroupEditor"; import { AttributeEditor, AttributeOperation } from "./AttributeEditor"; import { UAEventEmitter } from "./UAEventEmitter"; import { SubscriptionListEditor, SubscriptionListUpdate} from "./SubscriptionListEditor"; import { JsonObject, JsonValue } from "./Json"; /** * @hidden */ const UrbanAirshipModule = NativeModules.UrbanAirshipReactModule; /** * @hidden */ const EventEmitter = new UAEventEmitter(); /** * Enum of internal event type names used by UAEventEmitter * @hidden */ enum InternalEventType { Registration = "com.urbanairship.registration", NotificationResponse = "com.urbanairship.notification_response", PushReceived = "com.urbanairship.push_received", DeepLink = "com.urbanairship.deep_link", InboxUpdated = "com.urbanairship.inbox_updated", NotificationOptInStatus = "com.urbanairship.notification_opt_in_status", ShowInbox = "com.urbanairship.show_inbox", ConversationUpdated = "com.urbanairship.conversation_updated" } /** * Enum of event type names. */ export enum EventType { /** * Notification response event. On Android, this event will be dispatched * in the background for background notifications actions. */ NotificationResponse = "notificationResponse", /** * Push received event. On Android, this event will only be dispatched * in the background if the app is able to start a service or by sending a * high priority FCM message. */ PushReceived = "pushReceived", /** * Register event. */ Register = "register", /** * Registration event. */ Registration = "registration", /** * Deep link event. */ DeepLink = "deepLink", /** * Notification opt-in status event. */ NotificationOptInStatus = "notificationOptInStatus", /** * Inbox updated event. */ InboxUpdated = "inboxUpdated", /** * Show inbox event. */ ShowInbox = "showInbox", /** * Chat conversation updated. */ ConversationUpdated = "conversationUpdated" } /** * Inbox message object. */ export interface InboxMessage { /** * The message ID. Needed to display, mark as read, or delete the message. */ id: string; /** * The message title. */ title: string; /** * The message sent date in milliseconds. */ sentDate: number; /** * Optional - The icon url for the message. */ listIconUrl: string; /** * The unread / read status of the message. */ isRead: boolean; /** * The deleted status of the message. */ isDeleted: boolean; /** * String to String map of any message extras. */ extras: Record<string, string>; } /** * Event fired when a push is received. */ export interface PushReceivedEvent { /** * The alert. */ alert?: string; /** * The title. */ title?: string; /** * The notification ID. */ notificationId: string; /** * The notification extras. */ extras: JsonObject; } /** * Event fired when the user initiates a notification response. */ export interface NotificationResponseEvent { /** * The push notification. */ notification: PushReceivedEvent; /** * The action button ID, if avilable. */ actionId?: string; /** * Indicates whether the response was a foreground action. * This value is always if the user taps the main notification, * otherwise it is defined by the notification action button. */ isForeground: boolean } /** * Enum of notification options. iOS only. */ export enum NotificationOptionsIOS { /** * Alerts. */ Alert = "alert", /** * Sounds. */ Sound = "sound", /** * Badges. */ Badge = "badge" } /** * A map of notification options. iOS only. */ export type NotificationOptionsMapIOS = { [option in NotificationOptionsIOS]: boolean } /** * A map of foreground notification options. iOS only. */ export type ForegroundNotificationOptionsIOS = { [option in NotificationOptionsIOS]: boolean | null | undefined } /** * Enum of authorized notification settings. iOS only. */ export enum AuthorizedNotificationSettingsIOS { /** * Alerts. */ Alert = "alert", /** * Sounds. */ Sound = "sound", /** * Badges. */ Badge = "badge", /** * CarPlay. */ CarPlay = "carPlay", /** * Lock screen. */ LockScreen = "lockScreen", /** * Notification center. */ NotificationCenter = "notificationCenter" } /** * A map of authorized notification settings. */ export type iOSAuthorizedNotificationSettingsMap = { [setting in AuthorizedNotificationSettingsIOS]: boolean } /** * Event fired when the notification opt-in status changes. */ export interface NotificationOptInStatusEvent { /** * Whether the user is opted in to notifications. */ optIn: boolean; /** * The authorized notification settings. iOS only. */ authorizedNotificationSettings?: AuthorizedNotificationSettingsIOS; } /** * Event fired when the inbox is updated. */ export interface InboxUpdatedEvent { /** * The unread message count. */ messageUnreadCount: number; /** * The total message count. */ messageCount: number } /** * Event fired when the message center requests the inbox to be displayed. */ export interface ShowInboxEvent { /** * The message ID, if available. */ messageId?: string; } /** * Event fired when a deep link is opened. */ export interface DeepLinkEvent { /** * The deep link string. */ deepLink: string; } /** * A listener subscription. */ export class Subscription { onRemove: () => void; constructor(onRemove: () => void) { this.onRemove = onRemove; } /** * Removes the listener. */ remove(): void { this.onRemove(); } } /** * Event fired when a channel registration occurs. */ export interface RegistrationEvent { /** * The channel ID. */ channelId: string; /** * The registration token. The registration token might be undefined * if registration is currently in progress, if the app is not setup properly * for remote notifications, if running on an iOS simulator, or if running on * an Android device that has an outdated or missing version of Google Play Services. */ registrationToken?: string } /** * Converts between public and internal event types. * @hidden */ function convertEventEnum(type: EventType): string { if (type === EventType.NotificationResponse) { return InternalEventType.NotificationResponse; } else if (type === EventType.PushReceived) { return InternalEventType.PushReceived; } else if (type === EventType.Register || type === EventType.Registration) { return InternalEventType.Registration; } else if (type == EventType.DeepLink) { return InternalEventType.DeepLink; } else if (type == EventType.NotificationOptInStatus) { return InternalEventType.NotificationOptInStatus; } else if (type == EventType.InboxUpdated) { return InternalEventType.InboxUpdated; } else if (type == EventType.ShowInbox) { return InternalEventType.ShowInbox; } else if (type == EventType.ConversationUpdated) { return InternalEventType.ConversationUpdated; } throw new Error("Invalid event name: " + type); } function convertFeatureEnum(feature: String): Feature { if (feature == "FEATURE_NONE") { return Feature.FEATURE_NONE } else if (feature == "FEATURE_IN_APP_AUTOMATION") { return Feature.FEATURE_IN_APP_AUTOMATION } else if (feature == "FEATURE_MESSAGE_CENTER") { return Feature.FEATURE_MESSAGE_CENTER } else if (feature == "FEATURE_PUSH") { return Feature.FEATURE_PUSH } else if (feature == "FEATURE_CHAT") { return Feature.FEATURE_CHAT } else if (feature == "FEATURE_ANALYTICS") { return Feature.FEATURE_ANALYTICS } else if (feature == "FEATURE_TAGS_AND_ATTRIBUTES") { return Feature.FEATURE_TAGS_AND_ATTRIBUTES } else if (feature == "FEATURE_CONTACTS") { return Feature.FEATURE_CONTACTS } else if (feature == "FEATURE_LOCATION") { return Feature.FEATURE_LOCATION } else if (feature == "FEATURE_ALL") { return Feature.FEATURE_ALL } throw new Error("Invalid feature name: " + feature); } /** * Android notification config. */ export interface NotificationConfigAndroid { /** * The icon resource na,e. */ icon?: string; /** * The large icon resource name. */ largeIcon?: string; /** * The default android notification channel ID. */ defaultChannelId?: string; } /** * Enum of authorized Features. */ export enum Feature { FEATURE_NONE = "FEATURE_NONE", FEATURE_IN_APP_AUTOMATION = "FEATURE_IN_APP_AUTOMATION", FEATURE_MESSAGE_CENTER = "FEATURE_MESSAGE_CENTER", FEATURE_PUSH = "FEATURE_PUSH", FEATURE_CHAT = "FEATURE_CHAT", FEATURE_ANALYTICS = "FEATURE_ANALYTICS", FEATURE_TAGS_AND_ATTRIBUTES = "FEATURE_TAGS_AND_ATTRIBUTES", FEATURE_CONTACTS = "FEATURE_CONTACTS", FEATURE_LOCATION = "FEATURE_LOCATION", FEATURE_ALL = "FEATURE_ALL" } /** * The main Airship API. */ export class UrbanAirship { /** * Sets the Android notification config. Values not set will fallback to any values set in the airship config options. * * @param config The notification config object. */ static setAndroidNotificationConfig(config: NotificationConfigAndroid) { UrbanAirshipModule.setAndroidNotificationConfig(config); } /** * Sets user notifications enabled. The first time user notifications are enabled * on iOS, it will prompt the user for notification permissions. * * @param enabled true to enable notifications, false to disable. */ static setUserNotificationsEnabled(enabled: boolean) { UrbanAirshipModule.setUserNotificationsEnabled(enabled); } /** * Checks if user notifications are enabled or not. * * @return A promise with the result. */ static isUserNotificationsEnabled(): Promise<boolean> { return UrbanAirshipModule.isUserNotificationsEnabled(); } /** * Sets the SDK features that will be enabled. The rest of the features will be disabled. * * If all features are disabled the SDK will not make any network requests or collect data. * * @note All features are enabled by default. * @param feature An array of `Features` to enable. * @return A promise that returns true if the enablement was authorized. */ static setEnabledFeatures(features: Feature[]): Promise<boolean> { return UrbanAirshipModule.setEnabledFeatures(features); } /** * Gets a Feature array with the enabled features. * * @return A promise that returns the enabled features as a Feature array. */ static getEnabledFeatures(): Promise<Feature[]> { return new Promise((resolve, reject) => { UrbanAirshipModule.getEnabledFeatures().then((features: String[]) => { var convertedFeatures: Feature[] = new Array(); for (const feature of features){ convertedFeatures.push(convertFeatureEnum(feature)); } resolve(convertedFeatures); }), (error: Error) => { reject(error); }; }); } /** * Enables one or many features. * * @param feature An array of `Feature` to enable. * @return A promise that returns true if the enablement was authorized. */ static enableFeature(features: Feature[]): Promise<boolean> { return UrbanAirshipModule.enableFeature(features); } /** * Disables one or many features. * * @param feature An array of `Feature` to disable. * @return A promise that returns true if the disablement was authorized. */ static disableFeature(features: Feature[]): Promise<boolean> { return UrbanAirshipModule.disableFeature(features); } /** * Checks if a given feature is enabled or not. * * @return A promise that returns true if the features are enabled, false otherwise. */ static isFeatureEnabled(features: Feature[]): Promise<boolean> { return UrbanAirshipModule.isFeatureEnabled(features); } /** * Enables user notifications. * * @return A promise that returns true if enablement was authorized * or false if enablement was rejected */ static enableUserPushNotifications(): Promise<boolean> { return UrbanAirshipModule.enableUserPushNotifications(); } /** * Enables channel creation if `channelCreationDelayEnabled` was * enabled in the config. */ static enableChannelCreation() { UrbanAirshipModule.enableChannelCreation(); } /** * Checks if app notifications are enabled or not. Its possible to have `userNotificationsEnabled` * but app notifications being disabled if the user opted out of notifications. * * @return A promise with the result. */ static isUserNotificationsOptedIn(): Promise<boolean> { return UrbanAirshipModule.isUserNotificationsOptedIn(); } /** * Checks if app notifications are enabled at a system level or not. Its possible to have `userNotificationsEnabled` * but app notifications being disabled if the user opted out of notifications. * * @return A promise with the result. */ static isSystemNotificationsEnabledForApp(): Promise<boolean> { return UrbanAirshipModule.isSystemNotificationsEnabledForApp(); } /** * Gets the status of the specified Notification Channel. * This method is only supported on Android. iOS will throw an error. * * @param channel The channel's name. * @return A promise with the result. */ static getNotificationChannelStatus(channel: string): Promise<string> { if (Platform.OS != 'android') { throw new Error("This method is only supported on Android devices."); } return UrbanAirshipModule.getNotificationChannelStatus(channel); } /** * Sets the named user. * * @param namedUser The named user string, or null/undefined to clear the named user. */ static setNamedUser(namedUser: string | null | undefined) { UrbanAirshipModule.setNamedUser(namedUser); } /** * Gets the named user. * * @return A promise with the result. */ static getNamedUser(): Promise<string | null | undefined> { return UrbanAirshipModule.getNamedUser(); } /** * Adds a channel tag. * * @param tag A channel tag. */ static addTag(tag: string) { UrbanAirshipModule.addTag(tag); } /** * Removes a channel tag. * * @param tag A channel tag. */ static removeTag(tag: string) { UrbanAirshipModule.removeTag(tag); } /** * Gets the channel tags. * * @return A promise with the result. */ static getTags(): Promise<string[]> { return UrbanAirshipModule.getTags(); } /** * Creates an editor to modify the named user tag groups. * * @return A tag group editor instance. */ static editNamedUserTagGroups(): TagGroupEditor { return new TagGroupEditor((operations: TagGroupOperation[]) => { UrbanAirshipModule.editNamedUserTagGroups(operations); }); } /** * Creates an editor to modify the channel tag groups. * * @return A tag group editor instance. */ static editChannelTagGroups(): TagGroupEditor { return new TagGroupEditor((operations: TagGroupOperation[]) => { UrbanAirshipModule.editChannelTagGroups(operations); }); } /** * Creates an editor to modify the channel attributes. * * @return An attribute editor instance. */ static editChannelAttributes(): AttributeEditor { return new AttributeEditor((operations: AttributeOperation[]) => { UrbanAirshipModule.editChannelAttributes(operations); }); } /** * Creates an editor to modify the named user attributes. * * @return An attribute editor instance. */ static editNamedUserAttributes(): AttributeEditor { return new AttributeEditor((operations: AttributeOperation[]) => { UrbanAirshipModule.editNamedUserAttributes(operations); }); } /** * Edit the subscription List. * * @return A promise with the result. */ static editSubscriptionLists(): SubscriptionListEditor { return new SubscriptionListEditor((subscriptionListUpdates: SubscriptionListUpdate[]) => { UrbanAirshipModule.editSubscriptionLists(subscriptionListUpdates); }); } /** * Enables or disables analytics. * * Disabling analytics will delete any locally stored events * and prevent any events from uploading. Features that depend on analytics being * enabled may not work properly if it's disabled (reports, region triggers, * location segmentation, push to local time). * * @param enabled true to enable notifications, false to disable. */ static setAnalyticsEnabled(enabled: boolean) { UrbanAirshipModule.setAnalyticsEnabled(enabled); } /** * Checks if analytics is enabled or not. * * @return A promise with the result. */ static isAnalyticsEnabled(): Promise<boolean> { return UrbanAirshipModule.isAnalyticsEnabled(); } /** * Initiates screen tracking for a specific app screen, must be called once per tracked screen. * * @param screen The screen's string identifier */ static trackScreen(screen: string) { UrbanAirshipModule.trackScreen(screen); } /** * Gets the channel ID. * * @return A promise with the result. */ static getChannelId(): Promise<string | null | undefined> { return UrbanAirshipModule.getChannelId(); } /** * Gets the registration token. * * @return A promise with the result. The registration token might be undefined * if registration is currently in progress, if the app is not setup properly * for remote notifications, if running on an iOS simulator, or if running on * an Android device that has an outdated or missing version of Google Play Services. */ static getRegistrationToken(): Promise<string | null | undefined> { return UrbanAirshipModule.getRegistrationToken(); } /** * Associates an identifier for the Connect data stream. * * @param key The identifier's key. * @param id The identifier's id, or null/undefined to clear. */ static associateIdentifier(key: string, id?: string) { UrbanAirshipModule.associateIdentifier(key, id); } /** * Adds a custom event. * * @param event The custom event. * @return A promise that returns null if resolved, or an Error if the * custom event is rejected. */ static addCustomEvent(event: CustomEvent): Promise<null | Error> { const actionArg = { event_name: event._name, event_value: event._value, transaction_id: event._transactionId, properties: event._properties }; return new Promise((resolve, reject) => { UrbanAirshipModule.runAction("add_custom_event_action", actionArg).then(() => { resolve(); }, (error: Error) => { reject(error); }); }); } /** * Runs an Urban Airship action. * * @param name The name of the action. * @param value The action's value. * @return A promise that returns the action result if the action * successfully runs, or the Error if the action was unable to be run. */ static runAction(name: string, value?: JsonValue): Promise<JsonValue | Error> { return UrbanAirshipModule.runAction(name, value); } /** * Sets the foregorund presentation options for iOS. * This method is only supported on iOS. Android will no-op. * * @param options The map of options. */ static setForegroundPresentationOptions(options: ForegroundNotificationOptionsIOS) { if (Platform.OS == 'ios') { return UrbanAirshipModule.setForegroundPresentationOptions(options); } } /** * Adds a listener for an Urban Airship event. * * @param eventType The event type. Either EventType.NotificationResponse, EventType.PushReceived, * EventType.Register, EventType.Registration, EventType.DeepLink, EventType.NotificationOptInStatus, * EventType.InboxUpdated, or EventType.ShowInbox. * @param listener The event listener. * @return A subscription. */ static addListener(eventType: EventType, listener: (...args: any[]) => any): Subscription { EventEmitter.addListener(convertEventEnum(eventType), listener); return new Subscription(() => { UrbanAirship.removeListener(eventType, listener); }); } /** * Removes a listener for an Urban Airship event. * * @param eventType The event type. Either EventType.NotificationResponse, EventType.PushReceived, * EventType.Register, EventType.Registration, EventType.DeepLink, EventType.NotificationOptInStatus, * EventType.InboxUpdated, or EventType.ShowInbox. * @param listener The event listener. Should be a reference to the function passed into addListener. */ static removeListener(eventType: EventType, listener: (...args: any[]) => any) { EventEmitter.removeListener(convertEventEnum(eventType), listener); } /** * Removes all listeners for Urban Airship events. * * @param eventType The event type. Either EventType.NotificationResponse, EventType.PushReceived, * EventType.Register, EventType.Registration, EventType.DeepLink, EventType.NotificationOptInStatus, * EventType.InboxUpdated, or EventType.ShowInbox. */ static removeAllListeners(eventType: EventType) { EventEmitter.removeAllListeners(convertEventEnum(eventType)); } /** * Enables or disables autobadging on iOS. Badging is not supported for Android. * * @param enabled Whether or not to enable autobadging. */ static setAutobadgeEnabled(enabled: boolean) { if (Platform.OS == 'ios') { UrbanAirshipModule.setAutobadgeEnabled(enabled); } else { console.log("This feature is not supported on this platform."); } } /** * Checks to see if autobadging on iOS is enabled. Badging is not supported for Android. * * @return A promise with the result, either true or false. */ static isAutobadgeEnabled(): Promise<boolean> { if (Platform.OS == 'ios') { return UrbanAirshipModule.isAutobadgeEnabled(); } else { console.log("This feature is not supported on this platform."); return new Promise(resolve => resolve(false)); } } /** * Sets the badge number for iOS. Badging is not supported for Android. * * @param badgeNumber The badge number. */ static setBadgeNumber(badgeNumber: number) { if (Platform.OS == 'ios') { UrbanAirshipModule.setBadgeNumber(badgeNumber); } else { console.log("This feature is not supported on this platform."); } } /** * Gets the current badge number for iOS. Badging is not supported for Android * and this method will always return 0. * * @return A promise with the result. */ static getBadgeNumber(): Promise<number> { if (Platform.OS != 'ios') { console.log("This feature is not supported on this platform."); } return UrbanAirshipModule.getBadgeNumber(); } /** * Displays the default message center. */ static displayMessageCenter() { UrbanAirshipModule.displayMessageCenter(); } /** * Dismisses the default message center. */ static dismissMessageCenter() { UrbanAirshipModule.dismissMessageCenter(); } /** * Displays an inbox message. * * @param messageId The id of the message to be displayed. * @return A promise with the result. */ static displayMessage(messageId: string): Promise<boolean> { return UrbanAirshipModule.displayMessage(messageId); } /** * Dismisses the currently displayed inbox message. */ static dismissMessage() { UrbanAirshipModule.dismissMessage(); } /** * Retrieves the current inbox messages. * * @return A promise with the result. */ static getInboxMessages(): Promise<InboxMessage[]> { return UrbanAirshipModule.getInboxMessages(); } /** * Deletes an inbox message. * * @param messageId The id of the message to be deleted. * @return A promise with the result. */ static deleteInboxMessage(messageId: string): Promise<boolean> { return UrbanAirshipModule.deleteInboxMessage(messageId); } /** * Marks an inbox message as read. * * @param messageId The id of the message to be marked as read. * @return A promise with the result. */ static markInboxMessageRead(messageId: string): Promise<boolean> { return UrbanAirshipModule.markInboxMessageRead(messageId); } /** * Forces the inbox to refresh. This is normally not needed as the inbox will * automatically refresh on foreground or when a push arrives that's associated * with a message. * * @return{Promise.<boolean>} A promise with the result. */ static refreshInbox(): Promise<boolean> { return UrbanAirshipModule.refreshInbox(); } /** * Sets the default behavior when the message center is launched from a push * notification. If set to false the message center must be manually launched. * * @param enabled true to automatically launch the default message center, false to disable. */ static setAutoLaunchDefaultMessageCenter(enabled: boolean) { UrbanAirshipModule.setAutoLaunchDefaultMessageCenter(enabled); } /** * Overriding the locale. * * @param localeIdentifier The locale identifier. */ static setCurrentLocale(localeIdentifier: String) { UrbanAirshipModule.setCurrentLocale(localeIdentifier); } /** * Getting the locale currently used by Airship. * */ static getCurrentLocale(): Promise<String> { return UrbanAirshipModule.getCurrentLocale(); } /** * Resets the current locale. * */ static clearLocale() { UrbanAirshipModule.clearLocale(); } /** * Gets all the active notifications for the application. * Supported on Android Marshmallow (23)+ and iOS 10+. * * @return A promise with the result. */ static getActiveNotifications(): Promise<PushReceivedEvent[]> { return UrbanAirshipModule.getActiveNotifications(); } /** * Clears all notifications for the application. * Supported on Android and iOS 10+. For older iOS devices, you can set * the badge number to 0 to clear notifications. */ static clearNotifications() { UrbanAirshipModule.clearNotifications(); } /** * Clears a specific notification. * Supported on Android and iOS 10+. * * @param identifier The notification identifier. The identifier will be * available in the PushReceived event and in the active notification response * under the "notificationId" field. */ static clearNotification(identifier: string) { UrbanAirshipModule.clearNotification(identifier); } }
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * <p>Access to a resource was denied.</p> */ export interface AccessDeniedException extends __SmithyException, $MetadataBearer { name: "AccessDeniedException"; $fault: "client"; /** * <p>A message describing the problem.</p> */ Message?: string; } export namespace AccessDeniedException { /** * @internal */ export const filterSensitiveLog = (obj: AccessDeniedException): any => ({ ...obj, }); } /** * <p>A structure containing a tag key-value pair.</p> */ export interface LFTagPair { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The key-name for the tag.</p> */ TagKey: string | undefined; /** * <p>A list of possible values an attribute can take.</p> */ TagValues: string[] | undefined; } export namespace LFTagPair { /** * @internal */ export const filterSensitiveLog = (obj: LFTagPair): any => ({ ...obj, }); } /** * <p>A structure for the catalog object.</p> */ export interface CatalogResource {} export namespace CatalogResource { /** * @internal */ export const filterSensitiveLog = (obj: CatalogResource): any => ({ ...obj, }); } /** * <p>A structure for the database object.</p> */ export interface DatabaseResource { /** * <p>The identifier for the Data Catalog. By default, it is the account ID of the caller.</p> */ CatalogId?: string; /** * <p>The name of the database resource. Unique to the Data Catalog.</p> */ Name: string | undefined; } export namespace DatabaseResource { /** * @internal */ export const filterSensitiveLog = (obj: DatabaseResource): any => ({ ...obj, }); } /** * <p>A structure for a data location object where permissions are granted or revoked. </p> */ export interface DataLocationResource { /** * <p>The identifier for the Data Catalog where the location is registered with AWS Lake Formation. By default, it is the account ID of the caller.</p> */ CatalogId?: string; /** * <p>The Amazon Resource Name (ARN) that uniquely identifies the data location resource.</p> */ ResourceArn: string | undefined; } export namespace DataLocationResource { /** * @internal */ export const filterSensitiveLog = (obj: DataLocationResource): any => ({ ...obj, }); } /** * <p>A structure containing a tag key and values for a resource.</p> */ export interface LFTagKeyResource { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The key-name for the tag.</p> */ TagKey: string | undefined; /** * <p>A list of possible values an attribute can take.</p> */ TagValues: string[] | undefined; } export namespace LFTagKeyResource { /** * @internal */ export const filterSensitiveLog = (obj: LFTagKeyResource): any => ({ ...obj, }); } /** * <p>A structure that allows an admin to grant user permissions on certain conditions. For example, granting a role access to all columns not tagged 'PII' of tables tagged 'Prod'.</p> */ export interface LFTag { /** * <p>The key-name for the tag.</p> */ TagKey: string | undefined; /** * <p>A list of possible values an attribute can take.</p> */ TagValues: string[] | undefined; } export namespace LFTag { /** * @internal */ export const filterSensitiveLog = (obj: LFTag): any => ({ ...obj, }); } export enum ResourceType { DATABASE = "DATABASE", TABLE = "TABLE", } /** * <p>A structure containing a list of tag conditions that apply to a resource's tag policy.</p> */ export interface LFTagPolicyResource { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The resource type for which the tag policy applies.</p> */ ResourceType: ResourceType | string | undefined; /** * <p>A list of tag conditions that apply to the resource's tag policy.</p> */ Expression: LFTag[] | undefined; } export namespace LFTagPolicyResource { /** * @internal */ export const filterSensitiveLog = (obj: LFTagPolicyResource): any => ({ ...obj, }); } /** * <p>A wildcard object representing every table under a database.</p> */ export interface TableWildcard {} export namespace TableWildcard { /** * @internal */ export const filterSensitiveLog = (obj: TableWildcard): any => ({ ...obj, }); } /** * <p>A structure for the table object. A table is a metadata definition that represents your data. You can Grant and Revoke table privileges to a principal. </p> */ export interface TableResource { /** * <p>The identifier for the Data Catalog. By default, it is the account ID of the caller.</p> */ CatalogId?: string; /** * <p>The name of the database for the table. Unique to a Data Catalog. A database is a set of associated table definitions organized into a logical group. You can Grant and Revoke database privileges to a principal. </p> */ DatabaseName: string | undefined; /** * <p>The name of the table.</p> */ Name?: string; /** * <p>A wildcard object representing every table under a database.</p> * * <p>At least one of <code>TableResource$Name</code> or <code>TableResource$TableWildcard</code> is required.</p> */ TableWildcard?: TableWildcard; } export namespace TableResource { /** * @internal */ export const filterSensitiveLog = (obj: TableResource): any => ({ ...obj, }); } /** * <p>A wildcard object, consisting of an optional list of excluded column names or indexes.</p> */ export interface ColumnWildcard { /** * <p>Excludes column names. Any column with this name will be excluded.</p> */ ExcludedColumnNames?: string[]; } export namespace ColumnWildcard { /** * @internal */ export const filterSensitiveLog = (obj: ColumnWildcard): any => ({ ...obj, }); } /** * <p>A structure for a table with columns object. This object is only used when granting a SELECT permission.</p> * <p>This object must take a value for at least one of <code>ColumnsNames</code>, <code>ColumnsIndexes</code>, or <code>ColumnsWildcard</code>.</p> */ export interface TableWithColumnsResource { /** * <p>The identifier for the Data Catalog. By default, it is the account ID of the caller.</p> */ CatalogId?: string; /** * <p>The name of the database for the table with columns resource. Unique to the Data Catalog. A database is a set of associated table definitions organized into a logical group. You can Grant and Revoke database privileges to a principal. </p> */ DatabaseName: string | undefined; /** * <p>The name of the table resource. A table is a metadata definition that represents your data. You can Grant and Revoke table privileges to a principal. </p> */ Name: string | undefined; /** * <p>The list of column names for the table. At least one of <code>ColumnNames</code> or <code>ColumnWildcard</code> is required.</p> */ ColumnNames?: string[]; /** * <p>A wildcard specified by a <code>ColumnWildcard</code> object. At least one of <code>ColumnNames</code> or <code>ColumnWildcard</code> is required.</p> */ ColumnWildcard?: ColumnWildcard; } export namespace TableWithColumnsResource { /** * @internal */ export const filterSensitiveLog = (obj: TableWithColumnsResource): any => ({ ...obj, }); } /** * <p>A structure for the resource.</p> */ export interface Resource { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ Catalog?: CatalogResource; /** * <p>The database for the resource. Unique to the Data Catalog. A database is a set of associated table definitions organized into a logical group. You can Grant and Revoke database permissions to a principal. </p> */ Database?: DatabaseResource; /** * <p>The table for the resource. A table is a metadata definition that represents your data. You can Grant and Revoke table privileges to a principal. </p> */ Table?: TableResource; /** * <p>The table with columns for the resource. A principal with permissions to this resource can select metadata from the columns of a table in the Data Catalog and the underlying data in Amazon S3.</p> */ TableWithColumns?: TableWithColumnsResource; /** * <p>The location of an Amazon S3 path where permissions are granted or revoked. </p> */ DataLocation?: DataLocationResource; /** * <p>The tag key and values attached to a resource.</p> */ LFTag?: LFTagKeyResource; /** * <p>A list of tag conditions that define a resource's tag policy.</p> */ LFTagPolicy?: LFTagPolicyResource; } export namespace Resource { /** * @internal */ export const filterSensitiveLog = (obj: Resource): any => ({ ...obj, }); } export interface AddLFTagsToResourceRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The resource to which to attach a tag.</p> */ Resource: Resource | undefined; /** * <p>The tags to attach to the resource.</p> */ LFTags: LFTagPair[] | undefined; } export namespace AddLFTagsToResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: AddLFTagsToResourceRequest): any => ({ ...obj, }); } /** * <p>Contains details about an error.</p> */ export interface ErrorDetail { /** * <p>The code associated with this error.</p> */ ErrorCode?: string; /** * <p>A message describing the error.</p> */ ErrorMessage?: string; } export namespace ErrorDetail { /** * @internal */ export const filterSensitiveLog = (obj: ErrorDetail): any => ({ ...obj, }); } /** * <p>A structure containing an error related to a <code>TagResource</code> or <code>UnTagResource</code> operation.</p> */ export interface LFTagError { /** * <p>The key-name of the tag.</p> */ LFTag?: LFTagPair; /** * <p>An error that occurred with the attachment or detachment of the tag.</p> */ Error?: ErrorDetail; } export namespace LFTagError { /** * @internal */ export const filterSensitiveLog = (obj: LFTagError): any => ({ ...obj, }); } export interface AddLFTagsToResourceResponse { /** * <p>A list of failures to tag the resource.</p> */ Failures?: LFTagError[]; } export namespace AddLFTagsToResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: AddLFTagsToResourceResponse): any => ({ ...obj, }); } /** * <p>Two processes are trying to modify a resource simultaneously.</p> */ export interface ConcurrentModificationException extends __SmithyException, $MetadataBearer { name: "ConcurrentModificationException"; $fault: "client"; /** * <p>A message describing the problem.</p> */ Message?: string; } export namespace ConcurrentModificationException { /** * @internal */ export const filterSensitiveLog = (obj: ConcurrentModificationException): any => ({ ...obj, }); } /** * <p>A specified entity does not exist</p> */ export interface EntityNotFoundException extends __SmithyException, $MetadataBearer { name: "EntityNotFoundException"; $fault: "client"; /** * <p>A message describing the problem.</p> */ Message?: string; } export namespace EntityNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: EntityNotFoundException): any => ({ ...obj, }); } /** * <p>An internal service error occurred.</p> */ export interface InternalServiceException extends __SmithyException, $MetadataBearer { name: "InternalServiceException"; $fault: "server"; /** * <p>A message describing the problem.</p> */ Message?: string; } export namespace InternalServiceException { /** * @internal */ export const filterSensitiveLog = (obj: InternalServiceException): any => ({ ...obj, }); } /** * <p>The input provided was not valid.</p> */ export interface InvalidInputException extends __SmithyException, $MetadataBearer { name: "InvalidInputException"; $fault: "client"; /** * <p>A message describing the problem.</p> */ Message?: string; } export namespace InvalidInputException { /** * @internal */ export const filterSensitiveLog = (obj: InvalidInputException): any => ({ ...obj, }); } /** * <p>The operation timed out.</p> */ export interface OperationTimeoutException extends __SmithyException, $MetadataBearer { name: "OperationTimeoutException"; $fault: "client"; /** * <p>A message describing the problem.</p> */ Message?: string; } export namespace OperationTimeoutException { /** * @internal */ export const filterSensitiveLog = (obj: OperationTimeoutException): any => ({ ...obj, }); } /** * <p>A resource to be created or added already exists.</p> */ export interface AlreadyExistsException extends __SmithyException, $MetadataBearer { name: "AlreadyExistsException"; $fault: "client"; /** * <p>A message describing the problem.</p> */ Message?: string; } export namespace AlreadyExistsException { /** * @internal */ export const filterSensitiveLog = (obj: AlreadyExistsException): any => ({ ...obj, }); } export enum Permission { ALL = "ALL", ALTER = "ALTER", ALTER_TAG = "ALTER_TAG", ASSOCIATE_TAG = "ASSOCIATE_TAG", CREATE_DATABASE = "CREATE_DATABASE", CREATE_TABLE = "CREATE_TABLE", CREATE_TAG = "CREATE_TAG", DATA_LOCATION_ACCESS = "DATA_LOCATION_ACCESS", DELETE = "DELETE", DELETE_TAG = "DELETE_TAG", DESCRIBE = "DESCRIBE", DESCRIBE_TAG = "DESCRIBE_TAG", DROP = "DROP", INSERT = "INSERT", SELECT = "SELECT", } /** * <p>The AWS Lake Formation principal. Supported principals are IAM users or IAM roles.</p> */ export interface DataLakePrincipal { /** * <p>An identifier for the AWS Lake Formation principal.</p> */ DataLakePrincipalIdentifier?: string; } export namespace DataLakePrincipal { /** * @internal */ export const filterSensitiveLog = (obj: DataLakePrincipal): any => ({ ...obj, }); } /** * <p>A permission to a resource granted by batch operation to the principal.</p> */ export interface BatchPermissionsRequestEntry { /** * <p>A unique identifier for the batch permissions request entry.</p> */ Id: string | undefined; /** * <p>The principal to be granted a permission.</p> */ Principal?: DataLakePrincipal; /** * <p>The resource to which the principal is to be granted a permission.</p> */ Resource?: Resource; /** * <p>The permissions to be granted.</p> */ Permissions?: (Permission | string)[]; /** * <p>Indicates if the option to pass permissions is granted.</p> */ PermissionsWithGrantOption?: (Permission | string)[]; } export namespace BatchPermissionsRequestEntry { /** * @internal */ export const filterSensitiveLog = (obj: BatchPermissionsRequestEntry): any => ({ ...obj, }); } export interface BatchGrantPermissionsRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>A list of up to 20 entries for resource permissions to be granted by batch operation to the principal.</p> */ Entries: BatchPermissionsRequestEntry[] | undefined; } export namespace BatchGrantPermissionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: BatchGrantPermissionsRequest): any => ({ ...obj, }); } /** * <p>A list of failures when performing a batch grant or batch revoke operation.</p> */ export interface BatchPermissionsFailureEntry { /** * <p>An identifier for an entry of the batch request.</p> */ RequestEntry?: BatchPermissionsRequestEntry; /** * <p>An error message that applies to the failure of the entry.</p> */ Error?: ErrorDetail; } export namespace BatchPermissionsFailureEntry { /** * @internal */ export const filterSensitiveLog = (obj: BatchPermissionsFailureEntry): any => ({ ...obj, }); } export interface BatchGrantPermissionsResponse { /** * <p>A list of failures to grant permissions to the resources.</p> */ Failures?: BatchPermissionsFailureEntry[]; } export namespace BatchGrantPermissionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: BatchGrantPermissionsResponse): any => ({ ...obj, }); } export interface BatchRevokePermissionsRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>A list of up to 20 entries for resource permissions to be revoked by batch operation to the principal.</p> */ Entries: BatchPermissionsRequestEntry[] | undefined; } export namespace BatchRevokePermissionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: BatchRevokePermissionsRequest): any => ({ ...obj, }); } export interface BatchRevokePermissionsResponse { /** * <p>A list of failures to revoke permissions to the resources.</p> */ Failures?: BatchPermissionsFailureEntry[]; } export namespace BatchRevokePermissionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: BatchRevokePermissionsResponse): any => ({ ...obj, }); } export interface CreateLFTagRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The key-name for the tag.</p> */ TagKey: string | undefined; /** * <p>A list of possible values an attribute can take.</p> */ TagValues: string[] | undefined; } export namespace CreateLFTagRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateLFTagRequest): any => ({ ...obj, }); } export interface CreateLFTagResponse {} export namespace CreateLFTagResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateLFTagResponse): any => ({ ...obj, }); } /** * <p>A resource numerical limit was exceeded.</p> */ export interface ResourceNumberLimitExceededException extends __SmithyException, $MetadataBearer { name: "ResourceNumberLimitExceededException"; $fault: "client"; /** * <p>A message describing the problem.</p> */ Message?: string; } export namespace ResourceNumberLimitExceededException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNumberLimitExceededException): any => ({ ...obj, }); } export interface DeleteLFTagRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The key-name for the tag to delete.</p> */ TagKey: string | undefined; } export namespace DeleteLFTagRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteLFTagRequest): any => ({ ...obj, }); } export interface DeleteLFTagResponse {} export namespace DeleteLFTagResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteLFTagResponse): any => ({ ...obj, }); } export interface DeregisterResourceRequest { /** * <p>The Amazon Resource Name (ARN) of the resource that you want to deregister.</p> */ ResourceArn: string | undefined; } export namespace DeregisterResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeregisterResourceRequest): any => ({ ...obj, }); } export interface DeregisterResourceResponse {} export namespace DeregisterResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeregisterResourceResponse): any => ({ ...obj, }); } export interface DescribeResourceRequest { /** * <p>The resource ARN.</p> */ ResourceArn: string | undefined; } export namespace DescribeResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeResourceRequest): any => ({ ...obj, }); } /** * <p>A structure containing information about an AWS Lake Formation resource.</p> */ export interface ResourceInfo { /** * <p>The Amazon Resource Name (ARN) of the resource.</p> */ ResourceArn?: string; /** * <p>The IAM role that registered a resource.</p> */ RoleArn?: string; /** * <p>The date and time the resource was last modified.</p> */ LastModified?: Date; } export namespace ResourceInfo { /** * @internal */ export const filterSensitiveLog = (obj: ResourceInfo): any => ({ ...obj, }); } export interface DescribeResourceResponse { /** * <p>A structure containing information about an AWS Lake Formation resource.</p> */ ResourceInfo?: ResourceInfo; } export namespace DescribeResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeResourceResponse): any => ({ ...obj, }); } export interface GetDataLakeSettingsRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; } export namespace GetDataLakeSettingsRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetDataLakeSettingsRequest): any => ({ ...obj, }); } /** * <p>Permissions granted to a principal.</p> */ export interface PrincipalPermissions { /** * <p>The principal who is granted permissions.</p> */ Principal?: DataLakePrincipal; /** * <p>The permissions that are granted to the principal.</p> */ Permissions?: (Permission | string)[]; } export namespace PrincipalPermissions { /** * @internal */ export const filterSensitiveLog = (obj: PrincipalPermissions): any => ({ ...obj, }); } /** * <p>A structure representing a list of AWS Lake Formation principals designated as data lake administrators and lists of principal permission entries for default create database and default create table permissions.</p> */ export interface DataLakeSettings { /** * <p>A list of AWS Lake Formation principals. Supported principals are IAM users or IAM roles.</p> */ DataLakeAdmins?: DataLakePrincipal[]; /** * <p>A structure representing a list of up to three principal permissions entries for default create database permissions.</p> */ CreateDatabaseDefaultPermissions?: PrincipalPermissions[]; /** * <p>A structure representing a list of up to three principal permissions entries for default create table permissions.</p> */ CreateTableDefaultPermissions?: PrincipalPermissions[]; /** * <p>A list of the resource-owning account IDs that the caller's account can use to share their user access details (user ARNs). The user ARNs can be logged in the resource owner's AWS CloudTrail log.</p> * * <p>You may want to specify this property when you are in a high-trust boundary, such as the same team or company. </p> */ TrustedResourceOwners?: string[]; } export namespace DataLakeSettings { /** * @internal */ export const filterSensitiveLog = (obj: DataLakeSettings): any => ({ ...obj, }); } export interface GetDataLakeSettingsResponse { /** * <p>A structure representing a list of AWS Lake Formation principals designated as data lake administrators.</p> */ DataLakeSettings?: DataLakeSettings; } export namespace GetDataLakeSettingsResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetDataLakeSettingsResponse): any => ({ ...obj, }); } export interface GetEffectivePermissionsForPathRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The Amazon Resource Name (ARN) of the resource for which you want to get permissions.</p> */ ResourceArn: string | undefined; /** * <p>A continuation token, if this is not the first call to retrieve this list.</p> */ NextToken?: string; /** * <p>The maximum number of results to return.</p> */ MaxResults?: number; } export namespace GetEffectivePermissionsForPathRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetEffectivePermissionsForPathRequest): any => ({ ...obj, }); } /** * <p>A structure containing the additional details to be returned in the <code>AdditionalDetails</code> attribute of <code>PrincipalResourcePermissions</code>.</p> * * <p>If a catalog resource is shared through AWS Resource Access Manager (AWS RAM), then there will exist a corresponding RAM resource share ARN.</p> */ export interface DetailsMap { /** * <p>A resource share ARN for a catalog resource shared through AWS Resource Access Manager (AWS RAM).</p> */ ResourceShare?: string[]; } export namespace DetailsMap { /** * @internal */ export const filterSensitiveLog = (obj: DetailsMap): any => ({ ...obj, }); } /** * <p>The permissions granted or revoked on a resource.</p> */ export interface PrincipalResourcePermissions { /** * <p>The Data Lake principal to be granted or revoked permissions.</p> */ Principal?: DataLakePrincipal; /** * <p>The resource where permissions are to be granted or revoked.</p> */ Resource?: Resource; /** * <p>The permissions to be granted or revoked on the resource.</p> */ Permissions?: (Permission | string)[]; /** * <p>Indicates whether to grant the ability to grant permissions (as a subset of permissions granted).</p> */ PermissionsWithGrantOption?: (Permission | string)[]; /** * <p>This attribute can be used to return any additional details of <code>PrincipalResourcePermissions</code>. Currently returns only as a RAM resource share ARN.</p> */ AdditionalDetails?: DetailsMap; } export namespace PrincipalResourcePermissions { /** * @internal */ export const filterSensitiveLog = (obj: PrincipalResourcePermissions): any => ({ ...obj, }); } export interface GetEffectivePermissionsForPathResponse { /** * <p>A list of the permissions for the specified table or database resource located at the path in Amazon S3.</p> */ Permissions?: PrincipalResourcePermissions[]; /** * <p>A continuation token, if this is not the first call to retrieve this list.</p> */ NextToken?: string; } export namespace GetEffectivePermissionsForPathResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetEffectivePermissionsForPathResponse): any => ({ ...obj, }); } export interface GetLFTagRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The key-name for the tag.</p> */ TagKey: string | undefined; } export namespace GetLFTagRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetLFTagRequest): any => ({ ...obj, }); } export interface GetLFTagResponse { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The key-name for the tag.</p> */ TagKey?: string; /** * <p>A list of possible values an attribute can take.</p> */ TagValues?: string[]; } export namespace GetLFTagResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetLFTagResponse): any => ({ ...obj, }); } export interface GetResourceLFTagsRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The resource for which you want to return tags.</p> */ Resource: Resource | undefined; /** * <p>Indicates whether to show the assigned tags.</p> */ ShowAssignedLFTags?: boolean; } export namespace GetResourceLFTagsRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetResourceLFTagsRequest): any => ({ ...obj, }); } /** * <p>A structure containing the name of a column resource and the tags attached to it.</p> */ export interface ColumnLFTag { /** * <p>The name of a column resource.</p> */ Name?: string; /** * <p>The tags attached to a column resource.</p> */ LFTags?: LFTagPair[]; } export namespace ColumnLFTag { /** * @internal */ export const filterSensitiveLog = (obj: ColumnLFTag): any => ({ ...obj, }); } export interface GetResourceLFTagsResponse { /** * <p>A list of tags applied to a database resource.</p> */ LFTagOnDatabase?: LFTagPair[]; /** * <p>A list of tags applied to a table resource.</p> */ LFTagsOnTable?: LFTagPair[]; /** * <p>A list of tags applied to a column resource.</p> */ LFTagsOnColumns?: ColumnLFTag[]; } export namespace GetResourceLFTagsResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetResourceLFTagsResponse): any => ({ ...obj, }); } /** * <p>An encryption operation failed.</p> */ export interface GlueEncryptionException extends __SmithyException, $MetadataBearer { name: "GlueEncryptionException"; $fault: "client"; /** * <p>A message describing the problem.</p> */ Message?: string; } export namespace GlueEncryptionException { /** * @internal */ export const filterSensitiveLog = (obj: GlueEncryptionException): any => ({ ...obj, }); } export interface GrantPermissionsRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The principal to be granted the permissions on the resource. Supported principals are IAM users or IAM roles, and they are defined by their principal type and their ARN.</p> * <p>Note that if you define a resource with a particular ARN, then later delete, and recreate a resource with that same ARN, the resource maintains the permissions already granted. </p> */ Principal: DataLakePrincipal | undefined; /** * <p>The resource to which permissions are to be granted. Resources in AWS Lake Formation are the Data Catalog, databases, and tables.</p> */ Resource: Resource | undefined; /** * <p>The permissions granted to the principal on the resource. AWS Lake Formation defines privileges to grant and revoke access to metadata in the Data Catalog and data organized in underlying data storage such as Amazon S3. AWS Lake Formation requires that each principal be authorized to perform a specific task on AWS Lake Formation resources. </p> */ Permissions: (Permission | string)[] | undefined; /** * <p>Indicates a list of the granted permissions that the principal may pass to other users. These permissions may only be a subset of the permissions granted in the <code>Privileges</code>.</p> */ PermissionsWithGrantOption?: (Permission | string)[]; } export namespace GrantPermissionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: GrantPermissionsRequest): any => ({ ...obj, }); } export interface GrantPermissionsResponse {} export namespace GrantPermissionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: GrantPermissionsResponse): any => ({ ...obj, }); } export enum ResourceShareType { ALL = "ALL", FOREIGN = "FOREIGN", } export interface ListLFTagsRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>If resource share type is <code>ALL</code>, returns both in-account tags and shared tags that the requester has permission to view. If resource share type is <code>FOREIGN</code>, returns all share tags that the requester can view. If no resource share type is passed, lists tags in the given catalog ID that the requester has permission to view.</p> */ ResourceShareType?: ResourceShareType | string; /** * <p>The maximum number of results to return.</p> */ MaxResults?: number; /** * <p>A continuation token, if this is not the first call to retrieve this list.</p> */ NextToken?: string; } export namespace ListLFTagsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListLFTagsRequest): any => ({ ...obj, }); } export interface ListLFTagsResponse { /** * <p>A list of tags that the requested has permission to view.</p> */ LFTags?: LFTagPair[]; /** * <p>A continuation token, present if the current list segment is not the last.</p> */ NextToken?: string; } export namespace ListLFTagsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListLFTagsResponse): any => ({ ...obj, }); } export enum DataLakeResourceType { CATALOG = "CATALOG", DATABASE = "DATABASE", DATA_LOCATION = "DATA_LOCATION", LF_TAG = "LF_TAG", LF_TAG_POLICY = "LF_TAG_POLICY", LF_TAG_POLICY_DATABASE = "LF_TAG_POLICY_DATABASE", LF_TAG_POLICY_TABLE = "LF_TAG_POLICY_TABLE", TABLE = "TABLE", } export interface ListPermissionsRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>Specifies a principal to filter the permissions returned.</p> */ Principal?: DataLakePrincipal; /** * <p>Specifies a resource type to filter the permissions returned.</p> */ ResourceType?: DataLakeResourceType | string; /** * <p>A resource where you will get a list of the principal permissions.</p> * <p>This operation does not support getting privileges on a table with columns. Instead, call this operation on the table, and the operation returns the table and the table w columns.</p> */ Resource?: Resource; /** * <p>A continuation token, if this is not the first call to retrieve this list.</p> */ NextToken?: string; /** * <p>The maximum number of results to return.</p> */ MaxResults?: number; } export namespace ListPermissionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPermissionsRequest): any => ({ ...obj, }); } export interface ListPermissionsResponse { /** * <p>A list of principals and their permissions on the resource for the specified principal and resource types.</p> */ PrincipalResourcePermissions?: PrincipalResourcePermissions[]; /** * <p>A continuation token, if this is not the first call to retrieve this list.</p> */ NextToken?: string; } export namespace ListPermissionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListPermissionsResponse): any => ({ ...obj, }); } export enum ComparisonOperator { BEGINS_WITH = "BEGINS_WITH", BETWEEN = "BETWEEN", CONTAINS = "CONTAINS", EQ = "EQ", GE = "GE", GT = "GT", IN = "IN", LE = "LE", LT = "LT", NE = "NE", NOT_CONTAINS = "NOT_CONTAINS", } export enum FieldNameString { LAST_MODIFIED = "LAST_MODIFIED", RESOURCE_ARN = "RESOURCE_ARN", ROLE_ARN = "ROLE_ARN", } /** * <p>This structure describes the filtering of columns in a table based on a filter condition.</p> */ export interface FilterCondition { /** * <p>The field to filter in the filter condition.</p> */ Field?: FieldNameString | string; /** * <p>The comparison operator used in the filter condition.</p> */ ComparisonOperator?: ComparisonOperator | string; /** * <p>A string with values used in evaluating the filter condition.</p> */ StringValueList?: string[]; } export namespace FilterCondition { /** * @internal */ export const filterSensitiveLog = (obj: FilterCondition): any => ({ ...obj, }); } export interface ListResourcesRequest { /** * <p>Any applicable row-level and/or column-level filtering conditions for the resources.</p> */ FilterConditionList?: FilterCondition[]; /** * <p>The maximum number of resource results.</p> */ MaxResults?: number; /** * <p>A continuation token, if this is not the first call to retrieve these resources.</p> */ NextToken?: string; } export namespace ListResourcesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListResourcesRequest): any => ({ ...obj, }); } export interface ListResourcesResponse { /** * <p>A summary of the data lake resources.</p> */ ResourceInfoList?: ResourceInfo[]; /** * <p>A continuation token, if this is not the first call to retrieve these resources.</p> */ NextToken?: string; } export namespace ListResourcesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListResourcesResponse): any => ({ ...obj, }); } export interface PutDataLakeSettingsRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>A structure representing a list of AWS Lake Formation principals designated as data lake administrators.</p> */ DataLakeSettings: DataLakeSettings | undefined; } export namespace PutDataLakeSettingsRequest { /** * @internal */ export const filterSensitiveLog = (obj: PutDataLakeSettingsRequest): any => ({ ...obj, }); } export interface PutDataLakeSettingsResponse {} export namespace PutDataLakeSettingsResponse { /** * @internal */ export const filterSensitiveLog = (obj: PutDataLakeSettingsResponse): any => ({ ...obj, }); } export interface RegisterResourceRequest { /** * <p>The Amazon Resource Name (ARN) of the resource that you want to register.</p> */ ResourceArn: string | undefined; /** * <p>Designates an AWS Identity and Access Management (IAM) service-linked role by registering this role with the Data Catalog. A service-linked role is a unique type of IAM role that is linked directly to Lake Formation.</p> * * <p>For more information, see <a href="https://docs-aws.amazon.com/lake-formation/latest/dg/service-linked-roles.html">Using Service-Linked Roles for Lake Formation</a>.</p> */ UseServiceLinkedRole?: boolean; /** * <p>The identifier for the role that registers the resource.</p> */ RoleArn?: string; } export namespace RegisterResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: RegisterResourceRequest): any => ({ ...obj, }); } export interface RegisterResourceResponse {} export namespace RegisterResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: RegisterResourceResponse): any => ({ ...obj, }); } export interface RemoveLFTagsFromResourceRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The resource where you want to remove a tag.</p> */ Resource: Resource | undefined; /** * <p>The tags to be removed from the resource.</p> */ LFTags: LFTagPair[] | undefined; } export namespace RemoveLFTagsFromResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: RemoveLFTagsFromResourceRequest): any => ({ ...obj, }); } export interface RemoveLFTagsFromResourceResponse { /** * <p>A list of failures to untag a resource.</p> */ Failures?: LFTagError[]; } export namespace RemoveLFTagsFromResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: RemoveLFTagsFromResourceResponse): any => ({ ...obj, }); } export interface RevokePermissionsRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The principal to be revoked permissions on the resource.</p> */ Principal: DataLakePrincipal | undefined; /** * <p>The resource to which permissions are to be revoked.</p> */ Resource: Resource | undefined; /** * <p>The permissions revoked to the principal on the resource. For information about permissions, see <a href="https://docs-aws.amazon.com/lake-formation/latest/dg/security-data-access.html">Security * and Access Control to Metadata and Data</a>.</p> */ Permissions: (Permission | string)[] | undefined; /** * <p>Indicates a list of permissions for which to revoke the grant option allowing the principal to pass permissions to other principals.</p> */ PermissionsWithGrantOption?: (Permission | string)[]; } export namespace RevokePermissionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: RevokePermissionsRequest): any => ({ ...obj, }); } export interface RevokePermissionsResponse {} export namespace RevokePermissionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: RevokePermissionsResponse): any => ({ ...obj, }); } export interface SearchDatabasesByLFTagsRequest { /** * <p>A continuation token, if this is not the first call to retrieve this list.</p> */ NextToken?: string; /** * <p>The maximum number of results to return.</p> */ MaxResults?: number; /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>A list of conditions (<code>LFTag</code> structures) to search for in database resources.</p> */ Expression: LFTag[] | undefined; } export namespace SearchDatabasesByLFTagsRequest { /** * @internal */ export const filterSensitiveLog = (obj: SearchDatabasesByLFTagsRequest): any => ({ ...obj, }); } /** * <p>A structure describing a database resource with tags.</p> */ export interface TaggedDatabase { /** * <p>A database that has tags attached to it.</p> */ Database?: DatabaseResource; /** * <p>A list of tags attached to the database.</p> */ LFTags?: LFTagPair[]; } export namespace TaggedDatabase { /** * @internal */ export const filterSensitiveLog = (obj: TaggedDatabase): any => ({ ...obj, }); } export interface SearchDatabasesByLFTagsResponse { /** * <p>A continuation token, present if the current list segment is not the last.</p> */ NextToken?: string; /** * <p>A list of databases that meet the tag conditions.</p> */ DatabaseList?: TaggedDatabase[]; } export namespace SearchDatabasesByLFTagsResponse { /** * @internal */ export const filterSensitiveLog = (obj: SearchDatabasesByLFTagsResponse): any => ({ ...obj, }); } export interface SearchTablesByLFTagsRequest { /** * <p>A continuation token, if this is not the first call to retrieve this list.</p> */ NextToken?: string; /** * <p>The maximum number of results to return.</p> */ MaxResults?: number; /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>A list of conditions (<code>LFTag</code> structures) to search for in table resources.</p> */ Expression: LFTag[] | undefined; } export namespace SearchTablesByLFTagsRequest { /** * @internal */ export const filterSensitiveLog = (obj: SearchTablesByLFTagsRequest): any => ({ ...obj, }); } /** * <p>A structure describing a table resource with tags.</p> */ export interface TaggedTable { /** * <p>A table that has tags attached to it.</p> */ Table?: TableResource; /** * <p>A list of tags attached to the database where the table resides.</p> */ LFTagOnDatabase?: LFTagPair[]; /** * <p>A list of tags attached to the table.</p> */ LFTagsOnTable?: LFTagPair[]; /** * <p>A list of tags attached to columns in the table.</p> */ LFTagsOnColumns?: ColumnLFTag[]; } export namespace TaggedTable { /** * @internal */ export const filterSensitiveLog = (obj: TaggedTable): any => ({ ...obj, }); } export interface SearchTablesByLFTagsResponse { /** * <p>A continuation token, present if the current list segment is not the last.</p> */ NextToken?: string; /** * <p>A list of tables that meet the tag conditions.</p> */ TableList?: TaggedTable[]; } export namespace SearchTablesByLFTagsResponse { /** * @internal */ export const filterSensitiveLog = (obj: SearchTablesByLFTagsResponse): any => ({ ...obj, }); } export interface UpdateLFTagRequest { /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata store. It contains database definitions, table definitions, and other control information to manage your AWS Lake Formation environment. </p> */ CatalogId?: string; /** * <p>The key-name for the tag for which to add or delete values.</p> */ TagKey: string | undefined; /** * <p>A list of tag values to delete from the tag.</p> */ TagValuesToDelete?: string[]; /** * <p>A list of tag values to add from the tag.</p> */ TagValuesToAdd?: string[]; } export namespace UpdateLFTagRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateLFTagRequest): any => ({ ...obj, }); } export interface UpdateLFTagResponse {} export namespace UpdateLFTagResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateLFTagResponse): any => ({ ...obj, }); } export interface UpdateResourceRequest { /** * <p>The new role to use for the given resource registered in AWS Lake Formation.</p> */ RoleArn: string | undefined; /** * <p>The resource ARN.</p> */ ResourceArn: string | undefined; } export namespace UpdateResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateResourceRequest): any => ({ ...obj, }); } export interface UpdateResourceResponse {} export namespace UpdateResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateResourceResponse): any => ({ ...obj, }); }
the_stack
import * as React from 'react'; import * as Adapter from 'enzyme-adapter-react-16'; import * as Enzyme from 'enzyme'; import * as sinon from 'sinon'; import {Controlled, UnControlled} from '../src'; Enzyme.configure({adapter: new Adapter()}); (global as any).console = { warn: jest.fn(), log: console.log, error: console.error }; (global as any).focus = jest.fn(); describe('[Controlled, UnControlled]: init', () => { it('should render | props: {}', () => { const options = {lineNumbers: true}; const uncontrolled = Enzyme.shallow( <UnControlled options={options} />); const controlled = Enzyme.shallow( <Controlled value="" options={options} onBeforeChange={sinon.spy} />); expect(controlled.html()).not.toBeUndefined(); expect(uncontrolled.html()).not.toBeUndefined(); }); it('should unmount', () => { let uUnmounted = false; let cUnmounted = false; const uWrapper = Enzyme.mount( <UnControlled editorWillUnmount={cm => { uUnmounted = true; }} />); const cWrapper = Enzyme.mount( <Controlled value="" onBeforeChange={sinon.spy} editorWillUnmount={cm => { cUnmounted = true; }} />); uWrapper.unmount(); cWrapper.unmount(); expect(uUnmounted).toBeTruthy(); expect(cUnmounted).toBeTruthy(); }); // refs https://github.com/scniro/react-codemirror2/issues/100 // prior to 7115754851dde1e1ae90be9f1c1a5e46faecc016 would throw it('should allow inputStyle to be set (uses the constructor)', () => { let inputStyle = 'contenteditable' as const; const options = {inputStyle}; Enzyme.shallow( <UnControlled options={options} editorDidMount={(editor, value, next) => { expect(editor.getInputField().tagName).toBe('DIV'); }} />); Enzyme.shallow( <Controlled value="" options={options} onBeforeChange={sinon.spy} editorDidMount={(editor, value, next) => { expect(editor.getInputField().tagName).toBe('DIV'); }} />); }); it('should append a class name', () => { const uWrapper = Enzyme.mount( <UnControlled className={'class-uncontrolled'} />); const cWrapper = Enzyme.mount( <Controlled className={'class-controlled'} value="" onBeforeChange={sinon.spy} />); expect(/react-codemirror2 class-uncontrolled/g.test(uWrapper.html())).toBeTruthy(); expect(/react-codemirror2 class-controlled/g.test(cWrapper.html())).toBeTruthy(); }); }); describe('[Controlled, UnControlled]: editorDidConfigure', () => { it('editorDidConfigure(editor)', () => { Enzyme.shallow( <UnControlled editorDidMount={(editor, value, next) => { this.uCallback = sinon.spy(next); this.uCallback(); }} editorDidConfigure={editor => { this.uConfigured = true; }} />); Enzyme.shallow( <Controlled value="" onBeforeChange={sinon.spy} editorDidMount={(editor, value, next) => { this.cCallback = sinon.spy(next); this.cCallback(); }} editorDidConfigure={editor => { this.cConfigured = true; }} />); expect(this.uConfigured).toBe(true); expect(this.uCallback.called).toBe(true); expect(this.cConfigured).toBe(true); expect(this.cCallback.called).toBe(true); }); }); describe('[Controlled, UnControlled]: defineMode', () => { it('defineMode', () => { let mode: any = { name: 'testMode', fn: () => { return { startState: () => { }, token: (stream, state) => { stream.next(); } } } }; let uWrapper = Enzyme.shallow( <UnControlled defineMode={mode} editorDidMount={(editor, value, next) => { expect(editor.getDoc().getMode().name).toBe('testMode'); }}/> ); let cWrapper = Enzyme.shallow( <Controlled value="" onBeforeChange={sinon.spy} defineMode={mode} editorDidMount={(editor, value, next) => { expect(editor.getDoc().getMode().name).toBe('testMode'); }}/> ); cWrapper.unmount(); uWrapper.unmount(); }); }); describe('DOM Events', () => { it('[Controlled] onFocus', done => { let onFocus = false; const wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={sinon.spy} onFocus={() => { onFocus = true; wrapper.unmount(); }} editorWillUnmount={cm => { expect(onFocus).toBeTruthy(); done(); }} />); wrapper.instance().editor.focus(); }); it('[UnControlled] onFocus', done => { let onFocus = false; const wrapper = Enzyme.mount( <UnControlled value='foo' onFocus={() => { onFocus = true; wrapper.unmount(); }} editorWillUnmount={cm => { expect(onFocus).toBeTruthy(); done(); }} />); wrapper.instance().editor.focus(); }); it('[Controlled] onBlur', done => { let onBlur = false; const wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={sinon.spy} onBlur={() => { onBlur = true; wrapper.unmount(); }} editorWillUnmount={cm => { expect(onBlur).toBeTruthy(); done(); }} />); wrapper.instance().editor.focus(); wrapper.instance().editor.getInputField().blur(); }); it('[UnControlled] onBlur', done => { let onBlur = false; const wrapper = Enzyme.mount( <UnControlled value='foo' onBlur={() => { onBlur = true; wrapper.unmount(); }} editorWillUnmount={cm => { expect(onBlur).toBeTruthy(); done(); }} />); wrapper.instance().editor.focus(); wrapper.instance().editor.getInputField().blur(); }); }); describe('Change', () => { it('[Controlled] change:onChange', done => { const wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={(editor, data, value) => { wrapper.setProps({value}); }} onChange={(editor, data, value) => { expect(value).toEqual('foobar'); expect(editor.getValue()).toEqual('foobar'); done(); }} />); const doc = wrapper.instance().editor.getDoc(); doc.replaceRange('bar', {line: 1, ch: 1}); }); it('[Controlled] change:onRenderLine', done => { const wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={(editor, data, value) => { wrapper.setProps({value}); }} onRenderLine={(editor, line, element) => { expect(line.text).toEqual('foobar'); expect(element).toBeDefined(); expect(editor.getValue()).toEqual('foobar'); done(); }} />); const doc = wrapper.instance().editor.getDoc(); doc.replaceRange('bar', {line: 1, ch: 1}); }); it('[Controlled] change:undo|redo', done => { let n = 0; const wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={(editor, data, value) => { wrapper.setProps({value}); }} onChange={(editor, data, value) => { const doc = editor.getDoc(); n += 1; switch (n) { case 1: expect(editor.getValue()).toEqual('foobar'); doc.undo(); break; case 2: expect(editor.getValue()).toEqual('foo'); doc.redo(); break; case 3: expect(value).toEqual('foobar'); done(); break; } }} />); const doc = wrapper.instance().editor.getDoc(); doc.replaceRange('bar', {line: 1, ch: 1}); }); it('[UnControlled] change:onChange', done => { const wrapper = Enzyme.mount( <UnControlled value='foo' onChange={(editor, data, value) => { expect(value).toEqual('foobar'); expect(editor.getValue()).toEqual('foobar'); done(); }} />); const doc = wrapper.instance().editor.getDoc(); doc.replaceRange('bar', {line: 1, ch: 1}); }); it('[UnControlled] change:onRenderLine', done => { const wrapper = Enzyme.mount( <UnControlled value='foo' onRenderLine={(editor, line, element) => { expect(line.text).toEqual('foobar'); expect(element).toBeDefined(); expect(editor.getValue()).toEqual('foobar'); done(); }} />); const doc = wrapper.instance().editor.getDoc(); doc.replaceRange('bar', {line: 1, ch: 1}); }); it('[Controlled] change:undo|redo', done => { let n = 0; const wrapper = Enzyme.mount( <UnControlled value='foo' onChange={(editor, data, value) => { const doc = editor.getDoc(); n += 1; switch (n) { case 1: expect(editor.getValue()).toEqual('foobar'); doc.undo(); break; case 2: expect(editor.getValue()).toEqual('foo'); doc.redo(); break; case 3: expect(value).toEqual('foobar'); done(); break; } }} />); const doc = wrapper.instance().editor.getDoc(); doc.replaceRange('bar', {line: 1, ch: 1}); }); it('[Controlled] transform value', done => { const wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={(editor, data, value) => { wrapper.setProps({value: value.replace(/o/g, 'p')}); }} onChange={(editor, data, value) => { expect(value).toEqual('fppfpp'); expect(editor.getValue()).toEqual('fppfpp'); done(); }} />); const doc = wrapper.instance().editor.getDoc(); doc.replaceRange('foo', {line: 1, ch: 1}); }); }); describe('Props', () => { it('[Controlled]: scroll | newProps', () => { // todo can't find way to actually invoke a DOM scroll => `onScroll` let wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={sinon.spy} scroll={{ x: 50, y: 50 }} onScroll={(editor, data) => { // }} />); wrapper.setProps({ scroll: { x: 100, y: 100 } }); wrapper.unmount(); }); it('[UnControlled]: scroll | newProps', () => { // todo can't find way to actually invoke a DOM scroll => `onScroll` let wrapper = Enzyme.mount( <UnControlled value='foo' scroll={{ x: 50, y: 50 }} onScroll={(editor, data) => { //console.log(data) }} />); wrapper.setProps({ scroll: { x: 100, y: 100 } }); wrapper.unmount(); }); it('[Controlled, UnControlled]: selection', () => { let expected = ['oo']; Enzyme.mount( <Controlled value="foo" onBeforeChange={sinon.spy} selection={{ ranges: [{ anchor: {ch: 1, line: 0}, head: {ch: 3, line: 0} }] }} editorDidMount={(editor) => { expect(editor.getDoc().getSelections()).toEqual(expected) }} />); Enzyme.mount( <UnControlled value='foo' selection={{ ranges: [{ anchor: {ch: 1, line: 0}, head: {ch: 3, line: 0} }] }} editorDidMount={(editor) => { expect(editor.getDoc().getSelections()).toEqual(expected) }} />); }); it('[Controlled, UnControlled]: selection: focus', () => { let expected = ['oo']; Enzyme.mount( <Controlled value="foo" onBeforeChange={sinon.spy} selection={{ focus: true, ranges: [{ anchor: {ch: 1, line: 0}, head: {ch: 3, line: 0} }] }} editorDidMount={(editor) => { expect(editor.state.focused).toBeTruthy(); expect(editor.getDoc().getSelections()).toEqual(expected); }} />); Enzyme.mount( <UnControlled value='foo' selection={{ focus: true, ranges: [{ anchor: {ch: 1, line: 0}, head: {ch: 3, line: 0} }] }} editorDidMount={(editor) => { expect(editor.state.focused).toBeTruthy(); expect(editor.getDoc().getSelections()).toEqual(expected); }} />); }); it('[Controlled: selection | newProps', () => { let expectedRanges = [{ anchor: {ch: 1, line: 1}, head: {ch: 3, line: 1} }]; let wrapper = Enzyme.mount( <Controlled value='foo\nbar\nbaz' onBeforeChange={sinon.spy} onSelection={(editor) => { expect(editor.getDoc().getSelection()).toEqual(expectedRanges); }} />); wrapper.setProps({ selection: { ranges: [{ anchor: {ch: 1, line: 1}, head: {ch: 3, line: 1} }] } }); wrapper.unmount(); }); it('[UnControlled: selection | newProps', () => { let expectedRanges = [{ anchor: {ch: 1, line: 1}, head: {ch: 3, line: 1} }]; let wrapper = Enzyme.mount( <UnControlled value='foo\nbar\nbaz' onSelection={(editor) => { expect(editor.getDoc().getSelection()).toEqual(expectedRanges); }} />); wrapper.setProps({ selection: { ranges: [{ anchor: {ch: 1, line: 1}, head: {ch: 3, line: 1} }] } }); wrapper.unmount(); }); it('[Controlled, UnControlled]: cursor', () => { Enzyme.mount( <Controlled value='foo' onBeforeChange={sinon.spy} cursor={{ line: 0, ch: 3 }} onSelection={(editor) => { expect(editor.getDoc().getCursor()).not.toBeNull() }}/> ); Enzyme.mount( <UnControlled value='foo' cursor={{ line: 0, ch: 3 }} onSelection={(editor) => { expect(editor.getDoc().getCursor()).not.toBeNull() }}/> ); }); it('[Controlled]: cursor | newProps', () => { // todo can't find way to actually invoke a DOM cursor => `onCursor` let wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={sinon.spy} onCursor={(editor, data) => { console.log('oncursor') }}/> ); wrapper.setProps({ cursor: { line: 1, ch: 2 } }); wrapper.unmount(); }); it('[UnControlled]: cursor | newProps', () => { // todo can't find way to actually invoke a DOM cursor => `onCursor` let wrapper = Enzyme.mount( <UnControlled value='foo' onCursor={(editor, data) => { console.log('oncursor') }}/> ); wrapper.setProps({ cursor: { line: 1, ch: 2 } }); wrapper.unmount(); }); it('[Controlled]: cursor | newProps & props', () => { // todo can't find way to actually invoke a DOM cursor => `onCursor` let wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={sinon.spy} cursor={{ line: 1, ch: 1 }} onCursor={(editor, data) => { console.log('oncursor') }}/> ); wrapper.setProps({ cursor: { line: 1, ch: 2 } }); wrapper.unmount(); }); it('[UnControlled]: cursor | newProps & props', () => { // todo can't find way to actually invoke a DOM cursor => `onCursor` let wrapper = Enzyme.mount( <UnControlled value='foo' cursor={{ line: 1, ch: 1 }} onCursor={(editor, data) => { console.log('oncursor') }}/> ); wrapper.setProps({ cursor: { line: 1, ch: 2 } }); wrapper.unmount(); }); it('[Controlled]: cursor | newProps | autoCursor: false', () => { // todo can't find way to actually invoke a DOM cursor => `onCursor` let wrapper = Enzyme.mount( <Controlled autoCursor={false} value='foo' onBeforeChange={sinon.spy} cursor={{ line: 1, ch: 1 }} onCursor={(editor, data) => { // todo }}/> ); wrapper.setProps({ cursor: { line: 1, ch: 2 } }); wrapper.unmount(); }); it('[UnControlled]: cursor | newProps | autoCursor: false', () => { // todo can't find way to actually invoke a DOM cursor => `onCursor` let wrapper = Enzyme.mount( <UnControlled autoCursor={false} value='foo' cursor={{ line: 1, ch: 1 }} onCursor={(editor, data) => { // todo }}/> ); wrapper.setProps({ cursor: { line: 1, ch: 2 } }); wrapper.unmount(); }); it('[Controlled]: cursor | newProps | autoCursor: true', () => { // todo can't find way to actually invoke a DOM cursor => `onCursor` let wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={sinon.spy} cursor={{ line: 1, ch: 1 }} onCursor={(editor, data) => { // todo }}/> ); wrapper.setProps({ cursor: { line: 1, ch: 2 } }); wrapper.unmount(); }); it('[UnControlled]: cursor | newProps | autoCursor: true', () => { // todo can't find way to actually invoke a DOM cursor => `onCursor` let wrapper = Enzyme.mount( <UnControlled value='foo' cursor={{ line: 1, ch: 1 }} onCursor={(editor, data) => { // todo }}/> ); wrapper.setProps({ cursor: { line: 1, ch: 2 } }); wrapper.unmount(); }); it('[Controlled]: cursor | newProps | autoCursor: true, autoScroll: true', () => { // todo can't find way to actually invoke a DOM cursor => `onCursor` let wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={sinon.spy} autoScroll={true} cursor={{ line: 1, ch: 1 }} onCursor={(editor, data) => { // todo }}/> ); wrapper.setProps({ cursor: { line: 1, ch: 2 } }); wrapper.unmount(); }); it('[UnControlled]: cursor | newProps | autoCursor: true, autoScroll: true', () => { // todo can't find way to actually invoke a DOM cursor => `onCursor` let wrapper = Enzyme.mount( <UnControlled value='foo' autoScroll={true} cursor={{ line: 1, ch: 1 }} onCursor={(editor, data) => { // todo }}/> ); wrapper.setProps({ cursor: { line: 1, ch: 2 } }); wrapper.unmount(); }); it('[UnControlled]: new value | invoke apply pipeline accordingly`', () => { let wrapper = Enzyme.mount( <UnControlled value='foo' onChange={(editor, data) => { }}/> ); expect(wrapper.instance().appliedUserDefined).toBeFalsy(); wrapper.setProps({ value: 'bar' }); expect(wrapper.instance().appliedUserDefined).toBeTruthy(); wrapper.unmount(); }); it('[Controlled]: new value | invoke apply pipeline accordingly`', () => { let wrapper = Enzyme.mount( <Controlled value='foo' onBeforeChange={sinon.spy} onChange={(editor, data) => { }}/> ); expect(wrapper.instance().applied).toBeTruthy(); expect(wrapper.instance().appliedUserDefined).toBeFalsy(); expect(wrapper.instance().appliedNext).toBeFalsy(); wrapper.setProps({ value: 'bar' }); expect(wrapper.instance().appliedUserDefined).toBeTruthy(); expect(wrapper.instance().appliedNext).toBeTruthy(); wrapper.unmount(); }); it('[UnControlled]: detached | should detach', () => { const spy = sinon.spy(); const wrapper = Enzyme.mount( <UnControlled detach={false} editorDidDetach={() => spy()}/> ); expect(spy.called).toBeFalsy(); wrapper.setProps({detach: true}); expect(spy.called).toBeTruthy(); wrapper.unmount(); }); it('[UnControlled]: detached | should attach', () => { const spy = sinon.spy(); const wrapper = Enzyme.mount( <UnControlled detach={true} editorDidAttach={() => spy()}/> ); expect(spy.called).toBeFalsy(); wrapper.setProps({detach: false}); expect(spy.called).toBeTruthy(); wrapper.unmount(); }); it('[UnControlled]: detached:false | should update', done => { let instance; const spy = sinon.spy(); const wrapper = Enzyme.mount( <UnControlled editorDidMount={editor => instance = editor}/> ); instance.on('optionChange', () => spy()); wrapper.setProps({options: {lineNumbers: true}}); // force lose `.on` race setTimeout(() => { expect(spy.called).toBeTruthy(); wrapper.unmount(); done(); }, 200); }); it('[UnControlled]: detached:false | should *not* update | on mount', done => { let instance; const spy = sinon.spy(); const wrapper = Enzyme.mount( <UnControlled detach={true} editorDidMount={editor => instance = editor}/> ); instance.on('optionChange', () => spy()); wrapper.setProps({options: {lineNumbers: true}}); // force lose `.on` race setTimeout(() => { expect(spy.called).toBeFalsy(); wrapper.unmount(); done(); }, 200); }); it('[UnControlled]: detached:false | should *not* update | on props', done => { let instance; const spy = sinon.spy(); const wrapper = Enzyme.mount( <UnControlled editorDidMount={editor => instance = editor}/> ); instance.on('optionChange', () => spy()); wrapper.setProps({detach: true, options: {lineNumbers: true}}); // force lose `.on` race setTimeout(() => { expect(instance.getOption('lineNumbers')).toBeFalsy(); wrapper.unmount(); done(); }, 200); }); it('[Controlled: selection | newProps & props', done => { const currentRanges = [{ anchor: {ch: 1, line: 0}, head: {ch: 2, line: 0} }]; const expectedRanges = [{ anchor: {ch: 1, line: 0}, head: {ch: 3, line: 0} }]; const wrapper = Enzyme.mount( <Controlled value='foobar' onBeforeChange={sinon.spy} selection={{ranges: currentRanges}} onSelection={(editor, data) => { expect(data.ranges).toEqual(expectedRanges); done(); }}/> ); wrapper.setProps({ selection: { ranges: [{ anchor: {ch: 1, line: 0}, head: {ch: 3, line: 0} }] } }); wrapper.unmount(); }); });
the_stack
import { AnimationBuilder } from '@angular/animations'; import { AfterViewInit, Component, ElementRef, HostBinding, Input, NgZone, OnDestroy, ViewChild } from '@angular/core'; import { getResizeObserver, mkenum } from '../../core/utils'; import { IgxTabsBase } from '../tabs.base'; import { IgxTabsDirective } from '../tabs.directive'; export const IgxTabsAlignment = mkenum({ start: 'start', end: 'end', center: 'center', justify: 'justify' }); /** @hidden */ enum TabScrollButtonStyle { Visible = 'visible', Hidden = 'hidden', NotDisplayed = 'not_displayed' } export type IgxTabsAlignment = (typeof IgxTabsAlignment)[keyof typeof IgxTabsAlignment]; /** @hidden */ let NEXT_TAB_ID = 0; /** * Tabs component is used to organize or switch between similar data sets. * * @igxModule IgxTabsModule * * @igxTheme igx-tabs-theme * * @igxKeywords tabs * * @igxGroup Layouts * * @remarks * The Ignite UI for Angular Tabs component places tabs at the top and allows for scrolling when there are multiple tab items on the screen. * * @example * ```html * <igx-tabs> * <igx-tab-item> * <igx-tab-header> * <igx-icon igxTabHeaderIcon>folder</igx-icon> * <span igxTabHeaderLabel>Tab 1</span> * </igx-tab-header> * <igx-tab-content> * Content 1 * </igx-tab-content> * </igx-tab-item> * ... * </igx-tabs> * ``` */ @Component({ selector: 'igx-tabs', templateUrl: 'tabs.component.html', providers: [{ provide: IgxTabsBase, useExisting: IgxTabsComponent }] }) export class IgxTabsComponent extends IgxTabsDirective implements AfterViewInit, OnDestroy { /** * An @Input property which determines the tab alignment. Defaults to `start`. */ @Input() public get tabAlignment(): string | IgxTabsAlignment { return this._tabAlignment; }; public set tabAlignment(value: string | IgxTabsAlignment) { this._tabAlignment = value; requestAnimationFrame(() => { this.updateScrollButtons(); this.realignSelectedIndicator(); }); } /** @hidden */ @ViewChild('headerContainer', { static: true }) public headerContainer: ElementRef<HTMLElement>; /** @hidden */ @ViewChild('viewPort', { static: true }) public viewPort: ElementRef<HTMLElement>; /** @hidden */ @ViewChild('itemsWrapper', { static: true }) public itemsWrapper: ElementRef<HTMLElement>; /** @hidden */ @ViewChild('itemsContainer', { static: true }) public itemsContainer: ElementRef<HTMLElement>; /** @hidden */ @ViewChild('selectedIndicator') public selectedIndicator: ElementRef<HTMLElement>; /** @hidden */ @ViewChild('leftButton') public leftButton: ElementRef<HTMLElement>; /** @hidden */ @ViewChild('rightButton') public rightButton: ElementRef<HTMLElement>; /** @hidden */ @HostBinding('class.igx-tabs') public defaultClass = true; /** @hidden */ public offset = 0; /** @hidden */ protected componentName = 'igx-tabs'; private _tabAlignment: string | IgxTabsAlignment = 'start'; private _resizeObserver: ResizeObserver; constructor(builder: AnimationBuilder, private ngZone: NgZone) { super(builder); } /** @hidden @internal */ public ngAfterViewInit(): void { super.ngAfterViewInit(); this.ngZone.runOutsideAngular(() => { this._resizeObserver = new (getResizeObserver())(() => { this.updateScrollButtons(); this.realignSelectedIndicator(); }); this._resizeObserver.observe(this.headerContainer.nativeElement); this._resizeObserver.observe(this.viewPort.nativeElement); }); } /** @hidden @internal */ public ngOnDestroy(): void { super.ngOnDestroy(); this.ngZone.runOutsideAngular(() => { this._resizeObserver?.disconnect(); }); } /** @hidden */ public scrollLeft() { this.scroll(false); } /** @hidden */ public scrollRight() { this.scroll(true); } /** @hidden */ public realignSelectedIndicator() { if (this.selectedIndex >=0 && this.selectedIndex < this.items.length) { const header = this.items.get(this.selectedIndex).headerComponent.nativeElement; this.alignSelectedIndicator(header, 0); } } /** @hidden */ public resolveHeaderScrollClasses() { return { 'igx-tabs__header-scroll--start': this.tabAlignment === 'start', 'igx-tabs__header-scroll--end': this.tabAlignment === 'end', 'igx-tabs__header-scroll--center': this.tabAlignment === 'center', 'igx-tabs__header-scroll--justify': this.tabAlignment === 'justify', }; } /** @hidden */ protected scrollTabHeaderIntoView() { if (this.selectedIndex >= 0) { const tabItems = this.items.toArray(); const tabHeaderNativeElement = tabItems[this.selectedIndex].headerComponent.nativeElement; // Scroll left if there is need if (tabHeaderNativeElement.offsetLeft < this.offset) { this.scrollElement(tabHeaderNativeElement, false); } // Scroll right if there is need const viewPortOffsetWidth = this.viewPort.nativeElement.offsetWidth; const delta = (tabHeaderNativeElement.offsetLeft + tabHeaderNativeElement.offsetWidth) - (viewPortOffsetWidth + this.offset); // Fix for IE 11, a difference is accumulated from the widths calculations if (delta > 1) { this.scrollElement(tabHeaderNativeElement, true); } this.alignSelectedIndicator(tabHeaderNativeElement); } else { this.hideSelectedIndicator(); } } /** @hidden */ protected getNextTabId() { return NEXT_TAB_ID++; } /** @hidden */ protected onItemChanges() { super.onItemChanges(); Promise.resolve().then(() => { this.updateScrollButtons(); }); } private alignSelectedIndicator(element: HTMLElement, duration = 0.3): void { if (this.selectedIndicator) { this.selectedIndicator.nativeElement.style.visibility = 'visible'; this.selectedIndicator.nativeElement.style.transitionDuration = duration > 0 ? `${duration}s` : 'initial'; this.selectedIndicator.nativeElement.style.width = `${element.offsetWidth}px`; this.selectedIndicator.nativeElement.style.transform = `translate(${element.offsetLeft}px)`; } } private hideSelectedIndicator(): void { if (this.selectedIndicator) { this.selectedIndicator.nativeElement.style.visibility = 'hidden'; } } private scroll(scrollRight: boolean): void { const tabsArray = this.items.toArray(); for (const tab of tabsArray) { const element = tab.headerComponent.nativeElement; if (scrollRight) { if (element.offsetWidth + element.offsetLeft > this.viewPort.nativeElement.offsetWidth + this.offset) { this.scrollElement(element, scrollRight); break; } } else { if (element.offsetWidth + element.offsetLeft >= this.offset) { this.scrollElement(element, scrollRight); break; } } } } private scrollElement(element: any, scrollRight: boolean): void { const viewPortWidth = this.viewPort.nativeElement.offsetWidth; this.offset = (scrollRight) ? element.offsetWidth + element.offsetLeft - viewPortWidth : element.offsetLeft; this.itemsWrapper.nativeElement.style.transform = `translate(${-this.offset}px)`; this.updateScrollButtons(); } private updateScrollButtons() { const itemsContainerWidth = this.getTabItemsContainerWidth(); const leftButtonStyle = this.resolveLeftScrollButtonStyle(itemsContainerWidth); this.setScrollButtonStyle(this.leftButton.nativeElement, leftButtonStyle); const rightButtonStyle = this.resolveRightScrollButtonStyle(itemsContainerWidth); this.setScrollButtonStyle(this.rightButton.nativeElement, rightButtonStyle); } private setScrollButtonStyle(button: HTMLElement, buttonStyle: TabScrollButtonStyle) { if (buttonStyle === TabScrollButtonStyle.Visible) { button.style.visibility = 'visible'; button.style.display = ''; } else if (buttonStyle === TabScrollButtonStyle.Hidden) { button.style.visibility = 'hidden'; button.style.display = ''; } else if (buttonStyle === TabScrollButtonStyle.NotDisplayed) { button.style.display = 'none'; } } private resolveLeftScrollButtonStyle(itemsContainerWidth: number): TabScrollButtonStyle { const headerContainerWidth = this.headerContainer.nativeElement.offsetWidth; const offset = this.offset; if (offset === 0) { // Fix for IE 11, a difference is accumulated from the widths calculations. if (itemsContainerWidth - headerContainerWidth <= 1) { return TabScrollButtonStyle.NotDisplayed; } return TabScrollButtonStyle.Hidden; } else { return TabScrollButtonStyle.Visible; } } private resolveRightScrollButtonStyle(itemsContainerWidth: number): TabScrollButtonStyle { const viewPortWidth = this.viewPort.nativeElement.offsetWidth; const headerContainerWidth = this.headerContainer.nativeElement.offsetWidth; const offset = this.offset; const total = offset + viewPortWidth; // Fix for IE 11, a difference is accumulated from the widths calculations. if (itemsContainerWidth - headerContainerWidth <= 1 && offset === 0) { return TabScrollButtonStyle.NotDisplayed; } if (itemsContainerWidth > total) { return TabScrollButtonStyle.Visible; } else { return TabScrollButtonStyle.Hidden; } } private getTabItemsContainerWidth() { // We use this hacky way to get the width of the itemsContainer, // because there is inconsistency in IE we cannot use offsetWidth or scrollOffset. const itemsContainerChildrenCount = this.itemsContainer.nativeElement.children.length; let itemsContainerWidth = 0; if (itemsContainerChildrenCount > 1) { const lastTab = this.itemsContainer.nativeElement.children[itemsContainerChildrenCount - 1] as HTMLElement; itemsContainerWidth = lastTab.offsetLeft + lastTab.offsetWidth; } return itemsContainerWidth; } }
the_stack
import {TensorDebugMode} from './debugger_types'; import {parseDebugTensorValue} from './debug_tensor_value'; describe('parseDebugTensorValue', () => { describe('CURT_HEALTH', () => { it('returns correct value if tensor has no inf or nan', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.CURT_HEALTH, array: [ 123, // tensor ID 0, // has inf or nan? ], }); expect(debugValue).toEqual({ hasInfOrNaN: false, }); }); it('returns correct value if tensor has inf or nan', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.CURT_HEALTH, array: [ 123, // tensor ID 1, // has inf or nan? ], }); expect(debugValue).toEqual({ hasInfOrNaN: true, }); }); for (const array of [null, [0], [0, 1, 1]]) { it(`throws error for null or wrong array arg: ${JSON.stringify( array )}`, () => { expect(() => parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.CURT_HEALTH, array, }) ).toThrowError(/CURT_HEALTH.*expect.*length 2/); }); } }); describe('CONCISE_HEALTH', () => { it('returns correct value if tensor is all healthy', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.CONCISE_HEALTH, array: [ 123, 1000, // size 0, 0, 0, ], }); expect(debugValue).toEqual({ size: 1000, }); }); it('returns correct value if tensor has nan', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.CONCISE_HEALTH, array: [ 123, 1000, // size 0, 0, 1, ], }); expect(debugValue).toEqual({ size: 1000, numNaNs: 1, }); }); it('returns correct value if tensor has neg inf', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.CONCISE_HEALTH, array: [123, 1000, 2, 0, 0], }); expect(debugValue).toEqual({ size: 1000, numNegativeInfs: 2, }); }); it('returns correct value if tensor has pos inf', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.CONCISE_HEALTH, array: [ 123, 1000, // size 0, 22, 0, ], }); expect(debugValue).toEqual({ size: 1000, numPositiveInfs: 22, }); }); it('returns correct value if tensor has nan, -inf and inf', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.CONCISE_HEALTH, array: [ 123, 1000, // size 10, 20, 30, ], }); expect(debugValue).toEqual({ size: 1000, numNegativeInfs: 10, numPositiveInfs: 20, numNaNs: 30, }); }); for (const array of [null, [0, 10, 0, 0], [0, 10, 0, 0, 0, 0]]) { it(`throws error for null or wrong array arg: ${JSON.stringify( array )}`, () => { expect(() => parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.CONCISE_HEALTH, array, }) ).toThrowError(/CONCISE_HEALTH.*expect.*length 5/); }); } }); describe('SHAPE', () => { it('returns correct value for 0D bool', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.SHAPE, array: [ 123, 10, // bool 0, // rank 1, // size 0, 0, 0, 0, 0, 0, ], }); expect(debugValue).toEqual({ dtype: 'bool', rank: 0, size: 1, shape: [], }); }); it('returns correct value for 1D int32', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.SHAPE, array: [ 123, 3, // int32 1, // rank 46, // size 46, 0, 0, 0, 0, 0, ], }); expect(debugValue).toEqual({ dtype: 'int32', rank: 1, size: 46, shape: [46], }); }); it('returns correct value for 2D float32', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.SHAPE, array: [ 123, 1, // float32 2, // rank 1200, 30, 40, 0, 0, 0, 0, ], }); expect(debugValue).toEqual({ dtype: 'float32', rank: 2, size: 1200, shape: [30, 40], }); }); it('returns correct value for 6D float64', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.SHAPE, array: [ 123, 2, // float64 6, // rank 1200, 1, 2, 3, 4, 5, 10, ], }); expect(debugValue).toEqual({ dtype: 'float64', rank: 6, size: 1200, shape: [1, 2, 3, 4, 5, 10], }); }); it('returns correct value for truncated shape: 7D', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.SHAPE, array: [ 123, 5, // int16 7, // rank 7 1200, 3, 4, 1, 2, 1, 5, ], }); expect(debugValue).toEqual({ dtype: 'int16', rank: 7, size: 1200, // Truncated dimensions are filled with `undefined`s. shape: [undefined, 3, 4, 1, 2, 1, 5], }); }); it('returns correct value for truncated shape: 8D', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.SHAPE, array: [ 123, 1, // float32 8, // rank 8 1200, 3, 4, 1, 2, 1, 5, ], }); expect(debugValue).toEqual({ dtype: 'float32', rank: 8, size: 1200, // Truncated dimensions are filled with `undefined`s. shape: [undefined, undefined, 3, 4, 1, 2, 1, 5], }); }); for (const array of [ null, [123, 1, 8, 1200, 3, 4, 1, 2, 1], [123, 1, 8, 1200, 3, 4, 1, 2, 1, 5, 6], ]) { it(`throws error for null or wrong array arg: ${JSON.stringify( array )}`, () => { expect(() => parseDebugTensorValue({tensorDebugMode: TensorDebugMode.SHAPE, array}) ).toThrowError(/SHAPE.*expect.*length 10/); }); } }); describe('FULL_HEALTH', () => { it('returns correct value for float32 2D with no inf or nan', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.FULL_HEALTH, array: [ 123, 0, 1, // float32 2, // rank 600, // size 0, 0, 0, 100, 200, 300, ], }); expect(debugValue).toEqual({ dtype: 'float32', rank: 2, size: 600, numNegativeFinites: 100, numZeros: 200, numPositiveFinites: 300, }); }); it('returns correct value for float64 scalar nan', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.FULL_HEALTH, array: [ 123, 0, 2, // float64 0, // rank 1, // size 0, 0, 1, 0, 0, 0, ], }); expect(debugValue).toEqual({ dtype: 'float64', rank: 0, size: 1, numNaNs: 1, }); }); it('returns correct value for bfloat16 1D with -inf and +inf', () => { const debugValue = parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.FULL_HEALTH, array: [ 123, 0, 14, // bfloat16 1, // rank 10, // size 3, 7, 0, 0, 0, 0, ], }); expect(debugValue).toEqual({ dtype: 'bfloat16', rank: 1, size: 10, numNegativeInfs: 3, numPositiveInfs: 7, }); }); for (const array of [ null, [123, 0, 14, 1, 10, 3, 7, 0, 0, 0], [123, 0, 14, 1, 10, 3, 7, 0, 0, 0, 0, 0], ]) { it(`throws error for null or wrong array arg: ${JSON.stringify( array )}`, () => { expect(() => parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.FULL_HEALTH, array, }) ).toThrowError(/FULL_HEALTH.*expect.*length 11/); }); } }); describe('NO_TENSOR', () => { it('returns empty object', () => { expect( parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.NO_TENSOR, array: null, }) ).toEqual({}); }); for (const array of [[], [0]]) { it(`throws error for non-null array arg: ${JSON.stringify( array )}`, () => { expect(() => parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.NO_TENSOR, array, }) ).toThrowError(/non-null.*NO_TENSOR/); }); } }); describe('FULL_TENSOR', () => { it('returns empty object', () => { expect( parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.FULL_TENSOR, array: null, }) ).toEqual({}); }); for (const array of [[], [0]]) { it(`throws error for non-null array arg: ${JSON.stringify( array )}`, () => { expect(() => parseDebugTensorValue({ tensorDebugMode: TensorDebugMode.FULL_TENSOR, array, }) ).toThrowError(/non-null.*FULL_TENSOR/); }); } }); describe('Invalid TensorDebugMode', () => { for (const debugMode of [ null, undefined, NaN, TensorDebugMode.UNSPECIFIED, ]) { it('throws error', () => { expect(() => parseDebugTensorValue({ tensorDebugMode: debugMode as TensorDebugMode, array: null, }) ).toThrowError(); }); } }); });
the_stack
import chai = require('chai') const expect = chai.expect describe('insecurity', () => { const security = require('../../lib/insecurity') describe('cutOffPoisonNullByte', () => { it('returns string unchanged if it contains no null byte', () => { expect(security.cutOffPoisonNullByte('file.exe.pdf')).to.equal('file.exe.pdf') }) it('returns string up to null byte', () => { expect(security.cutOffPoisonNullByte('file.exe%00.pdf')).to.equal('file.exe') }) }) describe('userEmailFrom', () => { it('returns content of "x-user-email" header if present', () => { expect(security.userEmailFrom({ headers: { 'x-user-email': 'test@bla.blubb' } })).to.equal('test@bla.blubb') }) it('returns undefined if header "x-user-email" is not present', () => { expect(security.userEmailFrom({ headers: {} })).to.equal(undefined) expect(security.userEmailFrom({})).to.equal(undefined) }) }) describe('generateCoupon', () => { const z85 = require('z85') it('returns base85-encoded month, year and discount as coupon code', () => { const coupon = security.generateCoupon(20, new Date('1980-01-02')) expect(coupon).to.equal('n<MiifFb4l') expect(z85.decode(coupon).toString()).to.equal('JAN80-20') }) it('uses current month and year if not specified', () => { const coupon = security.generateCoupon(20) expect(coupon).to.equal(security.generateCoupon(20, new Date())) }) it('does not encode day of month or time into coupon code', () => { const coupon = security.generateCoupon(10, new Date('December 01, 1999')) expect(coupon).to.equal(security.generateCoupon(10, new Date('December 01, 1999 01:00:00'))) expect(coupon).to.equal(security.generateCoupon(10, new Date('December 02, 1999'))) expect(coupon).to.equal(security.generateCoupon(10, new Date('December 31, 1999 23:59:59'))) }) }) describe('discountFromCoupon', () => { const z85 = require('z85') it('returns undefined when not passing in a coupon code', () => { expect(security.discountFromCoupon(undefined)).to.equal(undefined) expect(security.discountFromCoupon(null)).to.equal(undefined) }) it('returns undefined for malformed coupon code', () => { expect(security.discountFromCoupon('')).to.equal(undefined) expect(security.discountFromCoupon('x')).to.equal(undefined) expect(security.discountFromCoupon('___')).to.equal(undefined) }) it('returns undefined for coupon code not according to expected pattern', () => { expect(security.discountFromCoupon(z85.encode('Test'))).to.equal(undefined) expect(security.discountFromCoupon(z85.encode('XXX00-10'))).to.equal(undefined) expect(security.discountFromCoupon(z85.encode('DEC18-999'))).to.equal(undefined) expect(security.discountFromCoupon(z85.encode('DEC18-1'))).to.equal(undefined) expect(security.discountFromCoupon(z85.encode('DEC2018-10'))).to.equal(undefined) }) it('returns undefined for expired coupon code', () => { expect(security.discountFromCoupon(z85.encode('SEP14-50'))).to.equal(undefined) }) it('returns discount from valid coupon code', () => { expect(security.discountFromCoupon(security.generateCoupon('05'))).to.equal(5) expect(security.discountFromCoupon(security.generateCoupon(10))).to.equal(10) expect(security.discountFromCoupon(security.generateCoupon(99))).to.equal(99) }) }) describe('authenticatedUsers', () => { it('returns user by associated token', () => { security.authenticatedUsers.put('11111', { data: { id: 1 } }) expect(security.authenticatedUsers.get('11111')).to.deep.equal({ data: { id: 1 } }) }) it('returns undefined if no token is passed in', () => { expect(security.authenticatedUsers.get(undefined)).to.equal(undefined) expect(security.authenticatedUsers.get(null)).to.equal(undefined) }) it('returns token by associated user', () => { security.authenticatedUsers.put('11111', { data: { id: 1 } }) expect(security.authenticatedUsers.tokenOf({ id: 1 })).to.equal('11111') }) it('returns undefined if no user is passed in', () => { expect(security.authenticatedUsers.tokenOf(undefined)).to.equal(undefined) expect(security.authenticatedUsers.tokenOf(null)).to.equal(undefined) }) it('returns user by associated token from request', () => { security.authenticatedUsers.put('11111', { data: { id: 1 } }) expect(security.authenticatedUsers.from({ headers: { authorization: 'Bearer 11111' } })).to.deep.equal({ data: { id: 1 } }) }) it('returns undefined if no token is present in request', () => { expect(security.authenticatedUsers.from({ headers: {} })).to.equal(undefined) expect(security.authenticatedUsers.from({})).to.equal(undefined) }) }) describe('sanitizeHtml', () => { it('handles empty inputs by returning their string representation', () => { expect(security.sanitizeHtml()).to.equal('undefined') expect(security.sanitizeHtml(undefined)).to.equal('undefined') expect(security.sanitizeHtml(null)).to.equal('null') expect(security.sanitizeHtml('')).to.equal('') }) it('returns input unchanged for plain text input', () => { expect(security.sanitizeHtml('This application is horrible!')).to.equal('This application is horrible!') }) it('returns input unchanged for HTML input with only harmless text formatting', () => { expect(security.sanitizeHtml('<strong>This</strong> application <em>is horrible</em>!')).to.equal('<strong>This</strong> application <em>is horrible</em>!') }) it('returns input unchanged for HTML input with only harmless links', () => { expect(security.sanitizeHtml('<a href="bla.blubb">Please see here for details!</a>')).to.equal('<a href="bla.blubb">Please see here for details!</a>') }) it('removes all Javascript from HTML input', () => { expect(security.sanitizeHtml('Sani<script>alert("ScriptXSS")</script>tizedScript')).to.equal('SanitizedScript') expect(security.sanitizeHtml('Sani<img src="alert("ImageXSS")"/>tizedImage')).to.equal('SanitizedImage') expect(security.sanitizeHtml('Sani<iframe src="alert("IFrameXSS")"></iframe>tizedIFrame')).to.equal('SanitizedIFrame') }) it('can be bypassed by exploiting lack of recursive sanitization', () => { expect(security.sanitizeHtml('<<script>Foo</script>iframe src="javascript:alert(`xss`)">')).to.equal('<iframe src="javascript:alert(`xss`)">') }) }) describe('sanitizeLegacy', () => { it('returns empty string for undefined input', () => { expect(security.sanitizeLegacy()).to.equal('') expect(security.sanitizeLegacy(undefined)).to.equal('') }) it('returns input unchanged for plain text input', () => { expect(security.sanitizeLegacy('bkimminich')).to.equal('bkimminich') expect(security.sanitizeLegacy('Kosh III.')).to.equal('Kosh III.') }) it('removes all opening tags and subsequent character from HTML input', () => { expect(security.sanitizeLegacy('<h1>Hello</h1>')).to.equal('ello</h1>') expect(security.sanitizeLegacy('<img src="test">')).to.equal('rc="test">') }) it('can be bypassed to allow working HTML payload to be returned', () => { expect(security.sanitizeLegacy('<<a|ascript>alert(`xss`)</script>')).to.equal('<script>alert(`xss`)</script>') }) }) describe('sanitizeSecure', () => { it('handles empty inputs by returning their string representation', () => { expect(security.sanitizeSecure()).to.equal('undefined') expect(security.sanitizeSecure(undefined)).to.equal('undefined') expect(security.sanitizeSecure(null)).to.equal('null') expect(security.sanitizeSecure('')).to.equal('') }) it('returns input unchanged for plain text input', () => { expect(security.sanitizeSecure('This application is horrible!')).to.equal('This application is horrible!') }) it('returns input unchanged for HTML input with only harmless text formatting', () => { expect(security.sanitizeSecure('<strong>This</strong> application <em>is horrible</em>!')).to.equal('<strong>This</strong> application <em>is horrible</em>!') }) it('returns input unchanged for HTML input with only harmless links', () => { expect(security.sanitizeSecure('<a href="bla.blubb">Please see here for details!</a>')).to.equal('<a href="bla.blubb">Please see here for details!</a>') }) it('removes all Javascript from HTML input', () => { expect(security.sanitizeSecure('Sani<script>alert("ScriptXSS")</script>tizedScript')).to.equal('SanitizedScript') expect(security.sanitizeSecure('Sani<img src="alert("ImageXSS")"/>tizedImage')).to.equal('SanitizedImage') expect(security.sanitizeSecure('Sani<iframe src="alert("IFrameXSS")"></iframe>tizedIFrame')).to.equal('SanitizedIFrame') }) it('cannot be bypassed by exploiting lack of recursive sanitization', () => { expect(security.sanitizeSecure('Bla<<script>Foo</script>iframe src="javascript:alert(`xss`)">Blubb')).to.equal('BlaBlubb') }) }) describe('hash', () => { it('throws type error for for undefined input', () => { expect(() => security.hash()).to.throw(TypeError) }) it('returns MD5 hash for any input string', () => { expect(security.hash('admin123')).to.equal('0192023a7bbd73250516f069df18b500') expect(security.hash('password')).to.equal('5f4dcc3b5aa765d61d8327deb882cf99') expect(security.hash('')).to.equal('d41d8cd98f00b204e9800998ecf8427e') }) }) describe('hmac', () => { it('throws type error for for undefined input', () => { expect(() => security.hmac()).to.throw(TypeError) }) it('returns SHA-256 HMAC with "pa4qacea4VK9t9nGv7yZtwmj" as salt any input string', () => { expect(security.hmac('admin123')).to.equal('6be13e2feeada221f29134db71c0ab0be0e27eccfc0fb436ba4096ba73aafb20') expect(security.hmac('password')).to.equal('da28fc4354f4a458508a461fbae364720c4249c27f10fccf68317fc4bf6531ed') expect(security.hmac('')).to.equal('f052179ec5894a2e79befa8060cfcb517f1e14f7f6222af854377b6481ae953e') }) }) })
the_stack
import * as crypto from "crypto"; import * as fs from "fs"; import * as jsBeautify from "js-beautify"; import * as sqlFormatter from "sql-formatter"; import { promisify } from "util"; import { ErrorWithCause } from "df/common/errors/errors"; import { SyntaxTreeNode, SyntaxTreeNodeType } from "df/sqlx/lexer"; import { v4 as uuidv4 } from "uuid"; const JS_BEAUTIFY_OPTIONS: JsBeautifyOptions = { indent_size: 2, preserve_newlines: true, max_preserve_newlines: 2 }; const MAX_SQL_FORMAT_ATTEMPTS = 5; export function format(text: string, fileExtension: string) { try { switch (fileExtension) { case "sqlx": return postProcessFormattedSqlx(formatSqlx(SyntaxTreeNode.create(text))); case "js": return `${formatJavaScript(text).trim()}\n`; default: return text; } } catch (e) { throw new ErrorWithCause(`Unable to format "${text?.substring(0, 20)}...".`, e); } } export async function formatFile( filename: string, options?: { overwriteFile?: boolean; } ) { const fileExtension = filename.split(".").slice(-1)[0]; const originalFileContent = await promisify(fs.readFile)(filename, "utf8"); const formattedText = format(originalFileContent, fileExtension); if (formattedText !== format(formattedText, fileExtension)) { throw new Error("Formatter unable to determine final formatted form."); } const noWhiteSpaceFormatted = formattedText.replace(/\s/g, ""); const noWhiteSpaceOriginal = originalFileContent.replace(/\s/g, ""); if (noWhiteSpaceFormatted.length !== noWhiteSpaceOriginal.length) { const isLonger = noWhiteSpaceFormatted.length > noWhiteSpaceOriginal.length; throw new Error(`Formatter ${isLonger ? "added" : "removed"} non-whitespace characters`); } if (options && options.overwriteFile) { await promisify(fs.writeFile)(filename, formattedText); } return formattedText; } function formatSqlx(node: SyntaxTreeNode, indent: string = "") { const { sqlxStatements, javascriptBlocks, innerSqlBlocks } = separateSqlxIntoParts( node.children() ); // First, format the JS blocks (including the config block). const formattedJsCodeBlocks = javascriptBlocks.map(jsCodeBlock => formatJavaScript(jsCodeBlock.concatenate()) ); // Second, format all the SQLX statements, replacing any placeholders with their formatted form. const formattedSqlxStatements = sqlxStatements.map(sqlxStatement => { const placeholders: { [placeholderId: string]: SyntaxTreeNode | string; } = {}; const unformattedPlaceholderSql = stripUnformattableText(sqlxStatement, placeholders).join(""); const formattedPlaceholderSql = formatSql(unformattedPlaceholderSql); return formatEveryLine( replacePlaceholders(formattedPlaceholderSql, placeholders), line => `${indent}${line}` ); }); // Third, format all "inner" SQL blocks, e.g. "pre_operations { ... }". const formattedSqlCodeBlocks = innerSqlBlocks.map((sqlCodeBlock): string => { // Strip out the declaration of this block, format the internals then add the declaration back. const firstPart = sqlCodeBlock.children()[0] as string; const upToFirstBrace = firstPart.slice(0, firstPart.indexOf("{") + 1); const lastPart = sqlCodeBlock.children()[sqlCodeBlock.children().length - 1] as string; const lastBraceOnwards = lastPart.slice(lastPart.lastIndexOf("}")); const sqlCodeBlockWithoutOuterBraces = sqlCodeBlock.children().length === 1 ? new SyntaxTreeNode(SyntaxTreeNodeType.SQL, [ firstPart.slice(firstPart.indexOf("{") + 1, firstPart.lastIndexOf("}")) ]) : new SyntaxTreeNode(SyntaxTreeNodeType.SQL, [ firstPart.slice(firstPart.indexOf("{") + 1), ...sqlCodeBlock.children().slice(1, -1), lastPart.slice(0, lastPart.lastIndexOf("}")) ]); return `${upToFirstBrace} ${formatSqlx(sqlCodeBlockWithoutOuterBraces, " ")} ${lastBraceOnwards}`; }); const finalText = ` ${formattedJsCodeBlocks.join("\n\n")} ${formattedSqlxStatements.join(`\n\n${indent}---\n\n`)} ${formattedSqlCodeBlocks.join("\n\n")} `; return `${indent}${finalText.trim()}`; } function separateSqlxIntoParts(nodeContents: Array<string | SyntaxTreeNode>) { const sqlxStatements: Array<Array<string | SyntaxTreeNode>> = [[]]; const javascriptBlocks: SyntaxTreeNode[] = []; const innerSqlBlocks: SyntaxTreeNode[] = []; nodeContents.forEach(child => { if (typeof child !== "string") { switch (child.type) { case SyntaxTreeNodeType.JAVASCRIPT: javascriptBlocks.push(child); return; case SyntaxTreeNodeType.SQL: innerSqlBlocks.push(child); return; case SyntaxTreeNodeType.SQL_STATEMENT_SEPARATOR: sqlxStatements.push([]); return; } } sqlxStatements[sqlxStatements.length - 1].push(child); }); return { sqlxStatements, javascriptBlocks, innerSqlBlocks }; } function stripUnformattableText( sqlxStatementParts: Array<string | SyntaxTreeNode>, placeholders: { [placeholderId: string]: SyntaxTreeNode | string; } ) { return sqlxStatementParts.map(part => { if (typeof part !== "string") { const placeholderId = generatePlaceholderId(); switch (part.type) { case SyntaxTreeNodeType.SQL_LITERAL_STRING: case SyntaxTreeNodeType.JAVASCRIPT_TEMPLATE_STRING_PLACEHOLDER: { placeholders[placeholderId] = part; return placeholderId; } case SyntaxTreeNodeType.SQL_COMMENT: { // sql-formatter knows how to format comments (as long as they keep to a single line); // give it a hint. const commentPlaceholderId = part.concatenate().startsWith("--") ? `--${placeholderId}` : `/*${placeholderId}*/`; placeholders[commentPlaceholderId] = part; return commentPlaceholderId; } default: throw new Error(`Misplaced SyntaxTreeNodeType inside SQLX: ${part.type}`); } } return part; }); } function generatePlaceholderId() { return uuidv4() .replace(/-/g, "") .substring(0, 16); } function replacePlaceholders( formattedSql: string, placeholders: { [placeholderId: string]: SyntaxTreeNode | string; } ) { return Object.keys(placeholders).reduce((partiallyFormattedSql, placeholderId) => { const placeholderValue = placeholders[placeholderId]; if (typeof placeholderValue === "string") { return partiallyFormattedSql.replace(placeholderId, placeholderValue); } return formatPlaceholderInSqlx(placeholderId, placeholderValue, partiallyFormattedSql); }, formattedSql); } function formatJavaScript(text: string) { return jsBeautify.js(text, JS_BEAUTIFY_OPTIONS); } function formatSql(text: string) { let formatted = sqlFormatter.format(text) as string; // Unfortunately sql-formatter does not always produce final formatted output (even on plain SQL) in a single pass. for (let attempts = 0; attempts < MAX_SQL_FORMAT_ATTEMPTS; attempts++) { const newFormatted = sqlFormatter.format(formatted) as string; if (newFormatted === formatted) { return newFormatted; } formatted = newFormatted; } throw new Error( `SQL formatter was unable to determine final formatted form within ${MAX_SQL_FORMAT_ATTEMPTS} attempts. Original text: ${text}` ); } function formatPlaceholderInSqlx( placeholderId: string, placeholderSyntaxNode: SyntaxTreeNode, sqlx: string ) { const wholeLine = getWholeLineContainingPlaceholderId(placeholderId, sqlx); const indent = " ".repeat(wholeLine.length - wholeLine.trimLeft().length); const formattedPlaceholder = formatSqlQueryPlaceholder(placeholderSyntaxNode, indent); // Replace the placeholder entirely if (a) it fits on one line and (b) it isn't a comment. // Otherwise, push the replacement onto its own line. if ( placeholderSyntaxNode.type !== SyntaxTreeNodeType.SQL_COMMENT && !formattedPlaceholder.includes("\n") ) { return sqlx.replace(placeholderId, () => formattedPlaceholder.trim()); } // Push multi-line placeholders to their own lines, if they're not already on one. const [textBeforePlaceholder, textAfterPlaceholder] = wholeLine.split(placeholderId); const newLines: string[] = []; if (textBeforePlaceholder.trim().length > 0) { newLines.push(`${indent}${textBeforePlaceholder.trim()}`); } newLines.push(formattedPlaceholder); if (textAfterPlaceholder.trim().length > 0) { newLines.push(`${indent}${textAfterPlaceholder.trim()}`); } return sqlx.replace(wholeLine, newLines.join("\n")); } function formatSqlQueryPlaceholder(node: SyntaxTreeNode, jsIndent: string): string { switch (node.type) { case SyntaxTreeNodeType.JAVASCRIPT_TEMPLATE_STRING_PLACEHOLDER: return formatJavaScriptPlaceholder(node, jsIndent); case SyntaxTreeNodeType.SQL_LITERAL_STRING: case SyntaxTreeNodeType.SQL_COMMENT: return formatEveryLine(node.concatenate(), line => `${jsIndent}${line.trimLeft()}`); default: throw new Error(`Unrecognized SyntaxTreeNodeType: ${node.type}`); } } function formatJavaScriptPlaceholder(node: SyntaxTreeNode, jsIndent: string) { const formattedJs = formatJavaScript(node.concatenate()); const textInsideBraces = formattedJs.slice( formattedJs.indexOf("{") + 1, formattedJs.lastIndexOf("}") ); // If the formatted JS is only a single line, trim all whitespace so that it stays a single line. const finalJs = textInsideBraces.trim().includes("\n") ? `\${${textInsideBraces}}` : `\${${textInsideBraces.trim()}}`; return formatEveryLine(finalJs, line => `${jsIndent}${line}`); } function formatEveryLine(text: string, mapFn: (line: string) => string) { return text .split("\n") .map(mapFn) .join("\n"); } function getWholeLineContainingPlaceholderId(placeholderId: string, text: string) { const regexpEscapedPlaceholderId = placeholderId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // This RegExp is safe because we only use a 'placeholderId' that this file has generated. // tslint:disable-next-line: tsr-detect-non-literal-regexp return text.match(new RegExp(".*" + regexpEscapedPlaceholderId + ".*"))[0]; } function postProcessFormattedSqlx(formattedSql: string) { let previousLineHadContent = false; formattedSql = formattedSql.split("\n").reduce((accumulatedSql, currentLine) => { const lineHasContent = currentLine.trim().length > 0; if (lineHasContent) { previousLineHadContent = true; return `${accumulatedSql}\n${currentLine.trimRight()}`; } if (previousLineHadContent) { previousLineHadContent = false; return `${accumulatedSql}\n`; } return accumulatedSql; }, ""); return `${formattedSql.trim()}\n`; }
the_stack
import 'chrome://tab-strip.top-chrome/tab.js'; import {getFavicon} from 'chrome://resources/js/icon.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {TabElement} from 'chrome://tab-strip.top-chrome/tab.js'; import {Tab, TabNetworkState} from 'chrome://tab-strip.top-chrome/tab_strip.mojom-webui.js'; import {CloseTabAction, TabsApiProxyImpl} from 'chrome://tab-strip.top-chrome/tabs_api_proxy.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {createTab, TestTabsApiProxy} from './test_tabs_api_proxy.js'; suite('Tab', function() { let testTabsApiProxy: TestTabsApiProxy; let tabElement: TabElement; function queryTab(): HTMLElement { return tabElement.shadowRoot!.querySelector<HTMLElement>('#tab')!; } const tab: Tab = createTab({ index: 0, showIcon: true, title: 'My Title', }); /** * Convenience function for creating a typed Tab object. */ function createTabData(overrides?: Partial<Tab>): Tab { return Object.assign({}, tab, overrides); } const strings = { closeTab: 'Close tab', loadingTab: 'Loading...', tabCrashed: '$1 has crashed', tabNetworkError: '$1 has a network error', }; setup(() => { loadTimeData.overrideValues(strings); document.body.innerHTML = ''; // Set CSS variable for animations document.body.style.setProperty('--tabstrip-tab-height', '100px'); document.body.style.setProperty('--tabstrip-tab-width', '280px'); document.body.style.setProperty('--tabstrip-tab-spacing', '20px'); testTabsApiProxy = new TestTabsApiProxy(); TabsApiProxyImpl.setInstance(testTabsApiProxy); tabElement = document.createElement('tabstrip-tab'); tabElement.tab = createTabData(); document.body.appendChild(tabElement); }); test('slideIn animates scale for the last tab', async () => { document.documentElement.dir = 'ltr'; tabElement.style.paddingRight = '100px'; const tabElementStyle = window.getComputedStyle(tabElement); const animationPromise = tabElement.slideIn(); // Before animation completes. assertEquals('20px', tabElementStyle.paddingRight); assertEquals('280px', tabElementStyle.maxWidth); assertEquals('matrix(0, 0, 0, 0, 0, 0)', tabElementStyle.transform); await animationPromise; // After animation completes. assertEquals('100px', tabElementStyle.paddingRight); assertEquals('none', tabElementStyle.maxWidth); assertEquals('none', tabElementStyle.transform); }); test('slideIn animations for not the last tab', async () => { // Add another element to make sure the element being tested is not the // last. document.body.appendChild(document.createElement('div')); document.documentElement.dir = 'ltr'; tabElement.style.paddingRight = '100px'; const tabElementStyle = window.getComputedStyle(tabElement); const animationPromise = tabElement.slideIn(); // Before animation completes. assertEquals('0px', tabElementStyle.paddingRight); assertEquals('0px', tabElementStyle.maxWidth); assertEquals('matrix(0, 0, 0, 0, 0, 0)', tabElementStyle.transform); await animationPromise; // After animation completes. assertEquals('100px', tabElementStyle.paddingRight); assertEquals('none', tabElementStyle.maxWidth); assertEquals('none', tabElementStyle.transform); }); test('slideIn animations right to left for RTL languages', async () => { // Add another element to make sure the element being tested is not the // last. document.body.appendChild(document.createElement('div')); document.documentElement.dir = 'rtl'; tabElement.style.paddingLeft = '100px'; const tabElementStyle = window.getComputedStyle(tabElement); const animationPromise = tabElement.slideIn(); // Before animation completes. assertEquals('0px', tabElementStyle.paddingLeft); assertEquals('0px', tabElementStyle.maxWidth); assertEquals('matrix(0, 0, 0, 0, 0, 0)', tabElementStyle.transform); await animationPromise; // After animation completes. assertEquals('100px', tabElementStyle.paddingLeft); assertEquals('none', tabElementStyle.maxWidth); assertEquals('none', tabElementStyle.transform); }); test('slideOut animates out the element', async () => { testTabsApiProxy.setVisible(true); const tabElementStyle = window.getComputedStyle(tabElement); const animationPromise = tabElement.slideOut(); // Before animation completes. assertEquals('1', tabElementStyle.opacity); assertEquals('none', tabElementStyle.maxWidth); assertEquals('matrix(1, 0, 0, 1, 0, 0)', tabElementStyle.transform); assertTrue(tabElement.isConnected); await animationPromise; // After animation completes. assertFalse(tabElement.isConnected); }); test('slideOut does not animate when tab strip is hidden', () => { testTabsApiProxy.setVisible(false); assertTrue(tabElement.isConnected); tabElement.slideOut(); // The tab should immediately be disconnected without waiting for the // animation to finish. assertFalse(tabElement.isConnected); }); test('slideOut resolves immediately when tab strip becomes hidden', () => { testTabsApiProxy.setVisible(true); assertTrue(tabElement.isConnected); tabElement.slideOut(); testTabsApiProxy.setVisible(false); document.dispatchEvent(new Event('visibilitychange')); // The tab should immediately be disconnected without waiting for the // animation to finish. assertFalse(tabElement.isConnected); }); test('toggles an [active] attribute when active', () => { tabElement.tab = createTabData({active: true}); assertTrue(tabElement.hasAttribute('active')); tabElement.tab = createTabData({active: false}); assertFalse(tabElement.hasAttribute('active')); }); test('sets [aria-selected] attribute when active', () => { tabElement.tab = createTabData({active: true}); assertEquals('true', queryTab().getAttribute('aria-selected')); tabElement.tab = createTabData({active: false}); assertEquals('false', queryTab().getAttribute('aria-selected')); }); test('hides entire favicon container when showIcon is false', () => { // disable transitions tabElement.style.setProperty('--tabstrip-tab-transition-duration', '0ms'); const faviconContainerStyle = window.getComputedStyle( tabElement.shadowRoot!.querySelector('#faviconContainer')!); tabElement.tab = createTabData({showIcon: true}); assertEquals( faviconContainerStyle.maxWidth, faviconContainerStyle.getPropertyValue('--favicon-size').trim()); assertEquals(faviconContainerStyle.opacity, '1'); tabElement.tab = createTabData({showIcon: false}); assertEquals(faviconContainerStyle.maxWidth, '0px'); assertEquals(faviconContainerStyle.opacity, '0'); }); test('updates dimensions based on CSS variables when pinned', () => { const tabElementStyle = window.getComputedStyle(tabElement); const expectedSize = '100px'; tabElement.style.setProperty('--tabstrip-pinned-tab-size', expectedSize); tabElement.tab = createTabData({pinned: true}); assertEquals(expectedSize, tabElementStyle.width); assertEquals(expectedSize, tabElementStyle.height); tabElement.style.setProperty('--tabstrip-tab-width', '100px'); tabElement.style.setProperty('--tabstrip-tab-height', '150px'); tabElement.tab = createTabData({pinned: false}); assertEquals('100px', tabElementStyle.width); assertEquals('150px', tabElementStyle.height); }); test('show spinner when loading or waiting', () => { function assertSpinnerVisible(color: string) { const spinnerStyle = window.getComputedStyle( tabElement.shadowRoot!.querySelector('#progressSpinner')!); assertEquals('block', spinnerStyle.display); assertEquals(color, spinnerStyle.backgroundColor); // Also assert it becomes hidden when network state is NONE tabElement.tab = createTabData({networkState: TabNetworkState.kNone}); assertEquals('none', spinnerStyle.display); } tabElement.style.setProperty( '--tabstrip-tab-loading-spinning-color', 'rgb(255, 0, 0)'); tabElement.tab = createTabData({networkState: TabNetworkState.kLoading}); assertSpinnerVisible('rgb(255, 0, 0)'); tabElement.style.setProperty( '--tabstrip-tab-waiting-spinning-color', 'rgb(0, 255, 0)'); tabElement.tab = createTabData({networkState: TabNetworkState.kWaiting}); assertSpinnerVisible('rgb(0, 255, 0)'); }); test('shows blocked indicator when tab is blocked', () => { const blockIndicatorStyle = window.getComputedStyle( tabElement.shadowRoot!.querySelector('#blocked')!); tabElement.tab = createTabData({blocked: true}); assertEquals('block', blockIndicatorStyle.display); tabElement.tab = createTabData({blocked: true, active: true}); assertEquals('none', blockIndicatorStyle.display); tabElement.tab = createTabData({blocked: false}); assertEquals('none', blockIndicatorStyle.display); }); test( 'hides the favicon and shows the crashed icon when tab is crashed', () => { // disable transitions tabElement.style.setProperty( '--tabstrip-tab-transition-duration', '0ms'); const faviconStyle = window.getComputedStyle( tabElement.shadowRoot!.querySelector('#favicon')!); const crashedIconStyle = window.getComputedStyle( tabElement.shadowRoot!.querySelector('#crashedIcon')!); tabElement.tab = createTabData({crashed: true}); assertEquals(faviconStyle.opacity, '0'); assertEquals(crashedIconStyle.opacity, '1'); tabElement.tab = createTabData({crashed: false}); assertEquals(faviconStyle.opacity, '1'); assertEquals(crashedIconStyle.opacity, '0'); }); test('clicking on the element activates the tab', async () => { queryTab().click(); const tabId = await testTabsApiProxy.whenCalled('activateTab'); assertEquals(tabId, tab.id); }); test('sets the title', () => { assertEquals( tab.title, tabElement.shadowRoot!.querySelector<HTMLElement>( '#titleText')!.innerText); }); test('sets the loading title while loading', () => { const loadingTabWithoutTitle = createTabData({ networkState: TabNetworkState.kWaiting, shouldHideThrobber: false, }); delete (loadingTabWithoutTitle as Partial<Tab>).title; tabElement.tab = loadingTabWithoutTitle; assertEquals( strings['loadingTab'], tabElement.shadowRoot!.querySelector<HTMLElement>( '#titleText')!.innerText); }); test('exposes the tab ID to an attribute', () => { tabElement.tab = createTabData({id: 1001}); assertEquals('1001', tabElement.getAttribute('data-tab-id')); }); test('closes the tab when clicking close button', async () => { tabElement.shadowRoot!.querySelector<HTMLElement>('#close')!.click(); const [tabId, closeTabAction] = await testTabsApiProxy.whenCalled('closeTab'); assertEquals(tabId, tab.id); assertEquals(closeTabAction, CloseTabAction.CLOSE_BUTTON); }); test('closes the tab on swipe', async () => { tabElement.dispatchEvent(new CustomEvent('swipe')); const [tabId, closeTabAction] = await testTabsApiProxy.whenCalled('closeTab'); assertEquals(tabId, tab.id); assertEquals(closeTabAction, CloseTabAction.SWIPED_TO_CLOSE); }); test('sets the favicon to the favicon URL', () => { const expectedFaviconUrl = 'data:mock-favicon'; tabElement.tab = createTabData({faviconUrl: {url: expectedFaviconUrl}}); const faviconElement = tabElement.shadowRoot!.querySelector<HTMLElement>('#favicon')!; assertEquals( faviconElement.style.backgroundImage, `url("${expectedFaviconUrl}")`); }); test( 'sets the favicon to the default favicon URL if there is none provided', () => { const updatedTab = createTabData(); delete updatedTab.faviconUrl; tabElement.tab = updatedTab; const faviconElement = tabElement.shadowRoot!.querySelector<HTMLElement>('#favicon')!; assertEquals(faviconElement.style.backgroundImage, getFavicon('')); }); test('removes the favicon if the tab is waiting', () => { tabElement.tab = createTabData({ faviconUrl: {url: 'data:mock-favicon'}, networkState: TabNetworkState.kWaiting, }); const faviconElement = tabElement.shadowRoot!.querySelector<HTMLElement>('#favicon')!; assertEquals(faviconElement.style.backgroundImage, 'none'); }); test( 'removes the favicon if the tab is loading with a default favicon', () => { tabElement.tab = createTabData({ faviconUrl: {url: 'data:mock-favicon'}, isDefaultFavicon: true, networkState: TabNetworkState.kWaiting, }); const faviconElement = tabElement.shadowRoot!.querySelector<HTMLElement>('#favicon')!; assertEquals(faviconElement.style.backgroundImage, 'none'); }); test('hides the thumbnail if there is no source yet', () => { const thumbnailImage = tabElement.shadowRoot!.querySelector<HTMLElement>('#thumbnailImg')!; assertFalse(thumbnailImage.hasAttribute('src')); assertEquals(window.getComputedStyle(thumbnailImage).display, 'none'); }); test('updates the thumbnail source', async () => { const thumbnailSource = 'data:mock-thumbnail-source'; tabElement.updateThumbnail(thumbnailSource); assertEquals( tabElement.shadowRoot!.querySelector<HTMLImageElement>( '#thumbnailImg')!.src, thumbnailSource); }); test('setting dragging state toggles an attribute', () => { tabElement.setDragging(true); assertTrue(tabElement.hasAttribute('dragging_')); tabElement.setDragging(false); assertFalse(tabElement.hasAttribute('dragging_')); }); test('gets the drag image', () => { assertEquals( tabElement.getDragImage(), tabElement.shadowRoot!.querySelector('#dragImage')); }); test('activating closes WebUI container', () => { assertEquals(testTabsApiProxy.getCallCount('closeContainer'), 0); queryTab().click(); assertEquals(testTabsApiProxy.getCallCount('closeContainer'), 1); }); test('sets an accessible title', () => { const titleTextElement = tabElement.shadowRoot!.querySelector<HTMLElement>('#titleText')!; assertEquals(titleTextElement.getAttribute('aria-label'), tab.title); tabElement.tab = createTabData({ crashed: true, title: 'My tab', }); assertEquals( titleTextElement.getAttribute('aria-label'), 'My tab has crashed'); tabElement.tab = createTabData({ crashed: false, networkState: TabNetworkState.kError, title: 'My tab', }); assertEquals( titleTextElement.getAttribute('aria-label'), 'My tab has a network error'); }); test('focusing on the host moves focus to inner tab element', () => { tabElement.focus(); assertEquals(tabElement.shadowRoot!.activeElement, queryTab()); }); test('supports Enter and Space key for activating tab', async () => { const innerTabElement = queryTab(); innerTabElement.dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter'})); assertEquals(await testTabsApiProxy.whenCalled('activateTab'), tab.id); testTabsApiProxy.reset(); innerTabElement.dispatchEvent(new KeyboardEvent('keydown', {key: ' '})); assertEquals(await testTabsApiProxy.whenCalled('activateTab'), tab.id); testTabsApiProxy.reset(); }); test('DragImagePreservesAspectRatio', () => { const originalBoundingBox = queryTab().getBoundingClientRect(); const originalAspectRatio = originalBoundingBox.width / originalBoundingBox.height; tabElement.setDragging(true); const dragImageBoundingBox = tabElement.getDragImage().querySelector<HTMLElement>( '#tab')!.getBoundingClientRect(); const dragImageAspectRatio = dragImageBoundingBox.width / dragImageBoundingBox.height; // Check the Math.floor values of these values to prevent possible // flakiness caused by comparing float values. assertEquals( Math.floor(originalAspectRatio), Math.floor(dragImageAspectRatio)); }); test('RightClickOpensContextMenu', async () => { queryTab().dispatchEvent(new PointerEvent('pointerup', { pointerType: 'mouse', button: 2, clientX: 50, clientY: 100, })); const [id, x, y] = await testTabsApiProxy.whenCalled('showTabContextMenu'); assertEquals(tab.id, id); assertEquals(50, x); assertEquals(100, y); }); });
the_stack
declare module 'react' { export = React; } declare module React { /** * Configure React's event system to handle touch events on mobile devices. * @param shouldUseTouch true if React should active touch events, false if it should not */ function initializeTouchEvents(shouldUseTouch: boolean): void; /** * Create a component given a specification. A component implements a render method which returns one single child. * That child may have an arbitrarily deep child structure. * One thing that makes components different than standard prototypal classes is that you don't need to call new on them. * They are convenience wrappers that construct backing instances (via new) for you. * * @param spec the component specification */ // we need mixins and type union here, until that manually specifies the type. function createClass<P, S>(spec: ReactComponentSpec<P, S>): ReactComponentFactory<P>; /** * Render a React component into the DOM in the supplied container. * If the React component was previously rendered into container, * this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component. * * @param component the component to render * @param container the node that should contain the result of rendering * @param callback an optional callback that will be executed after the component is rendered or updated. */ function renderComponent<C extends ReactComponent<any, any>>(component: C, container: Element, callback?: () => void): C; /** * Remove a mounted React component from the DOM and clean up its event handlers and state. * If no component was mounted in the container, calling this function does nothing. * Returns true if a component was unmounted and false if there was no component to unmount. * * @param container the node that should be cleaned from React component */ function unmountComponentAtNode(container: Element): boolean; /** * Render a component to its initial HTML. This should only be used on the server. * React will return an HTML string. You can use this method to generate HTML on the server * and send the markup down on the initial request for faster page loads and to allow search * engines to crawl your pages for SEO purposes. * * If you call React.renderComponent() on a node that already has this server-rendered markup, * React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience. * * @param component the component to render */ function renderComponentToString(component: ReactComponent<any, any>): string; /** * Similar to renderComponentToString, except this doesn't create extra DOM * attributes such as data-react-id, that React uses internally. This is useful * if you want to use React as a simple static page generator, as stripping * away the extra attributes can save lots of bytes. * * @param component the component to render */ function renderComponentToStaticMarkup(component: ReactComponent<any, any>): string; /** * Built-in Prop Type Validators * (incomplete) */ export var PropTypes: ReactPropTypes; export var addons: any; interface ReactPropTypes { 'number': PropTypeValidator; 'string': PropTypeValidator; 'any': PropTypeValidator; 'func': PropTypeValidator; 'object': PropTypeValidator; 'array': PropTypeValidator; 'arrayOf': TypedArrayValidatorFactory; 'shape': ShapedObjectValidatorFactory; 'bool': PropTypeValidator; } interface PropTypeValidatorOptions { [key: string]: PropTypeValidator; } interface ShapedObjectValidatorFactory { (opts: PropTypeValidatorOptions): PropTypeValidator; } interface TypedArrayValidatorFactory { (elementType: PropTypeValidator): PropTypeValidator; } interface PropTypeValidator { isRequired?: RequiredPropTypeValidator } interface RequiredPropTypeValidator extends PropTypeValidator { } /** * Component classses created by createClass() return instances of ReactComponent when called. * Most of the time when you're using React you're either creating or consuming these component objects. */ interface ReactComponent<P, S> { refs: { [ref: string]: ReactComponent<any, any>; } /** * If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. * This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements. */ getDOMNode(): Element; /** * When you're integrating with an external JavaScript application you may want to signal a change to a React component rendered with renderComponent(). * Simply call setProps() to change its properties and trigger a re-render. * * @param nextProps the object that will be merged with the component's props * @param callback an optional callback function that is executed once setProps is completed. */ setProps(nextProps: P, callback?: () => void): void; /** * Like setProps() but deletes any pre-existing props instead of merging the two objects. * * @param nextProps the object that will replace the component's props * @param callback an optional callback function that is executed once replaceProps is completed. */ replaceProps(nextProps: P, callback?: () => void): void; /** * Transfer properties from this component to a target component that have not already been set on the target component. * After the props are updated, targetComponent is returned as a convenience. * * @param target the component that will receive the props */ transferPropsTo<C extends ReactComponent<P, any>>(target: C): C; /** * Merges nextState with the current state. * This is the primary method you use to trigger UI updates from event handlers and server request callbacks. * In addition, you can supply an optional callback function that is executed once setState is completed. * * @param nextState the object that will be merged with the component's state * @param callback an optional callback function that is executed once setState is completed. */ setState(nextState: S, callback?: () => void): void; /** * Like setState() but deletes any pre-existing state keys that are not in nextState. * * @param nextState the object that will replace the component's state * @param callback an optional callback function that is executed once replaceState is completed. */ replaceState(nextState: S, callback?: () => void): void; /** * If your render() method reads from something other than this.props or this.state, * you'll need to tell React when it needs to re-run render() by calling forceUpdate(). * You'll also need to call forceUpdate() if you mutate this.state directly. * Calling forceUpdate() will cause render() to be called on the component and its children, * but React will still only update the DOM if the markup changes. * Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render(). * This makes your application much simpler and more efficient. * * @param callback an optional callback that is executed once forceUpdate is completed. */ forceUpdate(callback?: () => void): void; } interface ReactComponentFactory<P> { (properties?: P, ...children: any[]): ReactComponent<P, any> } /** * interface describing ReactComponentSpec */ interface ReactMixin<P, S> { /** * Invoked immediately before rendering occurs. * If you call setState within this method, render() will see the updated state and will be executed only once despite the state change. */ componentWillMount? (): void; /** * Invoked immediately after rendering occurs. * At this point in the lifecycle, the component has a DOM representation which you can access via the rootNode argument or by calling this.getDOMNode(). * If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, * or send AJAX requests, perform those operations in this method. */ componentDidMount? (): void; /** * Invoked when a component is receiving new props. This method is not called for the initial render. * * Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). * The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render. * * @param nextProps the props object that the component will receive */ componentWillReceiveProps? (nextProps: P): void; /** * Invoked before rendering when new props or state are being received. * This method is not called for the initial render or when forceUpdate is used. * Use this as an opportunity to return false when you're certain that the transition to the new props and state will not require a component update. * By default, shouldComponentUpdate always returns true to prevent subtle bugs when state is mutated in place, * but if you are careful to always treat state as immutable and to read only from props and state in render() * then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements. * * If performance is a bottleneck, especially with dozens or hundreds of components, use shouldComponentUpdate to speed up your app. * * @param nextProps the props object that the component will receive * @param nextState the state object that the component will receive */ shouldComponentUpdate? (nextProps: P, nextState: S): boolean; /** * Invoked immediately before rendering when new props or state are being received. This method is not called for the initial render. * Use this as an opportunity to perform preparation before an update occurs. * * @param nextProps the props object that the component has received * @param nextState the state object that the component has received */ componentWillUpdate? (nextProps: P, nextState: S): void; /** * Invoked immediately after updating occurs. This method is not called for the initial render. * Use this as an opportunity to operate on the DOM when the component has been updated. * * @param nextProps the props object that the component has received * @param nextState the state object that the component has received */ componentDidUpdate? (nextProps: P, nextState: S): void; /** * Invoked immediately before a component is unmounted from the DOM. * Perform any necessary cleanup in this method, such as invalidating timers or cleaning up any DOM elements that were created in componentDidMount. */ componentWillUnmount? (): void; } interface ReactComponentSpec<P, S> extends ReactMixin<P, S> { /** * The mixins array allows you to use mixins to share behavior among multiple components. */ mixins?: ReactMixin<any, any>[]; /** * The displayName string is used in debugging messages. JSX sets this value automatically. */ displayName?: string; /** * The propTypes object allows you to validate props being passed to your components. */ propTypes?: PropTypeValidatorOptions; /** * Invoked once before the component is mounted. The return value will be used as the initial value of this.state. */ getInitialState? (): S; /** * The render() method is required. When called, it should examine this.props and this.state and return a single child component. * This child component can be either a virtual representation of a native DOM component (such as <div /> or React.DOM.div()) * or another composite component that you've defined yourself. * The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, * and it does not read from or write to the DOM or otherwise interact with the browser (e.g., by using setTimeout). * If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. * Keeping render() pure makes server rendering more practical and makes components easier to think about. */ render(): ReactComponent<any, any>; /** * Invoked once when the component is mounted. * Values in the mapping will be set on this.props if that prop is not specified by the parent component (i.e. using an in check). * This method is invoked before getInitialState and therefore cannot rely on this.state or use this.setState. */ getDefaultProps? (): P; } export interface SyntheticEvent { bubbles: boolean; cancelable: boolean; currentTarget: EventTarget; defaultPrevented: boolean; eventPhase: number; isTrusted: boolean nativeEvent: Event; target: EventTarget type: string; timeStamp: Date; preventDefault(): void; stopPropagation(): void; } export interface ClipboardEvent extends SyntheticEvent { clipboardData: DataTransfer; } export interface KeyboardEvent extends SyntheticEvent { altKey: boolean; ctrlKey: boolean; charCode: number; key: string; keyCode: number; locale: string; location: number; metaKey: boolean; repeat: boolean; shiftKey: boolean; which: number; } export interface FocusEvent extends SyntheticEvent { relatedTarget: EventTarget; } export interface FormEvent extends SyntheticEvent { } export interface MouseEvent extends SyntheticEvent { altKey: boolean; button: number; buttons: number; clientX: number; clientY: number; ctrlKey: boolean; metaKey: boolean pageX: number; pageY: number; relatedTarget: EventTarget; screenX: number; screenY: number; shiftKey: boolean; } export interface TouchEvent extends SyntheticEvent { altKey: boolean; changedTouches: TouchEvent; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; targetTouches: any//DOMTouchList; touches: any//DOMTouchList; } export interface UIEvent extends SyntheticEvent { detail: number; view: Window; } export interface WheelEvent { deltaX: number; deltaMode: number; deltaY: number; deltaZ: number; } interface ReactEvents { onCopy?: (event: ClipboardEvent) => void; onCut?: (event: ClipboardEvent) => void; onPaste?: (event: ClipboardEvent) => void; onKeyDown?: (event: KeyboardEvent) => void; onKeyPress?: (event: KeyboardEvent) => void; onKeyUp?: (event: KeyboardEvent) => void; onFocus?: (event: FocusEvent) => void; onBlur?: (event: FocusEvent) => void; onChange?: (event: FormEvent) => void; onInput?: (event: FormEvent) => void; onSubmit?: (event: FormEvent) => void; onClick?: (event: MouseEvent) => void; onDoubleClick?: (event: MouseEvent) => void; onDrag?: (event: MouseEvent) => void; onDragEnd?: (event: MouseEvent) => void; onDragEnter?: (event: MouseEvent) => void; onDragExit?: (event: MouseEvent) => void; onDragLeave?: (event: MouseEvent) => void; onDragOver?: (event: MouseEvent) => void; onDragStart?: (event: MouseEvent) => void; onDrop?: (event: MouseEvent) => void; onMouseDown?: (event: MouseEvent) => void; onMouseEnter?: (event: MouseEvent) => void; onMouseLeave?: (event: MouseEvent) => void; onMouseMove?: (event: MouseEvent) => void; onMouseUp?: (event: MouseEvent) => void; onTouchCancel?: (event: TouchEvent) => void; onTouchEnd?: (event: TouchEvent) => void; onTouchMove?: (event: TouchEvent) => void; onTouchStart?: (event: TouchEvent) => void; onScroll?: (event: UIEvent) => void; onWheel?: (event: WheelEvent) => void; } interface ReactAttributes { key?: string; ref?: string; } interface HTMLGlobalAttributes extends ReactAttributes, ReactEvents { key?: string; accessKey?: string; className?: string; contentEditable?: string; contextMenu?: string; dir?: string; draggable?: boolean; hidden?: boolean; id?: string; lang?: string; spellCheck?: boolean; role?: string; scrollLeft?: number; scrollTop?: number; style?: { [styleNam: string]: string }; tabIndex?: number; title?: string; dangerouslySetInnerHTML?: { __html: string; }; } interface FormAttributes extends HTMLGlobalAttributes { accept?: string; action?: string; autoCapitalize?: string; autoComplete?: string; encType?: string; method?: string; name?: string; target?: string; } interface InputAttributes extends HTMLGlobalAttributes { accept?: string; alt?: string; autoCapitalize?: string; autoComplete?: string; autoFocus?: boolean; checked?: any; defaultValue?: any; disabled?: boolean; form?: string; height?: number; list?: string; max?: number; maxLength?: number; min?: number; multiple?: boolean; name?: string; pattern?: string; placeholder?: string; readOnly?: boolean; required?: boolean; size?: number; src?: string; step?: number; type?: string; value?: string; width?: number; } interface IframeAttributes extends HTMLGlobalAttributes { allowFullScreen?: boolean; allowTransparency?: boolean; frameBorder?: number; height?: number; name?: string; src?: string; width?: number; } interface AppletAttributes extends HTMLGlobalAttributes { alt?: string; } interface AreaAttributes extends HTMLGlobalAttributes { alt?: string; href?: string; rel?: string; target?: string; } interface ImgAttributes extends HTMLGlobalAttributes { alt?: string; height?: number; src?: string; width?: number; } interface ButtonAttributes extends HTMLGlobalAttributes { autoFocus?: boolean; disabled?: boolean; form?: string; name?: string; type?: string; value?: string; } interface KeygenAttributes extends HTMLGlobalAttributes { autoFocus?: boolean; form?: string; name?: string; } interface SelectAttributes extends HTMLGlobalAttributes { autoFocus?: boolean; disabled?: boolean; form?: string; multiple?: boolean; name?: string; required?: boolean; size?: number; } interface TextareaAttributes extends HTMLGlobalAttributes { autoFocus?: boolean; form?: string; maxLength?: string; name?: string; placeholder?: string; readOnly?: string; required?: boolean; } interface AudioAttributes extends HTMLGlobalAttributes { autoPlay?: boolean; controls?: boolean; loop?: boolean; preload?: string; src?: string; } interface VideoAttributes extends HTMLGlobalAttributes { autoPlay?: boolean; controls?: boolean; height?: number; loop?: boolean; poster?: string; preload?: string; src?: string; width?: number; } interface TableAttributes extends HTMLGlobalAttributes { cellPadding?: number; cellSpacing?: number; } interface MetaAttributes extends HTMLGlobalAttributes { charSet?: string; content?: string; httpEquiv?: string; name?: string; } interface ScriptAttributes extends HTMLGlobalAttributes { charSet?: string; src?: string; type?: string; } interface CommandAttributes extends HTMLGlobalAttributes { checked?: boolean; icon?: string; radioGroup?: string; type?: string; } interface TdAttributes extends HTMLGlobalAttributes { colSpan?: number; rowSpan?: number; } interface ThAttributes extends HTMLGlobalAttributes { colSpan?: number; rowSpan?: number; } interface ObjectAttributes extends HTMLGlobalAttributes { data?: string; form?: string; height?: number; name?: string; type?: string; width?: number; wmode?: string; } interface DelAttributes extends HTMLGlobalAttributes { dateTime?: Date; } interface InsAttributes extends HTMLGlobalAttributes { dateTime?: Date; } interface TimeAttributes extends HTMLGlobalAttributes { dateTime?: Date; } interface FieldsetAttributes extends HTMLGlobalAttributes { form?: string; name?: string; } interface LabelAttributes extends HTMLGlobalAttributes { form?: string; htmlFor?: string; } interface MeterAttributes extends HTMLGlobalAttributes { form?: string; max?: number; min?: number; value?: number; } interface OutputAttributes extends HTMLGlobalAttributes { form?: string; htmlFor?: string; name?: string; } interface ProgressAttributes extends HTMLGlobalAttributes { form?: string; max?: number; value?: number; } interface CanvasAttributes extends HTMLGlobalAttributes { height?: number; width?: number; } interface EmbedAttributes extends HTMLGlobalAttributes { height?: number; src?: string; type?: string; width?: number; } interface AAttributes extends HTMLGlobalAttributes { href?: string; rel?: string; target?: string; } interface BaseAttributes extends HTMLGlobalAttributes { href?: string; target?: string; } interface LinkAttributes extends HTMLGlobalAttributes { href?: string; rel?: string; } interface TrackAttributes extends HTMLGlobalAttributes { label?: string; src?: string; } interface BgsoundAttributes extends HTMLGlobalAttributes { loop?: boolean; } interface MarqueeAttributes extends HTMLGlobalAttributes { loop?: boolean; } interface MapAttributes extends HTMLGlobalAttributes { name?: string; } interface ParamAttributes extends HTMLGlobalAttributes { name?: string; value?: string; } interface OptionAttributes extends HTMLGlobalAttributes { selected?: boolean; value?: string; } interface SourceAttributes extends HTMLGlobalAttributes { src?: string; type?: string; } interface StyleAttributes extends HTMLGlobalAttributes { type?: string; } interface MenuAttributes extends HTMLGlobalAttributes { type?: string; } interface LiAttributes extends HTMLGlobalAttributes { value?: string; } interface SVGAttributes extends ReactAttributes, ReactEvents { id?: string; cx?: number; cy?: number; d?: number; fill?: string; fx?: number; fy?: number; gradientTransform?: any; gradientUnits?: string; offset?: number; points?: any; r?: number; rx?: number; ry?: number; spreadMethod?: string; stopColor?: string; stopOpacity?: number; stroke?: string; strokeLinecap?: string; strokeWidth?: number; transform?: string; version?: number; viewBox?: any; x1?: number; x2?: number; x?: number; y1?: number; y2?: number; y?: number; } export var DOM: { a: ReactComponentFactory<AAttributes>; abbr: ReactComponentFactory<HTMLGlobalAttributes>; address: ReactComponentFactory<HTMLGlobalAttributes>; area: ReactComponentFactory<AreaAttributes>; article: ReactComponentFactory<HTMLGlobalAttributes>; aside: ReactComponentFactory<HTMLGlobalAttributes>; audio: ReactComponentFactory<AudioAttributes>; b: ReactComponentFactory<HTMLGlobalAttributes>; base: ReactComponentFactory<BaseAttributes>; bdi: ReactComponentFactory<HTMLGlobalAttributes>; bdo: ReactComponentFactory<HTMLGlobalAttributes>; big: ReactComponentFactory<HTMLGlobalAttributes>; blockquote: ReactComponentFactory<HTMLGlobalAttributes>; body: ReactComponentFactory<HTMLGlobalAttributes>; br: ReactComponentFactory<HTMLGlobalAttributes>; button: ReactComponentFactory<ButtonAttributes>; canvas: ReactComponentFactory<CanvasAttributes>; caption: ReactComponentFactory<HTMLGlobalAttributes>; cite: ReactComponentFactory<HTMLGlobalAttributes>; code: ReactComponentFactory<HTMLGlobalAttributes>; col: ReactComponentFactory<HTMLGlobalAttributes>; colgroup: ReactComponentFactory<HTMLGlobalAttributes>; data: ReactComponentFactory<HTMLGlobalAttributes>; datalist: ReactComponentFactory<HTMLGlobalAttributes>; dd: ReactComponentFactory<HTMLGlobalAttributes>; del: ReactComponentFactory<DelAttributes>; details: ReactComponentFactory<HTMLGlobalAttributes>; dfn: ReactComponentFactory<HTMLGlobalAttributes>; div: ReactComponentFactory<HTMLGlobalAttributes>; dl: ReactComponentFactory<HTMLGlobalAttributes>; dt: ReactComponentFactory<HTMLGlobalAttributes>; em: ReactComponentFactory<HTMLGlobalAttributes>; embed: ReactComponentFactory<EmbedAttributes>; fieldset: ReactComponentFactory<FieldsetAttributes>; figcaption: ReactComponentFactory<HTMLGlobalAttributes>; figure: ReactComponentFactory<HTMLGlobalAttributes>; footer: ReactComponentFactory<HTMLGlobalAttributes>; form: ReactComponentFactory<FormAttributes>; h1: ReactComponentFactory<HTMLGlobalAttributes>; h2: ReactComponentFactory<HTMLGlobalAttributes>; h3: ReactComponentFactory<HTMLGlobalAttributes>; h4: ReactComponentFactory<HTMLGlobalAttributes>; h5: ReactComponentFactory<HTMLGlobalAttributes>; h6: ReactComponentFactory<HTMLGlobalAttributes>; head: ReactComponentFactory<HTMLGlobalAttributes>; header: ReactComponentFactory<HTMLGlobalAttributes>; hr: ReactComponentFactory<HTMLGlobalAttributes>; html: ReactComponentFactory<HTMLGlobalAttributes>; i: ReactComponentFactory<HTMLGlobalAttributes>; iframe: ReactComponentFactory<IframeAttributes>; img: ReactComponentFactory<ImgAttributes>; input: ReactComponentFactory<InputAttributes>; ins: ReactComponentFactory<InsAttributes>; kbd: ReactComponentFactory<HTMLGlobalAttributes>; keygen: ReactComponentFactory<KeygenAttributes>; label: ReactComponentFactory<LabelAttributes>; legend: ReactComponentFactory<HTMLGlobalAttributes>; li: ReactComponentFactory<LiAttributes>; link: ReactComponentFactory<LinkAttributes>; main: ReactComponentFactory<HTMLGlobalAttributes>; map: ReactComponentFactory<MapAttributes>; mark: ReactComponentFactory<HTMLGlobalAttributes>; menu: ReactComponentFactory<MenuAttributes>; menuitem: ReactComponentFactory<HTMLGlobalAttributes>; meta: ReactComponentFactory<MetaAttributes>; meter: ReactComponentFactory<MeterAttributes>; nav: ReactComponentFactory<HTMLGlobalAttributes>; noscript: ReactComponentFactory<HTMLGlobalAttributes>; object: ReactComponentFactory<ObjectAttributes>; ol: ReactComponentFactory<HTMLGlobalAttributes>; optgroup: ReactComponentFactory<HTMLGlobalAttributes>; option: ReactComponentFactory<OptionAttributes>; output: ReactComponentFactory<OutputAttributes>; p: ReactComponentFactory<HTMLGlobalAttributes>; param: ReactComponentFactory<ParamAttributes>; pre: ReactComponentFactory<HTMLGlobalAttributes>; progress: ReactComponentFactory<ProgressAttributes>; q: ReactComponentFactory<HTMLGlobalAttributes>; rp: ReactComponentFactory<HTMLGlobalAttributes>; rt: ReactComponentFactory<HTMLGlobalAttributes>; ruby: ReactComponentFactory<HTMLGlobalAttributes>; s: ReactComponentFactory<HTMLGlobalAttributes>; samp: ReactComponentFactory<HTMLGlobalAttributes>; script: ReactComponentFactory<ScriptAttributes>; section: ReactComponentFactory<HTMLGlobalAttributes>; select: ReactComponentFactory<SelectAttributes>; small: ReactComponentFactory<HTMLGlobalAttributes>; source: ReactComponentFactory<SourceAttributes>; span: ReactComponentFactory<HTMLGlobalAttributes>; strong: ReactComponentFactory<HTMLGlobalAttributes>; style: ReactComponentFactory<StyleAttributes>; sub: ReactComponentFactory<HTMLGlobalAttributes>; summary: ReactComponentFactory<HTMLGlobalAttributes>; sup: ReactComponentFactory<HTMLGlobalAttributes>; table: ReactComponentFactory<TableAttributes>; tbody: ReactComponentFactory<HTMLGlobalAttributes>; td: ReactComponentFactory<TdAttributes>; textarea: ReactComponentFactory<TextareaAttributes>; tfoot: ReactComponentFactory<HTMLGlobalAttributes>; th: ReactComponentFactory<ThAttributes>; thead: ReactComponentFactory<HTMLGlobalAttributes>; time: ReactComponentFactory<TimeAttributes>; title: ReactComponentFactory<HTMLGlobalAttributes>; tr: ReactComponentFactory<HTMLGlobalAttributes>; track: ReactComponentFactory<TrackAttributes>; u: ReactComponentFactory<HTMLGlobalAttributes>; ul: ReactComponentFactory<HTMLGlobalAttributes>; var: ReactComponentFactory<HTMLGlobalAttributes>; video: ReactComponentFactory<VideoAttributes>; wbr: ReactComponentFactory<HTMLGlobalAttributes>; //svg elements circle: ReactComponentFactory<SVGAttributes>; g: ReactComponentFactory<SVGAttributes>; line: ReactComponentFactory<SVGAttributes>; path: ReactComponentFactory<SVGAttributes>; polygon: ReactComponentFactory<SVGAttributes>; polyline: ReactComponentFactory<SVGAttributes>; rect: ReactComponentFactory<SVGAttributes>; svg: ReactComponentFactory<SVGAttributes>; text: ReactComponentFactory<SVGAttributes>; } }
the_stack
import { Account, AddressString, addressToScriptHash, Attribute, AttributeModel, Block, CallFlags, common, Contract, ForwardValue, GetOptions, Hash256String, InvokeSendUnsafeReceiveTransactionOptions, IterOptions, NetworkSettings, NetworkType, Param, ParamJSON, PublicKeyString, RawApplicationLogData, RawCallReceipt, RawInvokeReceipt, RawTransactionData, ScriptBuilder, ScriptBuilderParam, SourceMaps, Transaction, TransactionModel, TransactionOptions, TransactionReceipt, TransactionResult, Transfer, UInt160Hex, UserAccount, UserAccountID, utils, Witness, WitnessModel, } from '@neo-one/client-common'; import { AggregationType, globalStats, Measure, MeasureUnit, processActionsAndMessage, TagMap, } from '@neo-one/client-switch'; import { Labels, labelToTag, utils as commonUtils } from '@neo-one/utils'; import BigNumber from 'bignumber.js'; import debug from 'debug'; import { Observable } from 'rxjs'; import { clientUtils } from '../clientUtils'; import { InsufficientSystemFeeError, InvokeError, NoAccountError, NotImplementedError } from '../errors'; import { converters } from './converters'; const logger = debug('NEOONE:LocalUserAccountProvider'); const invokeTag = labelToTag(Labels.INVOKE_RAW_METHOD); export interface InvokeMethodOptions { readonly scriptHash: UInt160Hex; readonly params: ReadonlyArray<ScriptBuilderParam | undefined>; readonly invokeMethod: string; } export interface InvokeRawOptions<T extends TransactionReceipt> { readonly invokeMethodOptionsOrScript: InvokeMethodOptions | Buffer; readonly transfers?: readonly FullTransfer[]; readonly options?: TransactionOptions; readonly verify?: boolean; readonly onConfirm: (options: { readonly transaction: Transaction; readonly data: RawTransactionData; readonly receipt: TransactionReceipt; }) => Promise<T> | T; readonly method: string; readonly witnesses?: readonly WitnessModel[]; readonly labels?: Record<string, string>; readonly sourceMaps?: SourceMaps; } export interface ExecuteInvokeScriptOptions<T extends TransactionReceipt> { readonly script: Buffer; readonly from: UserAccountID; readonly attributes: readonly Attribute[]; readonly maxSystemFee: BigNumber; readonly maxNetworkFee: BigNumber; readonly validBlockCount: number; readonly witnesses: readonly WitnessModel[]; readonly onConfirm: (options: { readonly transaction: Transaction; readonly data: RawTransactionData; readonly receipt: TransactionReceipt; }) => Promise<T> | T; readonly sourceMaps?: SourceMaps; } export interface ExecuteInvokeMethodOptions<T extends TransactionReceipt> extends ExecuteInvokeScriptOptions<T> { readonly invokeMethodOptions: InvokeMethodOptions; } export interface Provider { readonly networks$: Observable<readonly NetworkType[]>; readonly getNetworks: () => readonly NetworkType[]; readonly getUnclaimed: (network: NetworkType, address: AddressString) => Promise<BigNumber>; readonly getTransactionReceipt: ( network: NetworkType, hash: Hash256String, options?: GetOptions, ) => Promise<TransactionReceipt>; readonly getApplicationLogData: (network: NetworkType, hash: Hash256String) => Promise<RawApplicationLogData>; readonly getTransactionData: (network: NetworkType, hash: Hash256String) => Promise<RawTransactionData>; readonly testInvoke: (network: NetworkType, script: Buffer) => Promise<RawCallReceipt>; readonly testTransaction: (network: NetworkType, transaction: TransactionModel) => Promise<RawCallReceipt>; readonly call: ( network: NetworkType, contract: UInt160Hex, method: string, params: ReadonlyArray<ScriptBuilderParam | undefined>, ) => Promise<RawCallReceipt>; readonly getNetworkSettings: (network: NetworkType) => Promise<NetworkSettings>; readonly getBlockCount: (network: NetworkType) => Promise<number>; readonly getFeePerByte: (network: NetworkType) => Promise<BigNumber>; readonly getExecFeeFactor: (network: NetworkType) => Promise<number>; readonly getTransaction: (network: NetworkType, hash: Hash256String) => Promise<Transaction>; readonly iterBlocks: (network: NetworkType, options?: IterOptions) => AsyncIterable<Block>; readonly getAccount: (network: NetworkType, address: AddressString) => Promise<Account>; readonly getContract: (network: NetworkType, address: AddressString) => Promise<Contract>; readonly getVerificationCost: ( network: NetworkType, hash: UInt160Hex, transaction: TransactionModel, ) => Promise<{ readonly fee: BigNumber; readonly size: number; }>; } interface TransactionOptionsFull { readonly from: UserAccountID; readonly attributes: readonly Attribute[]; readonly maxNetworkFee: BigNumber; readonly maxSystemFee: BigNumber; readonly validBlockCount: number; } const transferDurationSec = globalStats.createMeasureDouble('transfer/duration', MeasureUnit.SEC); const transferFailures = globalStats.createMeasureInt64('transfer/failures', MeasureUnit.UNIT); const claimDurationSec = globalStats.createMeasureDouble('claim/duration', MeasureUnit.SEC); const claimFailures = globalStats.createMeasureInt64('claim/failures', MeasureUnit.UNIT); const invokeDurationSec = globalStats.createMeasureDouble('invoke/duration', MeasureUnit.SEC); const invokeFailures = globalStats.createMeasureInt64('invoke/failures', MeasureUnit.UNIT); const NEO_TRANSFER_DURATION_SECONDS = globalStats.createView( 'neo_transfer_duration_seconds', transferDurationSec, AggregationType.DISTRIBUTION, [], 'Transfer durations in seconds', [1, 2, 5, 7.5, 10, 12.5, 15, 17.5, 20], ); globalStats.registerView(NEO_TRANSFER_DURATION_SECONDS); const NEO_TRANSFER_FAILURES_TOTAL = globalStats.createView( 'neo_transfer_failures_total', transferFailures, AggregationType.COUNT, [], 'Total transfer failures', ); globalStats.registerView(NEO_TRANSFER_FAILURES_TOTAL); const NEO_CLAIM_DURATION_SECONDS = globalStats.createView( 'neo_claim_duration_seconds', claimDurationSec, AggregationType.DISTRIBUTION, [], 'Claim durations in seconds', [1, 2, 5, 7.5, 10, 12.5, 15, 17.5, 20], ); globalStats.registerView(NEO_CLAIM_DURATION_SECONDS); const NEO_CLAIM_FAILURES_TOTAL = globalStats.createView( 'neo_claims_failures_total', claimFailures, AggregationType.COUNT, [], 'Total claims failures', ); globalStats.registerView(NEO_CLAIM_FAILURES_TOTAL); const NEO_INVOKE_RAW_DURATION_SECONDS = globalStats.createView( 'neo_invoke_raw_duration_seconds', invokeDurationSec, AggregationType.DISTRIBUTION, [invokeTag], 'Invoke durations in seconds', [1, 2, 5, 7.5, 10, 12.5, 15, 17.5, 20], ); globalStats.registerView(NEO_INVOKE_RAW_DURATION_SECONDS); const NEO_INVOKE_RAW_FAILURES_TOTAL = globalStats.createView( 'neo_invoke_raw_failures_total', invokeFailures, AggregationType.COUNT, [invokeTag], 'Total invocation failures', ); globalStats.registerView(NEO_INVOKE_RAW_FAILURES_TOTAL); interface FullTransfer extends Transfer { readonly from: UserAccountID; } export abstract class UserAccountProviderBase<TProvider extends Provider> { public readonly provider: TProvider; protected mutableBlockCount: number; public constructor({ provider }: { readonly provider: TProvider }) { this.provider = provider; this.mutableBlockCount = 0; } public getCurrentUserAccount(): UserAccount | undefined { throw new NotImplementedError('getCurrentUserAccount'); } public getUserAccounts(): readonly UserAccount[] { throw new NotImplementedError('getUserAccounts'); } public getNetworks(): readonly NetworkType[] { throw new NotImplementedError('getNetworks'); } public async selectUserAccount(_id?: UserAccountID): Promise<void> { throw new NotImplementedError('selectUserAccount'); } public iterBlocks(network: NetworkType, options?: IterOptions): AsyncIterable<Block> { return this.provider.iterBlocks(network, options); } public async getBlockCount(network: NetworkType): Promise<number> { return this.provider.getBlockCount(network); } public async getAccount(network: NetworkType, address: AddressString): Promise<Account> { return this.provider.getAccount(network, address); } public async transfer(transfers: readonly Transfer[], options?: TransactionOptions): Promise<TransactionResult> { const { from, attributes, maxNetworkFee, maxSystemFee, validBlockCount } = this.getTransactionOptions(options); return this.capture( async () => this.executeTransfer(transfers, from, attributes, maxNetworkFee, maxSystemFee, validBlockCount), { name: 'neo_transfer', measures: { total: transferDurationSec, error: transferFailures, }, }, ); } public async claim(options?: TransactionOptions): Promise<TransactionResult> { const { from, attributes, maxNetworkFee, maxSystemFee, validBlockCount } = this.getTransactionOptions(options); return this.capture(async () => this.executeClaim(from, attributes, maxNetworkFee, maxSystemFee, validBlockCount), { name: 'neo_claim', measures: { total: claimDurationSec, error: claimFailures, }, }); } public async vote(publicKey: PublicKeyString, options?: TransactionOptions): Promise<TransactionResult> { const { from, attributes, maxNetworkFee, maxSystemFee, validBlockCount } = this.getTransactionOptions(options); return this.capture( async () => this.executeVote(publicKey, from, attributes, maxNetworkFee, maxSystemFee, validBlockCount), { name: 'neo_vote' }, ); } public async invoke( contract: AddressString, method: string, params: ReadonlyArray<ScriptBuilderParam | undefined>, paramsZipped: ReadonlyArray<readonly [string, Param | undefined]>, verify: boolean, options: InvokeSendUnsafeReceiveTransactionOptions = {}, sourceMaps: SourceMaps = {}, ): Promise<TransactionResult<RawInvokeReceipt>> { const { attributes = [] } = options; const transactionOptions = this.getTransactionOptions(options); const { from } = transactionOptions; const send = options.sendFrom === undefined ? [] : options.sendFrom; const receive = options.sendTo === undefined ? [] : options.sendTo; const contractID: UserAccountID = { address: contract, network: from.network, }; return this.invokeRaw({ invokeMethodOptionsOrScript: { scriptHash: addressToScriptHash(contract), invokeMethod: method, params, }, transfers: send .map((transfer) => ({ ...transfer, from: contractID })) .concat(receive.map((transfer) => ({ ...transfer, from, to: contract }))), options: { ...transactionOptions, attributes: attributes.concat( this.getInvokeAttributes( contract, method, paramsZipped, // If we are sending from the contract, the script is already added as an input verify && options.sendFrom === undefined && options.sendTo !== undefined, // If we are sending to the contract, the script is already added as an input // If we are sending from the contract, the script will not be automatically added in sendTransaction options.sendTo === undefined && options.sendFrom !== undefined ? from.address : undefined, ), ), }, onConfirm: ({ receipt, data }): RawInvokeReceipt => ({ blockIndex: receipt.blockIndex, blockHash: receipt.blockHash, transactionIndex: receipt.transactionIndex, globalIndex: receipt.globalIndex, result: data.executionResult, actions: data.actions, }), witnesses: this.getInvokeScripts( method, params, verify && (options.sendFrom !== undefined || options.sendTo !== undefined), ), method: 'invoke', labels: { [Labels.INVOKE_METHOD]: method, }, sourceMaps, }); } public async call( network: NetworkType, contract: AddressString, method: string, params: ReadonlyArray<ScriptBuilderParam | undefined>, ): Promise<RawCallReceipt> { return this.provider.call(network, contract, method, params); } public async getSystemFee({ network, transaction, maxFee, }: { readonly network: NetworkType; readonly transaction: TransactionModel; readonly maxFee: BigNumber; }): Promise<BigNumber> { const callReceipt = await this.provider.testInvoke(network, transaction.script); if (callReceipt.result.state === 'FAULT') { const message = await processActionsAndMessage({ actions: callReceipt.actions, message: callReceipt.result.message, }); throw new InvokeError(message); } const gas = callReceipt.result.gasConsumed; if (gas.gt(utils.ZERO_BIG_NUMBER) && maxFee.lt(gas) && !maxFee.eq(utils.NEGATIVE_ONE_BIG_NUMBER)) { throw new InsufficientSystemFeeError(maxFee, gas); } return gas; } protected getTransactionOptions(options: TransactionOptions = {}): TransactionOptionsFull { const { attributes = [], maxNetworkFee = utils.ZERO_BIG_NUMBER, maxSystemFee = utils.ZERO_BIG_NUMBER, from: fromIn, validBlockCount = 86400000 / 15000 - 1, // TODO: should not be hardcoded. should come from network settings } = options; let from = fromIn; if (from === undefined) { const fromAccount = this.getCurrentUserAccount(); if (fromAccount === undefined) { throw new NoAccountError(); } from = fromAccount.id; } return { from, attributes, maxNetworkFee, maxSystemFee, validBlockCount, }; } // Keep this for now for if they add back transaction attributes later protected getInvokeAttributes( _contract: AddressString, _method: string, _paramsZipped: ReadonlyArray<readonly [string, Param | undefined]>, _verify: boolean, _from?: AddressString, ): readonly Attribute[] { return [].filter(commonUtils.notNull); } protected getInvokeScripts( method: string, params: ReadonlyArray<ScriptBuilderParam | undefined>, verify: boolean, ): readonly WitnessModel[] { return [ verify ? new WitnessModel({ invocation: clientUtils.getInvokeMethodInvocationScript({ method, params, }), verification: Buffer.alloc(0, 0), }) : undefined, ].filter(commonUtils.notNull); } protected addWitness({ transaction, witness, }: { readonly transaction: TransactionModel; readonly witness: WitnessModel; }): TransactionModel { return transaction.clone({ witnesses: [witness] }); } protected getInvokeAttributeTag( contract: AddressString, method: string, paramsZipped: ReadonlyArray<readonly [string, Param | undefined]>, ): string { return JSON.stringify({ contract, method, params: paramsZipped.map(([name, param]) => [name, this.paramToJSON(param)]), }); } protected paramToJSON(param: Param): ParamJSON | undefined { if (param === undefined) { return param; } if (Array.isArray(param)) { return param.map((value) => this.paramToJSON(value)); } if (BigNumber.isBigNumber(param) || param instanceof BigNumber) { return param.toString(); } if (typeof param === 'object') { return this.paramToJSON((param as ForwardValue).param); } return param; } protected convertAttributes(attributes: readonly Attribute[]): readonly AttributeModel[] { return attributes.map((attribute) => converters.attribute(attribute)); } protected convertWitness(script: Witness): WitnessModel { return converters.witness(script); } protected async capture<T>( func: () => Promise<T>, { name, labels = {}, measures, invoke = false, }: { readonly name: string; readonly labels?: Record<string, string>; readonly measures?: { readonly total?: Measure; readonly error?: Measure; }; readonly invoke?: boolean; }, ): Promise<T> { const tags = new TagMap(); if (invoke) { const value = labels[Labels.INVOKE_RAW_METHOD]; // tslint:disable-next-line: strict-type-predicates if (value === undefined) { throw new Error('Invocation should have an invoke method'); } tags.set(invokeTag, { value }); } const startTime = commonUtils.nowSeconds(); try { const result = await func(); logger('%o', { name, level: 'verbose', ...labels }); if (measures !== undefined && measures.total !== undefined) { globalStats.record( [ { measure: measures.total, value: commonUtils.nowSeconds() - startTime, }, ], tags, ); } return result; } catch (error) { logger('%o', { name, level: 'error', error: error.message, ...labels }); if (measures !== undefined && measures.error !== undefined) { globalStats.record( [ { measure: measures.error, value: 1, }, ], tags, ); } throw error; } } protected abstract async executeInvokeMethod<T extends TransactionReceipt>( options: ExecuteInvokeMethodOptions<T>, ): Promise<TransactionResult<T>>; protected abstract async executeInvokeScript<T extends TransactionReceipt>( options: ExecuteInvokeScriptOptions<T>, ): Promise<TransactionResult<T>>; protected abstract async executeTransfer( transfers: readonly Transfer[], from: UserAccountID, attributes: readonly Attribute[], maxNetworkFee: BigNumber, maxSystemFee: BigNumber, validBlockCount: number, ): Promise<TransactionResult>; protected abstract async executeClaim( from: UserAccountID, attributes: readonly Attribute[], maxNetworkFee: BigNumber, maxSystemFee: BigNumber, validBlockCount: number, ): Promise<TransactionResult>; protected abstract async executeVote( publicKey: PublicKeyString, from: UserAccountID, attributes: readonly Attribute[], maxNetworkFee: BigNumber, maxSystemFee: BigNumber, validBlockCount: number, ): Promise<TransactionResult>; protected async invokeRaw<T extends TransactionReceipt>({ invokeMethodOptionsOrScript, options = {}, onConfirm, method, witnesses = [], labels = {}, sourceMaps, transfers = [], }: InvokeRawOptions<T>) { const { from, attributes, maxSystemFee, maxNetworkFee, validBlockCount } = this.getTransactionOptions(options); const { script: scriptIn, invokeMethodOptions } = this.getScriptAndInvokeMethodOptions(invokeMethodOptionsOrScript); const sb = new ScriptBuilder(); transfers.forEach((transfer) => { sb.emitDynamicAppCall( common.stringToUInt160(transfer.asset), 'transfer', CallFlags.All, common.stringToUInt160(addressToScriptHash(transfer.from.address)), common.stringToUInt160(addressToScriptHash(transfer.to)), transfer.amount.toNumber(), {}, ); }); const script = Buffer.concat([sb.build(), scriptIn]); return this.capture( async () => invokeMethodOptions === undefined ? this.executeInvokeScript({ script, from, attributes, maxSystemFee, maxNetworkFee, validBlockCount, witnesses, onConfirm, sourceMaps, }) : this.executeInvokeMethod({ script, invokeMethodOptions, from, attributes, maxSystemFee, maxNetworkFee, validBlockCount, witnesses, onConfirm, sourceMaps, }), { name: 'neo_invoke_raw', invoke: true, measures: { total: invokeDurationSec, error: invokeFailures, }, labels: { [Labels.INVOKE_RAW_METHOD]: method, ...labels, }, }, ); } private getScriptAndInvokeMethodOptions(invokeMethodOptionsOrScript: InvokeMethodOptions | Buffer): { readonly script: Buffer; readonly invokeMethodOptions: InvokeMethodOptions | undefined; } { let script: Buffer; let invokeMethodOptions: InvokeMethodOptions | undefined; if (invokeMethodOptionsOrScript instanceof Buffer) { script = invokeMethodOptionsOrScript; } else { invokeMethodOptions = invokeMethodOptionsOrScript; const { scriptHash, invokeMethod, params } = invokeMethodOptions; script = clientUtils.getInvokeMethodScript({ scriptHash, method: invokeMethod, params, }); } return { script, invokeMethodOptions }; } }
the_stack
import {BoxrecRequests} from "boxrec-requests"; import { BoxrecLocationEventParams, BoxrecLocationsPeopleParams, BoxrecRole } from "boxrec-requests/dist/boxrec-requests.constants"; import * as fs from "fs"; import {WriteStream} from "fs"; import {CookieJar, RequestResponse} from "request"; import {BoxrecPageChampions} from "./boxrec-pages/champions/boxrec.page.champions"; import {BoxrecPageDate} from "./boxrec-pages/date/boxrec.page.date"; import {BoxrecPageEventBout} from "./boxrec-pages/event/bout/boxrec.page.event.bout"; import {BoxrecPageEvent} from "./boxrec-pages/event/boxrec.page.event"; import {BoxrecPageLocationEvent} from "./boxrec-pages/location/event/boxrec.page.location.event"; import {BoxrecPageLocationBoxer} from "./boxrec-pages/location/people/boxrec.page.location.boxer"; import {BoxrecPageLocationPeople} from "./boxrec-pages/location/people/boxrec.page.location.people"; import {BoxrecPageProfileBoxer} from "./boxrec-pages/profile/boxrec.page.profile.boxer"; import {BoxrecPageProfileEvents} from "./boxrec-pages/profile/boxrec.page.profile.events"; import {BoxrecPageProfileManager} from "./boxrec-pages/profile/boxrec.page.profile.manager"; import {BoxrecPageProfileOtherCommon} from "./boxrec-pages/profile/boxrec.page.profile.other.common"; import {BoxrecPageProfilePromoter} from "./boxrec-pages/profile/boxrec.page.profile.promoter"; import {BoxrecPageRatings} from "./boxrec-pages/ratings/boxrec.page.ratings"; import {BoxrecRatingsParams} from "./boxrec-pages/ratings/boxrec.ratings.constants"; import {BoxrecResultsParams} from "./boxrec-pages/results/boxrec.results.constants"; import {BoxrecPageSchedule} from "./boxrec-pages/schedule/boxrec.page.schedule"; import {BoxrecScheduleParams} from "./boxrec-pages/schedule/boxrec.schedule.constants"; import {BoxrecPageSearch} from "./boxrec-pages/search/boxrec.page.search"; import {BoxrecSearch, BoxrecSearchParams, BoxrecStatus} from "./boxrec-pages/search/boxrec.search.constants"; import {BoxrecPageTitle} from "./boxrec-pages/title/boxrec.page.title"; import {BoxrecTitlesParams} from "./boxrec-pages/titles/boxrec.page.title.constants"; import {BoxrecPageTitles} from "./boxrec-pages/titles/boxrec.page.titles"; import {BoxrecPageVenue} from "./boxrec-pages/venue/boxrec.page.venue"; import {BoxrecPageWatch} from "./boxrec-pages/watch/boxrec.page.watch"; import {BoxrecPageWatchRow} from "./boxrec-pages/watch/boxrec.page.watch.row"; // https://github.com/Microsoft/TypeScript/issues/14151 if (typeof (Symbol as any).asyncIterator === "undefined") { (Symbol as any).asyncIterator = Symbol("asyncIterator"); } export class Boxrec { /** * Makes a request to BoxRec to log the user in * This is required before making any additional calls * The session cookie is stored inside this class and lost * Note: credentials are sent over HTTP, BoxRec doesn't support HTTPS * @param {string} username your BoxRec username * @param {string} password your BoxRec password * @returns {Promise<CookieJar>} If the response is undefined, you have successfully logged in. * Otherwise an error will be thrown */ static async login(username: string, password: string): Promise<CookieJar> { return BoxrecRequests.login(username, password); } /** * Makes a request to BoxRec to get information about an individual bout * @param {jar} cookieJar * @param {string} eventBoutId * @returns {Promise<BoxrecPageEventBout>} */ static async getBoutById(cookieJar: CookieJar, eventBoutId: string): Promise<BoxrecPageEventBout> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getBout(cookieJar, eventBoutId); return new BoxrecPageEventBout(boxrecPageBody); } /** * Makes a request to BoxRec to return/save the PDF version of a boxer profile * @param {jar} cookieJar * @param {number} globalId the BoxRec global id of the boxer * @param {string} pathToSaveTo directory to save to. if not used will only return data * @param {string} fileName file name to save as. Will save as {globalId}.pdf as default. Add .pdf to end of filename * @returns {Promise<string>} */ static async getBoxerPDF(cookieJar: CookieJar, globalId: number, pathToSaveTo?: string, fileName?: string): Promise<string> { return this.getBoxerOther(cookieJar, globalId, "pdf", pathToSaveTo, fileName); } /** * Makes a request to BoxRec to return/save the printable version of a boxer profile * @param {jar} cookieJar * @param {number} globalId the BoxRec global id of the boxer * @param {string} pathToSaveTo directory to save to. if not used will only return data * @param {string} fileName file name to save as. Will save as {globalId}.html as default. Add .html to end of filename * @returns {Promise<string>} */ static async getBoxerPrint(cookieJar: CookieJar, globalId: number, pathToSaveTo?: string, fileName?: string): Promise<string> { return this.getBoxerOther(cookieJar, globalId, "print", pathToSaveTo, fileName); } /** * Makes a request to BoxRec to return a list of current champions * @param {jar} cookieJar * @returns {Promise<BoxrecPageChampions>} */ static async getChampions(cookieJar: CookieJar): Promise<BoxrecPageChampions> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getChampions(cookieJar); return new BoxrecPageChampions(boxrecPageBody); } /** * Makes a request to BoxRec to get events/bouts on the particular date * @param {jar} cookieJar * @param {string} dateString date to search for. Format ex. `2012-06-07` * @returns {Promise<void>} */ static async getDate(cookieJar: CookieJar, dateString: string): Promise<BoxrecPageDate> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getDate(cookieJar, dateString); return new BoxrecPageDate(boxrecPageBody); } /** * Makes a request to BoxRec to retrieve an event by id * @param {jar} cookieJar * @param {number} eventId the event id from BoxRec * @returns {Promise<BoxrecPageEvent>} */ static async getEventById(cookieJar: CookieJar, eventId: number): Promise<BoxrecPageEvent> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getEventById(cookieJar, eventId); return new BoxrecPageEvent(boxrecPageBody); } /** * Makes a request to BoxRec to list events by location * @param {jar} cookieJar * @param {BoxrecLocationEventParams} params params included in this search * @param {BoxrecLocationEventParams.sport} params.sports if this is not a valid option, will send strange results * @param {number} offset the number of rows to offset the search * @returns {Promise<BoxrecPageLocationEvent>} */ static async getEventsByLocation(cookieJar: CookieJar, params: BoxrecLocationEventParams, offset: number = 0): Promise<BoxrecPageLocationEvent> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getEvents(cookieJar, params, offset); return new BoxrecPageLocationEvent(boxrecPageBody); } /** * Make a request to BoxRec to search for people by location * @param {jar} cookieJar * @param {BoxrecLocationsPeopleParams} params params included in this search * @param {number} offset the number of rows to offset the search * @returns {Promise<BoxrecPageLocationPeople>} */ static async getPeopleByLocation(cookieJar: CookieJar, params: BoxrecLocationsPeopleParams, offset: number = 0): Promise<BoxrecPageLocationPeople | BoxrecPageLocationBoxer> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getPeople(cookieJar, params, offset); if (params.role === BoxrecRole.proBoxer) { return new BoxrecPageLocationBoxer(boxrecPageBody); } return new BoxrecPageLocationPeople(boxrecPageBody); } /** * Make a request to BoxRec to get a person by their BoxRec Global ID * @param {jar} cookieJar * @param {number} globalId the BoxRec profile id * @param {BoxrecRole} role the role of the person in boxing (there seems to be multiple profiles for people if they fall under different roles) * @param {number} offset offset number of bouts/events in the profile * We offset by number and not pages because the number of bouts per page may change * @returns {Promise<BoxrecPageProfileBoxer | BoxrecPageProfileOtherCommon | BoxrecPageProfileEvents | BoxrecPageProfileManager>} */ static async getPersonById(cookieJar: CookieJar, globalId: number, role: BoxrecRole | null = null, offset: number = 0): Promise<BoxrecPageProfileBoxer | BoxrecPageProfileOtherCommon | BoxrecPageProfileEvents | BoxrecPageProfileManager | BoxrecPageProfilePromoter> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getPersonById(cookieJar, globalId, role, offset); // there are 9 roles on the BoxRec website // the differences are that the boxers have 2 more columns `last6` for each boxer // the judge and others don't have those columns // the doctor and others have `events` // manager is unique in that the table is a list of boxers that they manage switch (role) { case BoxrecRole.proBoxer: return new BoxrecPageProfileBoxer(boxrecPageBody); case BoxrecRole.judge: case BoxrecRole.supervisor: case BoxrecRole.referee: return new BoxrecPageProfileOtherCommon(boxrecPageBody); case BoxrecRole.promoter: return new BoxrecPageProfilePromoter(boxrecPageBody); case BoxrecRole.doctor: case BoxrecRole.inspector: case BoxrecRole.matchmaker: return new BoxrecPageProfileEvents(boxrecPageBody); case BoxrecRole.manager: return new BoxrecPageProfileManager(boxrecPageBody); // todo we should be able to figure out the default role if one was not specified and use the correct class } // by default we'll use the boxer profile so at least some of the data will be returned return new BoxrecPageProfileBoxer(boxrecPageBody); } /** * Makes a request to BoxRec to get a list of ratings/rankings, either P4P or by a single weight class * @param {jar} cookieJar * @param {BoxrecRatingsParams} params params included in this search * @param {number} offset the number of rows to offset the search * @returns {Promise<BoxrecPageRatings>} */ static async getRatings(cookieJar: CookieJar, params: BoxrecRatingsParams, offset: number = 0): Promise<BoxrecPageRatings> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getRatings(cookieJar, params, offset); return new BoxrecPageRatings(boxrecPageBody); } /** * Makes a request to BoxRec to get a list of results. * Uses same class * @param {jar} cookieJar * @param {BoxrecResultsParams} params params included in this search * @param {number} offset the number of rows to offset this search * @returns {Promise<BoxrecPageSchedule>} */ static async getResults(cookieJar: CookieJar, params: BoxrecResultsParams, offset: number = 0): Promise<BoxrecPageSchedule> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getResults(cookieJar, params, offset); return new BoxrecPageSchedule(boxrecPageBody); } /** * Makes a request to BoxRec to get a list of scheduled events * @param {jar} cookieJar * @param {BoxrecScheduleParams} params params included in this search * @param {number} offset the number of rows to offset the search * @returns {Promise<BoxrecPageSchedule>} */ static async getSchedule(cookieJar: CookieJar, params: BoxrecScheduleParams, offset: number = 0): Promise<BoxrecPageSchedule> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getSchedule(cookieJar, params, offset); return new BoxrecPageSchedule(boxrecPageBody); } /** * Makes a request to BoxRec to the specific title URL to get a belt's history * @param {jar} cookieJar * @param {string} titleString in the format of "6/Middleweight" which would be the WBC Middleweight title * @param {number} offset the number of rows to offset the search * @returns {Promise<BoxrecPageTitle>} */ static async getTitleById(cookieJar: CookieJar, titleString: string, offset: number = 0): Promise<BoxrecPageTitle> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getTitleById(cookieJar, titleString, offset); return new BoxrecPageTitle(boxrecPageBody); } /** * Makes a request to BoxRec to return scheduled and previous bouts in regards to a belt/division * @param {jar} cookieJar * @param {BoxrecTitlesParams} params * @param {number} offset * @returns {Promise<any>} */ static async getTitles(cookieJar: CookieJar, params: BoxrecTitlesParams, offset: number = 0): Promise<any> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getTitles(cookieJar, params, offset); return new BoxrecPageTitles(boxrecPageBody); } /** * Makes a request to BoxRec to get the information of a venue * @param {jar} cookieJar * @param {number} venueId * @param {number} offset the number of rows to offset the search * @returns {Promise<BoxrecPageVenue>} */ static async getVenueById(cookieJar: CookieJar, venueId: number, offset: number = 0): Promise<BoxrecPageVenue> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getVenueById(cookieJar, venueId, offset); return new BoxrecPageVenue(boxrecPageBody); } /** * Lists all boxers that are watched by the user * @param {jar} cookieJar * @returns {Promise<BoxrecPageWatchRow>} */ static async getWatched(cookieJar: CookieJar): Promise<BoxrecPageWatchRow[]> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.getWatched(cookieJar); return new BoxrecPageWatch(boxrecPageBody).list; } /** * Makes a request to BoxRec to search people by name, role and if they are active * Note: currently only supports boxers * @param {jar} cookieJar * @param {BoxrecSearchParams} params params included in this search * @param {number} offset the number of rows to offset the search * @returns {Promise<BoxrecSearch[]>} */ static async search(cookieJar: CookieJar, params: BoxrecSearchParams, offset: number = 0): Promise<BoxrecSearch[]> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.search(cookieJar, params, offset); return new BoxrecPageSearch(boxrecPageBody).results; } /** * Removes the boxer from the users watch list, returns true if they were successfully removed * @param {jar} cookieJar * @param {number} boxerGlobalId * @returns {Promise<boolean>} */ static async unwatch(cookieJar: CookieJar, boxerGlobalId: number): Promise<boolean> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.unwatch(cookieJar, boxerGlobalId); const isBoxerInList: boolean = new BoxrecPageWatch(boxrecPageBody).checkForBoxerInList(boxerGlobalId); if (isBoxerInList) { throw new Error("Boxer appears in list after being removed"); } return !isBoxerInList; } /** * Adds the boxer to the users watch list, returns true if they were successfully added to the list * @param {jar} cookieJar * @param {number} boxerGlobalId * @returns {Promise<boolean>} */ static async watch(cookieJar: CookieJar, boxerGlobalId: number): Promise<boolean> { const boxrecPageBody: RequestResponse["body"] = await BoxrecRequests.watch(cookieJar, boxerGlobalId); const isBoxerInList: boolean = new BoxrecPageWatch(boxrecPageBody).checkForBoxerInList(boxerGlobalId); if (!isBoxerInList) { throw new Error("Boxer did not appear in list after being added"); } return isBoxerInList; } /** * Makes a search request to BoxRec to get all people that match that name * by using a generator, we're able to prevent making too many calls to BoxRec * @param {jar} cookieJar * @param {string} firstName the person's first name * @param {string} lastName the person's last name * @param {string} role the role of the person * @param {BoxrecStatus} status whether the person is active in Boxing or not * @param {number} offset the number of rows to offset the search * @yields {BoxrecPageProfileBoxer | BoxrecPageProfileOtherCommon | BoxrecPageProfileEvents | BoxrecPageProfileManager} returns a generator to fetch the next person by ID */ // todo remove async static async* getPeopleByName(cookieJar: CookieJar, firstName: string, lastName: string, role: BoxrecRole = BoxrecRole.proBoxer, status: BoxrecStatus = BoxrecStatus.all, offset: number = 0): AsyncIterableIterator<BoxrecPageProfileBoxer | BoxrecPageProfileOtherCommon | BoxrecPageProfileEvents | BoxrecPageProfileManager> { const params: BoxrecSearchParams = { first_name: firstName, last_name: lastName, role, status, }; const searchResults: RequestResponse["body"] = await Boxrec.search(cookieJar, params, offset); for (const result of searchResults) { yield await Boxrec.getPersonById(cookieJar, result.id); } } /** * Returns/saves a boxer's profile in print/pdf format * @param {jar} cookieJar * @param {number} globalId * @param {"pdf" | "print"} type * @param {string} pathToSaveTo * @param {string} fileName * @returns {Promise<string>} */ private static async getBoxerOther(cookieJar: CookieJar, globalId: number, type: "pdf" | "print", pathToSaveTo?: string, fileName?: string): Promise<string> { let boxrecPageBody: RequestResponse["body"]; if (type === "pdf") { boxrecPageBody = await BoxrecRequests.getBoxerPDF(cookieJar, globalId, pathToSaveTo, fileName); } else { boxrecPageBody = await BoxrecRequests.getBoxerPrint(cookieJar, globalId, pathToSaveTo, fileName); } if (pathToSaveTo) { let fileNameToSaveAs: string; if (fileName) { fileNameToSaveAs = fileName; } else { fileNameToSaveAs = `${globalId}.` + (type === "pdf" ? "pdf" : "html"); } let updatedPathToSave: string = pathToSaveTo; if (updatedPathToSave.slice(-1) !== "/") { updatedPathToSave += "/"; } const file: WriteStream = fs.createWriteStream(updatedPathToSave + fileNameToSaveAs); boxrecPageBody.pipe(file); } return boxrecPageBody; } }
the_stack
import React from 'react' import applyDevTools from 'prosemirror-dev-tools' import { EditorState, Selection, Transaction } from 'prosemirror-state'; import { DirectEditorProps, EditorView } from 'prosemirror-view'; import { Node as PMNode } from 'prosemirror-model'; import { PortalProviderAPI } from './react-portals' import { EventDispatcher, createDispatch, Dispatch } from './utils/event-dispatcher' import { ProviderFactory } from './provider-factory/ProviderFactory' import { startMeasure, stopMeasure } from './performance/measure' import { findChangedNodesFromTransaction, validateNodes, validNode, } from './utils/nodes' import { getDocStructure, SimplifiedNode } from './utils/document-logger'; import { createPMPlugins, processPluginsList } from './create-editor/create-plugins' import { createPluginsList } from './create-editor/create-plugins-list' import { createSchema } from './create-editor/create-schema' import { getUAPrefix } from './utils/browser' import { EditorProps } from './Editor' import { EditorConfig, EditorPlugin } from './types' export interface EditorViewProps { editorProps: EditorProps; providerFactory: ProviderFactory; portalProviderAPI: PortalProviderAPI; render?: (props: { editor: JSX.Element; view?: EditorView; config: EditorConfig; eventDispatcher: EventDispatcher; }) => JSX.Element onEditorCreated: (instance: { view: EditorView; config: EditorConfig; eventDispatcher: EventDispatcher; // transformer?: Transformer<string>; }) => void; onEditorDestroyed: (instance: { view: EditorView; config: EditorConfig; eventDispatcher: EventDispatcher; // transformer?: Transformer<string>; }) => void; } export class ReactEditorView extends React.Component<EditorViewProps, {}> { config!: EditorConfig; editorState: EditorState editorView?: EditorView eventDispatcher: EventDispatcher dispatch: Dispatch // ProseMirror is instantiated prior to the initial React render cycle, // so we allow transactions by default, to avoid discarding the initial one. private canDispatchTransactions = true; private focusTimeoutId: number | undefined; constructor(props: EditorViewProps) { super(props) this.eventDispatcher = new EventDispatcher() this.dispatch = createDispatch(this.eventDispatcher) this.editorState = this.createEditorState({ props, replaceDoc: true, }) } componentDidMount() { // Transaction dispatching is already enabled by default prior to // mounting, but we reset it here, just in case the editor view // instance is ever recycled (mounted again after unmounting) with // the same key. // Although storing mounted state is an anti-pattern in React, // we do so here so that we can intercept and abort asynchronous // ProseMirror transactions when a dismount is imminent. this.canDispatchTransactions = true; } /** * Clean up any non-PM resources when the editor is unmounted */ componentWillUnmount() { // We can ignore any transactions from this point onwards. // This serves to avoid potential runtime exceptions which could arise // from an async dispatched transaction after it's unmounted. // this.canDispatchTransactions = false; this.eventDispatcher.destroy(); clearTimeout(this.focusTimeoutId); if (this.editorView) { // Destroy the state if the Editor is being unmounted const editorState = this.editorView.state; editorState.plugins.forEach(plugin => { const state = plugin.getState(editorState); if (state && state.destroy) { state.destroy(); } }); } // this.editorView will be destroyed when React unmounts in handleEditorViewRef } // Helper to allow tests to inject plugins directly getPlugins( editorProps: EditorProps, prevEditorProps?: EditorProps, ): EditorPlugin[] { return createPluginsList(editorProps, prevEditorProps); } createEditorState = (options: { props: EditorViewProps; replaceDoc?: boolean; }) => { if (this.editorView) { /** * There's presently a number of issues with changing the schema of a * editor inflight. A significant issue is that we lose the ability * to keep track of a user's history as the internal plugin state * keeps a list of Steps to undo/redo (which are tied to the schema). * Without a good way to do work around this, we prevent this for now. */ // eslint-disable-next-line no-console console.warn( 'The editor does not support changing the schema dynamically.', ); return this.editorState; } this.config = processPluginsList( this.getPlugins( options.props.editorProps, undefined, ), ); const schema = createSchema(this.config); const plugins = createPMPlugins({ schema, dispatch: this.dispatch, editorConfig: this.config, eventDispatcher: this.eventDispatcher, providerFactory: options.props.providerFactory, portalProviderAPI: this.props.portalProviderAPI, }); let doc; let selection: Selection | undefined; if (doc) { // ED-4759: Don't set selection at end for full-page editor - should be at start selection = options.props.editorProps.appearance === 'full-page' ? Selection.atStart(doc) : Selection.atEnd(doc); } // Workaround for ED-3507: When media node is the last element, scrollIntoView throws an error const patchedSelection = selection ? Selection.findFrom(selection.$head, -1, true) || undefined : undefined; return EditorState.create({ schema, plugins, doc, selection: patchedSelection, }); }; reconfigureState = (props: EditorViewProps) => { if (!this.editorView) { return; } // We cannot currently guarantee when all the portals will have re-rendered during a reconfigure // so we blur here to stop ProseMirror from trying to apply selection to detached nodes or // nodes that haven't been re-rendered to the document yet. if (this.editorView.dom instanceof HTMLElement && this.editorView.hasFocus()) { this.editorView.dom.blur(); } this.config = processPluginsList( this.getPlugins( props.editorProps, this.props.editorProps, ), ); const state = this.editorState; const plugins = createPMPlugins({ schema: state.schema, dispatch: this.dispatch, editorConfig: this.config, eventDispatcher: this.eventDispatcher, providerFactory: props.providerFactory, portalProviderAPI: props.portalProviderAPI, }); const newState = state.reconfigure({ plugins }); // need to update the state first so when the view builds the nodeviews it is // using the latest plugins this.editorView.updateState(newState); return this.editorView.update({ ...this.editorView.props, state: newState }); } private dispatchTransaction = (transaction: Transaction) => { if (!this.editorView) { return; } const shouldTrack = true shouldTrack && startMeasure(`🦉 ReactEditorView::dispatchTransaction`); const nodes: PMNode[] = findChangedNodesFromTransaction(transaction); const changedNodesValid = validateNodes(nodes); if (changedNodesValid) { const oldEditorState = this.editorView.state; // go ahead and update the state now we know the transaction is good shouldTrack && startMeasure(`🦉 EditorView::state::apply`); const editorState = this.editorView.state.apply(transaction); shouldTrack && stopMeasure(`🦉 EditorView::state::apply`); if (editorState === oldEditorState) { return; } shouldTrack && startMeasure(`🦉 EditorView::updateState`); this.editorView.updateState(editorState); shouldTrack && stopMeasure(`🦉 EditorView::updateState`); this.editorState = editorState; } else { const invalidNodes = nodes .filter(node => !validNode(node)) .map<SimplifiedNode | string>(node => getDocStructure(node)); if (shouldTrack) { console.error('Invalid nodes in transaction') console.log(transaction) console.log(invalidNodes) } } shouldTrack && stopMeasure(`🦉 ReactEditorView::dispatchTransaction`, () => {}); } getDirectEditorProps = (state?: EditorState): DirectEditorProps => { return { state: state || this.editorState, dispatchTransaction: (tr: Transaction) => { // Block stale transactions: // Prevent runtime exceptions from async transactions that would attempt to // update the DOM after React has unmounted the Editor. if (this.canDispatchTransactions) { this.dispatchTransaction(tr); } }, // Disables the contentEditable attribute of the editor if the editor is disabled editable: _state => true, // !this.props.editorProps.disabled, attributes: { 'data-gramm': 'false' }, } } createEditorView(element: HTMLDivElement) { // Creates the editor-view from this.editorState. If an editor has been mounted // previously, this will contain the previous state of the editor. this.editorView = new EditorView({ mount: element }, this.getDirectEditorProps()) applyDevTools(this.editorView!) } handleEditorViewRef = (node: HTMLDivElement) => { if (!this.editorView && node) { this.createEditorView(node); const view = this.editorView!; this.props.onEditorCreated({ view, config: this.config, eventDispatcher: this.eventDispatcher, // transformer: this.contentTransformer, }); if ( this.props.editorProps.shouldFocus ) { this.focusTimeoutId = handleEditorFocus(view); } // Force React to re-render so consumers get a reference to the editor view this.forceUpdate(); } else if (this.editorView && !node) { // When the appearance is changed, React will call handleEditorViewRef with node === null // to destroy the old EditorView, before calling this method again with node === div to // create the new EditorView this.props.onEditorDestroyed({ view: this.editorView, config: this.config, eventDispatcher: this.eventDispatcher, }); this.editorView.destroy(); // Destroys the dom node & all node views this.editorView = undefined; } } private editor = ( <div className={getUAPrefix()} key="ProseMirror" ref={this.handleEditorViewRef} /> ) render() { return this.props.render ? this.props.render({ editor: this.editor, view: this.editorView, config: this.config, eventDispatcher: this.eventDispatcher, }) : this.editor } } function handleEditorFocus(view: EditorView): number | undefined { if (view.hasFocus()) { return; } return window.setTimeout(() => { view.focus(); }, 0); }
the_stack
import * as React from 'react'; import { eventFrom, setEventFrom, EventFromInput } from 'event-from'; import { stateChanged, enterKeyTrigger, spaceKeyTrigger, cursorPointer, elementSupportsDisabled, classNameToString, setUserSelectNone, resetUserSelect, } from './utils'; import { PolymorphicForwardRefExoticComponent, PolymorphicPropsWithoutRef, PolymorphicPropsWithRef, PolymorphicMemoExoticComponent, } from 'react-polymorphic-types'; export { eventFrom, setEventFrom, EventFromInput }; export type ActiveState = 'mouseActive' | 'touchActive' | 'keyActive' | false; export type FocusState = | 'focusFromMouse' | 'focusFromTouch' | 'focusFromKey' | false; /** * State object used by React Interactive to determine how the `<Interactive>` component is rendered. * The InteractiveState object is also passed to the `onStateChange` callback and `children` (when `children` is a function). */ export interface InteractiveState { hover: boolean; active: ActiveState; focus: FocusState; } export type InteractiveStateKey = 'hover' | 'active' | 'focus'; /** * InteractiveStateChange is the type for the argument passed to the `onStateChange` callback. */ export interface InteractiveStateChange { state: InteractiveState; prevState: InteractiveState; } const initialState: InteractiveState = { hover: false, active: false, focus: false, }; // event listeners set by RI const eventMap: Record<string, string> = { mouseover: 'onMouseOver', mouseleave: 'onMouseLeave', mousedown: 'onMouseDown', mouseup: 'onMouseUp', pointerover: 'onPointerOver', pointerleave: 'onPointerLeave', pointerdown: 'onPointerDown', pointerup: 'onPointerUp', pointercancel: 'onPointerCancel', touchstart: 'onTouchStart', touchend: 'onTouchEnd', touchcancel: 'onTouchCancel', keydown: 'onKeyDown', keyup: 'onKeyUp', focus: 'onFocus', blur: 'onBlur', dragstart: 'onDragStart', dragend: 'onDragEnd', }; const eventListenerPropNames = Object.values(eventMap); const defaultAs = 'button'; export interface InteractiveOwnProps { children?: React.ReactNode | ((state: InteractiveState) => React.ReactNode); onStateChange?: ({ state, prevState }: InteractiveStateChange) => void; disabled?: boolean; useExtendedTouchActive?: boolean; hoverClassName?: string; activeClassName?: string; mouseActiveClassName?: string; touchActiveClassName?: string; keyActiveClassName?: string; focusClassName?: string; focusFromKeyClassName?: string; focusFromMouseClassName?: string; focusFromTouchClassName?: string; disabledClassName?: string; hoverStyle?: React.CSSProperties; activeStyle?: React.CSSProperties; mouseActiveStyle?: React.CSSProperties; touchActiveStyle?: React.CSSProperties; keyActiveStyle?: React.CSSProperties; focusStyle?: React.CSSProperties; focusFromKeyStyle?: React.CSSProperties; focusFromMouseStyle?: React.CSSProperties; focusFromTouchStyle?: React.CSSProperties; disabledStyle?: React.CSSProperties; } /** * Usage: `InteractiveProps<'button'>`, or `InteractiveProps<typeof Component>` * * Only use the `InteractiveProps` type when typing props that are directly passed to an `<Interactive>` component. * `InteractiveProps` includes the `as` prop and `ref` prop and should not be used for * typing components that wrap an `<Interactive>` component. * * For typing components that wrap an `<Interactive>` component use the type `InteractiveExtendableProps` * * For more see: https://github.com/rafgraph/react-interactive#using-with-typescript */ export type InteractiveProps< T extends React.ElementType = typeof defaultAs > = PolymorphicPropsWithRef<InteractiveOwnProps, T>; /** * Usage: `InteractiveExtendableProps<'button'>`, or `InteractiveExtendableProps<typeof Component>` * * Use the `InteractiveExtendableProps` type when typing components that wrap an `<Interactive>` component * where the props are passed through to the `<Interactive>` component. * * For more see: https://github.com/rafgraph/react-interactive#using-with-typescript */ export type InteractiveExtendableProps< T extends React.ElementType = typeof defaultAs > = Omit<InteractiveProps<T>, 'as' | 'ref'>; // InteractiveNotMemoized is wrapped in React.memo() and exported at the end of this file const InteractiveNotMemoized: PolymorphicForwardRefExoticComponent< InteractiveOwnProps, typeof defaultAs > = React.forwardRef(function <T extends React.ElementType = typeof defaultAs>( { as, children, onStateChange, disabled = false, useExtendedTouchActive = false, hoverClassName = 'hover', activeClassName = 'active', mouseActiveClassName = 'mouseActive', touchActiveClassName = 'touchActive', keyActiveClassName = 'keyActive', focusClassName = 'focus', focusFromKeyClassName = 'focusFromKey', focusFromMouseClassName = 'focusFromMouse', focusFromTouchClassName = 'focusFromTouch', disabledClassName = 'disabled', hoverStyle, activeStyle, mouseActiveStyle, touchActiveStyle, keyActiveStyle, focusStyle, focusFromKeyStyle, focusFromMouseStyle, focusFromTouchStyle, disabledStyle, ...restProps }: PolymorphicPropsWithoutRef<InteractiveOwnProps, T>, ref: React.ForwardedRef<Element>, ) { //////////////////////////////////// // what RI is rendered as in the DOM, default is <button> const As = as || defaultAs; //////////////////////////////////// // interactive state of the component (hover, active, focus) // save both current and previous state to pass to onStateChange prop callback const [iState, setIState] = React.useState<InteractiveStateChange>({ state: initialState, prevState: initialState, }); // used as a dependency for useEffect, as well as for logic involving useExtendedTouchActive const inTouchActiveState = iState.state.active === 'touchActive'; //////////////////////////////////// // onStateChange prop callback React.useEffect( () => { if (onStateChange) { onStateChange(iState); } }, // only call this effect if the current state has changed // eslint-disable-next-line react-hooks/exhaustive-deps [iState.state.hover, iState.state.active, iState.state.focus], ); //////////////////////////////////// // if disabled and As is a component, will need to re-render if there is a new ref // to know if the DOM element supports disabled because don't have access to the DOM element on the first render, // the forceUpdate only happens after the first render (and only if disabled and As component), // and when the As component renders a different DOM element while in the disabled state const disabledAndAsComponent = React.useRef<boolean>(false); disabledAndAsComponent.current = disabled && typeof As !== 'string'; const [, forceUpdateDisabledComponent] = React.useState(false); //////////////////////////////////// // support passed in ref prop as object or callback, and track ref locally const localRef = React.useRef<Element | null>(null); const callbackRef = React.useCallback( (node: Element | null) => { localRef.current = node; if (typeof ref === 'function') { ref(node); } else if (ref) { ref.current = node; } // if disabled and As is a component, and receive a new ref (i.e. callbackRef is called) // then re-render to pass the disabled prop to the As component if the DOM element supports it if (disabledAndAsComponent.current) { forceUpdateDisabledComponent((s) => !s); } }, [ref], ); //////////////////////////////////// // track enter key and space key state (down/up) as ref // used to determine keyActive state const keyTracking = React.useRef<{ enterKeyDown: boolean; spaceKeyDown: boolean; }>({ enterKeyDown: false, spaceKeyDown: false }); // track if the element is being dragged // used to stay in the respective active state while dragging const dragTracking = React.useRef<{ isDragging: boolean; }>({ isDragging: false }); //////////////////////////////////// // centralized stateChange function that takes a payload indicating the state change: // - iStateKey: hover | active | focus // - state: the state value to change // - action: enter | exit // action: enter - always enter that state // action: exit - exit that state (to false) only if currently in the specified state, otherwise do nothing // note that entering a state happens as a result of enter/down/start events, // while exiting a state happens as a result of leave/up/end/cancel events (and some others) // the stateChange function is idempotent so event handlers can be dumb (don't need to know the current state) // stateChange will bail on updating the state if the state hasn't changed to prevent unnecessary renders // for example mousedown and pointerdown (from mouse) event handlers // will both call stateChange with action enter mouseActive state // the first call will enter the mouseActive state, and the second call will cause stateChange to bail on the state update interface HoverStateChange { iStateKey: 'hover'; state: boolean; action: 'enter' | 'exit'; } interface ActiveStateChange { iStateKey: 'active'; state: ActiveState; action: 'enter' | 'exit'; } interface FocusStateChange { iStateKey: 'focus'; state: FocusState; action: 'enter' | 'exit'; } type StateChangeFunction = ( ...changes: (HoverStateChange | ActiveStateChange | FocusStateChange)[] ) => void; const stateChange: StateChangeFunction = React.useCallback((...changes) => { setIState((previous) => { const newState = { ...previous.state }; // stateChange accepts multiple changes in each function call // so update the newState for each change received changes.forEach(({ iStateKey, state, action }) => { if (action === 'enter') { // TS should known that iStateKey and state values are matched to each other // based on the StateChangeFunction type above, but TS doesn't understand this, so use as any newState[iStateKey] = state as any; } else if ( // only exit a state (to false) if currently in that state action === 'exit' && previous.state[iStateKey] === state && // if currently dragging the element, then don't exit the active state (!dragTracking.current.isDragging || iStateKey !== 'active') ) { newState[iStateKey] = false; } }); const newInteractiveStateChange = { state: newState, prevState: previous.state, }; // if the state has changed (deep equal comparison), then return the newInteractiveStateChange // otherwise bail on the setIState call and return the previous state (object with referential equality) return stateChanged(newInteractiveStateChange) ? newInteractiveStateChange : previous; }); }, []); //////////////////////////////////// // react bug where the blur event is not dispatched when a button becomes disabled // see https://github.com/facebook/react/issues/9142 // so break out blurInteractive() as it's own function // to be called from the blur event handler (normal behavior) // and the below useEffect (workaround for react bug) const blurInteractive = React.useCallback(() => { // reset keyTracking when the element is blurred (can't be the target of key events) keyTracking.current.enterKeyDown = false; keyTracking.current.spaceKeyDown = false; stateChange( { iStateKey: 'focus', state: false, action: 'enter', }, { iStateKey: 'active', state: 'keyActive', action: 'exit', }, ); }, [stateChange]); // if RI is disabled and in a focus state, then call blur on the DOM element and blurInteractive() React.useEffect(() => { if ( disabled && iState.state.focus && // if As is a Component that renders an element which doesn't support the disabled attribute (so disabled not passed to the DOM element) // then don't do anything as have no control over what gets rendered (better to just do no harm) // note that for DOM elements that don't support disabled but As is a string (e.g. as="div", as="a") // this works b/c RI also sets tabIndex and href to undefined when disabled which makes the element not focusable // otherwise would get a flash of focus and then blur if the user tried to re-focus the element (elementSupportsDisabled(localRef.current || {}) || typeof As === 'string') ) { // when a button that currently has focus is disabled there are bugs in both firefox (v87) and safari (v14) // firefox doesn't dispatch a blur event (button is still document.activeElement) but key events are no longer registered on the button, https://bugzilla.mozilla.org/show_bug.cgi?id=1650092 // safari leaves focus on the button (no blur event) and key events are still registered, but once focus leaves the button it can't be re-focused // so call blur() on the DOM element to fix these bugs if ( localRef.current && typeof (localRef.current as HTMLElement).blur === 'function' ) { (localRef.current as HTMLElement).blur(); } blurInteractive(); } }, [disabled, iState.state.focus, blurInteractive, As]); //////////////////////////////////// // handleEvent handles all events that change the interactive state of the component // for example <As onMouseOver={handleEvent} onPointerOver={handleEvent} etc...> // always set all pointer/mouse/touch event listeners // instead of just pointer event listeners (when supported by the browser) // or mouse and touch listeners when pointer events are not supported // because // - 1. the pointer events implementation is buggy on some devices // so pointer events on its own is not a good option // for example, on iPadOS pointer events from mouse will cease to fire for the entire page // after using mouse and touch input at the same time (note that mouse events are unaffected) // - 2. the pointercancel event is useful for syncing the touchActive state with browser generated click events // as it fires as soon as the browser uses the touch interaction for another purpose (e.g. scrolling) // and this can't be replicated with touch events (touchcancel behaves differently) // - 3. the touchend/cancel event is useful to support useExtendedTouchActive as it won't fire until the // the touch point is removed from the screen, which can only be replicated with pointer events // if touch-action: none is set on the element, which has unwanted side effects (e.g. can't scroll if the touch started on the element) // so instead of trying to identify and work around all of the edge cases and bugs and set different listeners in each situation // the solution is to always set all listeners and make the stateChange function idempotent // and bail on updating state in setIState if the state hasn't changed to prevent unnecessary renders // also note that setting listeners for events not supported by the browser has no effect // note: use onMouseOver and onPointerOver instead of onMouseEnter and onPointerEnter because // of a react bug where enter events are not dispatched on an element when the element above it is removed, // this also effects when navigating around a single page app where the user clicks on a link // and the element that's rendered on the new page under the mouse doesn't receive enter events // see: https://github.com/facebook/react/issues/13956 // note that since stateChange is idempotent the extra mouse/pointer over events will have no effect // useCallback so event handlers passed to <As> are referentially equivalent between renders const handleEvent = React.useCallback( ( e: | React.MouseEvent | React.PointerEvent | React.TouchEvent | React.KeyboardEvent | React.FocusEvent | React.DragEvent, ) => { // nested switch statement to determine the appropriate stateChange // uses both e.type and eventFrom(e) in its routing logic // switch on e.type // focus -> focus: enter focusFrom[eventFrom(e)] // blur -> focus: enter false, active: exit keyActive // keydown -> active: enter keyActive // keyup -> active: exit keyActive // dragstart -> active: enter `${eventFrom(e)}Active` // dragend -> active: enter false // default switch on eventFrom(e) // eventFrom mouse // switch on e.type // mouse/pointer over -> hover: enter true // mouse/pointer leave, pointercancel -> hover: enter false, active: exit mouseActive // mouse/pointer down -> active: enter mouseActive // mouse/pointer up -> active: exit mouseActive // eventFrom touch // switch on e.type // touchstart/pointerdown -> active: enter touchActive // touchend/pointerup/touchcancel/pointercancel/mouseover -> active: exit touchActive // mouseleave -> hover: enter false, active: exit mouseActive switch (e.type) { case 'focus': // only enter focus state if RI is the target of the focus event (focus events bubble in react) if (e.target === localRef.current) { stateChange({ iStateKey: 'focus', state: `focusFrom${eventFrom(e).replace(/^\w/, (c) => c.toUpperCase(), )}` as FocusState, action: 'enter', }); } break; case 'blur': // break out blur logic as a separate function because of a react bug // where the blur event is not dispatched when a button becomes disabled // so also need to call blurInteractive() after receiving a disabled prop blurInteractive(); break; case 'keydown': case 'keyup': // update keyTracking and bail if the event is not from the space or enter key if ((e as React.KeyboardEvent).key === ' ') { keyTracking.current.spaceKeyDown = e.type === 'keydown'; } else if ((e as React.KeyboardEvent).key === 'Enter') { keyTracking.current.enterKeyDown = e.type === 'keydown'; } else { // break (bail out) if e.key is not the space or enter key so stateChange isn't called break; } stateChange({ iStateKey: 'active', state: 'keyActive', action: // use space and enter key down state to determine the enter/exit action // based on what keys trigger the the RI element // some elements are triggered by the space key, some by the enter key, and some by both (keyTracking.current.enterKeyDown && enterKeyTrigger(localRef.current || {})) || (keyTracking.current.spaceKeyDown && spaceKeyTrigger(localRef.current || {})) ? 'enter' : 'exit', }); break; case 'dragstart': dragTracking.current.isDragging = true; stateChange({ iStateKey: 'active', state: `${eventFrom(e)}Active` as ActiveState, action: 'enter', }); break; case 'dragend': dragTracking.current.isDragging = false; stateChange({ iStateKey: 'active', state: false, action: 'enter', }); break; default: // switch on eventFrom for pointer, mouse, and touch events // for example, a mouse event from mouse input is very different than a mouse event from touch input switch (eventFrom(e)) { case 'mouse': switch (e.type) { case 'mouseover': case 'pointerover': stateChange({ iStateKey: 'hover', state: true, action: 'enter', }); break; case 'mouseleave': case 'pointerleave': case 'pointercancel': stateChange( { iStateKey: 'hover', state: false, action: 'enter', }, // leave events also exit mouseActive because after the mouse leaves, mouseup events are not fired on the element // for example, mouse enter -> button down -> mouse leave -> button up, would leave RI stuck in the mouseActive state { iStateKey: 'active', state: 'mouseActive', action: 'exit', }, ); break; case 'mousedown': case 'pointerdown': stateChange({ iStateKey: 'active', state: 'mouseActive', action: 'enter', }); break; case 'mouseup': case 'pointerup': stateChange({ iStateKey: 'active', state: 'mouseActive', action: 'exit', }); break; } break; case 'touch': switch (e.type) { case 'touchstart': case 'pointerdown': stateChange({ iStateKey: 'active', state: 'touchActive', action: 'enter', }); break; case 'touchend': case 'touchcancel': case 'pointerup': case 'pointercancel': // exit touchActive on mouseover eventFrom touch // because on android, mouse events (and focus and context menu) fire ~500ms after touch start // once they fire, click will never be fired, so exit touchActive // eslint-disable-next-line no-fallthrough case 'mouseover': // if useExtendedTouchActive then only exit touchActive on touchend and touchcancel events // which won't fire until the touch point is removed from the screen if ( !useExtendedTouchActive || ['touchend', 'touchcancel'].includes(e.type) ) { stateChange({ iStateKey: 'active', state: 'touchActive', action: 'exit', }); } break; // when using both mouse and touch input on a hybrid device the following can happen: // the mouse enters an RI element, so hover: true, // then tap someplace else on the screen which fires a mouseleave event // this is correctly treated as an eventFrom touch (caused by a touch interaction) // but RI is now stuck in the hover state // so RI needs to exit the hover state on a mouseleave eventFrom touch, // note that if no scrolling is involved this is not too bad because // when the mouse is used again it will be over the RI element (and will fire mouseover event), // but if the user scrolled with the touch interaction then RI will be stuck in the hover state // until the user re-hovers and exits the RI element with their mouse, which is bad, // also note that on touch only devices this stateChange call will have no effect because RI is never in the hover or mouseActive states case 'mouseleave': stateChange( { iStateKey: 'hover', state: false, action: 'enter', }, { iStateKey: 'active', state: 'mouseActive', action: 'exit', }, ); break; } break; } break; } // call event handler prop for the current event if the prop is passed in if (restProps[eventMap[e.type] as any]) { restProps[eventMap[e.type] as any](e); } }, // handleEvent is dependent on event handler props that are also in eventMap // for example, restProps.onMouseOver, restProps.onTouchStart, etc // this generates an array of event handler props that are also in eventMap // handleEvent is also dependent on stateChange, but this will always be referentially equivalent // eslint-disable-next-line react-hooks/exhaustive-deps [ // eslint-disable-next-line react-hooks/exhaustive-deps ...eventListenerPropNames.map( (listenerPropName) => restProps[listenerPropName as any], ), useExtendedTouchActive, stateChange, blurInteractive, ], ); //////////////////////////////////// // create object with event listeners to pass to <As {...eventListeners}> const eventListeners: Record<string, React.ReactEventHandler> = {}; eventListenerPropNames.forEach((listenerPropName) => { eventListeners[listenerPropName] = handleEvent; }); //////////////////////////////////// // to sync the touchActive state with the click event fired by the browser // only stay in the touchActive state for a max of 750ms // note that most of the time another event (up/end/cancel) will exit touchActive before the timer finishes // in which case the effect clean up will run (because inTouchActiveState state changed) // and the timer will be cleared // track touchActive timer id as ref const touchActiveTimeoutId = React.useRef<number | undefined>(undefined); // effect run on touchActive state change, or if useExtendedTouchActive prop changes // it will always clear the existing timer before potentially setting a new one React.useEffect(() => { if (inTouchActiveState && !useExtendedTouchActive) { touchActiveTimeoutId.current = window.setTimeout(() => { stateChange({ iStateKey: 'active', state: 'touchActive', action: 'exit', }); }, 750); return () => window.clearTimeout(touchActiveTimeoutId.current); } return; }, [inTouchActiveState, useExtendedTouchActive, stateChange]); //////////////////////////////////// // set user-select: none when useExtendedTouchActive and in the touchActive state // to prevent the browser from selecting text on long touch // note that it needs to be set on the body not the RI element // because iOS will still select nearby text if it is only set on the element React.useEffect(() => { if (inTouchActiveState && useExtendedTouchActive) { setUserSelectNone(); return resetUserSelect; } return; }, [inTouchActiveState, useExtendedTouchActive]); //////////////////////////////////// // compute className and style props based on the current state // css classes are merged into this string let className: string = classNameToString(restProps.className); // style objects are merged into this object with the following precedence: // style object <= default styles <= style prop <= (disabledStyle || hoverStyle <= activeStyle <= [input]ActiveStyle <= focusStyle <= focusFrom[input]Style) const style: React.CSSProperties = {}; // add default styles if ( // if clicking does something and RI is not disabled, then set the cursor to pointer for better UX !disabled && cursorPointer( localRef.current || {}, Boolean(restProps.onClick || restProps.onClickCapture), ) ) { style.cursor = 'pointer'; } // add style prop passed to RI Object.assign(style, restProps.style); // helper function to merge class names and style objects into the className and style props const addToClassAndStyleProps = ( addClassName: string, addStyle?: React.CSSProperties, ) => { className = [className, classNameToString(addClassName)] .filter((cN) => cN) .join(' '); Object.assign(style, addStyle); }; // if disabled, add disabled className and style props, // otherwise add hover, active, and focus className/style props if (disabled) { addToClassAndStyleProps(disabledClassName, disabledStyle); } else { if (iState.state.hover) { addToClassAndStyleProps(hoverClassName, hoverStyle); } if (iState.state.active) { addToClassAndStyleProps(activeClassName, activeStyle); switch (iState.state.active) { case 'mouseActive': addToClassAndStyleProps(mouseActiveClassName, mouseActiveStyle); break; case 'touchActive': addToClassAndStyleProps(touchActiveClassName, touchActiveStyle); break; case 'keyActive': addToClassAndStyleProps(keyActiveClassName, keyActiveStyle); break; } } if (iState.state.focus) { addToClassAndStyleProps(focusClassName, focusStyle); switch (iState.state.focus) { case 'focusFromMouse': addToClassAndStyleProps(focusFromMouseClassName, focusFromMouseStyle); break; case 'focusFromTouch': addToClassAndStyleProps(focusFromTouchClassName, focusFromTouchStyle); break; case 'focusFromKey': addToClassAndStyleProps(focusFromKeyClassName, focusFromKeyStyle); break; } } } // memoize style object so it remains referentially equivalent if the style hasn't changed const memoizedStyle = React.useMemo( () => style, // join styles into string b/c react errors if the dependency array is not the same length each render // eslint-disable-next-line react-hooks/exhaustive-deps [Object.entries(style).join()], ); //////////////////////////////////// // disable RI when it is passed a disabled prop // note that the RI state will continue to change when disabled // but the className and style props are set to disabledClassName and disabledStyle (see above), // and click event handlers and href props will be removed // disable certain props by setting the value to undefined if RI is disabled let disabledProps: Record<string, undefined | boolean> | null = null; if (disabled) { disabledProps = { onClick: undefined, onClickCapture: undefined, onDoubleClick: undefined, onDoubleClickCapture: undefined, // make elements not focusable when disabled, this also blurs the element if it currently has focus tabIndex: undefined, // remove href to disable <a> and <area> tags, this also blurs the element if it currently has focus // setting href to undefined makes it ok to pass to any element/component, not just <a> and <area> href: undefined, }; // if the As DOM element supports the disabled prop, then pass through the disabled prop if ( elementSupportsDisabled( // on the first render localRef.current will be null, but should still pass through disabled prop if supported typeof As === 'string' ? { tagName: (As as string).toUpperCase() } : localRef.current || {}, ) ) { disabledProps.disabled = true; } } //////////////////////////////////// return ( <As {...restProps} {...eventListeners} {...disabledProps} className={className === '' ? undefined : className} style={memoizedStyle} ref={callbackRef} > { // if children is a function, then pass it the current interactive state typeof children === 'function' ? children(iState.state) : children } </As> ); }); type InteractivePropsWithoutAs< T extends React.ElementType = typeof defaultAs > = Omit<InteractiveProps<T>, 'as'>; interface PolymorphicInteractive extends PolymorphicMemoExoticComponent< InteractiveOwnProps, typeof defaultAs > { Button: React.ForwardRefExoticComponent<InteractivePropsWithoutAs<'button'>>; A: React.ForwardRefExoticComponent<InteractivePropsWithoutAs<'a'>>; Input: React.ForwardRefExoticComponent<InteractivePropsWithoutAs<'input'>>; Select: React.ForwardRefExoticComponent<InteractivePropsWithoutAs<'select'>>; Div: React.ForwardRefExoticComponent<InteractivePropsWithoutAs<'div'>>; Span: React.ForwardRefExoticComponent<InteractivePropsWithoutAs<'span'>>; } // use Object.assign because the properties are required // by the PolymorphicInteractive interface so can't add them later export const Interactive: PolymorphicInteractive = Object.assign( React.memo(InteractiveNotMemoized), { // button is the defaultAs for Interactive, so no need to createInteractive('button') // but can't set "Button: Interactive" because Interactive hasn't been defined yet // so just use React.memo(InteractiveNotMemoized) instead Button: React.memo(InteractiveNotMemoized), A: createInteractive('a'), Input: createInteractive('input'), Select: createInteractive('select'), Div: createInteractive('div'), Span: createInteractive('span'), }, ); export function createInteractive< T extends React.ElementType = typeof defaultAs >(as: T): React.ForwardRefExoticComponent<InteractivePropsWithoutAs<T>> { // eslint-disable-next-line react/display-name const WrappedInteractive = React.forwardRef(function < T extends React.ElementType = typeof as >( props: PolymorphicPropsWithoutRef<InteractiveOwnProps, T>, ref: React.ForwardedRef<Element>, ) { return <Interactive {...props} as={as} ref={ref} />; // without type casting get TS error on return type of WrappedInteractive }) as React.ForwardRefExoticComponent<InteractivePropsWithoutAs<T>>; if (process.env.NODE_ENV !== 'production') { WrappedInteractive.displayName = `createInteractive.${ typeof as === 'string' ? as : Object(as).displayName }`; } return WrappedInteractive; } if (process.env.NODE_ENV !== 'production') { Interactive.displayName = 'Interactive'; }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type AnalyticsPricingContextCategoryEnum = "ARCHITECTURE" | "BOOKS_AND_PORTFOLIOS" | "DESIGN_DECORATIVE_ART" | "DRAWING_COLLAGE_OTHER_WORK_ON_PAPER" | "FASHION" | "INSTALLATION" | "JEWELRY" | "MIXED_MEDIA" | "OTHER" | "PAINTING" | "PERFORMANCE" | "PHOTOGRAPHY" | "POSTERS" | "PRINT" | "SCULPTURE" | "SOUND" | "TEXTILE" | "VIDEO_FILM_ANIMATION" | "WORK_ON_PAPER" | "%future added value"; export type AnalyticsPricingContextDimensionEnum = "LARGE" | "MEDIUM" | "SMALL" | "%future added value"; export type PricingContextTestQueryVariables = {}; export type PricingContextTestQueryResponse = { readonly artwork: { readonly " $fragmentRefs": FragmentRefs<"PricingContext_artwork">; } | null; }; export type PricingContextTestQueryRawResponse = { readonly artwork: ({ readonly listPrice: ({ readonly __typename: "PriceRange"; readonly maxPrice: ({ readonly minor: number; }) | null; readonly minPrice: ({ readonly minor: number; }) | null; } | { readonly __typename: "Money"; readonly minor: number; } | { readonly __typename: string; }) | null; readonly artists: ReadonlyArray<({ readonly slug: string; readonly id: string | null; }) | null> | null; readonly category: string | null; readonly pricingContext: ({ readonly appliedFiltersDisplay: string | null; readonly appliedFilters: { readonly dimension: AnalyticsPricingContextDimensionEnum | null; readonly category: AnalyticsPricingContextCategoryEnum | null; }; readonly bins: ReadonlyArray<{ readonly maxPrice: string | null; readonly maxPriceCents: number; readonly minPrice: string | null; readonly minPriceCents: number; readonly numArtworks: number; }>; }) | null; readonly id: string | null; }) | null; }; export type PricingContextTestQuery = { readonly response: PricingContextTestQueryResponse; readonly variables: PricingContextTestQueryVariables; readonly rawResponse: PricingContextTestQueryRawResponse; }; /* query PricingContextTestQuery { artwork(id: "unused") { ...PricingContext_artwork id } } fragment PricingContext_artwork on Artwork { listPrice { __typename ... on PriceRange { maxPrice { minor } minPrice { minor } } ... on Money { minor } } artists { slug id } category pricingContext { appliedFiltersDisplay appliedFilters { dimension category } bins { maxPrice maxPriceCents minPrice minPriceCents numArtworks } } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "unused" } ], v1 = [ { "alias": null, "args": null, "kind": "ScalarField", "name": "minor", "storageKey": null } ], v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "category", "storageKey": null }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "PricingContextTestQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "PricingContext_artwork" } ], "storageKey": "artwork(id:\"unused\")" } ], "type": "Query" }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "PricingContextTestQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "listPrice", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, { "kind": "InlineFragment", "selections": [ { "alias": null, "args": null, "concreteType": "Money", "kind": "LinkedField", "name": "maxPrice", "plural": false, "selections": (v1/*: any*/), "storageKey": null }, { "alias": null, "args": null, "concreteType": "Money", "kind": "LinkedField", "name": "minPrice", "plural": false, "selections": (v1/*: any*/), "storageKey": null } ], "type": "PriceRange" }, { "kind": "InlineFragment", "selections": (v1/*: any*/), "type": "Money" } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Artist", "kind": "LinkedField", "name": "artists", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "slug", "storageKey": null }, (v2/*: any*/) ], "storageKey": null }, (v3/*: any*/), { "alias": null, "args": null, "concreteType": "AnalyticsPricingContext", "kind": "LinkedField", "name": "pricingContext", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "appliedFiltersDisplay", "storageKey": null }, { "alias": null, "args": null, "concreteType": "AnalyticsPriceContextFilterType", "kind": "LinkedField", "name": "appliedFilters", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "dimension", "storageKey": null }, (v3/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "AnalyticsHistogramBin", "kind": "LinkedField", "name": "bins", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "maxPrice", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "maxPriceCents", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "minPrice", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "minPriceCents", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "numArtworks", "storageKey": null } ], "storageKey": null } ], "storageKey": null }, (v2/*: any*/) ], "storageKey": "artwork(id:\"unused\")" } ] }, "params": { "id": null, "metadata": {}, "name": "PricingContextTestQuery", "operationKind": "query", "text": "query PricingContextTestQuery {\n artwork(id: \"unused\") {\n ...PricingContext_artwork\n id\n }\n}\n\nfragment PricingContext_artwork on Artwork {\n listPrice {\n __typename\n ... on PriceRange {\n maxPrice {\n minor\n }\n minPrice {\n minor\n }\n }\n ... on Money {\n minor\n }\n }\n artists {\n slug\n id\n }\n category\n pricingContext {\n appliedFiltersDisplay\n appliedFilters {\n dimension\n category\n }\n bins {\n maxPrice\n maxPriceCents\n minPrice\n minPriceCents\n numArtworks\n }\n }\n}\n" } }; })(); (node as any).hash = '37bdf393ca38349295578c08ff133e1e'; export default node;
the_stack
/// <reference types="jquery" /> declare namespace FlexSlider { interface SliderObject { [index: number]: JQuery; length: number; /** * The ul.slides within the slider */ container: JQuery; /** * The slides of the slider */ slides: JQuery; /** * The total number of slides in the slider */ count: number; /** * The slide currently being shown */ currentSlide: number; /** * Useful in .before(), the slide currently animating to */ animatingTo: number; /** * is slider animating? */ animating: boolean; /** * is the slider at either end? */ atEnd: boolean; /** * force slider to stay paused during pauseOnHover event */ manualPause: boolean; /** * The slider controlNav */ controlNav: JQuery; /** * The slider directionNav */ directionNav: JQuery; /** * The controlsContainer element of the slider */ controlsContainer: JQuery; /** * The manualControls element of the slider */ manualControls: JQuery; /** * Move slider */ flexAnimate: (target: any, pause?: boolean, override?: boolean, withSync?: boolean, fromNav?: boolean) => any; /** * Pause slider slideshow interval */ pause: () => any; /** * Play slider slideshow interval */ play: () => void; /** * Resume slider slideshow interval */ resume: () => any; /** * returns boolean if slider can advance */ canAdvance: (target: any, fromNav?: boolean) => boolean; /** * get target given a direction */ getTarget: (dir: 'next' | 'prev') => any; } interface Options { /** * Prefix string attached to the class of every element generated by the * plugin */ namespace?: string | undefined; /** * Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at * your own peril */ selector?: string | undefined; /** * Select your animation type, "fade" or "slide" * @default fade */ animation?: 'fade' | 'slide' | undefined; /** * Determines the easing method used in jQuery transitions. jQuery easing * plugin is supported! * @default swing */ easing?: 'swing' | 'linear' | string | undefined; /** * Select the sliding direction, "horizontal" or "vertical" * @default horizontal * @since v1.9 */ direction?: 'horizontal' | 'vertical' | undefined; /** * Reverse the animation direction * @default false */ reverse?: boolean | undefined; /** * Should the animation loop? If false, directionNav will received "disable" * classes at either end * @default true */ animationLoop?: boolean | undefined; /** * Allow height of the slider to animate smoothly in horizontal mode * @default false */ smoothHeight?: boolean | undefined; /** * The slide that the slider should start on. Array notation (0 = first * slide) * @default 0 * @since v1.9 */ startAt?: number | undefined; /** * Animate slider automatically * @default true */ slideshow?: boolean | undefined; /** * Set the speed of the slideshow cycling, in milliseconds * @default 7000 */ slideshowSpeed?: number | undefined; /** * Set the speed of animations, in milliseconds * @default 600 * @since v1.9 */ animationSpeed?: number | undefined; /** * Set an initialization delay, in milliseconds * @default 0 */ initDelay?: number | undefined; /** * Randomize slide order * @default false */ randomize?: boolean | undefined; /** * Fade in the first slide when animation type is "fade" * @default true */ fadeFirstSlide?: boolean | undefined; /** * Whether or not to put captions on thumbnails when using the "thumbnails" * controlNav. * @default false */ thumbCaptions?: boolean | undefined; // Usability features /** * Pause the slideshow when interacting with control elements, highly * recommended. * @default true */ pauseOnAction?: boolean | undefined; /** * Pause the slideshow when hovering over slider, then resume when no longer * hovering * @default false */ pauseOnHover?: boolean | undefined; /** * Pause the slideshow when tab is invisible, resume when visible. Provides * better UX, lower CPU usage. * @default true */ pauseInvisible?: boolean | undefined; /** * Slider will use CSS3 transitions if available * @default true */ useCSS?: boolean | undefined; /** * Allow touch swipe navigation of the slider on touch-enabled devices * @default true */ touch?: boolean | undefined; /** * If using video in the slider, will prevent CSS3 3D Transforms to avoid * graphical glitches * @default false */ video?: boolean | undefined; // Primary Controls /** * Create navigation for paging control of each slide? Note: Leave true for * manualControls usage * @default true */ controlNav?: 'thumbnails' | boolean | undefined; /** * Create navigation for previous/next navigation? (true/false) * @default true */ directionNav?: boolean | undefined; /** * Set the text for the "previous" directionNav item * @default Previous */ prevText?: string | undefined; /** * Set the text for the "next" directionNav item * @default Next */ nextText?: string | undefined; // Secondary Navigation /** * Allow slider navigating via keyboard left/right keys * @default true * @since v1.9 */ keyboard?: boolean | undefined; /** * Allow keyboard navigation to affect multiple sliders. Default behavior * cuts out keyboard navigation with more than one slider present. * @default false */ multipleKeyboard?: boolean | undefined; /** * Requires jquery.mousewheel.js * (https://github.com/brandonaaron/jquery-mousewheel) - Allows slider * navigating via mousewheel * @default false */ mousewheel?: boolean | undefined; /** * Create pause/play dynamic element * @default false */ pausePlay?: boolean | undefined; /** * Set the text for the "pause" pausePlay item * @default Pause */ pauseText?: string | undefined; /** * Set the text for the "play" pausePlay item * @default Play */ playText?: string | undefined; // Special properties /** * Declare which container the navigation elements should be appended too. * Default container is the FlexSlider element. Example use would be * $(".flexslider-container"). Property is ignored if given element is not * found. */ controlsContainer?: JQuery | undefined; /** * Declare custom control navigation. Examples would be $(".flex-control-nav * li") or "#tabs-nav li img", etc. The number of elements in your * controlNav should match the number of slides/tabs. */ manualControls?: JQuery | undefined; /** * Custom prev / next button. Must be two jQuery elements. In order to make * the events work they have to have the classes "prev" and "next" (plus * namespace) */ customDirectionNav?: JQuery | undefined; /** * Mirror the actions performed on this slider with another * slider. Use with care. */ sync?: string | undefined; /** * Internal property exposed for turning the slider into a * thumbnail navigation for another slider */ asNavFor?: string | undefined; // Carousel Options /** * Box-model width of individual carousel items, including * horizontal borders and padding. * @default 0 */ itemWidth?: number | undefined; /** * Margin between carousel items. * @default 0 */ itemMargin?: number | undefined; /** * Minimum number of carousel items that should be visible. * Items will resize fluidly when below this. * @default 1 */ minItems?: number | undefined; /** * Maxmimum number of carousel items that should be visible. * Items will resize fluidly when above this limit. * @default 0 */ maxItems?: number | undefined; /** * Number of carousel items that should move on animation. If * 0, slider will move all visible items. * @default 0 */ move?: number | undefined; /** * Whether or not to allow a slider comprised of a single slide * @default true */ allowOneSlide?: boolean | undefined; // Browser Specific /** * Set to true when Firefox is the browser used. * @default false */ isFirefox?: boolean | undefined; /** * Whether or not to enable RTL mode * @default false */ rtl?: boolean | undefined; } interface Methods { /** * Fires when the slider loads the first slide */ start?: ((slider: SliderObject) => void) | undefined; /** * Fires asynchronously with each slider animation */ before?: ((slider: SliderObject) => void) | undefined; /** * Fires after each slider animation completes */ after?: ((slider: SliderObject) => void) | undefined; /** * Fires when the slider reaches the last slide (asynchronous) */ end?: ((slider: SliderObject) => void) | undefined; /** * Fires after a slide is added */ added?: ((slider: SliderObject) => void) | undefined; /** * Fires after a slide is removed */ removed?: ((slider: SliderObject) => void) | undefined; /** * Fires after the slider is initially setup */ init?: ((slider: SliderObject) => void) | undefined; } type HelperActions = 'play' | 'pause' | 'stop' | 'next' | 'prev' | 'previous'; } interface JQuery { flexslider(options?: FlexSlider.Options | FlexSlider.Methods | FlexSlider.HelperActions | number): any; }
the_stack
import * as _ from 'lodash' import * as Context from '../editor/context' import { tacticAutomationRoute } from '../peacoq/routes' import { Control } from '../sertop/command' import { StmAdd, StmQuery } from '../sertop/control-command' import { Vernac } from '../sertop/query-command' interface ProofTreeAutomationInput { commandObserver : Rx.Observer<Command$> completed$ : Completed$ doc : ICoqDocument error$ : Error$ notice$ : Notice$ stmActionsInFlightCounter$ : Rx.Observable<number> stmAdded$ : StmAdded$ stopAutomationRound$ : Rx.Observable<{}> } export function setup( completed$ : Completed$, doc : ICoqDocument, error$ : Error$, notice$ : Notice$, stmActionsInFlightCounter$ : Rx.Observable<number>, stmAdded$ : StmAdded$, stopAutomationRound$ : Rx.Observable<{}> ) : void { const pause$ = makePause$(stmActionsInFlightCounter$) // tip$.subscribe(t => console.log(Date.now(), 'TIP CHANGED')) // pause$.subscribe(b => console.log(Date.now(), b ? 'RESUME' : 'PAUSE')) doc.debouncedTip$ .concatMap<ISentence<IStage>>(tip => tip.caseOf({ nothing : () => [], just : s => [s] })) .concatMap(sentence => sentence.waitUntilProcessed()) // Observable<ISentence<IProcessed>> .concatMap( sentence => sentence.stage.getContext(), (sentence, context) => getTacticsForContext(context, sentence) ) // Observable<Tactic[]> .map(tactics => Rx.Observable.from(tactics) // Observable<tactic> .map(tactic => makeCandidate(doc, tactic, completed$, error$, notice$, stmAdded$)) // Observable<{ commands$, done$ }> .concatMap(({ commands$, done$ }) => Rx.Observable.of(commands$).merge(done$) ) // Observable<commands$> ) // Observable<Observable<commands$>> // ^ one per sentence // ^ one per tactic to try for that sentence // ^ each tactic involves 3 commands // We want to interrupt the tactics for a given sentence when tip$ // emits, and then start trying for the next sentence. .pausableBuffered(pause$) // I don't know why but this is needed for the next pausableBuffered call to work correctly .concatMap(candidatesForOneSentence$ => candidatesForOneSentence$ // .do(cs => cs.take(1).subscribe((cmd : Command.Control<ControlCommand.StmAdd>) => console.log(Date.now(), 'Before pause', cmd.controlCommand.sentence))) .pausableBuffered(pause$) // .do(cs => cs.take(1).subscribe((cmd : Command.Control<ControlCommand.StmAdd>) => console.log(Date.now(), 'After pause', cmd.controlCommand.sentence))) .takeUntil(doc.tip$) ) .subscribe(commands$ => doc.sendCommands(commands$)) } function makeGroup(name : string, tactics : string[]) : TacticGroup { return { 'name' : name, 'tactics' : _(tactics).map(s => `${s}.`).value(), } } /* This strategy tries many tactics, not trying to be smart. */ function tacticsToTry(e : PeaCoqContextElement) : TacticGroup[] { const hyps = e.ppgoal.hyps const curHypsFull = _(hyps).clone().reverse() const curHyps = curHypsFull.map(h => h.name) // TODO : there is a better way to do this const curNames = curHyps // _(curHyps).union(namesPossiblyInScope.reverse()) const res = [ makeGroup( 'terminators', ([] as string[]).concat( // (pt.goalIsReflexive() ? ['reflexivity'] : []) ['reflexivity'], [ 'discriminate', 'assumption', 'eassumption', ] ) ), makeGroup( 'automation', [ // 'auto', // 'eauto', ] ), makeGroup( 'introduction', ['intros', 'intro'] ), makeGroup( 'destructuring', [ 'break_if', 'f_equal', 'repeat f_equal', 'subst' ] ), makeGroup( 'simplification', ([] as string[]).concat( ['simpl'], curHyps.map(h => `simpl in ${h}`), curHyps.length > 0 ? ['simpl in *'] : [] ) ), // makeGroup( // 'constructors', // (pt.goalIsDisjunction() ? ['left', 'right'] : []) // .concat(pt.goalIsConjunction() ? ['split'] : []) // .concat([ // 'constructor', // 'econstructor', // 'eexists', // ]) // ), // // makeGroup( // 'destructors', // _(curHyps) // .filter(function(h) { return isLowerCase(h[0]); }) // .map(function(h) { return 'destruct ' + h; }) // .value() // ), makeGroup( 'induction', curHyps.map(h => `induction ${h}`) // This was used for the study because induction applies to everything :( // _(curHypsFull) // .filter(function(h) { // return h.hType.tag === 'Var' && h.hType.contents === 'natlist' // }) // .map(function(h) { return 'induction ' + h.hName; }) // .value() ), // makeGroup( // 'inversion', // curHyps.map(h => `inversion ${h}`) // ), makeGroup( 'solver', [ // 'congruence', // 'omega', // 'firstorder' ] ), makeGroup( 'application', ([] as string[]).concat( curNames.map(n => `apply ${n}`), curNames.map(n => `eapply ${n}`) ) ), makeGroup( 'rewriting', ([] as string[]).concat( curNames.map(n => `rewrite -> {n}`), curNames.map(n => `rewrite <- {n}`), ) ), // makeGroup( // 'applications in', // _(curNames).map(function(n) { // return _(curHyps) // .map(function(h) { // if (h === n) { return []; } // return ([ // 'apply ' + n + ' in ' + h, // 'eapply ' + n + ' in ' + h, // ]) // }) // .flatten(true).value() // }).flatten(true).value() // ), // // makeGroup( // 'rewrites in', // _(curNames).map(function(n) { // return _(curHyps) // .map(function(h) { // if (h === n) { return []; } // return ([ // ('rewrite -> ' + n + ' in ' + h), // ('rewrite <- ' + n + ' in ' + h) // ]) // }) // .flatten(true).value() // // }).flatten(true).value() // ), makeGroup( 'revert', curHyps.map(h => `revert ${h}`) ), ] return res } function getTacticsForContext( context : PeaCoqContext, sentence : ISentence<IProcessed> ) : CandidateInput[] { if (context.fgGoals.length === 0) { return [] } return ( _(tacticsToTry(context.fgGoals[0])) .flatMap(group => group.tactics.map(tactic => ({ context, group : group.name, tactic, sentence }) ) ) .value() ) } interface CandidateInput { context : PeaCoqContext group : string tactic : string sentence : ISentence<IProcessed> } // We keep separate commands$ and done$ because we want the recipient to // be able to send commands$ (atomically) and then immediately send // other things without waiting for the responses. done$ is used to make // sure we only try one tactic at a time and stay interruptable between // two trials. function makeCandidate( doc : ICoqDocument, input : CandidateInput, completed$ : Completed$, error$ : Error$, notice$ : Notice$, stmAdded$ : StmAdded$ ) : { commands$ : CommandStreamItem<ISertop.ICommand> done$ : Rx.Observable<any> } { const { context, group, tactic, sentence } = input const stateId = sentence.stage.stateId // FIXME : not sure how to better do this, but we do not want to send // any command if the tip has moved. Somehow, takeUntil(tip$) does not // necessarily do a good job, so double-checking here : const curSid = _.max(doc.getAllSentences().map(s => s.getStateId().caseOf({ nothing : () => 0, just : sid => sid }))) if (stateId !== curSid) { // console.log('Was expecting', stateId, 'but we are at', curSid, 'aborting') return { commands$ : Rx.Observable.empty<ISertop.ICommand>(), done$ : Rx.Observable.empty<any>(), } } else { // console.log('Was expecting', stateId, 'and we are at', curSid, 'proceeding') } const add = new Control(new StmAdd({ ontop : stateId }, tactic, true)) // listen for the STM added answer (there should be 0 if failed otherwise 1) const filteredStmAdded$ = stmAdded$.filter(a => a.cmdTag === add.tag) .takeUntil(completed$.filter(a => a.cmdTag === add.tag)) const getContext$ = filteredStmAdded$ .map(a => new Control(new StmQuery( { sid : a.answer.stateId, // route is used so that the rest of PeaCoq can safely ignore those feedback messages route : tacticAutomationRoute }, new Vernac('PeaCoqGetContext.'), true ))) .share() const stmAddErrored$ = filteredStmAdded$.flatMap(a => error$.filter(e => e.editOrStateId === a.answer.stateId)) // now, try to pick up the notice feedback for that state id const addNotice$ = filteredStmAdded$ .flatMap(a => { return notice$ .filter(n => n.editOrStateId === a.answer.stateId) .takeUntil(stmAddErrored$) .take(1) }) // we can send the next candidate when we receive either the error or // the notice, unless we need to stop. addNotice$ .subscribe(n => { const afterContext = Context.create(n.feedbackContent.message) // we only add tactics that change something if (!Context.isEqual(afterContext, context)) { sentence.addCompletion(tactic, group, afterContext) } }) const editAt = new Control(new StmEditAt(stateId)) const commands$ = Rx.Observable.concat<ISertop.ICommand>([ Rx.Observable.just(add), getContext$, Rx.Observable.just(editAt) ]).share() // this is an empty stream that waits until either stream emits const done$ : Rx.Observable<any> = Rx.Observable.amb(stmAddErrored$, addNotice$).take(1).ignoreElements() return { commands$, done$ } } // Due to the asynchronicity of interactions with coqtop, we may have // bad races. For instance, we don't want to send a tactic if we sent a // StmAdd and are about to change state. We cannot rely on tip$ or // stmAdded$ because we might receive their acknowledgment later. The // only reliable way is to track pairs of StmAdd-StmAdded and pairs of // StmCancel-StmCanceled, and to only allow the emission of a // tactic-to-try when pairs are matched. We also regulate the // tactic-to-try flow so that only one tactic is being tried at a time, // so that we can interrupt the flow between any two attempts. function makePause$(stmActionsInFlightCounter$ : Rx.Observable<number>) : Rx.Observable<boolean> { const pause$ = stmActionsInFlightCounter$ // .do(c => console.log('COUNT', c)) .map(n => n === 0) .startWith(true) .distinctUntilChanged() // .do(b => console.log('BOOL', b)) // We need replay because the paused stream will subscribe to pause$ // later, and it needs to know the last value of pause$ upon // subscription. Otherwise, when calling pausableBuffered, the // stream will assume false and pause, even though the last value of // pause$ was true. .replay(false, 1) pause$.connect() // make pause$ start running immediately return pause$ // .share() }
the_stack
import { Component, Element, Prop, h, Watch, Event, EventEmitter } from '@stencil/core'; import { select, event } from 'd3-selection'; import { max, min } from 'd3-array'; import { timeMillisecond, timeSecond, timeMinute, timeHour, timeDay, timeWeek, timeMonth, timeYear } from 'd3-time'; import { scalePoint, scaleLinear, scaleTime } from 'd3-scale'; import { nest } from 'd3-collection'; import { IBoxModelType, IHoverStyleType, IClickStyleType, IAxisType, IReferenceStyleType, IFocusStyleType, IBarStyleType, IMarkerStyleType, ISeriesLabelType, IDifferenceLabelType, IDataLabelType, ITooltipLabelType, IAccessibilityType, IAnimationConfig, ILegendType } from '@visa/charts-types'; import { DumbbellPlotDefaultValues } from './dumbbell-plot-default-values'; import { easeCircleIn } from 'd3-ease'; import 'd3-transition'; import Utils from '@visa/visa-charts-utils'; import { v4 as uuid } from 'uuid'; const { getAccessibleStrokes, ensureTextContrast, createTextStrokeFilter, createUrl, initializeDescriptionRoot, initializeElementAccess, setElementFocusHandler, setElementAccessID, setAccessibilityController, hideNonessentialGroups, setAccessTitle, setAccessSubtitle, setAccessLongDescription, setAccessExecutiveSummary, setAccessPurpose, setAccessContext, setAccessStatistics, setAccessChartCounts, setAccessXAxis, setAccessYAxis, setAccessStructure, setAccessAnnotation, retainAccessFocus, checkAccessFocus, setElementInteractionAccessState, setAccessibilityDescriptionWidth, drawTooltip, annotate, chartAccessors, checkInteraction, checkClicked, checkHovered, convertVisaColor, drawAxis, drawGrid, drawLegend, setLegendInteractionState, formatDataLabel, getColors, getLicenses, getPadding, getScopedData, initTooltipStyle, overrideTitleTooltip, placeDataLabels, scopeDataKeys, visaColors, transitionEndAll, validateAccessibilityProps, findTagLevel, prepareRenderChange, roundTo, getTextWidth, resolveLabelCollision } = Utils; @Component({ tag: 'dumbbell-plot', styleUrl: 'dumbbell-plot.scss' }) export class DumbbellPlot { @Event() clickFunc: EventEmitter; @Event() hoverFunc: EventEmitter; @Event() mouseOutFunc: EventEmitter; // Chart Attributes (1/7) @Prop({ mutable: true }) mainTitle: string = DumbbellPlotDefaultValues.mainTitle; @Prop({ mutable: true }) subTitle: string = DumbbellPlotDefaultValues.subTitle; @Prop({ mutable: true }) height: number = DumbbellPlotDefaultValues.height; @Prop({ mutable: true }) width: number = DumbbellPlotDefaultValues.width; @Prop({ mutable: true }) margin: IBoxModelType = DumbbellPlotDefaultValues.margin; @Prop({ mutable: true }) padding: IBoxModelType = DumbbellPlotDefaultValues.padding; @Prop({ mutable: true }) highestHeadingLevel: string | number = DumbbellPlotDefaultValues.highestHeadingLevel; // Data (2/7) @Prop() data: object[]; @Prop() uniqueID: string; @Prop({ mutable: true }) ordinalAccessor: string = DumbbellPlotDefaultValues.ordinalAccessor; @Prop({ mutable: true }) valueAccessor: string = DumbbellPlotDefaultValues.valueAccessor; @Prop({ mutable: true }) seriesAccessor: string = DumbbellPlotDefaultValues.seriesAccessor; @Prop({ mutable: true }) sortOrder: string = DumbbellPlotDefaultValues.sortOrder; // Axis (3/7) @Prop({ mutable: true }) xAxis: IAxisType = DumbbellPlotDefaultValues.xAxis; @Prop({ mutable: true }) yAxis: IAxisType = DumbbellPlotDefaultValues.yAxis; @Prop({ mutable: true }) wrapLabel: boolean = DumbbellPlotDefaultValues.wrapLabel; @Prop({ mutable: true }) layout: string = DumbbellPlotDefaultValues.layout; @Prop({ mutable: true }) showBaselineX: boolean = DumbbellPlotDefaultValues.showBaselineX; @Prop({ mutable: true }) showBaselineY: boolean = DumbbellPlotDefaultValues.showBaselineY; // Color & Shape (4/7) @Prop({ mutable: true }) colorPalette: string = DumbbellPlotDefaultValues.colorPalette; @Prop({ mutable: true }) colors: string[]; @Prop({ mutable: true }) hoverStyle: IHoverStyleType = DumbbellPlotDefaultValues.hoverStyle; @Prop({ mutable: true }) hoverOpacity: number = DumbbellPlotDefaultValues.hoverOpacity; @Prop({ mutable: true }) animationConfig: IAnimationConfig = DumbbellPlotDefaultValues.animationConfig; @Prop({ mutable: true }) clickStyle: IClickStyleType = DumbbellPlotDefaultValues.clickStyle; @Prop({ mutable: true }) referenceStyle: IReferenceStyleType = DumbbellPlotDefaultValues.referenceStyle; @Prop({ mutable: true }) cursor: string = DumbbellPlotDefaultValues.cursor; @Prop({ mutable: true }) focusMarker: IFocusStyleType = DumbbellPlotDefaultValues.focusMarker; @Prop({ mutable: true }) marker: IMarkerStyleType = DumbbellPlotDefaultValues.marker; @Prop({ mutable: true }) barStyle: IBarStyleType = DumbbellPlotDefaultValues.barStyle; // Data label (5/7) @Prop({ mutable: true }) dataLabel: IDataLabelType = DumbbellPlotDefaultValues.dataLabel; @Prop({ mutable: true }) seriesLabel: ISeriesLabelType = DumbbellPlotDefaultValues.seriesLabel; @Prop({ mutable: true }) differenceLabel: IDifferenceLabelType = DumbbellPlotDefaultValues.differenceLabel; @Prop({ mutable: true }) showTooltip: boolean = DumbbellPlotDefaultValues.showTooltip; @Prop({ mutable: true }) tooltipLabel: ITooltipLabelType = DumbbellPlotDefaultValues.tooltipLabel; @Prop({ mutable: true }) accessibility: IAccessibilityType = DumbbellPlotDefaultValues.accessibility; @Prop({ mutable: true }) legend: ILegendType = DumbbellPlotDefaultValues.legend; @Prop({ mutable: true }) annotations: object[] = DumbbellPlotDefaultValues.annotations; // Calculation (6/7) @Prop({ mutable: true }) maxValueOverride: number; @Prop({ mutable: true }) minValueOverride: number; @Prop({ mutable: true }) referenceLines: object[] = DumbbellPlotDefaultValues.referenceLines; // Interactivity (7/7) @Prop({ mutable: true }) suppressEvents: boolean = DumbbellPlotDefaultValues.suppressEvents; @Prop({ mutable: true }) hoverHighlight: object; @Prop({ mutable: true }) clickHighlight: object[] = DumbbellPlotDefaultValues.clickHighlight; @Prop({ mutable: true }) interactionKeys: string[]; // Testing & Debug (8/7) @Prop() unitTest: boolean = false; // @Prop() debugMode: boolean = false; @Element() dumbbellPlotEl: HTMLElement; shouldValidateAccessibility: boolean = true; svg: any; root: any; rootG: any; gridG: any; defs: any; x: any; y: any; nest: any; map: any; innerHeight: number; innerWidth: number; innerPaddedHeight: number; innerPaddedWidth: number; innerXAxis: any; innerYAxis: any; baselineG: any; references: any; defaults: boolean; duration: number; enter: any; exit: any; update: any; enterMarkers: any; updateMarkers: any; exitMarkers: any; enteringLabels: any; exitingLabels: any; updatingLabels: any; enterSeriesLabel: any; updateSeriesLabel: any; exitSeriesLabel: any; enterDiffLabel: any; updateDiffLabel: any; exitDiffLabel: any; enterLabels: any; updateLabels: any; enterLabelChildren: any; updateLabelChildren: any; exitLabelChildren: any; exitLabels: any; enterSize: number; exitSize: number; legendG: any; tooltipG: any; legendData: any; ordinalLabel: any; labels: any; dumbbellG: any; colorArr: any; rawColors: any; textColors: any; markerData: any; xAccessor: any; yAccessor: any; placement: string; layoutOverride: any; seriesLabelDetails: any; diffLabelDetails: any; diffLabelWrapper: any; isVertical: boolean; seriesInteraction: any; dumbbellInteraction: any; innerInteractionKeys: any; innerLabelAccessor: string; url: string; tableData: any; tableColumns: any; updated: boolean = true; time = { timemillisecond: timeMillisecond, timesecond: timeSecond, timeminute: timeMinute, timehour: timeHour, timeday: timeDay, timeweek: timeWeek, timemonth: timeMonth, timeyear: timeYear }; chartID: string; markerG: any; seriesData: any; seriesLabelWrapper: any; shouldUpdateLayout: boolean = false; shouldValidate: boolean = false; // shouldUpdateAccessibility: boolean = false; shouldUpdateAnnotations: boolean = false; shouldUpdateReferenceLines: boolean = false; shouldResetRoot: boolean = false; shouldUpdateXAxis: boolean = false; shouldUpdateXGrid: boolean = false; shouldUpdateYAxis: boolean = false; shouldUpdateYGrid: boolean = false; shouldUpdateScales: boolean = false; shouldUpdateBaseline: boolean = false; shouldCheckValueAxis: boolean = false; shouldCheckLabelAxis: boolean = false; shouldSetColors: boolean = false; shouldUpdateLegend: boolean = false; shouldSetGlobalSelections: boolean = false; shouldSetSeriesSelections: boolean = false; shouldSetTestingAttributes: boolean = false; shouldUpdateData: boolean = false; shouldEnterUpdateExit: boolean = false; shouldEnterUpdateExitMarkers: boolean = false; shouldUpdateMarkerOpacity: boolean = false; shouldUpdateGeometries: boolean = false; shouldUpdateSeriesLabels: boolean = false; shouldUpdateDifferenceLabels: boolean = false; shouldUpdateLabels: boolean = false; shouldValidateInteractionKeys: boolean = false; shouldUpdateTableData: boolean = false; shouldValidateDataLabelPlacement: boolean = false; shouldValidateDataLabelAccessor: boolean = false; shouldAddStrokeUnder: boolean = false; shouldUpdateBaselineX: boolean = false; shouldUpdateBaselineY: boolean = false; shouldUpdateLegendData: boolean = false; shouldUpdateMarkerIDs: boolean = false; shouldValidateLayout: boolean = false; shouldValidateSeriesLabelPlacement: boolean = false; shouldValidateDiffLabelPlacement: boolean = false; shouldBindInteractivity: boolean = false; shouldBindLegendInteractivity: boolean = false; shouldBindSeriesInteractivity: boolean = false; shouldUpdateCursor: boolean = false; shouldSetLegendCursor: boolean = false; shouldSetSeriesCursor: boolean = false; shouldSetLabelOpacity: boolean = false; shouldSetSeriesLabelOpacity: boolean = false; shouldSetDifferenceLabelOpacity: boolean = false; shouldSetSelectionClass: boolean = false; shouldDrawInteractionState: boolean = false; shouldRenderMarkerGroup: boolean = false; shouldUpdateBarStyle: boolean = false; shouldUpdateMarkerSize: boolean = false; shouldUpdateDiffLabelColor: boolean = false; shouldUpdateMarkerStyle: boolean = false; shouldDrawMarkerGeometries: boolean = false; shouldUpdateMarkerData: boolean = false; shouldUpdateSeriesData: boolean = false; shouldUpdateDescriptionWrapper: boolean = false; shouldSetChartAccessibilityTitle: boolean = false; shouldSetChartAccessibilitySubtitle: boolean = false; shouldSetChartAccessibilityLongDescription: boolean = false; shouldSetChartAccessibilityExecutiveSummary: boolean = false; shouldSetChartAccessibilityStatisticalNotes: boolean = false; shouldSetChartAccessibilityStructureNotes: boolean = false; shouldSetParentSVGAccessibility: boolean = false; shouldSetGeometryAccessibilityAttributes: boolean = false; shouldSetGeometryAriaLabels: boolean = false; shouldSetGroupAccessibilityAttributes: boolean = false; shouldSetGroupAccessibilityLabel: boolean = false; shouldSetChartAccessibilityPurpose: boolean = false; shouldSetChartAccessibilityContext: boolean = false; shouldRedrawWrapper: boolean = false; shouldSetTagLevels: boolean = false; shouldSetChartAccessibilityCount: boolean = false; shouldSetYAxisAccessibility: boolean = false; shouldSetXAxisAccessibility: boolean = false; shouldSetAnnotationAccessibility: boolean = false; topLevel: string = 'h2'; bottomLevel: string = 'p'; strokes: any = {}; bitmaps: any; @Watch('mainTitle') mainTitleWatcher(_newData, _oldData) { this.shouldValidate = true; this.shouldUpdateDescriptionWrapper = true; this.shouldSetChartAccessibilityTitle = true; this.shouldSetParentSVGAccessibility = true; } @Watch('subTitle') subTitleWatcher(_newData, _oldData) { this.shouldSetChartAccessibilitySubtitle = true; this.shouldSetParentSVGAccessibility = true; } @Watch('height') @Watch('width') @Watch('padding') @Watch('margin') dimensionWatcher(_newVal, _oldVal) { this.shouldUpdateLayout = true; this.shouldUpdateScales = true; this.shouldResetRoot = true; this.shouldUpdateGeometries = true; this.shouldUpdateXAxis = true; this.shouldUpdateYAxis = true; this.shouldUpdateXGrid = true; this.shouldUpdateYGrid = true; this.shouldUpdateLabels = true; this.shouldUpdateSeriesLabels = true; this.shouldUpdateDifferenceLabels = true; this.shouldUpdateLegend = true; this.shouldUpdateReferenceLines = true; this.shouldUpdateBaselineX = true; this.shouldUpdateBaselineY = true; this.shouldUpdateAnnotations = true; } @Watch('data') dataWatcher(_newData, _oldData) { this.updated = true; this.shouldUpdateData = true; this.shouldUpdateMarkerData = true; this.shouldUpdateSeriesData = true; this.shouldSetGlobalSelections = true; this.shouldSetTestingAttributes = true; this.shouldEnterUpdateExit = true; this.shouldEnterUpdateExitMarkers = true; this.shouldUpdateMarkerSize = true; this.shouldUpdateMarkerIDs = true; this.shouldUpdateLegendData = true; this.shouldUpdateTableData = true; this.shouldUpdateScales = true; this.shouldValidate = true; this.shouldUpdateGeometries = true; this.shouldUpdateXAxis = true; this.shouldSetXAxisAccessibility = true; this.shouldUpdateYAxis = true; this.shouldSetYAxisAccessibility = true; this.shouldUpdateXGrid = true; this.shouldUpdateYGrid = true; this.shouldSetLabelOpacity = true; this.shouldUpdateLabels = true; this.shouldUpdateSeriesLabels = true; this.shouldUpdateDifferenceLabels = true; this.shouldUpdateLegend = true; this.shouldUpdateReferenceLines = true; this.shouldUpdateBaselineX = true; this.shouldUpdateBaselineY = true; this.shouldUpdateAnnotations = true; this.shouldSetGeometryAccessibilityAttributes = true; this.shouldSetGeometryAriaLabels = true; this.shouldUpdateBarStyle = true; this.shouldSetColors = true; } @Watch('uniqueID') idWatcher(newID, _oldID) { this.chartID = newID || 'dumbbell-plot-' + uuid(); this.dumbbellPlotEl.id = this.chartID; this.shouldValidate = true; this.shouldUpdateDescriptionWrapper = true; this.shouldSetParentSVGAccessibility = true; this.shouldUpdateLegend = true; this.shouldAddStrokeUnder = true; this.shouldUpdateMarkerIDs = true; } @Watch('highestHeadingLevel') headingWatcher(_newVal, _oldVal) { this.shouldRedrawWrapper = true; this.shouldSetTagLevels = true; this.shouldSetChartAccessibilityCount = true; this.shouldSetYAxisAccessibility = true; this.shouldSetXAxisAccessibility = true; this.shouldSetAnnotationAccessibility = true; this.shouldUpdateDescriptionWrapper = true; this.shouldSetChartAccessibilityTitle = true; this.shouldSetChartAccessibilitySubtitle = true; this.shouldSetChartAccessibilityLongDescription = true; this.shouldSetChartAccessibilityContext = true; this.shouldSetChartAccessibilityExecutiveSummary = true; this.shouldSetChartAccessibilityPurpose = true; this.shouldSetChartAccessibilityStatisticalNotes = true; this.shouldSetChartAccessibilityStructureNotes = true; } @Watch('ordinalAccessor') ordinalAccessorWatcher(_newVal, _oldVal) { this.shouldUpdateData = true; this.shouldUpdateMarkerData = true; this.shouldUpdateSeriesData = true; this.shouldUpdateTableData = true; this.shouldUpdateScales = true; this.shouldSetGlobalSelections = true; this.shouldUpdateGeometries = true; this.shouldEnterUpdateExit = true; this.shouldEnterUpdateExitMarkers = true; this.shouldUpdateMarkerSize = true; this.shouldDrawInteractionState = true; this.shouldSetLabelOpacity = true; this.shouldSetSeriesLabelOpacity = true; this.shouldSetDifferenceLabelOpacity = true; this.shouldCheckLabelAxis = true; // this.shouldUpdateLabels = true; this.shouldUpdateSeriesLabels = true; this.shouldUpdateDifferenceLabels = true; this.shouldUpdateReferenceLines = true; this.shouldUpdateBaselineX = true; this.shouldUpdateBaselineY = true; this.shouldUpdateAnnotations = true; this.shouldSetGeometryAriaLabels = true; if (!(this.interactionKeys && this.interactionKeys.length)) { this.shouldValidateInteractionKeys = true; this.shouldSetSelectionClass = true; } } @Watch('valueAccessor') valueAccessorWatcher(_newVal, _oldVal) { this.shouldUpdateTableData = true; this.shouldUpdateData = true; this.shouldUpdateMarkerData = true; this.shouldUpdateSeriesData = true; this.shouldSetGlobalSelections = true; this.shouldUpdateScales = true; this.shouldUpdateGeometries = true; this.shouldDrawInteractionState = true; this.shouldEnterUpdateExit = true; this.shouldEnterUpdateExitMarkers = true; this.shouldUpdateMarkerSize = true; this.shouldSetLabelOpacity = true; this.shouldSetSeriesLabelOpacity = true; this.shouldCheckValueAxis = true; this.shouldValidateDataLabelAccessor = true; // this.shouldUpdateLabels = true; this.shouldUpdateSeriesLabels = true; this.shouldUpdateDifferenceLabels = true; this.shouldUpdateReferenceLines = true; this.shouldUpdateBaselineX = true; this.shouldUpdateBaselineY = true; this.shouldUpdateAnnotations = true; this.shouldSetGeometryAriaLabels = true; } @Watch('seriesAccessor') seriesAccessorWatcher(_newVal, _oldVal) { this.shouldUpdateTableData = true; this.shouldUpdateData = true; this.shouldSetGlobalSelections = true; this.shouldUpdateMarkerData = true; this.shouldUpdateSeriesData = true; this.shouldUpdateLegendData = true; this.shouldDrawInteractionState = true; this.shouldEnterUpdateExit = true; this.shouldEnterUpdateExitMarkers = true; this.shouldUpdateMarkerSize = true; this.shouldUpdateSeriesLabels = true; // this.shouldUpdateLabels = true; this.shouldUpdateDifferenceLabels = true; this.shouldAddStrokeUnder = true; this.shouldSetLabelOpacity = true; this.shouldSetSeriesLabelOpacity = true; this.shouldUpdateLegend = true; this.shouldSetGeometryAriaLabels = true; this.shouldUpdateTableData = true; if (!(this.interactionKeys && this.interactionKeys.length)) { this.shouldValidateInteractionKeys = true; this.shouldSetSelectionClass = true; } } @Watch('sortOrder') sortWatcher(_newVal, _oldVal) { this.updated = true; this.shouldUpdateData = true; this.shouldUpdateMarkerData = true; this.shouldUpdateSeriesData = true; this.shouldSetGlobalSelections = true; this.shouldSetTestingAttributes = true; this.shouldEnterUpdateExit = true; this.shouldEnterUpdateExitMarkers = true; this.shouldUpdateTableData = true; this.shouldUpdateScales = true; this.shouldUpdateGeometries = true; this.shouldUpdateLabels = true; this.shouldUpdateSeriesLabels = true; this.shouldUpdateDifferenceLabels = true; this.shouldAddStrokeUnder = true; this.shouldUpdateAnnotations = true; this.shouldSetGeometryAccessibilityAttributes = true; this.shouldSetGeometryAriaLabels = true; } @Watch('xAxis') xAxisWatcher(_newVal, _oldVal) { const newGridVal = _newVal && _newVal.gridVisible; const oldGridVal = _oldVal && _oldVal.gridVisible; const newTickInterval = _newVal && _newVal.tickInterval ? _newVal.tickInterval : 0; const oldTickInterval = _oldVal && _oldVal.tickInterval ? _oldVal.tickInterval : 0; const newFormatVal = _newVal && _newVal.format ? _newVal.format : false; const oldFormatVal = _oldVal && _oldVal.format ? _oldVal.format : false; const newUnitVal = _newVal && _newVal.unit ? _newVal.unit : false; const oldUnitVal = _oldVal && _oldVal.unit ? _oldVal.unit : false; if (newGridVal !== oldGridVal || newTickInterval !== oldTickInterval) { this.shouldUpdateXGrid = true; } if (newFormatVal !== oldFormatVal || newUnitVal !== oldUnitVal) { this.shouldUpdateScales = true; if (newUnitVal !== oldUnitVal) { this.shouldUpdateGeometries = true; this.shouldUpdateLabels = true; this.shouldUpdateSeriesLabels = true; this.shouldUpdateDifferenceLabels = true; this.shouldUpdateReferenceLines = true; this.shouldUpdateAnnotations = true; } } this.shouldUpdateXAxis = true; this.shouldSetXAxisAccessibility = true; } @Watch('yAxis') yAxisWatcher(_newVal, _oldVal) { const newGridVal = _newVal && _newVal.gridVisible; const oldGridVal = _oldVal && _oldVal.gridVisible; const newTickInterval = _newVal && _newVal.tickInterval ? _newVal.tickInterval : 0; const oldTickInterval = _oldVal && _oldVal.tickInterval ? _oldVal.tickInterval : 0; if (newGridVal !== oldGridVal || newTickInterval !== oldTickInterval) { this.shouldUpdateYGrid = true; } this.shouldUpdateYAxis = true; this.shouldSetYAxisAccessibility = true; } @Watch('wrapLabel') wrapLabelWatcher(_newVal, _oldVal) { this.shouldCheckLabelAxis = true; } @Watch('layout') layoutWatcher(_newVal, _oldVal) { this.shouldValidateLayout = true; this.shouldValidateDataLabelPlacement = true; this.shouldValidateSeriesLabelPlacement = true; this.shouldUpdateSeriesData = true; this.shouldValidateDiffLabelPlacement = true; this.shouldUpdateScales = true; this.shouldResetRoot = true; this.shouldUpdateGeometries = true; this.shouldUpdateXAxis = true; this.shouldUpdateYAxis = true; this.shouldUpdateXGrid = true; this.shouldUpdateYGrid = true; this.shouldUpdateLabels = true; this.shouldUpdateSeriesLabels = true; this.shouldUpdateDifferenceLabels = true; this.shouldAddStrokeUnder = true; this.shouldUpdateLegend = true; this.shouldUpdateReferenceLines = true; this.shouldUpdateBaselineX = true; this.shouldUpdateBaselineY = true; this.shouldUpdateAnnotations = true; this.shouldSetGeometryAccessibilityAttributes = true; } @Watch('showBaselineX') showBaselineXWatcher(_newVal, _oldVal) { this.shouldUpdateBaselineX = true; } @Watch('showBaselineY') showBaselineYWatcher(_newVal, _oldVal) { this.shouldUpdateBaselineY = true; } @Watch('colorPalette') @Watch('colors') paletteWatcher(_newVal, _oldVal) { this.shouldUpdateMarkerIDs = true; this.shouldSetColors = true; this.shouldUpdateBarStyle = true; this.shouldUpdateMarkerStyle = true; this.shouldUpdateLegend = true; this.shouldUpdateLabels = true; this.shouldUpdateSeriesLabels = true; this.shouldUpdateDiffLabelColor = true; } @Watch('hoverStyle') hoverStyleWatcher(_newVal, _oldVal) { this.shouldUpdateMarkerIDs = true; this.shouldUpdateBarStyle = true; this.shouldUpdateMarkerSize = true; this.shouldDrawInteractionState = true; this.shouldSetSeriesLabelOpacity = true; } @Watch('clickStyle') clickStyleWatcher(_newVal, _oldVal) { this.shouldUpdateMarkerIDs = true; this.shouldUpdateBarStyle = true; this.shouldUpdateMarkerSize = true; this.shouldDrawInteractionState = true; this.shouldSetSeriesLabelOpacity = true; } @Watch('hoverOpacity') hoverOpacityWatcher(_newVal, _oldVal) { this.shouldDrawInteractionState = true; this.shouldSetLabelOpacity = true; this.shouldSetSeriesLabelOpacity = true; this.shouldSetDifferenceLabelOpacity = true; } @Watch('cursor') cursorWatcher(_newVal, _oldVal) { this.shouldUpdateCursor = true; this.shouldSetLegendCursor = true; this.shouldSetSeriesCursor = true; } @Watch('focusMarker') focusMarkerWatcher(_newVal, _oldVal) { this.shouldDrawMarkerGeometries = true; this.shouldSetGlobalSelections = true; this.shouldSetTestingAttributes = true; this.shouldUpdateMarkerIDs = true; this.shouldUpdateData = true; this.shouldUpdateMarkerData = true; this.shouldUpdateSeriesData = true; this.shouldUpdateLabels = true; const newSizeVal = _newVal && _newVal.sizeFromBar ? _newVal.sizeFromBar : 0; const oldSizeVal = _oldVal && _oldVal.sizeFromBar ? _oldVal.sizeFromBar : 0; if (newSizeVal !== oldSizeVal) { this.shouldUpdateMarkerSize = true; } const newKey = _newVal && _newVal.key ? _newVal.key : false; const oldKey = _oldVal && _oldVal.key ? _oldVal.key : false; if (newKey !== oldKey) { this.shouldUpdateDiffLabelColor = true; this.shouldUpdateMarkerSize = true; this.shouldUpdateBarStyle = true; } } @Watch('marker') markerWatcher(_newVal, _oldVal) { const newVisVal = _newVal && _newVal.visible; const oldVisVal = _oldVal && _oldVal.visible; if (newVisVal !== oldVisVal) { this.shouldUpdateMarkerOpacity = true; } const newTypeVal = _newVal && _newVal.type ? _newVal.type : false; const oldTypeVal = _oldVal && _oldVal.type ? _oldVal.type : false; if (newTypeVal !== oldTypeVal) { this.shouldRenderMarkerGroup = true; this.shouldEnterUpdateExitMarkers = true; } this.shouldSetGlobalSelections = true; this.shouldSetTestingAttributes = true; this.shouldUpdateMarkerIDs = true; this.shouldUpdateMarkerData = true; this.shouldUpdateSeriesData = true; this.shouldUpdateData = true; this.shouldUpdateLabels = true; const newSizeVal = _newVal && _newVal.sizeFromBar ? _newVal.sizeFromBar : 0; const oldSizeVal = _oldVal && _oldVal.sizeFromBar ? _oldVal.sizeFromBar : 0; if (newSizeVal !== oldSizeVal) { this.shouldUpdateMarkerSize = true; } } @Watch('barStyle') barStyleWatcher(_newVal, _oldVal) { this.shouldUpdateMarkerIDs = true; this.shouldUpdateBarStyle = true; this.shouldUpdateMarkerSize = true; this.shouldUpdateDiffLabelColor = true; this.shouldDrawInteractionState = true; const newSizeVal = _newVal && _newVal.width ? _newVal.width : 0; const oldSizeVal = _oldVal && _oldVal.width ? _oldVal.width : 0; if (newSizeVal !== oldSizeVal) { this.shouldDrawInteractionState = true; this.shouldUpdateMarkerData = true; this.shouldUpdateData = true; this.shouldUpdateMarkerSize = true; this.shouldUpdateGeometries = true; this.shouldUpdateLabels = true; this.shouldUpdateDifferenceLabels = true; this.shouldUpdateSeriesLabels = true; } } @Watch('dataLabel') dataLabelWatcher(_newVal, _oldVal) { this.shouldUpdateLabels = true; this.shouldUpdateTableData = true; const newPlacementVal = _newVal && _newVal.placement ? _newVal.placement : false; const oldPlacementVal = _oldVal && _oldVal.placement ? _oldVal.placement : false; const newVisibleVal = _newVal && _newVal.visible; const oldVisibleVal = _oldVal && _oldVal.visible; const newAccessor = _newVal && _newVal.labelAccessor ? _newVal.labelAccessor : false; const oldAccessor = _oldVal && _oldVal.labelAccessor ? _oldVal.labelAccessor : false; if (newVisibleVal !== oldVisibleVal) { this.shouldSetLabelOpacity = true; } if (newPlacementVal !== oldPlacementVal) { this.shouldValidateDataLabelPlacement = true; // this.shouldCheckLabelColor = true; } if (newAccessor !== oldAccessor) { this.shouldValidateDataLabelAccessor = true; } } @Watch('seriesLabel') seriesLabelWatcher(_newVal, _oldVal) { this.shouldValidateSeriesLabelPlacement = true; this.shouldUpdateSeriesLabels = true; this.shouldAddStrokeUnder = true; this.shouldUpdateTableData = true; const newVisibleVal = _newVal && _newVal.visible; const oldVisibleVal = _oldVal && _oldVal.visible; if (newVisibleVal !== oldVisibleVal) { this.shouldSetSeriesLabelOpacity = true; } const newPlacementVal = _newVal && _newVal.placement ? _newVal.placement : false; const oldPlacementVal = _oldVal && _oldVal.placement ? _oldVal.placement : false; if (newPlacementVal !== oldPlacementVal) { this.shouldUpdateSeriesData = true; this.shouldSetSeriesSelections = true; } } @Watch('differenceLabel') differenceLabelWatcher(_newVal, _oldVal) { this.shouldUpdateDifferenceLabels = true; this.shouldUpdateDiffLabelColor = true; this.shouldAddStrokeUnder = true; this.shouldUpdateTableData = true; const newVisibleVal = _newVal && _newVal.visible; const oldVisibleVal = _oldVal && _oldVal.visible; if (newVisibleVal !== oldVisibleVal) { this.shouldSetDifferenceLabelOpacity = true; } const newPlacementVal = _newVal && _newVal.placement ? _newVal.placement : false; const oldPlacementVal = _oldVal && _oldVal.placement ? _oldVal.placement : false; if (newPlacementVal !== oldPlacementVal) { this.shouldValidateDiffLabelPlacement = true; } } @Watch('showTooltip') showTooltipWatcher(_newVal, _oldVal) { this.shouldDrawInteractionState = true; } @Watch('tooltipLabel') tooltipLabelWatcher(_newVal, _oldVal) { this.shouldUpdateTableData = true; } @Watch('accessibility') accessibilityWatcher(_newVal, _oldVal) { this.shouldValidate = true; const newTitle = _newVal && _newVal.title ? _newVal.title : false; const oldTitle = _oldVal && _oldVal.title ? _oldVal.title : false; if (newTitle !== oldTitle) { this.shouldUpdateDescriptionWrapper = true; this.shouldSetChartAccessibilityTitle = true; this.shouldSetParentSVGAccessibility = true; } const newExecutiveSummary = _newVal && _newVal.executiveSummary ? _newVal.executiveSummary : false; const oldExecutiveSummary = _oldVal && _oldVal.executiveSummary ? _oldVal.executiveSummary : false; if (newExecutiveSummary !== oldExecutiveSummary) { this.shouldSetChartAccessibilityExecutiveSummary = true; } const newPurpose = _newVal && _newVal.purpose ? _newVal.purpose : false; const oldPurpose = _oldVal && _oldVal.purpose ? _oldVal.purpose : false; if (newPurpose !== oldPurpose) { this.shouldSetChartAccessibilityPurpose = true; } const newLongDescription = _newVal && _newVal.longDescription ? _newVal.longDescription : false; const oldLongDescription = _oldVal && _oldVal.longDescription ? _oldVal.longDescription : false; if (newLongDescription !== oldLongDescription) { this.shouldSetChartAccessibilityLongDescription = true; } const newContext = _newVal && _newVal.contextExplanation ? _newVal.contextExplanation : false; const oldContext = _oldVal && _oldVal.contextExplanation ? _oldVal.contextExplanation : false; if (newContext !== oldContext) { this.shouldSetChartAccessibilityContext = true; } const newStatisticalNotes = _newVal && _newVal.statisticalNotes ? _newVal.statisticalNotes : false; const oldStatisticalNotes = _oldVal && _oldVal.statisticalNotes ? _oldVal.statisticalNotes : false; if (newStatisticalNotes !== oldStatisticalNotes) { this.shouldSetChartAccessibilityStatisticalNotes = true; } const newStructureNotes = _newVal && _newVal.structureNotes ? _newVal.structureNotes : false; const oldStructureNotes = _oldVal && _oldVal.structureNotes ? _oldVal.structureNotes : false; if (newStructureNotes !== oldStructureNotes) { this.shouldSetChartAccessibilityStructureNotes = true; } const newincludeDataKeyNames = _newVal && _newVal.includeDataKeyNames; const oldincludeDataKeyNames = _oldVal && _oldVal.includeDataKeyNames; const newElementDescriptionAccessor = _newVal && _newVal.elementDescriptionAccessor ? _newVal.elementDescriptionAccessor : false; const oldElementDescriptionAccessor = _oldVal && _oldVal.elementDescriptionAccessor ? _oldVal.elementDescriptionAccessor : false; if ( newincludeDataKeyNames !== oldincludeDataKeyNames || newElementDescriptionAccessor !== oldElementDescriptionAccessor ) { if (newincludeDataKeyNames !== oldincludeDataKeyNames) { // this one is tricky because it needs to run after the lifecycle // AND it could run in the off-chance this prop is changed this.shouldSetGroupAccessibilityLabel = true; } this.shouldSetGeometryAriaLabels = true; this.shouldSetParentSVGAccessibility = true; } const newStrokes = _newVal && _newVal.hideStrokes ? _newVal.hideStrokes : false; const oldStrokes = _oldVal && _oldVal.hideStrokes ? _oldVal.hideStrokes : false; if (newStrokes !== oldStrokes) { this.shouldUpdateBarStyle = true; this.shouldUpdateMarkerStyle = true; this.shouldAddStrokeUnder = true; this.shouldUpdateLegend = true; } const newKeyNav = _newVal && _newVal.keyboardNavConfig && _newVal.keyboardNavConfig.disabled ? _newVal.keyboardNavConfig.disabled : false; const oldKeyNav = _oldVal && _oldVal.keyboardNavConfig && _oldVal.keyboardNavConfig.disabled ? _oldVal.keyboardNavConfig.disabled : false; const newInterface = _newVal && _newVal.elementsAreInterface ? _newVal.elementsAreInterface : false; const oldInterface = _oldVal && _oldVal.elementsAreInterface ? _oldVal.elementsAreInterface : false; if (newKeyNav !== oldKeyNav || newInterface !== oldInterface) { this.shouldSetGeometryAriaLabels = true; this.shouldSetParentSVGAccessibility = true; this.shouldUpdateDescriptionWrapper = true; this.shouldRedrawWrapper = true; this.shouldSetChartAccessibilityTitle = true; this.shouldSetChartAccessibilitySubtitle = true; this.shouldSetChartAccessibilityLongDescription = true; this.shouldSetChartAccessibilityContext = true; this.shouldSetChartAccessibilityExecutiveSummary = true; this.shouldSetChartAccessibilityPurpose = true; this.shouldSetChartAccessibilityStatisticalNotes = true; this.shouldSetChartAccessibilityStructureNotes = true; } if (newInterface !== oldInterface) { this.shouldSetSelectionClass = true; } } @Watch('legend') legendWatcher(_newVal, _oldVal) { this.shouldUpdateLegend = true; const newInteractiveVal = _newVal && _newVal.interactive; const oldInteractiveVal = _oldVal && _oldVal.interactive; if (newInteractiveVal !== oldInteractiveVal) { this.shouldBindLegendInteractivity = true; this.shouldSetLegendCursor = true; } } @Watch('annotations') annotationsWatcher(_newVal, _oldVal) { this.shouldValidate = true; this.shouldUpdateAnnotations = true; this.shouldSetAnnotationAccessibility = true; } @Watch('maxValueOverride') @Watch('minValueOverride') valueOverrideWatcher(_newVal, _oldVal) { this.shouldUpdateScales = true; this.shouldUpdateGeometries = true; this.shouldCheckValueAxis = true; this.shouldUpdateLabels = true; this.shouldUpdateSeriesLabels = true; this.shouldUpdateDifferenceLabels = true; this.shouldUpdateReferenceLines = true; this.shouldUpdateBaselineX = true; this.shouldUpdateBaselineY = true; this.shouldUpdateAnnotations = true; } @Watch('referenceStyle') @Watch('referenceLines') referenceWatcher(_newVal, _oldVal) { this.shouldUpdateReferenceLines = true; } @Watch('suppressEvents') suppressWatcher(_newVal, _oldVal) { this.shouldBindInteractivity = true; this.shouldBindLegendInteractivity = true; this.shouldBindSeriesInteractivity = true; this.shouldUpdateCursor = true; this.shouldSetLegendCursor = true; this.shouldSetSeriesCursor = true; this.shouldSetGeometryAriaLabels = true; this.shouldSetParentSVGAccessibility = true; this.shouldUpdateDescriptionWrapper = true; this.shouldRedrawWrapper = true; this.shouldValidate = true; this.shouldSetChartAccessibilityTitle = true; this.shouldSetChartAccessibilitySubtitle = true; this.shouldSetChartAccessibilityLongDescription = true; this.shouldSetChartAccessibilityContext = true; this.shouldSetChartAccessibilityExecutiveSummary = true; this.shouldSetChartAccessibilityPurpose = true; this.shouldSetChartAccessibilityStatisticalNotes = true; this.shouldSetChartAccessibilityStructureNotes = true; } @Watch('hoverHighlight') hoverWatcher(_newVal, _oldVal) { this.shouldUpdateMarkerIDs = true; this.shouldDrawInteractionState = true; this.shouldUpdateMarkerSize = true; this.shouldUpdateMarkerStyle = true; this.shouldSetLabelOpacity = true; this.shouldSetSeriesLabelOpacity = true; this.shouldSetDifferenceLabelOpacity = true; this.shouldUpdateData = true; // this.shouldUpdateLabels = true; this.shouldUpdateMarkerData = true; this.shouldSetGlobalSelections = true; } @Watch('clickHighlight') clickWatcher(_newVal, _oldVal) { this.shouldUpdateMarkerIDs = true; this.shouldDrawInteractionState = true; this.shouldUpdateMarkerSize = true; this.shouldUpdateMarkerStyle = true; this.shouldSetLabelOpacity = true; this.shouldSetSelectionClass = true; this.shouldSetSeriesLabelOpacity = true; this.shouldSetDifferenceLabelOpacity = true; this.shouldUpdateData = true; // this.shouldUpdateLabels = true; this.shouldUpdateMarkerData = true; this.shouldSetGlobalSelections = true; } @Watch('interactionKeys') interactionWatcher(_newVal, _oldVal) { this.shouldValidateInteractionKeys = true; this.shouldUpdateMarkerSize = true; this.shouldDrawInteractionState = true; this.shouldUpdateMarkerStyle = true; this.shouldSetLabelOpacity = true; this.shouldSetSeriesLabelOpacity = true; this.shouldSetDifferenceLabelOpacity = true; this.shouldSetSelectionClass = true; this.shouldSetGeometryAriaLabels = true; this.shouldUpdateTableData = true; this.shouldUpdateData = true; // this.shouldUpdateLabels = true; this.shouldUpdateMarkerData = true; this.shouldSetGlobalSelections = true; // if the new value is the seriesAccessor rebind the legend // should also compare this to old val to be even more efficient const newValSeriesCheck = _newVal && _newVal.length === 1 ? _newVal[0] === this.seriesAccessor : false; const oldValSeriesCheck = _oldVal && _oldVal.length === 1 ? _oldVal[0] === this.seriesAccessor : false; if (newValSeriesCheck !== oldValSeriesCheck) { this.shouldBindSeriesInteractivity = true; // this has to be added to handle updates to series labels this.shouldSetSeriesCursor = true; this.shouldBindLegendInteractivity = true; this.shouldSetLegendCursor = true; } } @Watch('unitTest') unitTestWatcher(_newVal, _oldVal) { this.shouldSetTestingAttributes = true; } componentWillLoad() { // contrary to componentWillUpdate, this method appears safe to use for // any calculations we need. Keeping them here reduces future refactor, // since componentWillUpdate should eventually mirror this method return new Promise(resolve => { this.duration = 0; this.chartID = this.uniqueID || 'dumbbell-plot-' + uuid(); this.dumbbellPlotEl.id = this.chartID; this.setTagLevels(); this.checkIfSafari(); this.validateLayout(); this.validateDataLabelPlacement(); this.validateSeriesLabelPlacement(); this.validateDiffLabelPlacement(); this.validateInteractionKeys(); this.prepareData(); this.prepareMarkerData(); this.prepareSeriesData(); this.prepareLegendData(); this.setLayoutData(); this.prepareScales(); this.validateDataLabelAccessor(); this.setTableData(); this.shouldValidateAccessibilityProps(); this.setColors(); resolve('component will load'); }); } componentWillUpdate() { // NEVER put items in this method (until stencil bug is resolved) // All items that belong here are currently at the top of componentDidUpdate // see: https://github.com/ionic-team/stencil/issues/2061#issuecomment-578282178 return new Promise(resolve => { resolve('component will update'); }); } componentDidLoad() { return new Promise(resolve => { this.defaults = true; this.shouldValidateAccessibilityProps(); this.renderRootElements(); this.setTooltipInitialStyle(); this.setChartDescriptionWrapper(); this.setChartAccessibilityTitle(); this.setChartAccessibilitySubtitle(); this.setChartAccessibilityLongDescription(); this.setChartAccessibilityExecutiveSummary(); this.setChartAccessibilityPurpose(); this.setChartAccessibilityContext(); this.setChartAccessibilityStatisticalNotes(); this.setChartAccessibilityStructureNotes(); this.setParentSVGAccessibility(); this.reSetRoot(); this.drawXGrid(); this.drawYGrid(); this.renderMarkerGroup(); this.setGlobalSelections(); this.setTestingAttributes(); this.enterMarkerGeometries(); this.updateMarkerGeometries(); this.exitMarkerGeometries(); this.updateMarkerSize(); this.enterDumbbells(); this.updateDumbbells(); this.exitDumbbells(); this.enterSeriesLabels(); this.updateSeriesLabels(); this.exitSeriesLabels(); this.enterDataLabels(); this.updateDataLabels(); this.exitDataLabels(); this.enterDifferenceLabels(); this.updateDifferenceLabels(); this.exitDifferenceLabels(); this.updateMarkerIds(); this.drawDumbbells(); this.updateInteractionState(); this.setChartCountAccessibility(); this.setGeometryAccessibilityAttributes(); this.setGeometryAriaLabels(); // this.updateBarStyle(); this.drawLegendElements(); this.drawDataLabels(); this.drawSeriesLabels(); this.drawDifferenceLabels(); this.addStrokeUnder(); this.drawReferenceLines(); this.setSelectedClass(); this.setLabelOpacity(); // this.updateCursor(); // this.bindInteractivity(); this.bindLegendInteractivity(); // this.bindSeriesInteractivity(); this.setLegendCursor(); // this.setSeriesCursor(); this.drawAnnotations(); this.setAnnotationAccessibility(); this.drawXAxis(); this.setXAxisAccessibility(); this.drawYAxis(); this.setYAxisAccessibility(); this.drawBaselineX(); this.drawBaselineY(); this.onChangeHandler(); // we want to hide all child <g> of this.root BUT we want to make sure not to hide the // parent<g> that contains our geometries! In a subGroup chart (like stacked bars), // we want to pass the PARENT of all the <g>s that contain bars hideNonessentialGroups(this.root.node(), this.dumbbellG.node()); this.setGroupAccessibilityAttributes(); this.setGroupAccessibilityID(); this.defaults = false; resolve('component did load'); }); } componentDidUpdate() { return new Promise(resolve => { this.duration = !this.animationConfig || !this.animationConfig.disabled ? 750 : 0; if (this.shouldUpdateDescriptionWrapper) { this.setChartDescriptionWrapper(); this.shouldUpdateDescriptionWrapper = false; } if (this.shouldSetChartAccessibilityCount) { this.setChartCountAccessibility(); this.shouldSetChartAccessibilityCount = false; } if (this.shouldSetChartAccessibilityTitle) { this.setChartAccessibilityTitle(); this.shouldSetChartAccessibilityTitle = false; } if (this.shouldSetChartAccessibilitySubtitle) { this.setChartAccessibilitySubtitle(); this.shouldSetChartAccessibilitySubtitle = false; } if (this.shouldSetChartAccessibilityLongDescription) { this.setChartAccessibilityLongDescription(); this.shouldSetChartAccessibilityLongDescription = false; } if (this.shouldSetChartAccessibilityExecutiveSummary) { this.setChartAccessibilityExecutiveSummary(); this.shouldSetChartAccessibilityExecutiveSummary = false; } if (this.shouldSetChartAccessibilityPurpose) { this.setChartAccessibilityPurpose(); this.shouldSetChartAccessibilityPurpose = false; } if (this.shouldSetChartAccessibilityContext) { this.setChartAccessibilityContext(); this.shouldSetChartAccessibilityContext = false; } if (this.shouldSetChartAccessibilityStatisticalNotes) { this.setChartAccessibilityStatisticalNotes(); this.shouldSetChartAccessibilityStatisticalNotes = false; } if (this.shouldSetChartAccessibilityStructureNotes) { this.setChartAccessibilityStructureNotes(); this.shouldSetChartAccessibilityStructureNotes = false; } if (this.shouldSetParentSVGAccessibility) { this.setParentSVGAccessibility(); this.shouldSetParentSVGAccessibility = false; } if (this.shouldResetRoot) { this.reSetRoot(); this.shouldResetRoot = false; } if (this.shouldRenderMarkerGroup) { this.renderMarkerGroup(); this.shouldRenderMarkerGroup = false; } if (this.shouldSetGlobalSelections) { this.setGlobalSelections(); this.shouldSetGlobalSelections = false; } if (this.shouldSetSeriesSelections) { this.setSeriesSelections(); this.shouldSetSeriesSelections = false; } if (this.shouldSetTestingAttributes) { this.setTestingAttributes(); this.shouldSetTestingAttributes = false; } if (this.shouldUpdateXGrid) { this.drawXGrid(); this.shouldUpdateXGrid = false; } if (this.shouldUpdateYGrid) { this.drawYGrid(); this.shouldUpdateYGrid = false; } if (this.shouldEnterUpdateExitMarkers) { this.enterMarkerGeometries(); this.updateMarkerGeometries(); this.exitMarkerGeometries(); this.shouldEnterUpdateExitMarkers = false; this.shouldUpdateMarkerOpacity = false; } if (this.shouldUpdateMarkerOpacity) { this.updateMarkerGeometries(); this.shouldUpdateMarkerOpacity = false; } if (this.shouldEnterUpdateExit) { this.enterDumbbells(); this.updateDumbbells(); this.exitDumbbells(); this.enterSeriesLabels(); this.updateSeriesLabels(); this.exitSeriesLabels(); this.enterDataLabels(); this.updateDataLabels(); this.exitDataLabels(); this.enterDifferenceLabels(); this.updateDifferenceLabels(); this.exitDifferenceLabels(); this.shouldEnterUpdateExit = false; } if (this.shouldUpdateMarkerIDs) { this.updateMarkerIds(); this.shouldUpdateMarkerIDs = false; } if (this.shouldUpdateGeometries) { this.drawDumbbells(); this.shouldUpdateGeometries = false; } if (this.shouldUpdateBarStyle) { this.updateBarStyle(); this.shouldUpdateBarStyle = false; } if (this.shouldUpdateMarkerStyle) { this.updateMarkerStyle(); this.shouldUpdateMarkerStyle = false; } if (this.shouldUpdateMarkerSize) { this.updateMarkerSize(); this.shouldUpdateMarkerSize = false; } if (this.shouldDrawMarkerGeometries) { this.drawMarkerGeometries(); this.shouldDrawMarkerGeometries = false; } if (this.shouldSetGeometryAccessibilityAttributes) { this.setGeometryAccessibilityAttributes(); this.shouldSetGeometryAccessibilityAttributes = false; } if (this.shouldSetGeometryAriaLabels) { this.setGeometryAriaLabels(); this.shouldSetGeometryAriaLabels = false; } if (this.shouldSetGroupAccessibilityLabel) { this.setGroupAccessibilityID(); this.shouldSetGroupAccessibilityLabel = false; } if (this.shouldUpdateLegend) { this.drawLegendElements(); this.shouldUpdateLegend = false; } if (this.shouldUpdateLabels) { this.drawDataLabels(); this.shouldUpdateLabels = false; } if (this.shouldUpdateSeriesLabels) { this.drawSeriesLabels(); this.shouldUpdateSeriesLabels = false; } if (this.shouldUpdateDifferenceLabels) { this.drawDifferenceLabels(); this.shouldUpdateDifferenceLabels = false; } if (this.shouldAddStrokeUnder) { this.addStrokeUnder(); this.shouldAddStrokeUnder = false; } if (this.shouldUpdateReferenceLines) { this.drawReferenceLines(); this.shouldUpdateReferenceLines = false; } if (this.shouldSetLabelOpacity) { this.setLabelOpacity(); this.shouldSetLabelOpacity = false; } if (this.shouldSetSeriesLabelOpacity) { this.setSeriesLabelOpacity(); this.shouldSetSeriesLabelOpacity = false; } if (this.shouldSetDifferenceLabelOpacity) { this.setDifferenceLabelOpacity(); this.shouldSetDifferenceLabelOpacity = false; } if (this.shouldUpdateDiffLabelColor) { this.updateDiffLabelColor(); this.shouldUpdateDiffLabelColor = false; } if (this.shouldDrawInteractionState) { this.updateInteractionState(); this.shouldDrawInteractionState = false; } if (this.shouldSetSelectionClass) { this.setSelectedClass(); this.shouldSetSelectionClass = false; } if (this.shouldBindLegendInteractivity) { this.bindLegendInteractivity(); this.shouldBindLegendInteractivity = false; } if (this.shouldBindSeriesInteractivity) { this.bindSeriesInteractivity(); this.shouldBindSeriesInteractivity = false; } if (this.shouldSetLegendCursor) { this.setLegendCursor(); this.shouldSetLegendCursor = false; } if (this.shouldSetSeriesCursor) { this.setSeriesCursor(); this.shouldSetSeriesCursor = false; } if (this.shouldUpdateCursor) { this.updateCursor(); this.shouldUpdateCursor = false; } if (this.shouldBindInteractivity) { this.bindInteractivity(); this.shouldBindInteractivity = false; } if (this.shouldUpdateAnnotations) { this.drawAnnotations(); this.shouldUpdateAnnotations = false; } if (this.shouldSetAnnotationAccessibility) { this.setAnnotationAccessibility(); this.shouldSetAnnotationAccessibility = false; } if (this.shouldUpdateXAxis) { this.drawXAxis(); this.shouldUpdateXAxis = false; } if (this.shouldSetXAxisAccessibility) { this.setXAxisAccessibility(); this.shouldSetXAxisAccessibility = false; } if (this.shouldUpdateYAxis) { this.drawYAxis(); this.shouldUpdateYAxis = false; } if (this.shouldSetYAxisAccessibility) { this.setYAxisAccessibility(); this.shouldSetYAxisAccessibility = false; } if (this.shouldUpdateBaselineX) { this.drawBaselineX(); this.shouldUpdateBaseline = false; } if (this.shouldUpdateBaselineY) { this.drawBaselineY(); this.shouldUpdateBaseline = false; } this.onChangeHandler(); resolve('component did update'); }); } shouldValidateAccessibilityProps() { if (this.shouldValidateAccessibility && !this.accessibility.disableValidation) { this.shouldValidateAccessibility = false; validateAccessibilityProps( this.chartID, { ...this.accessibility }, { annotations: this.annotations, data: this.data, uniqueID: this.uniqueID, context: { mainTitle: this.mainTitle, onClickFunc: !this.suppressEvents ? this.clickFunc.emit : undefined } } ); } } validateInteractionKeys() { this.innerInteractionKeys = this.interactionKeys && this.interactionKeys.length ? this.interactionKeys : [this.ordinalAccessor]; this.seriesInteraction = this.innerInteractionKeys.length === 1 && this.innerInteractionKeys[0] === this.seriesAccessor; this.dumbbellInteraction = this.innerInteractionKeys.length === 1 && this.innerInteractionKeys[0] === this.ordinalAccessor; } validateDataLabelAccessor() { this.innerLabelAccessor = this.dataLabel.labelAccessor ? this.dataLabel.labelAccessor : this.valueAccessor; } validateLayout() { this.layoutOverride = !this.layout || this.data[0][this.ordinalAccessor] instanceof Date ? 'vertical' : this.layout; this.isVertical = this.layoutOverride === 'vertical'; } validateDataLabelPlacement() { this.placement = this.dataLabel.placement; // this.layoutOverride = !this.layout || this.data[0][this.ordinalAccessor] instanceof Date ? 'vertical' : this.layout; if (this.isVertical) { if (this.placement !== 'left' && this.placement !== 'right' && this.placement !== 'auto') { this.placement = 'ends'; } } else { if (this.placement !== 'top' && this.placement !== 'bottom' && this.placement !== 'auto') { this.placement = 'ends'; } } } validateSeriesLabelPlacement() { this.seriesLabelDetails = { ...this.seriesLabel }; if (!this.seriesLabelDetails.placement) { this.seriesLabelDetails.placement = this.isVertical ? 'right' : 'top'; } if ( this.isVertical && (this.seriesLabelDetails.placement !== 'right' && this.seriesLabelDetails.placement !== 'left' && this.seriesLabelDetails.placement !== 'auto') ) { this.seriesLabelDetails.placement = 'right'; } else if ( !this.isVertical && (this.seriesLabelDetails.placement !== 'top' && this.seriesLabelDetails.placement !== 'bottom' && this.seriesLabelDetails.placement !== 'auto') ) { this.seriesLabelDetails.placement = 'top'; } if (!this.seriesLabelDetails.label || !this.seriesLabelDetails.label.length) { this.seriesLabelDetails.label = ''; } } validateDiffLabelPlacement() { this.diffLabelDetails = { ...this.differenceLabel }; if (!this.diffLabelDetails.placement) { this.diffLabelDetails.placement = this.isVertical ? 'left' : 'top'; } if ( this.isVertical && (this.diffLabelDetails.placement !== 'right' && this.diffLabelDetails.placement !== 'left' && this.diffLabelDetails.placement !== 'auto') ) { this.diffLabelDetails.placement = 'left'; } else if ( !this.isVertical && (this.diffLabelDetails.placement !== 'top' && this.diffLabelDetails.placement !== 'bottom' && this.diffLabelDetails.placement !== 'auto') ) { this.diffLabelDetails.placement = 'top'; } } checkIfSafari() { this.url = createUrl(); } setColors() { this.colors = this.colors ? convertVisaColor(this.colors) : ''; this.rawColors = this.colors || getColors(this.colorPalette, 3); this.colorArr = this.rawColors; this.textColors = {}; this.strokes = {}; this.rawColors.forEach(color => { if (!this.accessibility.hideStrokes) { const strokes = getAccessibleStrokes(color); const adjusted = strokes.length === 2 ? strokes[1] : strokes[0]; this.strokes[color.toLowerCase()] = adjusted; } this.textColors[color.toLowerCase()] = ensureTextContrast(color, '#ffffff', 4.5); }); if (this.hoverStyle && this.hoverStyle.color) { if (!this.accessibility.hideStrokes) { const strokes = getAccessibleStrokes(this.hoverStyle.color); const adjusted = strokes.length === 2 ? strokes[1] : strokes[0]; this.strokes[this.hoverStyle.color.toLowerCase()] = adjusted; } this.textColors[this.hoverStyle.color.toLowerCase()] = ensureTextContrast(this.hoverStyle.color, '#ffffff', 4.5); } if (this.clickStyle && this.clickStyle.color) { if (!this.accessibility.hideStrokes) { const strokes = getAccessibleStrokes(this.clickStyle.color); const adjusted = strokes.length === 2 ? strokes[1] : strokes[0]; this.strokes[this.clickStyle.color.toLowerCase()] = adjusted; } this.textColors[this.clickStyle.color.toLowerCase()] = ensureTextContrast(this.clickStyle.color, '#ffffff', 4.5); } } // eventually we might use textures for dumbbell, but unfortunately marker elements scale their interior fill // this causes markers to have terrible looking textures at larger sizes! Unfortunate. // setTextures() { // // dumbbell will only ever need 3 colors, but this ensures that in some weird circumstances where colors array has // // more than 6 colors passed into it, the textures function won't throw any errors, since it maxes out at 6 textures. // const colorsArray = !(this.colorArr.length > 6) ? this.colorArr : this.colorArr.slice(0,6); // if (!this.accessibility.hideTextures) { // this.colorArr = convertColorsToTextures({ // colors: colorsArray, // rootSVG: this.svg.node(), // id: this.chartID, // scheme: 'categorical' // }); // } else { // this.colorArr = this.rawColors // } // } setLayoutData() { this.padding = typeof this.padding === 'string' ? getPadding(this.padding) : this.padding; this.innerHeight = this.height - this.margin.top - this.margin.bottom; this.innerWidth = this.width - this.margin.left - this.margin.right; this.innerPaddedHeight = this.innerHeight - this.padding.top - this.padding.bottom; this.innerPaddedWidth = this.innerWidth - this.padding.left - this.padding.right; } setTableData() { // generate scoped and formatted data for data-table component const keys = scopeDataKeys(this, chartAccessors, 'dumbbell-plot'); this.tableData = getScopedData(this.data, keys); this.tableColumns = Object.keys(keys); } prepareData() { const nested = nest() .key(d => d[this.ordinalAccessor]) .entries(this.data); nested.forEach(parent => { parent.focusMarker = false; parent.greaterIndex = 1; let firstMarker = 'marker'; let secondMarker = 'marker'; if (parent.values[0][this.seriesAccessor] === this.focusMarker.key) { parent.focusMarker = 0; firstMarker = 'focusMarker'; } else if (parent.values[1][this.seriesAccessor] === this.focusMarker.key) { parent.focusMarker = 1; secondMarker = 'focusMarker'; } const bar0Width = checkClicked(parent.values[0], this.clickHighlight, this.innerInteractionKeys) ? parseFloat(this.clickStyle.strokeWidth + '') || this.barStyle.width : checkHovered(parent.values[0], this.hoverHighlight, this.innerInteractionKeys) ? parseFloat(this.hoverStyle.strokeWidth + '') || this.barStyle.width : this.barStyle.width; // : this.barStyle.width; const bar1Width = checkClicked(parent.values[1], this.clickHighlight, this.innerInteractionKeys) ? parseFloat(this.clickStyle.strokeWidth + '') || this.barStyle.width : checkHovered(parent.values[1], this.hoverHighlight, this.innerInteractionKeys) ? parseFloat(this.hoverStyle.strokeWidth + '') || this.barStyle.width : this.barStyle.width; // : this.barStyle.width; parent.values[0].offset = parent.focusMarker !== 0 && !this.marker.visible ? 1 : this.marker.type === 'dot' ? (this[firstMarker].sizeFromBar * (bar0Width + 1)) / 2 : this.marker.type === 'stroke' ? (this[firstMarker].sizeFromBar * (bar0Width + 1)) / 5 : !parent.focusMarker ? (this[firstMarker].sizeFromBar * (bar0Width + 1)) / 2 : (this[firstMarker].sizeFromBar * (bar0Width + 1)) / 5; parent.values[1].offset = parent.focusMarker !== 1 && !this.marker.visible ? -1 : this.marker.type === 'dot' ? -(this[secondMarker].sizeFromBar * (bar1Width + 1)) / 2 : this.marker.type === 'stroke' ? -(this[secondMarker].sizeFromBar * (bar1Width + 1)) / 5 : parent.focusMarker ? -(this[secondMarker].sizeFromBar * (bar1Width + 1)) / 2 : -(this[secondMarker].sizeFromBar * (bar1Width + 1)) / 5; if (parent.values[0][this.valueAccessor] >= parent.values[1][this.valueAccessor]) { parent.greaterIndex = 0; parent.values[0].offset = -parent.values[0].offset; parent.values[1].offset = -parent.values[1].offset; } }); const prepareMessage = d => { const hash = { absoluteDiff: 'Absolute Difference ', difference: 'Difference ' }; const calculation = this.differenceLabel && this.differenceLabel.calculation && hash[this.differenceLabel.calculation] ? this.differenceLabel.calculation : 'difference'; const format = this.differenceLabel && this.differenceLabel.format && this.differenceLabel.visible ? this.differenceLabel.format : this.differenceLabel && this.dataLabel.format && this.dataLabel.visible ? this.dataLabel.format : '0[.][0][0]a'; return hash[calculation] + formatDataLabel(d, calculation, format); }; this.nest = nested.sort((a, b) => { a.difference = a.values[0][this.valueAccessor] - a.values[1][this.valueAccessor]; b.difference = b.values[0][this.valueAccessor] - b.values[1][this.valueAccessor]; a.absoluteDiff = Math.abs(a.difference); b.absoluteDiff = Math.abs(b.difference); a.middle = (a.values[0][this.valueAccessor] + a.values[1][this.valueAccessor]) / 2; b.middle = (b.values[0][this.valueAccessor] + b.values[1][this.valueAccessor]) / 2; a.message = prepareMessage(a); b.message = prepareMessage(b); const focusIndex = a.focusMarker !== false ? a.focusMarker : 0; return a.values[0][this.ordinalAccessor] instanceof Date ? 0 : this.sortOrder === 'asc' || this.sortOrder === 'diffAsc' ? a.difference - b.difference : this.sortOrder === 'desc' || this.sortOrder === 'diffDesc' ? b.difference - a.difference : this.sortOrder === 'focusAsc' ? a.values[focusIndex][this.valueAccessor] - b.values[focusIndex][this.valueAccessor] : this.sortOrder === 'focusDesc' ? b.values[focusIndex][this.valueAccessor] - a.values[focusIndex][this.valueAccessor] : this.sortOrder === 'absoluteDiffAsc' ? a.absoluteDiff - b.absoluteDiff : this.sortOrder === 'absoluteDiffDesc' ? b.absoluteDiff - a.absoluteDiff : 0; }); // this.map = nest() // .key(d => d[this.ordinalAccessor]) // .map(this.data); } prepareMarkerData() { this.markerData = []; const first = { focus: false, label: this.nest[0].values[0][this.seriesAccessor] }; const second = { focus: false, label: this.nest[0].values[1][this.seriesAccessor] }; if (this.nest[0].focusMarker) { second.focus = true; } else if (this.nest[0].focusMarker === 0) { first.focus = true; } // if (!this.isVertical) { // first.value = this.nest[0].values[0][this.valueAccessor]; // second.value = this.nest[0].values[1][this.valueAccessor]; // } const third = { ...first, limitOpacity: true }; const fourth = { ...second, limitOpacity: true }; const fifth = { ...first }; const sixth = { ...second }; this.markerData.push(first); this.markerData.push(second); this.markerData.push(third); this.markerData.push(fourth); this.markerData.push(fifth); this.markerData.push(sixth); let i = 0; this.markerData.forEach(d => { d.index = i; d.referenceIndex = i < 2 ? i : i < 4 ? i - 2 : i - 4; i++; }); } prepareSeriesData() { const isAuto = this.seriesLabelDetails.placement === 'auto'; const checkString = this.isVertical ? 'right' : 'top'; const isStandard = isAuto ? true : this.seriesLabelDetails.placement.includes(checkString); const first = { label: this.nest[0].values[0][this.seriesAccessor], [this.seriesAccessor]: this.nest[0].values[0][this.seriesAccessor], value: isStandard ? this.nest[this.nest.length - 1].values[0][this.valueAccessor] : this.nest[0].values[0][this.valueAccessor] }; const second = { label: this.nest[0].values[1][this.seriesAccessor], [this.seriesAccessor]: this.nest[0].values[1][this.seriesAccessor], value: isStandard ? this.nest[this.nest.length - 1].values[1][this.valueAccessor] : this.nest[0].values[1][this.valueAccessor] }; this.seriesData = [first, second]; } prepareLegendData() { const first = { label: this.nest[0].values[0][this.seriesAccessor], [this.seriesAccessor]: this.nest[0].values[0][this.seriesAccessor] }; const second = { label: this.nest[0].values[1][this.seriesAccessor], [this.seriesAccessor]: this.nest[0].values[1][this.seriesAccessor] }; this.legendData = [first, second]; this.ordinalLabel = this.legendData.map(d => { return d.label; }); } prepareScales() { const minValue = min(this.data, d => parseFloat(d[this.valueAccessor])); const maxValue = max(this.data, d => parseFloat(d[this.valueAccessor])); if (this.isVertical) { this.xAccessor = this.ordinalAccessor; this.yAccessor = this.valueAccessor; this.y = scaleLinear() .domain([ this.minValueOverride || this.minValueOverride === 0 ? this.minValueOverride : minValue - (maxValue - minValue) * 0.15, this.maxValueOverride || this.maxValueOverride === 0 ? this.maxValueOverride : maxValue + (maxValue - minValue) * 0.15 ]) .range([this.innerPaddedHeight, 0]); // set xAxis scale : date if (this.data[0][this.ordinalAccessor] instanceof Date) { const maxDate = max(this.data, d => d[this.ordinalAccessor]); const minDate = min(this.data, d => d[this.ordinalAccessor]); this.x = scaleTime() .domain([minDate, maxDate]) .range([0, this.innerPaddedWidth]); if (this.xAxis.unit) { const timeTool = this.time['time' + this.xAxis.unit]; this.x.domain([timeTool.offset(minDate, -1), timeTool.offset(maxDate, +1)]); } } else { // set xAxis scale : ordinal value this.x = scalePoint() .domain(this.nest.map(d => d.key)) .padding(0.5) .range([0, this.innerPaddedWidth]); } } else if (!this.isVertical) { this.xAccessor = this.valueAccessor; this.yAccessor = this.ordinalAccessor; this.x = scaleLinear() .domain([ this.minValueOverride || this.minValueOverride === 0 ? this.minValueOverride : minValue - (maxValue - minValue) * 0.15, this.maxValueOverride || this.maxValueOverride === 0 ? this.maxValueOverride : maxValue + (maxValue - minValue) * 0.15 ]) .range([0, this.innerPaddedWidth]); this.y = scalePoint() .domain(this.nest.map(d => d.key)) .padding(0.5) .range([this.innerPaddedHeight, 0]); } } addStrokeUnder() { const filter = createTextStrokeFilter({ root: this.svg.node(), id: this.chartID, color: '#ffffff' }); this.seriesLabelWrapper.selectAll('text').attr('filter', !this.accessibility.hideStrokes ? filter : null); this.diffLabelWrapper.attr('filter', !this.accessibility.hideStrokes ? filter : null); this.labels.attr('filter', !this.accessibility.hideStrokes ? filter : null); this.labels.attr('filter', !this.accessibility.hideStrokes ? filter : null); this.dumbbellG.attr('filter', !this.accessibility.hideStrokes ? filter : null); } // reset graph size based on window size renderRootElements() { this.svg = select(this.dumbbellPlotEl) .select('.visa-viz-d3-dumbbell-container') .append('svg') .attr('width', this.width) .attr('height', this.height) .attr('viewBox', '0 0 ' + this.width + ' ' + this.height); this.root = this.svg.append('g').attr('id', 'visa-viz-margin-container-g-' + this.chartID); this.rootG = this.root.append('g').attr('id', 'visa-viz-padding-container-g-' + this.chartID); this.defs = this.rootG.append('defs'); this.baselineG = this.rootG.append('g').attr('class', 'baseline-group'); this.gridG = this.rootG.append('g').attr('class', 'gridline-group'); this.dumbbellG = this.rootG.append('g').attr('class', 'dumbbell-group'); this.seriesLabelWrapper = this.rootG.select('.dumbbell-series-wrapper'); this.seriesLabelWrapper = this.rootG.append('g').attr('class', 'dumbbell-series-wrapper'); this.diffLabelWrapper = this.rootG.select('.dumbbell-diff-label-wrapper'); this.diffLabelWrapper = this.rootG.append('g').attr('class', 'dumbbell-diff-label-wrapper'); this.legendG = select(this.dumbbellPlotEl) .select('.dumbbell-legend') .append('svg'); this.tooltipG = select(this.dumbbellPlotEl).select('.dumbbell-tooltip'); this.labels = this.rootG.append('g').attr('class', 'dumbbell-dataLabel-group'); this.references = this.rootG.append('g').attr('class', 'dumbbell-reference-line-group'); } renderMarkerGroup() { this.markerG = this.defs.select('.' + this.marker.type + 'markers'); if (!this.markerG.node()) { this.defs.selectAll('g').remove(); this.markerG = this.defs.append('g').attr('class', this.marker.type + 'markers'); } } setSeriesSelections() { const dataBoundToSeriesLabel = this.seriesLabelWrapper .selectAll('.dumbbell-series-label') .data(this.seriesData, d => d.label); this.enterSeriesLabel = dataBoundToSeriesLabel.enter().append('text'); this.exitSeriesLabel = dataBoundToSeriesLabel.exit(); this.updateSeriesLabel = dataBoundToSeriesLabel.merge(this.enterSeriesLabel); } setGlobalSelections() { const dataBoundToGeometries = this.dumbbellG.selectAll('.dumbbell-plot').data(this.nest, d => d.key); this.enter = dataBoundToGeometries.enter().append('path'); this.exit = dataBoundToGeometries.exit(); this.update = dataBoundToGeometries.merge(this.enter); this.exitSize = this.exit.size(); this.enterSize = this.enter.size(); // const dataBoundToMarkers = this.markerG.selectAll('marker').data(this.markerData, (d, i) => { // d.referenceIndex = i < 2 ? i : i < 4 ? i - 2 : i - 4; // const basicId = this.generateId(d, i); // this['marker' + i] = basicId; // d.id = basicId; // return d.label + i; // }); const dataBoundToMarkers = this.markerG.selectAll('marker').data(this.markerData, (d, i) => { return d.label + i; }); this.enterMarkers = dataBoundToMarkers.enter().append('marker'); this.exitMarkers = dataBoundToMarkers.exit(); this.updateMarkers = dataBoundToMarkers.merge(this.enterMarkers); this.setSeriesSelections(); const dataBountToDiffLabel = this.diffLabelWrapper.selectAll('.dumbbell-diff-label').data(this.nest, d => d.key); this.enterDiffLabel = dataBountToDiffLabel.enter().append('text'); this.exitDiffLabel = dataBountToDiffLabel.exit(); this.updateDiffLabel = dataBountToDiffLabel.merge(this.enterDiffLabel); const dataBoundToLabels = this.labels.selectAll('g').data(this.nest, d => d.key); this.enterLabels = dataBoundToLabels.enter().append('g'); this.exitLabels = dataBoundToLabels.exit(); this.updateLabels = dataBoundToLabels.merge(this.enterLabels); const dataBoundToLabelChildren = this.updateLabels .selectAll('.dumbbell-dataLabel') .data(d => [d.values[0], d.values[1]], d => d[this.seriesAccessor]); this.enterLabelChildren = dataBoundToLabelChildren.enter().append('text'); this.exitLabelChildren = dataBoundToLabelChildren.exit(); this.updateLabelChildren = dataBoundToLabelChildren.merge(this.enterLabelChildren); } setTestingAttributes() { if (this.unitTest) { select(this.dumbbellPlotEl) .select('.visa-viz-d3-dumbbell-container') .attr('data-testid', 'chart-container'); select(this.dumbbellPlotEl) .select('.dumbbell-main-title') .attr('data-testid', 'main-title'); select(this.dumbbellPlotEl) .select('.dumbbell-sub-title') .attr('data-testid', 'sub-title'); this.root.attr('data-testid', 'margin-container'); this.rootG.attr('data-testid', 'padding-container'); this.legendG.attr('data-testid', 'legend-container'); this.tooltipG.attr('data-testid', 'tooltip-container'); this.dumbbellG.attr('data-testid', 'dumbbell-group'); this.baselineG.attr('data-testid', 'baseline-group'); this.references.attr('data-testid', 'reference-line-group'); this.updateLabels.attr('data-testid', 'dataLabel-wrapper'); this.updateLabelChildren .attr('data-testid', 'dataLabel') .attr('data-id', d => `label-${d[this.ordinalAccessor]}-${d[this.seriesAccessor]}`); this.updateDiffLabel.attr('data-testid', 'difference-label').attr('data-id', d => `difference-label-${d.key}`); this.updateSeriesLabel.attr('data-testid', 'series-label'); this.updateMarkers.attr('data-testid', 'marker'); // .attr('data-id', d => `marker-${d[this.ordinalAccessor]}-${d[this.seriesAccessor]}`); this.update.attr('data-testid', 'line').attr('data-id', d => `line-${d.key}`); } else { select(this.dumbbellPlotEl) .select('.visa-viz-d3-dumbbell-container') .attr('data-testid', null); select(this.dumbbellPlotEl) .select('.dumbbell-main-title') .attr('data-testid', null); select(this.dumbbellPlotEl) .select('.dumbbell-sub-title') .attr('data-testid', null); this.root.attr('data-testid', null); this.rootG.attr('data-testid', null); this.legendG.attr('data-testid', null); this.tooltipG.attr('data-testid', null); this.dumbbellG.attr('data-testid', null); this.baselineG.attr('data-testid', null); this.references.attr('data-testid', null); this.updateLabels.attr('data-testid', null); this.updateLabelChildren.attr('data-testid', null).attr('data-id', null); this.updateDiffLabel.attr('data-testid', null).attr('data-id', null); this.updateSeriesLabel.attr('data-testid', null); this.updateMarkers.attr('data-testid', null); // .attr('data-id', null); this.update.attr('data-testid', null).attr('data-id', null); } } reSetRoot() { const changeSvg = prepareRenderChange({ selection: this.svg, duration: this.duration, namespace: 'root_reset', easing: easeCircleIn }); changeSvg .attr('width', this.width) .attr('height', this.height) .attr('viewBox', '0 0 ' + this.width + ' ' + this.height); const changeRoot = prepareRenderChange({ selection: this.root, duration: this.duration, namespace: 'root_reset', easing: easeCircleIn }); changeRoot.attr('transform', `translate(${this.margin.left}, ${this.margin.top})`); const changeRootG = prepareRenderChange({ selection: this.rootG, duration: this.duration, namespace: 'root_reset', easing: easeCircleIn }); changeRootG.attr('transform', `translate(${this.padding.left}, ${this.padding.top})`); setAccessibilityDescriptionWidth(this.chartID, this.width); } drawXAxis() { const bandWidth = (this.innerPaddedWidth / this.nest.length) * 0.7; drawAxis({ root: this.rootG, height: this.innerPaddedHeight, width: this.innerPaddedWidth, axisScale: this.x, left: false, wrapLabel: this.wrapLabel ? bandWidth : '', dateFormat: this.xAxis.format, format: this.xAxis.format, tickInterval: this.xAxis.tickInterval, label: this.xAxis.label, padding: this.padding, hide: !this.xAxis.visible, duration: this.duration }); } drawYAxis() { drawAxis({ root: this.rootG, height: this.innerPaddedHeight, width: this.innerPaddedWidth, axisScale: this.y, left: true, wrapLabel: this.wrapLabel ? 100 : '', format: this.yAxis.format, tickInterval: this.yAxis.tickInterval, label: this.yAxis.label, padding: this.padding, hide: !this.yAxis.visible, duration: this.duration }); } setXAxisAccessibility() { setAccessXAxis({ rootEle: this.dumbbellPlotEl, hasXAxis: this.xAxis ? this.xAxis.visible : false, xAxis: this.x ? this.x : false, // this is optional for some charts, if hasXAxis is always false xAxisLabel: this.xAxis.label ? this.xAxis.label : '' // this is optional for some charts, if hasXAxis is always false }); } setYAxisAccessibility() { setAccessYAxis({ rootEle: this.dumbbellPlotEl, hasYAxis: this.yAxis ? this.yAxis.visible : false, yAxis: this.y ? this.y : false, // this is optional for some charts, if hasXAxis is always false yAxisLabel: this.yAxis.label ? this.yAxis.label : '' // this is optional for some charts, if hasXAxis is always false }); } drawBaselineX() { drawAxis({ root: this.baselineG, height: this.innerPaddedHeight, width: this.innerPaddedWidth, axisScale: this.y, left: true, padding: this.padding, markOffset: this.x(0), hide: !this.isVertical ? !this.showBaselineY : true, duration: this.duration }); } drawBaselineY() { drawAxis({ root: this.baselineG, height: this.innerPaddedHeight, width: this.innerPaddedWidth, axisScale: this.x, left: false, padding: this.padding, markOffset: this.y(0), hide: this.isVertical ? !this.showBaselineX : true, duration: this.duration }); } // dashed line grid for chart drawXGrid() { drawGrid( this.gridG, this.innerPaddedHeight, this.innerPaddedWidth, this.x, false, !this.xAxis.gridVisible, this.xAxis.tickInterval, this.duration ); } drawYGrid() { drawGrid( this.gridG, this.innerPaddedHeight, this.innerPaddedWidth, this.y, true, !this.yAxis.gridVisible, this.yAxis.tickInterval, this.duration ); } enterMarkerGeometries() { this.enterMarkers .attr('orient', 'auto') .attr('markerUnits', 'userSpaceOnUse') .attr('id', d => this.generateId(d, d.index)) .attr('class', 'marker-' + this.marker.type) .attr('stroke', this.handleMarkerColors); if (this.marker.type === 'dot') { this.enterMarkers.append('circle').attr('r', 5); } else if (this.marker.type === 'stroke') { this.enterMarkers.append('path'); } else if (this.marker.type === 'arrow') { this.enterMarkers.append('path'); } this.updateMarkerSize(this.enterMarkers); } updateMarkerGeometries() { this.updateMarkers.interrupt(); this.updateMarkers.attr('opacity', d => { return (this.marker.visible || d.focus) && !d.limitOpacity ? 1 : this.marker.visible || d.focus ? this.hoverOpacity : 0; }); } updateMarkerStyle() { this.updateMarkers.attr('stroke', this.handleMarkerColors); } exitMarkerGeometries() { this.exitMarkers .transition('exit') .duration(this.duration) .ease(easeCircleIn) .remove(); } // geometry based on data enterDumbbells() { this.enter.interrupt(); this.enter .attr('class', 'dumbbell-plot') .attr('d', d => { const centerX1 = this.x(d.values[0][this.xAccessor]); const centerY1 = this.y(d.values[0][this.yAccessor]); const centerX2 = this.x(d.values[1][this.xAccessor]); const centerY2 = this.y(d.values[1][this.yAccessor]); const ymod = this.isVertical ? (centerY1 > centerY2 ? 0.001 : -0.001) : 0; const xmod = !this.isVertical ? (centerX1 > centerX2 ? 0.001 : -0.001) : 0; return `M ${centerX1 + xmod} ${centerY1 + ymod} L ${centerX1} ${centerY1} L ${centerX1} ${centerY1} L ${centerX2} ${centerY2} L ${centerX2} ${centerY2} L ${centerX2} ${centerY2} L ${centerX1} ${centerY1} L ${centerX1} ${centerY1} L ${centerX1} ${centerY1} L ${centerX2} ${centerY2} L ${centerX2} ${centerY2} L ${centerX2 - xmod} ${centerY2 - ymod}`; }) .attr('cursor', !this.suppressEvents ? this.cursor : null) .attr('opacity', 0) .each((_d, i, n) => { initializeElementAccess(n[i]); }) .on( 'click', !this.suppressEvents ? (d, i, n) => { if (d.values) { const node = n[i]; const mouseEvent = event; const index = this.findMarkerIndex(d, node, mouseEvent); this.onClickHandler(d.values[index]); } } : null ) .on( 'mouseover', !this.suppressEvents ? (d, i, n) => { let data = d; if (d.values) { const node = n[i]; const mouseEvent = event; const index = this.findMarkerIndex(d, node, mouseEvent); overrideTitleTooltip(this.chartID, true); data = d.values[index]; this.hoverFunc.emit(data); } this.showTooltip ? this.eventsTooltip({ data: this.tooltipLabel.labelAccessor && this.tooltipLabel.labelAccessor.length ? data : d, evt: event, isToShow: true }) : ''; } : null ) .on('mouseout', !this.suppressEvents ? () => this.onMouseOutHandler() : null) .attr('stroke', this.handleBarColors) .attr('fill-opacity', this.handleBarOpacity); this.update.order(); } updateBarStyle() { this.update.attr('stroke', this.handleBarColors).attr('fill-opacity', this.handleBarOpacity); } handleMarkerColors = (d, i, n) => { const rawColor = this.rawColors[d.referenceIndex] || this.rawColors[0]; const strokeColor = i < 2 && this.clickHighlight.length ? this.clickStyle.color || rawColor : i < 4 ? rawColor : this.hoverStyle.color || rawColor; const baseColor = this.colorArr[d.referenceIndex] || this.colorArr[0]; const fillColor = i < 2 && this.clickHighlight.length ? this.clickStyle.color || baseColor : i < 4 ? baseColor : this.hoverStyle.color || baseColor; select(n[i]).attr('fill', fillColor); return !this.accessibility.hideStrokes ? this.strokes[strokeColor.toLowerCase()] : fillColor; }; handleSeriesLabelColors = (d, i) => { let hovered; let clicked; if (this.seriesInteraction) { hovered = checkHovered(d, this.hoverHighlight, this.innerInteractionKeys); clicked = checkClicked(d, this.clickHighlight, this.innerInteractionKeys); } const baseColor = this.rawColors[i] || this.rawColors[0]; const fillColor = this.seriesInteraction ? clicked && this.clickHighlight.length ? this.clickStyle.color || baseColor : hovered && this.hoverHighlight ? this.hoverStyle.color || baseColor : baseColor : baseColor; return this.textColors[fillColor.toLowerCase()]; }; handleLabelColors = (d, i) => { const hovered = checkHovered(d, this.hoverHighlight, this.innerInteractionKeys); const clicked = checkClicked(d, this.clickHighlight, this.innerInteractionKeys); const baseColor = this.rawColors[i] || this.rawColors[0]; const fillColor = clicked && this.clickHighlight.length ? this.clickStyle.color || baseColor : hovered && this.hoverHighlight ? this.hoverStyle.color || baseColor : baseColor; return this.textColors[fillColor.toLowerCase()]; }; handleBarColors = (d, i, n) => { d.focusMarker = false; if (d.values[0][this.seriesAccessor] === this.focusMarker.key) { d.focusMarker = 0; } else if (d.values[1][this.seriesAccessor] === this.focusMarker.key) { d.focusMarker = 1; } const clicked = checkClicked(d.values[0], this.clickHighlight, this.innerInteractionKeys) && checkClicked(d.values[1], this.clickHighlight, this.innerInteractionKeys); const hovered = checkHovered(d.values[0], this.hoverHighlight, this.innerInteractionKeys) && checkHovered(d.values[1], this.hoverHighlight, this.innerInteractionKeys); const rawColor = this.barStyle.colorRule === 'focus' && (d.focusMarker || d.focusMarker === 0) ? this.rawColors[d.focusMarker] : this.barStyle.colorRule === 'greaterValue' ? this.rawColors[d.greaterIndex] : this.rawColors[2]; const strokeColor = clicked && this.clickHighlight.length ? this.clickStyle.color || rawColor : hovered && this.hoverHighlight ? this.hoverStyle.color || rawColor : rawColor; const baseColor = this.barStyle.colorRule === 'focus' && (d.focusMarker || d.focusMarker === 0) ? this.colorArr[d.focusMarker] : this.barStyle.colorRule === 'greaterValue' ? this.colorArr[d.greaterIndex] : this.colorArr[2]; const fillColor = clicked && this.clickHighlight.length ? this.clickStyle.color || baseColor : hovered && this.hoverHighlight ? this.hoverStyle.color || baseColor : baseColor; select(n[i]).attr('fill', fillColor); return !this.accessibility.hideStrokes ? this.strokes[strokeColor.toLowerCase()] : fillColor; }; handleBarOpacity = (d, i, n) => { const first = checkInteraction( d.values[0], 1, 0, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ); const second = checkInteraction( d.values[1], 1, 0, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ); const opacity = first && second ? this.barStyle.opacity : this.hoverOpacity; select(n[i]).attr('stroke-opacity', opacity); return opacity; }; updateMarkerSize(selection?) { const markersToResize = selection || this.updateMarkers; markersToResize.each((d, i, n) => { const me = select(n[i]); const barSize = i < 2 && this.clickHighlight.length ? parseFloat(this.clickStyle.strokeWidth + '') : i < 4 ? this.barStyle.width : parseFloat(this.hoverStyle.strokeWidth + ''); const barMult = d.focus ? this.focusMarker.sizeFromBar : this.marker.sizeFromBar; const mult = this.marker.type === 'dot' ? 1 : this.marker.type === 'stroke' ? 2 : (d.focus && this.focusMarker.key) || (!this.focusMarker.key && d.referenceIndex === 0) ? 1 : 2; const unit = barMult * mult * (barSize + 1); const strokeUnit = unit ? 10 / unit : 0; me.attr('viewBox', `0 0 ${10 + strokeUnit} ${10 + strokeUnit}`) .attr('refX', 5 + strokeUnit / 2) .attr('refY', 5 + strokeUnit / 2) .attr('stroke-width', strokeUnit) .attr('markerWidth', unit) .attr('markerHeight', unit); if (this.marker.type === 'dot') { me.select('circle') .attr('cx', 5 + strokeUnit / 2) .attr('cy', 5 + strokeUnit / 2); } else if (this.marker.type === 'stroke') { me.select('path').attr( 'd', `M 4.5 ${0 + strokeUnit / 2} L 4.5 ${10 + strokeUnit / 2} L 6 ${10 + strokeUnit / 2} L 6 ${0 + strokeUnit / 2} z` ); } else if (this.marker.type === 'arrow') { me.select('path') .attr( 'transform', d.focus && this.focusMarker.key && d.referenceIndex === 1 ? `rotate(180,${5 + strokeUnit / 2},${5 + strokeUnit / 2})` : null ) .attr( 'd', (d.focus && this.focusMarker.key) || (!this.focusMarker.key && d.referenceIndex === 0) ? `M ${0 + strokeUnit / 2} ${5 + strokeUnit / 4} L ${10 + strokeUnit / 2} ${0 + strokeUnit / 2} L ${10 + strokeUnit / 2} ${10 + strokeUnit / 2} z` : `M 4.5 ${0 + strokeUnit / 2} L 4.5 ${10 + strokeUnit / 2} L 6 ${10 + strokeUnit / 2} L 6 ${0 + strokeUnit / 2} z` ); } }); } // unlike normal draw__ functions, this only runs if focusMarker changes drawMarkerGeometries() { this.updateMarkers.selectAll('.marker-' + this.marker.type).data(d => [d]); // data must be explicitly rebound to child elements (this normally only happens on enter) if (this.marker.type === 'arrow') { // Note: dot and stroke do not change "direction" (only size), and thus don't redraw this.updateMarkers.selectAll('path').attr('d', (d, i, n) => { const barSize = i < 2 && this.clickHighlight.length ? parseFloat(this.clickStyle.strokeWidth + '') : i < 4 ? this.barStyle.width : parseFloat(this.hoverStyle.strokeWidth + ''); const barMult = d.focus ? this.focusMarker.sizeFromBar : this.marker.sizeFromBar; const mult = this.marker.type === 'dot' ? 1 : this.marker.type === 'stroke' ? 2 : (d.focus && this.focusMarker.key) || (!this.focusMarker.key && d.referenceIndex === 0) ? 1 : 2; const unit = barMult * mult * (barSize + 1); const strokeUnit = unit ? 10 / unit : 0; select(n[i]).attr( 'transform', d.focus && this.focusMarker.key && d.referenceIndex === 1 ? `rotate(180,${5 + strokeUnit / 2},${5 + strokeUnit / 2})` : null ); return (d.focus && this.focusMarker.key) || (!this.focusMarker.key && d.referenceIndex === 0) ? `M ${0 + strokeUnit / 2} ${5 + strokeUnit / 4} L ${10 + strokeUnit / 2} ${0 + strokeUnit / 2} L ${10 + strokeUnit / 2} ${10 + strokeUnit / 2} z` : `M 4.5 ${0 + strokeUnit / 2} L 4.5 ${10 + strokeUnit / 2} L 6 ${10 + strokeUnit / 2} L 6 ${0 + strokeUnit / 2} z`; }); } } updateDumbbells() { this.update.interrupt(); this.enter .transition('opacity') .duration(this.duration) .ease(easeCircleIn) .attr('opacity', 1); } exitDumbbells() { this.exit.interrupt(); this.exit .transition('exit') .ease(easeCircleIn) .duration(this.duration / 2) .attr('opacity', 0) .attr('d', (_, i, n) => { const me = select(n[i]); const centerX1 = +me.attr('data-centerX1'); const centerY1 = +me.attr('data-centerY1'); const centerX2 = +me.attr('data-centerX2'); const centerY2 = +me.attr('data-centerY2'); const ymod = this.isVertical ? (centerY1 > centerY2 ? 0.001 : -0.001) : 0; const xmod = !this.isVertical ? (centerX1 > centerX2 ? 0.001 : -0.001) : 0; return `M ${centerX1 + xmod} ${centerY1 + ymod} L ${centerX1} ${centerY1} L ${centerX1} ${centerY1} L ${centerX2} ${centerY2} L ${centerX2} ${centerY2} L ${centerX2} ${centerY2} L ${centerX1} ${centerY1} L ${centerX1} ${centerY1} L ${centerX1} ${centerY1} L ${centerX2} ${centerY2} L ${centerX2} ${centerY2} L ${centerX2 - xmod} ${centerY2 - ymod}`; }); // We use this.update instead of this.exit to ensure the functions at the end // of our lifecycle run, even though we are removing the exiting elements from // inside this transition's endAll. // (If we put this in this.exit, it will only run if elements exit. // We want this to run every lifecycle.) this.update .transition('accessibilityAfterExit') .duration(this.duration) .ease(easeCircleIn) .call(transitionEndAll, () => { // before we exit geometries, we need to check if a focus exists or not const focusDidExist = checkAccessFocus(this.rootG.node()); // then we must remove the exiting elements this.exit.remove(); // then our util can count geometries this.setChartCountAccessibility(); // our group's label should update with new counts too this.setGroupAccessibilityID(); // since items exited, labels must receive updated values this.setGeometryAriaLabels(); // and also make sure the user's focus isn't lost retainAccessFocus({ parentGNode: this.rootG.node(), focusDidExist // recursive: true }); }); } setBarSize = (d, i, n) => { const clicked = checkClicked(d.values[0], this.clickHighlight, this.innerInteractionKeys) && checkClicked(d.values[1], this.clickHighlight, this.innerInteractionKeys); const hovered = checkHovered(d.values[0], this.hoverHighlight, this.innerInteractionKeys) && checkHovered(d.values[1], this.hoverHighlight, this.innerInteractionKeys); const barSize = this.dumbbellInteraction ? clicked ? parseFloat(this.clickStyle.strokeWidth + '') || this.barStyle.width : hovered ? parseFloat(this.hoverStyle.strokeWidth + '') || this.barStyle.width : this.barStyle.width : this.barStyle.width; const centerX1 = this.x(d.values[0][this.xAccessor]); const centerY1 = this.y(d.values[0][this.yAccessor]); const centerX2 = this.x(d.values[1][this.xAccessor]); const centerY2 = this.y(d.values[1][this.yAccessor]); const ymod = this.isVertical ? (centerY1 > centerY2 ? 0.001 : -0.001) : 0; const xmod = !this.isVertical ? (centerX1 > centerX2 ? 0.001 : -0.001) : 0; const widthMod = this.isVertical ? barSize / 2 : 0; const heightMod = !this.isVertical ? barSize / 2 : 0; select(n[i]) .attr('data-barSize', barSize) .attr('data-centerX1', d => this.x(d.values[0][this.xAccessor])) .attr('data-centerY1', d => this.y(d.values[0][this.yAccessor])) .attr('data-centerX2', d => this.x(d.values[1][this.xAccessor])) .attr('data-centerY2', d => this.y(d.values[1][this.yAccessor])); return `M ${centerX1 + xmod} ${centerY1 + ymod} L ${centerX1} ${centerY1} L ${centerX1 + widthMod} ${centerY1 + heightMod} L ${centerX2 + widthMod} ${centerY2 + heightMod} L ${centerX2} ${centerY2} L ${centerX2 - widthMod} ${centerY2 - heightMod} L ${centerX1 - widthMod} ${centerY1 - heightMod} L ${centerX1} ${centerY1} L ${centerX1 + widthMod} ${centerY1 + heightMod} L ${centerX2 + widthMod} ${centerY2 + heightMod} L ${centerX2} ${centerY2} L ${centerX2 - xmod} ${centerY2 - ymod}`; }; drawDumbbells() { this.update .classed('moving', (d, i, n) => { const me = select(n[i]); const clicked = checkClicked(d.values[0], this.clickHighlight, this.innerInteractionKeys) && checkClicked(d.values[1], this.clickHighlight, this.innerInteractionKeys); const hovered = checkHovered(d.values[0], this.hoverHighlight, this.innerInteractionKeys) && checkHovered(d.values[1], this.hoverHighlight, this.innerInteractionKeys); const barSize = this.dumbbellInteraction ? clicked ? parseFloat(this.clickStyle.strokeWidth + '') || this.barStyle.width : hovered ? parseFloat(this.hoverStyle.strokeWidth + '') || this.barStyle.width : this.barStyle.width : this.barStyle.width; const centerX1 = this.x(d.values[0][this.xAccessor]); const centerY1 = this.y(d.values[0][this.yAccessor]); const centerX2 = this.x(d.values[1][this.xAccessor]); const centerY2 = this.y(d.values[1][this.yAccessor]); const oldBar = +me.attr('data-barSize'); const oldX1 = +me.attr('data-centerX1'); const oldY1 = +me.attr('data-centerY1'); const oldX2 = +me.attr('data-centerX2'); const oldY2 = +me.attr('data-centerY2'); return ( barSize !== oldBar || centerX1 !== oldX1 || centerY1 !== oldY1 || centerX2 !== oldX2 || centerY2 !== oldY2 ); }) .attr('data-translate-x', this.margin.left + this.padding.left) .attr('data-translate-y', this.margin.top + this.padding.top) .attr('data-d', this.setBarSize) .transition('update') .ease(easeCircleIn) .duration(this.duration) .attr('d', this.setBarSize) .call(transitionEndAll, () => { this.update.classed('moving', false); // we must make sure if geometries move, that our focus indicator does too retainAccessFocus({ parentGNode: this.rootG.node() // focusDidExist // this only matters for exiting selections // recursive: true // this only matters for }); }); } updateMarkerIds() { this.updateMarkers.attr('id', d => this.generateId(d, d.index)); this.update .attr('marker-start', d => { const check = checkInteraction( d.values[0], 1, 0, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ); const hovered = checkHovered(d.values[0], this.hoverHighlight, this.innerInteractionKeys); const clicked = checkClicked(d.values[0], this.clickHighlight, this.innerInteractionKeys); const marker = hovered && !clicked ? this.updateMarkers._groups[0][4].id : clicked || check ? this.updateMarkers._groups[0][0].id : this.updateMarkers._groups[0][2].id; return this.url + marker + ')'; }) .attr('marker-end', d => { const check = checkInteraction( d.values[1], 1, 0, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ); const hovered = checkHovered(d.values[1], this.hoverHighlight, this.innerInteractionKeys); const clicked = checkClicked(d.values[1], this.clickHighlight, this.innerInteractionKeys); const marker = hovered && !clicked ? this.updateMarkers._groups[0][5].id : clicked || check ? this.updateMarkers._groups[0][1].id : this.updateMarkers._groups[0][3].id; return this.url + marker + ')'; }); } updateInteractionState() { // we created an "opacity" transition namespace in update's transition // we override it here to instantly display opacity state (below) this.update.interrupt('opacity'); // this.updateSeriesLabel.interrupt('opacity'); // this.updateDiffLabel.interrupt('opacity'); this.updateLabelChildren.interrupt('opacity'); this.updateMarkers.interrupt(); // we use this.update and this.labelCurrent from setGlobalSelection here // the lifecycle state does not matter (enter/update/exit) // since interaction state can happen at any time this.updateMarkers.attr('opacity', d => { return (this.marker.visible || d.focus) && !d.limitOpacity ? 1 : this.marker.visible || d.focus ? this.hoverOpacity : 0; }); this.update .attr('opacity', 1) .attr('stroke', this.handleBarColors) .attr('fill-opacity', this.handleBarOpacity) .each((_, i, n) => { const me = select(n[i]); if (!me.classed('moving')) { me.attr('d', this.setBarSize); } }); // we have to make sure this call does not clash with shouldUpdateLabels in watchers this.drawDataLabels(true); if ( this.seriesLabelDetails.visible && (this.seriesLabelDetails.placement === 'auto' || this.seriesLabelDetails.collisionHideOnly) ) { this.drawSeriesLabels(true); } if ( this.diffLabelDetails.visible && (this.diffLabelDetails.placement === 'auto' || this.diffLabelDetails.collisionHideOnly) ) { this.drawDifferenceLabels(true); } retainAccessFocus({ parentGNode: this.rootG.node() }); setLegendInteractionState({ root: this.legendG, uniqueID: this.chartID, interactionKeys: this.innerInteractionKeys, groupAccessor: this.seriesAccessor, hoverHighlight: this.hoverHighlight, clickHighlight: this.clickHighlight, hoverStyle: this.hoverStyle, clickStyle: this.clickStyle, hoverOpacity: this.hoverOpacity }); } enterSeriesLabels() { this.enterSeriesLabel.interrupt(); const isAuto = this.seriesLabelDetails.placement === 'auto'; const checkString = this.isVertical ? 'right' : 'top'; const isStandard = isAuto ? true : this.seriesLabelDetails.placement.includes(checkString); this.enterSeriesLabel .attr('opacity', d => { const seriesLabelOpacity = !this.seriesLabelDetails.visible ? 0 : 1; if (!this.seriesInteraction) { return seriesLabelOpacity; } else { return checkInteraction( d, seriesLabelOpacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) < 1 ? 0 : Number.EPSILON; } }) .attr('class', 'dumbbell-series-label') .attr('fill', this.handleSeriesLabelColors) .attr('cursor', !this.suppressEvents && this.seriesInteraction ? this.cursor : null) .on('click', !this.suppressEvents && this.seriesInteraction ? d => this.onClickHandler(d) : null) .on('mouseover', !this.suppressEvents && this.seriesInteraction ? d => this.onHoverHandler(d, false) : null) .on('mouseout', !this.suppressEvents && this.seriesInteraction ? () => this.onMouseOutHandler() : null) .attr('text-anchor', this.isVertical && isStandard ? 'start' : this.isVertical ? 'end' : 'middle') .attr('x', d => (this.isVertical && isStandard ? this.innerPaddedWidth : !this.isVertical ? this.x(d.value) : 0)) .attr('y', d => this.isVertical ? this.y(d.value) : !this.isVertical && !isStandard ? this.innerPaddedHeight : 0 ) .attr('dx', this.isVertical && isStandard ? '0.1em' : this.isVertical ? '-0.1em' : '0') .attr('dy', this.isVertical ? '0.3em' : '-0.1em'); } updateSeriesLabels() { this.updateSeriesLabel.interrupt(); this.updateSeriesLabel .transition('opacity_series_labels') .ease(easeCircleIn) .duration(this.duration) .attr('opacity', d => { const seriesLabelOpacity = !this.seriesLabelDetails.visible ? 0 : 1; if (!this.seriesInteraction) { return seriesLabelOpacity; } else { return checkInteraction( d, seriesLabelOpacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) < 1 ? 0 : 1; } }); } exitSeriesLabels() { this.exitSeriesLabel .transition('exit_series_labels') .ease(easeCircleIn) .duration(this.duration) .attr('opacity', 0) .remove(); } drawSeriesLabels(interactionOverride?) { const isAuto = this.seriesLabelDetails.placement === 'auto'; const checkString = this.isVertical ? 'right' : 'top'; const isStandard = isAuto ? true : this.seriesLabelDetails.placement.includes(checkString); const hideOnly = !isAuto && this.seriesLabelDetails.collisionHideOnly; const seriesLabelUpdate = this.updateSeriesLabel .text((d, i) => (this.seriesLabelDetails.label ? this.seriesLabelDetails.label[i] : d.label)) .style('visibility', (_, i, n) => isAuto || this.seriesLabelDetails.collisionHideOnly ? select(n[i]).style('visibility') : null ) .attr('fill', this.handleSeriesLabelColors) .attr('data-x', d => this.isVertical && isStandard ? this.innerPaddedWidth : !this.isVertical ? this.x(d.value) : 0 ) .attr('data-y', (d, i, n) => { const textElement = n[i]; const style = getComputedStyle(textElement); const fontSize = parseFloat(style.fontSize); const textHeight = Math.max(fontSize - 1, 1); // clone.getBBox().height; return this.isVertical ? this.y(d.value) + 0.3 * textHeight // we need to account for dy here for series labels : !this.isVertical && !isStandard ? this.innerPaddedHeight : 0; }) .attr('data-translate-x', this.margin.left + this.padding.left) .attr('data-translate-y', this.margin.top + this.padding.top) .attr('data-use-dx', hideOnly) .attr('data-use-dy', hideOnly) .attr('data-text-anchor', this.isVertical && isStandard ? 'start' : this.isVertical ? 'end' : 'middle') .attr('dx', this.isVertical && isStandard ? '0.1em' : this.isVertical ? '-0.1em' : '0') .attr('dy', this.isVertical ? '0.3em' : '-0.1em') .transition('update_series_labels') .ease(easeCircleIn) .duration(() => { if (interactionOverride) { return 0; } return this.duration; }); if ( this.seriesLabelDetails.visible && (this.seriesLabelDetails.placement === 'auto' || this.seriesLabelDetails.collisionHideOnly) ) { // for series labels we are only going to check middle for now // const validPositions = hideOnly ? ['middle'] : this.isVertical ? ['right', 'middle', 'left'] : ['top', 'middle', 'bottom']; this.bitmaps = resolveLabelCollision({ bitmaps: this.bitmaps, labelSelection: seriesLabelUpdate, avoidMarks: [], validPositions: ['middle'], offsets: [1], // hideOnly ? [1] : [4, 1, 4], accessors: [this.seriesAccessor], size: [roundTo(this.width, 0), roundTo(this.height, 0)], hideOnly: this.seriesLabelDetails.visible && this.seriesLabelDetails.collisionHideOnly && this.seriesLabelDetails.placement !== 'auto' }); // if we are in hide only we need to add attributes back if (hideOnly) { seriesLabelUpdate .attr('text-anchor', this.isVertical && isStandard ? 'start' : this.isVertical ? 'end' : 'middle') .attr('x', d => this.isVertical && isStandard ? this.innerPaddedWidth : !this.isVertical ? this.x(d.value) : 0 ) .attr('y', d => this.isVertical ? this.y(d.value) : !this.isVertical && !isStandard ? this.innerPaddedHeight : 0 ) .attr('dx', this.isVertical && isStandard ? '0.1em' : this.isVertical ? '-0.1em' : '0') .attr('dy', this.isVertical ? '0.3em' : '-0.1em'); } } else { seriesLabelUpdate .attr('text-anchor', this.isVertical && isStandard ? 'start' : this.isVertical ? 'end' : 'middle') .attr('x', d => this.isVertical && isStandard ? this.innerPaddedWidth : !this.isVertical ? this.x(d.value) : 0 ) .attr('y', d => this.isVertical ? this.y(d.value) : !this.isVertical && !isStandard ? this.innerPaddedHeight : 0 ) .attr('dx', this.isVertical && isStandard ? '0.1em' : this.isVertical ? '-0.1em' : '0') .attr('dy', this.isVertical ? '0.3em' : '-0.1em'); } } setSeriesLabelOpacity() { this.updateSeriesLabel.interrupt('opacity_series_labels'); this.updateSeriesLabel.attr('opacity', d => { const seriesLabelOpacity = !this.seriesLabelDetails.visible ? 0 : 1; // check if interactionKeys includes seriesAccessor, if not then don't check seriesLabel for interaction if (!this.seriesInteraction) { return seriesLabelOpacity; } else { return checkInteraction( d, seriesLabelOpacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) < 1 ? 0 : 1; } }); } enterDifferenceLabels() { this.enterDiffLabel.interrupt(); const checkString = this.isVertical ? 'left' : 'top'; const isStandard = this.diffLabelDetails.placement.includes(checkString); this.enterDiffLabel .attr('class', 'dumbbell-diff-label') .attr('opacity', d => { const diffLabelOpacity = this.differenceLabel.visible ? 1 : 0; // check if interactionKeys includes seriesAccessor, if not then don't check seriesLabel for interaction if (!this.dumbbellInteraction) { return diffLabelOpacity; } else { return checkInteraction( d.values[0], diffLabelOpacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) < 1 ? 0 : Number.EPSILON; } }) .attr('fill', this.setDiffLabelColor) .attr('cursor', !this.suppressEvents && this.dumbbellInteraction ? this.cursor : null) .on( 'click', !this.suppressEvents && this.dumbbellInteraction && this.differenceLabel.visible ? d => this.onClickHandler(d) : null ) .on( 'mouseover', !this.suppressEvents && this.dumbbellInteraction && this.differenceLabel.visible ? d => this.onHoverHandler(d, true) : null ) .on( 'mouseout', !this.suppressEvents && this.dumbbellInteraction && this.differenceLabel.visible ? () => this.onMouseOutHandler() : null ) .attr('x', d => (this.isVertical ? this.x(d.values[0][this.ordinalAccessor]) : this.x(d.middle))) .attr('y', d => !this.isVertical && isStandard ? this.y(d.key) - this.barStyle.width / 2 - 4 : !this.isVertical ? this.y(d.key) + this.barStyle.width / 2 + 4 : this.y(d.middle) ) .attr( 'dx', this.isVertical && isStandard ? -this.barStyle.width / 2 - 4 : this.isVertical ? this.barStyle.width / 2 + 4 : '0' ) .attr('dy', !this.isVertical && isStandard ? '0' : !this.isVertical ? '0.6em' : '0.3em'); } updateDifferenceLabels() { this.updateDiffLabel.interrupt(); this.updateDiffLabel .transition('opacity_diff_labels') .ease(easeCircleIn) .duration(this.duration) .attr('opacity', d => { const diffLabelOpacity = this.differenceLabel.visible ? 1 : 0; // check if interactionKeys includes seriesAccessor, if not then don't check seriesLabel for interaction if (!this.dumbbellInteraction) { return diffLabelOpacity; } else { return checkInteraction( d.values[0], diffLabelOpacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) < 1 ? 0 : 1; } }); } exitDifferenceLabels() { this.exitDiffLabel .transition('exit_diff_label') .ease(easeCircleIn) .duration(this.duration) .attr('opacity', 0) .remove(); } drawDifferenceLabels(interactionOverride?) { const isAuto = this.diffLabelDetails.placement === 'auto'; const checkString = this.isVertical ? 'left' : 'top'; const isStandard = isAuto ? true : this.diffLabelDetails.placement.includes(checkString); const hideOnly = !isAuto && this.differenceLabel.collisionHideOnly; const updatingDiffLabels = this.updateDiffLabel .text(d => formatDataLabel(d, this.differenceLabel.calculation, this.differenceLabel.format)) .style('visibility', (_, i, n) => isAuto || this.differenceLabel.collisionHideOnly ? select(n[i]).style('visibility') : null ) .attr('data-x', d => (this.isVertical ? this.x(d.values[0][this.ordinalAccessor]) : this.x(d.middle))) .attr('data-y', d => !this.isVertical && isStandard ? this.y(d.key) - this.barStyle.width / 2 - 4 : !this.isVertical ? this.y(d.key) + this.barStyle.width / 2 + 4 : this.y(d.middle) ) .attr('data-translate-x', this.margin.left + this.padding.left) .attr('data-translate-y', this.margin.top + this.padding.top) .attr('data-use-dx', hideOnly) .attr('data-use-dy', hideOnly) .attr( 'dx', this.isVertical && isStandard ? -this.barStyle.width / 2 - 4 : this.isVertical ? this.barStyle.width / 2 + 4 : '0' ) .attr('dy', !this.isVertical && isStandard ? '0' : !this.isVertical ? '0.6em' : '0.3em') // text-anchor adds a blip to the update of these labels, placement also seems ok without it .attr('text-anchor', (_, i, n) => isAuto && select(n[i]).attr('text-anchor') ? select(n[i]).attr('text-anchor') : this.isVertical && isStandard ? 'end' : this.isVertical ? 'start' : 'middle' ) .transition('update_diff_label') .ease(easeCircleIn) .duration(() => { if (interactionOverride) { return 0; } return this.duration; }); if ( this.differenceLabel.visible && (this.diffLabelDetails.placement === 'auto' || this.differenceLabel.collisionHideOnly) ) { const validPositions = hideOnly ? ['middle'] : this.isVertical ? ['left', 'right'] : ['top', 'bottom']; const offsets = hideOnly ? [this.barStyle.width / 2 + 4] : [this.barStyle.width / 2 + 4, this.barStyle.width / 2 + 4]; this.bitmaps = resolveLabelCollision({ bitmaps: this.bitmaps, labelSelection: updatingDiffLabels, avoidMarks: [this.update], validPositions, offsets, accessors: ['key'], size: [roundTo(this.width, 0), roundTo(this.height, 0)], // we need the whole width and height for pie hideOnly: this.differenceLabel.visible && this.differenceLabel.collisionHideOnly && this.diffLabelDetails.placement !== 'auto' }); // if we are in hide only we need to add attributes back if (hideOnly) { updatingDiffLabels .attr('x', d => (this.isVertical ? this.x(d.values[0][this.ordinalAccessor]) : this.x(d.middle))) .attr('y', d => !this.isVertical && isStandard ? this.y(d.key) - this.barStyle.width / 2 - 4 : !this.isVertical ? this.y(d.key) + this.barStyle.width / 2 + 4 : this.y(d.middle) ) .attr( 'dx', this.isVertical && isStandard ? -this.barStyle.width / 2 - 4 : this.isVertical ? this.barStyle.width / 2 + 4 : '0' ) .attr('dy', !this.isVertical && isStandard ? '0' : !this.isVertical ? '0.6em' : '0.3em') .attr('text-anchor', this.isVertical && isStandard ? 'end' : this.isVertical ? 'start' : 'middle'); } } else { updatingDiffLabels .attr('x', d => (this.isVertical ? this.x(d.values[0][this.ordinalAccessor]) : this.x(d.middle))) .attr('y', d => !this.isVertical && isStandard ? this.y(d.key) - this.barStyle.width / 2 - 4 : !this.isVertical ? this.y(d.key) + this.barStyle.width / 2 + 4 : this.y(d.middle) ) .attr( 'dx', this.isVertical && isStandard ? -this.barStyle.width / 2 - 4 : this.isVertical ? this.barStyle.width / 2 + 4 : '0' ) .attr('dy', !this.isVertical && isStandard ? '0' : !this.isVertical ? '0.6em' : '0.3em') .attr('text-anchor', this.isVertical && isStandard ? 'end' : this.isVertical ? 'start' : 'middle'); } } enterDataLabels() { this.enterLabels.interrupt(); this.enterLabels .attr('class', 'dumbbell-label-wrapper') .attr('opacity', 0) .attr('fill', this.handleLabelColors); this.enterLabelChildren .attr('class', 'dumbbell-dataLabel') .attr('opacity', d => { return checkInteraction( d, 1, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) < 1 ? 0 : Number.EPSILON; }) .attr('fill', this.handleLabelColors) .attr('cursor', !this.suppressEvents && this.dataLabel.visible ? this.cursor : null) .on('click', !this.suppressEvents && this.dataLabel.visible ? d => this.onClickHandler(d) : null) .on('mouseover', !this.suppressEvents && this.dataLabel.visible ? d => this.onHoverHandler(d, true) : null) .on('mouseout', !this.suppressEvents && this.dataLabel.visible ? () => this.onMouseOutHandler() : null); placeDataLabels({ root: this.enterLabelChildren, xScale: this.x, yScale: this.y, ordinalAccessor: this.ordinalAccessor, valueAccessor: this.valueAccessor, placement: this.placement, chartType: 'dumbbell', layout: this.layoutOverride, labelOffset: this.markerData }); } setDifferenceLabelOpacity() { this.updateDiffLabel.interrupt('opacity_diff_labels'); this.updateDiffLabel.attr('opacity', d => { const diffLabelOpacity = this.differenceLabel.visible ? 1 : 0; // check if interactionKeys includes seriesAccessor, if not then don't check seriesLabel for interaction if (!this.dumbbellInteraction) { return diffLabelOpacity; } else { return checkInteraction( d.values[0], diffLabelOpacity, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) < 1 ? 0 : 1; } }); } updateDataLabels() { this.updateLabelChildren.classed('transitioning', true); this.updateLabels .transition('opacity') .ease(easeCircleIn) .duration(this.duration) .attr('opacity', () => { const labelOpacity = !this.dataLabel.visible ? 0 : 1; return labelOpacity; }) .call(transitionEndAll, () => { this.updateLabelChildren.classed('transitioning', false); }); } exitDataLabels() { this.exitLabels.interrupt(); this.exitLabels .selectAll('.dumbbell-dataLabel') .transition('exit') .ease(easeCircleIn) .duration(this.duration / 2) .attr('opacity', 0) .call(transitionEndAll, () => { this.exitLabels.remove(); }); this.exitLabelChildren .transition('exit_dataLabel') .ease(easeCircleIn) .duration(this.duration) .attr('opacity', 0) .remove(); } drawDataLabels(interactionOverride?) { const isAuto = this.placement === 'auto'; const hideOnly = this.placement !== 'auto' && this.dataLabel.collisionHideOnly; this.updateLabelChildren.text(d => { return formatDataLabel(d, this.innerLabelAccessor, this.dataLabel.format); }); const labelUpdate = this.updateLabelChildren .attr('fill', this.handleLabelColors) .style('visibility', (_, i, n) => isAuto || this.dataLabel.collisionHideOnly ? select(n[i]).style('visibility') : null ) .attr('data-translate-x', this.margin.left + this.padding.left) .attr('data-translate-y', this.margin.top + this.padding.top) .attr('data-use-dx', hideOnly) .attr('data-use-dy', hideOnly) .attr('dx', d => (this.isVertical ? '0.0em' : d.offset >= 0 ? '-0.1em' : '0.1em')) .attr('dy', d => { return this.isVertical && d.offset >= 0 ? '0.9em' : this.isVertical ? '-0.3em' : '0.0em'; }) // .attr('data-x',d => this.isVertical ? this.x(d[this.ordinalAccessor]) : this.x(d[this.valueAccessor]) - d.offset) .attr('data-y', (d, i, n) => { const textElement = n[i]; const style = getComputedStyle(textElement); const fontSize = parseFloat(style.fontSize); const textHeight = Math.max(fontSize - 1, 1); // clone.getBBox().height; const textWidth = getTextWidth(textElement.textContent, fontSize, true, style.fontFamily); const xAdjust = this.layoutOverride !== 'horizontal' ? 0 : d.offset >= 0 // (offset >= 0 means right item) ? -textWidth / 2 : textWidth / 2; const heightAdjust = // since we have some logic in util that assumes certain placements, we need to adjust for it here this.layoutOverride !== 'vertical' ? -textHeight / 2 : d.offset >= 0 // (offset >= 0 means bottom item) ? textHeight / 2 : -textHeight + -textHeight / 2; select(textElement).attr( 'data-x', d => (this.isVertical ? this.x(d[this.ordinalAccessor]) : this.x(d[this.valueAccessor]) - d.offset) + xAdjust ); return this.isVertical ? this.y(d[this.valueAccessor]) + d.offset + heightAdjust // + d.offset // + heightAdjust : this.y(d[this.ordinalAccessor]) + heightAdjust; }) .attr('data-offset', d => d.offset) // to be removed .transition('update_dataLabel') .ease(easeCircleIn) .duration(() => { if (interactionOverride) { return 0; } return this.duration; }); this.bitmaps = placeDataLabels({ root: labelUpdate, xScale: this.x, yScale: this.y, ordinalAccessor: this.ordinalAccessor, valueAccessor: this.valueAccessor, placement: this.placement, chartType: 'dumbbell', layout: this.layoutOverride, labelOffset: this.markerData, avoidCollision: { runOccupancyBitmap: this.dataLabel.visible && this.placement === 'auto', labelSelection: labelUpdate, avoidMarks: [this.update], validPositions: ['middle'], offsets: [1], accessors: [this.ordinalAccessor, this.seriesAccessor, 'key'], // key is created for lines by nesting done in line, size: [roundTo(this.width, 0), roundTo(this.height, 0)], boundsScope: 'centroid', hideOnly: this.dataLabel.visible && this.dataLabel.collisionHideOnly } }); } updateDiffLabelColor() { this.updateDiffLabel.attr('fill', this.setDiffLabelColor); } setDiffLabelColor = d => { d.focusMarker = false; if (d.values[0][this.seriesAccessor] === this.focusMarker.key) { d.focusMarker = 0; } else if (d.values[1][this.seriesAccessor] === this.focusMarker.key) { d.focusMarker = 1; } const baseColor = this.barStyle.colorRule === 'focus' && (d.focusMarker || d.focusMarker === 0) ? this.rawColors[d.focusMarker] : this.barStyle.colorRule === 'greaterValue' ? this.rawColors[d.greaterIndex] : this.rawColors[2]; let hovered; let clicked; if (this.dumbbellInteraction) { clicked = checkClicked(d.values[0], this.clickHighlight, this.innerInteractionKeys) && checkClicked(d.values[1], this.clickHighlight, this.innerInteractionKeys); hovered = checkHovered(d.values[0], this.hoverHighlight, this.innerInteractionKeys) && checkHovered(d.values[1], this.hoverHighlight, this.innerInteractionKeys); } const fillColor = this.dumbbellInteraction ? clicked && this.clickHighlight.length ? this.clickStyle.color || baseColor : hovered && this.hoverHighlight ? this.hoverStyle.color || baseColor : baseColor : baseColor; return this.textColors[fillColor.toLowerCase()]; }; setLabelOpacity() { this.updateLabels.attr('opacity', this.dataLabel.visible ? 1 : 0); this.updateLabelChildren.attr('opacity', d => { return checkInteraction( d, 1, this.hoverOpacity, this.hoverHighlight, this.clickHighlight, this.innerInteractionKeys ) < 1 ? 0 : 1; }); } updateMarkerOpacity() { this.updateMarkers.interrupt(); this.updateMarkers.attr('opacity', d => { return (this.marker.visible || d.focus) && !d.limitOpacity ? 1 : this.marker.visible || d.focus ? this.hoverOpacity : 0; }); } drawReferenceLines() { const currentReferences = this.references.selectAll('g').data(this.referenceLines, d => d.label); const enterReferences = currentReferences .enter() .append('g') .attr('class', '.dumbbell-reference') .attr('opacity', 1); const enterLines = enterReferences.append('line'); enterLines // .attr('id', (_, i) => 'reference-line-' + i) .attr('class', 'dumbbell-reference-line') .attr('data-testid', this.unitTest ? 'reference-line' : null) .attr('opacity', 0); const enterLabels = enterReferences.append('text'); enterLabels // .attr('id', (_, i) => 'reference-line-' + i + '-label') .attr('class', 'dumbbell-reference-line-label') .attr('opacity', 0); const mergeReferences = currentReferences.merge(enterReferences); const mergeLines = mergeReferences .selectAll('.dumbbell-reference-line') .data(d => [d]) .transition('merge') .ease(easeCircleIn) .duration(this.duration); const mergeLabels = mergeReferences .selectAll('.dumbbell-reference-line-label') .data(d => [d]) .transition('merge') .ease(easeCircleIn) .duration(this.duration) .text(d => d.label); const exitReferences = currentReferences.exit(); exitReferences .transition('exit') .ease(easeCircleIn) .duration(this.duration) .attr('opacity', 0) .remove(); enterReferences.attr('transform', d => { const scale = !this.isVertical ? 'x' : 'y'; return 'translate(0,' + this[scale](d.value) + ')'; }); mergeReferences .transition('merge') .ease(easeCircleIn) .duration(this.duration) .attr('transform', d => { const scale = !this.isVertical ? 'x' : 'y'; return 'translate(0,' + this[scale](d.value) + ')'; }); enterLines .attr('x1', 0) .attr('y1', 0) .attr('y2', 0) .attr('x2', this.innerPaddedWidth); enterLabels .attr('text-anchor', d => ((d.labelPlacementHorizontal || 'right') === 'right' ? 'start' : 'end')) .attr('x', d => ((d.labelPlacementHorizontal || 'right') === 'right' ? this.innerPaddedWidth : 0)) .attr('y', 0) .attr('dx', d => ((d.labelPlacementHorizontal || 'right') === 'right' ? '0.1em' : '-0.1em')) .attr('dy', '0.3em'); mergeLines .attr('x1', 0) .attr('y1', 0) .attr('y2', 0) .attr('x2', this.innerPaddedWidth); mergeLabels .attr('text-anchor', d => ((d.labelPlacementHorizontal || 'right') === 'right' ? 'start' : 'end')) .attr('x', d => ((d.labelPlacementHorizontal || 'right') === 'right' ? this.innerPaddedWidth : 0)) .attr('y', 0) .attr('dx', d => ((d.labelPlacementHorizontal || 'right') === 'right' ? '0.1em' : '-0.1em')) .attr('dy', '0.3em'); mergeLines .style('stroke', visaColors[this.referenceStyle.color] || this.referenceStyle.color) .style('stroke-width', this.referenceStyle.strokeWidth) .attr('stroke-dasharray', this.referenceStyle.dashed ? this.referenceStyle.dashed : '') .attr('opacity', this.referenceStyle.opacity); mergeLabels.style('fill', visaColors[this.referenceStyle.color] || this.referenceStyle.color).attr('opacity', 1); } setSelectedClass() { this.update.classed('highlight', (d, i, n) => { const first = checkInteraction(d.values[0], 1, 0, {}, this.clickHighlight, this.innerInteractionKeys); const second = checkInteraction(d.values[1], 1, 0, {}, this.clickHighlight, this.innerInteractionKeys); let selected = first || second; selected = this.clickHighlight && this.clickHighlight.length ? selected : false; const selectable = this.accessibility.elementsAreInterface; setElementInteractionAccessState(n[i], selected, selectable); return selected; }); } drawAnnotations() { annotate({ source: this.rootG.node(), data: this.annotations, xScale: this.x, xAccessor: this.layoutOverride !== 'horizontal' ? this.ordinalAccessor : this.valueAccessor, yScale: this.y, yAccessor: this.layoutOverride !== 'horizontal' ? this.valueAccessor : this.ordinalAccessor, width: this.width, height: this.height, padding: this.padding, margin: this.margin, bitmaps: this.bitmaps }); } setAnnotationAccessibility() { setAccessAnnotation(this.dumbbellPlotEl, this.annotations); } // new accessibility functions added here setTagLevels() { this.topLevel = findTagLevel(this.highestHeadingLevel); this.bottomLevel = findTagLevel(this.highestHeadingLevel, 3); } setChartDescriptionWrapper() { initializeDescriptionRoot({ rootEle: this.dumbbellPlotEl, title: this.accessibility.title || this.mainTitle, chartTag: 'dumbbell-plot', uniqueID: this.chartID, highestHeadingLevel: this.highestHeadingLevel, redraw: this.shouldRedrawWrapper, disableKeyNav: this.suppressEvents && this.accessibility.elementsAreInterface === false && this.accessibility.keyboardNavConfig && this.accessibility.keyboardNavConfig.disabled }); this.shouldRedrawWrapper = false; } setParentSVGAccessibility() { const keys = scopeDataKeys(this, chartAccessors, 'dumbbell-plot'); delete keys[this.ordinalAccessor]; setAccessibilityController({ node: this.svg.node(), chartTag: 'dumbbell-plot', title: this.accessibility.title || this.mainTitle, description: this.subTitle, uniqueID: this.chartID, geomType: 'dumbbell', includeKeyNames: this.accessibility.includeDataKeyNames, dataKeys: keys, // groupAccessor: this.groupAccessor // groupName: 'node', groupKeys: ['message'], nested: 'values', disableKeyNav: this.suppressEvents && this.accessibility.elementsAreInterface === false && this.accessibility.keyboardNavConfig && this.accessibility.keyboardNavConfig.disabled // recursive: true // bar chart does not include these }); } setGeometryAccessibilityAttributes() { this.update.each((_d, i, n) => { initializeElementAccess(n[i]); }); } setGeometryAriaLabels() { const keys = scopeDataKeys(this, chartAccessors, 'dumbbell-plot'); delete keys[this.ordinalAccessor]; this.update.each((_d, i, n) => { setElementFocusHandler({ node: n[i], geomType: 'dumbbell', includeKeyNames: this.accessibility.includeDataKeyNames, dataKeys: keys, groupKeys: ['message'], nested: ['values'], uniqueID: this.chartID, disableKeyNav: this.suppressEvents && this.accessibility.elementsAreInterface === false && this.accessibility.keyboardNavConfig && this.accessibility.keyboardNavConfig.disabled }); setElementAccessID({ node: n[i], uniqueID: this.chartID }); }); } setGroupAccessibilityAttributes() { // if a component's <g> elements can enter/exit, this will need to be called in the // lifecycle more than just initially, like how setGeometryAccessibilityAttributes works initializeElementAccess(this.dumbbellG.node()); } setGroupAccessibilityID() { this.dumbbellG.each((_, i, n) => { setElementAccessID({ node: n[i], uniqueID: this.chartID }); }); } setChartAccessibilityTitle() { setAccessTitle(this.dumbbellPlotEl, this.accessibility.title || this.mainTitle); } setChartAccessibilitySubtitle() { setAccessSubtitle(this.dumbbellPlotEl, this.subTitle); } setChartAccessibilityLongDescription() { setAccessLongDescription(this.dumbbellPlotEl, this.accessibility.longDescription); } setChartAccessibilityExecutiveSummary() { setAccessExecutiveSummary(this.dumbbellPlotEl, this.accessibility.executiveSummary); } setChartAccessibilityPurpose() { setAccessPurpose(this.dumbbellPlotEl, this.accessibility.purpose); } setChartAccessibilityContext() { setAccessContext(this.dumbbellPlotEl, this.accessibility.contextExplanation); } setChartAccessibilityStatisticalNotes() { setAccessStatistics(this.dumbbellPlotEl, this.accessibility.statisticalNotes); } setChartCountAccessibility() { setAccessChartCounts({ rootEle: this.dumbbellPlotEl, parentGNode: this.dumbbellG.node(), // pass the wrapper to <g> or geometries here, should be single node selection chartTag: 'dumbbell-plot', geomType: 'dumbbell' // groupName: 'line', // bar chart doesn't use this, so it is omitted // recursive: true // bar chart doesn't use this, so it is omitted }); } setChartAccessibilityStructureNotes() { setAccessStructure(this.dumbbellPlotEl, this.accessibility.structureNotes); } // new accessibility stuff ends here onChangeHandler() { if (this.accessibility && typeof this.accessibility.onChangeFunc === 'function') { const d = { updated: this.updated, added: this.enterSize, removed: this.exitSize }; this.accessibility.onChangeFunc(d); } this.updated = false; this.enterSize = 0; this.exitSize = 0; } onClickHandler(d) { this.clickFunc.emit(d); } onHoverHandler(d, hasTooltip) { overrideTitleTooltip(this.chartID, true); this.hoverFunc.emit(d); if (this.showTooltip && hasTooltip) { this.eventsTooltip({ data: d, evt: event, isToShow: true }); } } onMouseOutHandler() { overrideTitleTooltip(this.chartID, false); this.mouseOutFunc.emit(); if (this.showTooltip) { this.eventsTooltip({ isToShow: false }); } } // set initial style (instead of copying css class across the lib) setTooltipInitialStyle() { initTooltipStyle(this.tooltipG); } // tooltip eventsTooltip({ data, evt, isToShow }: { data?: any; evt?: any; isToShow: boolean }) { drawTooltip({ root: this.tooltipG, data, event: evt, isToShow, tooltipLabel: this.tooltipLabel, xAxis: this.xAxis, yAxis: this.yAxis, dataLabel: this.dataLabel, ordinalAccessor: this.ordinalAccessor, valueAccessor: this.valueAccessor, groupAccessor: this.seriesAccessor, diffLabelDetails: this.diffLabelDetails, chartType: 'dumbbell' }); } updateCursor() { this.update.attr('cursor', !this.suppressEvents ? this.cursor : null); this.updateDiffLabel.attr( 'cursor', !this.suppressEvents && this.dumbbellInteraction && this.differenceLabel.visible ? this.cursor : null ); this.updateLabelChildren.attr('cursor', !this.suppressEvents && this.dataLabel.visible ? this.cursor : null); } drawLegendElements() { drawLegend({ root: this.legendG, uniqueID: this.chartID, width: this.innerPaddedWidth, height: this.margin.top + 20, colorArr: this.colorArr, baseColorArr: !this.accessibility.hideStrokes ? this.rawColors : null, hideStrokes: this.accessibility.hideStrokes, margin: this.margin, padding: this.padding, duration: this.duration, type: 'bar', fontSize: 16, data: this.legendData, label: this.legend.labels || this.ordinalLabel, hide: !this.legend.visible, interactionKeys: this.innerInteractionKeys, groupAccessor: this.seriesAccessor, hoverHighlight: this.hoverHighlight, clickHighlight: this.clickHighlight, hoverStyle: this.hoverStyle, clickStyle: this.clickStyle, hoverOpacity: this.hoverOpacity }); } bindLegendInteractivity() { select(this.dumbbellPlotEl) .selectAll('.legend') .on( 'click', this.legend.interactive && this.seriesInteraction && !this.suppressEvents ? d => this.onClickHandler(d) : null ) .on( 'mouseover', this.legend.interactive && this.seriesInteraction && !this.suppressEvents ? d => this.onHoverHandler(d, false) : null ) .on( 'mouseout', this.legend.interactive && this.seriesInteraction && !this.suppressEvents ? () => this.onMouseOutHandler() : null ); } setLegendCursor() { select(this.dumbbellPlotEl) .selectAll('.legend') .style('cursor', this.legend.interactive && this.seriesInteraction && !this.suppressEvents ? this.cursor : null); } setSeriesCursor() { this.updateSeriesLabel.attr('cursor', !this.suppressEvents && this.seriesInteraction ? this.cursor : null); } bindSeriesInteractivity() { this.updateSeriesLabel .on('click', !this.suppressEvents && this.seriesInteraction ? d => this.onClickHandler(d) : null) .on('mouseover', !this.suppressEvents && this.seriesInteraction ? d => this.onHoverHandler(d, false) : null) .on('mouseout', !this.suppressEvents && this.seriesInteraction ? () => this.onMouseOutHandler() : null); } bindInteractivity() { this.update .on( 'click', !this.suppressEvents ? (d, i, n) => { if (d.values) { const node = n[i]; const mouseEvent = event; const index = this.findMarkerIndex(d, node, mouseEvent); this.onClickHandler(d.values[index]); } } : null ) .on( 'mouseover', !this.suppressEvents ? (d, i, n) => { let data = d; if (d.values) { const node = n[i]; const mouseEvent = event; const index = this.findMarkerIndex(d, node, mouseEvent); overrideTitleTooltip(this.chartID, true); data = d.values[index]; this.hoverFunc.emit(data); } this.showTooltip ? this.eventsTooltip({ data: this.tooltipLabel.labelAccessor && this.tooltipLabel.labelAccessor.length ? data : d, evt: event, isToShow: true }) : ''; } : null ) .on('mouseout', !this.suppressEvents ? () => this.onMouseOutHandler() : null); this.updateLabelChildren .on('click', !this.suppressEvents && this.dataLabel.visible ? d => this.onClickHandler(d) : null) .on('mouseover', !this.suppressEvents && this.dataLabel.visible ? d => this.onHoverHandler(d, true) : null) .on('mouseout', !this.suppressEvents && this.dataLabel.visible ? () => this.onMouseOutHandler() : null); this.updateDiffLabel .on( 'click', !this.suppressEvents && this.dumbbellInteraction && this.differenceLabel.visible ? d => this.onClickHandler(d) : null ) .on( 'mouseover', !this.suppressEvents && this.dumbbellInteraction && this.differenceLabel.visible ? d => this.onHoverHandler(d, true) : null ) .on( 'mouseout', !this.suppressEvents && this.dumbbellInteraction && this.differenceLabel.visible ? () => this.onMouseOutHandler() : null ); } findMarkerIndex(data, node, mouseEvent) { const pos = this.isVertical ? this.findPosition(node, mouseEvent)[1] : this.findPosition(node, mouseEvent)[0]; const a = this.isVertical ? 'Y' : 'X'; const start = +select(node).attr('data-center' + a + '1'); const end = +select(node).attr('data-center' + a + '2'); const middle = (end - start) / 2 + start; const adjust = data.values[0][this.valueAccessor] >= data.values[1][this.valueAccessor] ? 0 : 1; return pos <= middle ? 0 + adjust : 1 - adjust; } findPosition(node, mouseEvent) { const svg = node.ownerSVGElement || node; let point = svg.createSVGPoint(); point.x = mouseEvent.clientX; point.y = mouseEvent.clientY; point = point.matrixTransform(node.getScreenCTM().inverse()); return [point.x, point.y]; } generateId(d, i) { let mult = this.marker.type === 'dot' ? 1 : this.marker.type === 'stroke' ? 2 : (d.focus && this.focusMarker.key) || (!this.focusMarker.key && d.referenceIndex === 0) ? 1 : 2; mult = d.focus ? this.focusMarker.sizeFromBar * mult : this.marker.sizeFromBar * mult; const opacity = this.marker.visible || d.focus ? 1 : 0; const fill = this.rawColors[d.referenceIndex][0] === '#' ? this.rawColors[d.referenceIndex].substring(1) : this.rawColors[d.referenceIndex]; let barWidth = (i < 2 && this.clickHighlight.length ? this.clickStyle.strokeWidth : i < 4 ? this.barStyle.width : this.hoverStyle.strokeWidth ).toString(); barWidth = '' + barWidth; barWidth = barWidth.replace(/\D/g, 'n'); const basicId = 'marker-' + this.chartID + i + this.marker.type + mult + fill + barWidth + opacity; return basicId; } render() { // everything between this comment and the third should eventually // be moved into componentWillUpdate (if the stenicl bug is fixed) this.init(); if (this.shouldSetTagLevels) { this.setTagLevels(); this.shouldSetTagLevels = false; } if (this.shouldValidate) { this.shouldValidateAccessibilityProps(); this.shouldValidate = false; } if (this.shouldValidateLayout) { this.validateLayout(); } if (this.shouldValidateDataLabelPlacement) { this.validateDataLabelPlacement(); this.shouldValidateDataLabelPlacement = false; } if (this.shouldValidateSeriesLabelPlacement) { this.validateSeriesLabelPlacement(); this.shouldValidateSeriesLabelPlacement = false; } if (this.shouldValidateDiffLabelPlacement) { this.validateDiffLabelPlacement(); this.shouldValidateDiffLabelPlacement = false; } if (this.shouldValidateDataLabelAccessor) { this.validateDataLabelAccessor(); this.shouldValidateDataLabelAccessor = false; } if (this.shouldUpdateLayout) { this.setLayoutData(); this.shouldUpdateLayout = false; } if (this.shouldValidateInteractionKeys) { this.validateInteractionKeys(); this.shouldValidateInteractionKeys = false; } if (this.shouldUpdateData) { this.prepareData(); this.shouldUpdateData = false; } if (this.shouldUpdateMarkerData) { this.prepareMarkerData(); this.shouldUpdateMarkerData = false; } if (this.shouldUpdateSeriesData) { this.prepareSeriesData(); this.shouldUpdateSeriesData = false; } if (this.shouldUpdateLegendData) { this.prepareLegendData(); this.shouldUpdateLegendData = false; } if (this.shouldUpdateScales) { this.prepareScales(); this.shouldUpdateScales = false; } if (this.shouldCheckValueAxis) { if (this.layout === 'horizontal') { this.shouldUpdateXAxis = true; this.shouldSetXAxisAccessibility = true; this.shouldUpdateXGrid = true; } else if (this.layout === 'vertical' || this.layoutOverride) { this.shouldUpdateYAxis = true; this.shouldSetYAxisAccessibility = true; this.shouldUpdateYGrid = true; } this.shouldCheckValueAxis = false; } if (this.shouldCheckLabelAxis) { if (this.layout === 'vertical' || this.layoutOverride) { this.shouldUpdateXAxis = true; this.shouldSetXAxisAccessibility = true; this.shouldUpdateXGrid = true; } else if (this.layout === 'horizontal') { this.shouldUpdateYAxis = true; this.shouldSetYAxisAccessibility = true; this.shouldUpdateYGrid = true; } this.shouldCheckLabelAxis = false; } if (this.shouldUpdateTableData) { this.setTableData(); this.shouldUpdateTableData = false; } if (this.shouldSetColors) { this.setColors(); this.shouldSetColors = false; } // Everything between this comment and the first should eventually // be moved into componentWillUpdate (if the stenicl bug is fixed) return ( <div class="o-layout"> <div class="o-layout--chart"> <this.topLevel class="dumbbell-main-title vcl-main-title" data-testid="main-title"> {this.mainTitle} </this.topLevel> <this.bottomLevel class="visa-ui-text--instructions dumbbell-sub-title vcl-sub-title" data-testid="sub-title"> {this.subTitle} </this.bottomLevel> <div class="dumbbell-legend vcl-legend" style={{ display: this.legend.visible ? 'block' : 'none' }} /> <keyboard-instructions uniqueID={this.chartID} geomType={'dumbbell'} chartTag={'dumbbell-plot'} width={this.width - (this.margin ? this.margin.right || 0 : 0)} isInteractive={this.accessibility.elementsAreInterface} disabled={ this.suppressEvents && this.accessibility.elementsAreInterface === false && this.accessibility.keyboardNavConfig && this.accessibility.keyboardNavConfig.disabled } // the chart is "simple" /> <div class="visa-viz-d3-dumbbell-container" /> <div class="dumbbell-tooltip vcl-tooltip" style={{ display: this.showTooltip ? 'block' : 'none' }} /> <data-table uniqueID={this.chartID} isCompact tableColumns={this.tableColumns} data={this.tableData} padding={this.padding} margin={this.margin} hideDataTable={this.accessibility.hideDataTableButton} /> </div> {/* <canvas id="bitmap-render" /> */} </div> ); } private init() { // reading properties const keys = Object.keys(DumbbellPlotDefaultValues); let i = 0; const exceptions = { wrapLabel: { exception: false }, strokeWidth: { exception: 0 }, showDots: { exception: false }, dotRadius: { exception: 0 }, hoverOpacity: { exception: 0 }, showTooltip: { exception: false }, mainTitle: { exception: '' }, subTitle: { exception: '' }, showBaselineX: { exception: false } }; for (i = 0; i < keys.length; i++) { const exception = !exceptions[keys[i]] ? false : this[keys[i]] === exceptions[keys[i]].exception; this[keys[i]] = this[keys[i]] || exception ? this[keys[i]] : DumbbellPlotDefaultValues[keys[i]]; } } } // incorporate OSS licenses into build window['VisaChartsLibOSSLicenses'] = getLicenses(); // tslint:disable-line no-string-literal
the_stack
import { BoundingBox, Document, Element, Font, Heading, Line, Page, Paragraph, TableCell, Word, } from '../../types/DocumentRepresentation'; import * as utils from '../../utils'; import logger from '../../utils/Logger'; import { LinesToParagraphModule } from '../LinesToParagraphModule/LinesToParagraphModule'; import { Module } from '../Module'; import { RandomForestClassifier } from './train_model/model'; import * as CommandExecuter from '../../utils/CommandExecuter'; export class MlHeadingDetectionModule extends Module { public static moduleName = 'ml-heading-detection'; public static dependencies = [LinesToParagraphModule]; public async main(doc: Document): Promise<Document> { if (this.headingsDetected(doc)) { logger.warn( 'Warning: this page already has some headings in it. Not performing heading detection.', ); return doc; } // get the main fonts from all the words in document const mainCommonFonts = this.commonFonts(doc); doc.pages.forEach((page: Page) => { const newContents = this.extractHeadings(page, mainCommonFonts, doc); const paras: Paragraph[] = this.mergeLinesIntoParagraphs(newContents.paragraphLines); const headings: Heading[] = this.mergeLinesIntoHeadings(newContents.headingLines); page.elements = newContents.rootElements.concat([...headings, ...paras]); }); if (this.headingsDetected(doc)) { await this.computeHeadingLevels(doc, mainCommonFonts); } return doc; } /** * Takes into account potential headings inside a paragraph * splits a paragraph into multiple ones and returns heading candidates * @param page Page to extract headings from each paragraph * @param commonFont Most used font in document * @param headingFonts Array of only fonts that all headings should use */ private extractHeadings( page: Page, commonFonts: Font[], doc: Document, ): { headingLines: Line[][]; paragraphLines: Line[][]; rootElements: Element[] } { // get all paragraphs in page root const pageParagraphs = this.pageParagraphs(page); return { ...this.extractHeadingsInParagraphs(pageParagraphs, commonFonts, doc), rootElements: this.createHeadingsInOtherElements( this.pageOtherElements(page), commonFonts, doc, ), }; } private createHeadingsInOtherElements( elements: Element[], commonFonts: Font[], doc: Document, ): Element[] { this.getElementsWithParagraphs(elements, []) // this is to avoid setting table content as headings .filter(e => !(e instanceof TableCell)) .forEach(element => { const newContents = this.extractHeadingsInParagraphs( this.getParagraphsInElement(element), commonFonts, doc, ); const paras: Paragraph[] = this.mergeLinesIntoParagraphs(newContents.paragraphLines); const headings: Heading[] = this.mergeLinesIntoHeadings(newContents.headingLines); element.content = [...headings, ...paras]; }); return elements; } private extractHeadingsInParagraphs( paragraphs: Paragraph[], commonFonts: Font[], doc: Document, ): { headingLines: Line[][]; paragraphLines: Line[][] } { const paragraphLines: Line[][] = []; const headingLines: Line[][] = []; paragraphs .map(paragraph => paragraph.content) .forEach(linesInParagraph => { const instanceOfFontCheck = commonFonts.map(font => { return font instanceof Font; }) .reduce((acc, curr) => acc && curr); if (instanceOfFontCheck) { const headingIdx: number[] = linesInParagraph .map((line: Line, pos: number) => { if (this.isHeadingLine(line, commonFonts, doc)) { return pos; } else { return undefined; } }) .filter((i: number) => i !== undefined); if (headingIdx.length > 0) { const lineIdx: number[] = [...Array(linesInParagraph.length).keys()].filter( x => !headingIdx.includes(x), ); utils.groupConsecutiveNumbersInArray(lineIdx).forEach((group: number[]) => { const newLines: Line[] = []; group.forEach((id: number) => { newLines.push(linesInParagraph[id]); }); if (newLines.length > 0) { paragraphLines.push(newLines); } }); this.groupHeadingsByFont(headingIdx, linesInParagraph).forEach(headingGroup => { utils.groupConsecutiveNumbersInArray(headingGroup).forEach((group: number[]) => { const newHeadings: Line[] = []; group.forEach((id: number) => { newHeadings.push(linesInParagraph[id]); }); if (newHeadings.length > 0) { headingLines.push(newHeadings); } }); }); } else { paragraphLines.push(linesInParagraph); } } else { logger.warn("can't account for headings while para merge - no font info available"); } }); if (headingLines.length > 0) { return { headingLines, paragraphLines }; } return { headingLines: [], paragraphLines: paragraphs.map(paragraph => paragraph.content) }; } private isHeadingLine(line: Line, commonFonts: Font[], doc: Document): boolean { const lineStr = line.toString(); if (lineStr.length === 1 || !isNaN(lineStr as any)) { return false; } const wordCount = line.content.length; const lineFont = line.getMainFont(); const isDifferentStyle = commonFonts.map(font => { return lineFont.weight !== font.weight ? 1 : 0; }) .reduce((acc, curr) => acc && curr); const isFontBigger = commonFonts.map(font => { return lineFont.size > font.size ? 1 : 0; }) .reduce((acc, curr) => acc && curr); const differentColor = commonFonts.map(font => { return lineFont.color !== font.color ? 1 : 0; }) .reduce((acc, curr) => acc && curr); const isFontUnique = line.isUniqueFont() ? 1 : 0; const isNumber = !isNaN(lineStr as any) ? 1 : 0; const textCase = this.textCase(lineStr); const fontRatio = this.fontRatio(doc, lineFont); const features = [ isDifferentStyle, isFontBigger, isFontUnique, textCase, wordCount, differentColor, isNumber, fontRatio, ]; const clf = new RandomForestClassifier(); return clf.predict(features) === 1; } private textCase(lineStr: string) { const isTitleCase = lineStr .split(' ') .map(word => { const lengthThreshold = 4; if (word.length > lengthThreshold) { return /^[A-Z]\w+/.test(word) || /^(?:\W*\d+\W*)+\w+/.test(word); } else { return true; } }) .reduce((acc, curr) => acc && curr); const isLowerCase = lineStr.toLowerCase() === lineStr; const isUpperCase = lineStr.toUpperCase() === lineStr; let textCase = 3; if (isTitleCase) { textCase = 2; } else if (isLowerCase) { textCase = 0; } else if (isUpperCase) { textCase = 1; } return textCase; } /* 🤔 Maybe we should also use 'page font ratio' as feature because I really think that it could help a lot to decrease false positives. For instance think about one document with a lot of pages with too much text but first page only contains one H1 and two or three or four lines in the bottom part with some annotation text. Font ratio for H1 could be like 0.0001 (for instance) and for bottom paragraph could be 0.002. But if we take care of page ratio then we could have: - H1 ratio 0.01 - Bottom paragraph 0.99 Having this ratios I really think that bottom paragraph should not be considered as header */ private fontRatio(document: Document, font: Font) { const allWords = document.getElementsOfType<Word>(Word, true); const allFonts = [...allWords.map(w => w.font).filter(f => f !== undefined)]; const count = allFonts.filter(f => f.name === font.name && f.size === font.size && f.weight === font.weight && f.isItalic === font.isItalic && f.isUnderline === font.isUnderline && f.color === font.color).length; return count / allFonts.length; } private groupHeadingsByFont(headingIndexes: number[], lines: Line[]): number[][] { // Skip join heading lines if they doesn't have same font const fontGroupedHeadings: number[][] = []; let joinedHeadings: number[] = []; headingIndexes.forEach((pos, index) => { const currentHeadingLineFont = lines[pos].getMainFont(); const prevHeadingLineFont = index > 0 ? lines[index - 1].getMainFont() : null; if (!prevHeadingLineFont || currentHeadingLineFont.isEqual(prevHeadingLineFont)) { joinedHeadings.push(pos); } else { fontGroupedHeadings.push(joinedHeadings); joinedHeadings = [pos]; } }); if (joinedHeadings.length > 0) { fontGroupedHeadings.push(joinedHeadings); } return fontGroupedHeadings; } private mergeLinesIntoParagraphs(joinedLines: Line[][]): Paragraph[] { return joinedLines.map((group: Line[]) => { const paragraph: Paragraph = utils.mergeElements<Line, Paragraph>( new Paragraph(BoundingBox.merge(group.map((l: Line) => l.box))), ...group, ); paragraph.properties.order = group[0].properties.order; return paragraph; }); } private mergeLinesIntoHeadings(joinedLines: Line[][]): Heading[] { return joinedLines.map((group: Line[]) => { const heading: Heading = utils.mergeElements<Line, Heading>( new Heading(BoundingBox.merge(group.map((l: Line) => l.box))), ...group, ); heading.properties.order = group[0].properties.order; return heading; }); } /** * Returns most used font in document * @param doc The document to extract heading fonts * 🤔 I'm not sure if having only one 'main font' is enought because a * normal document should have only one main font for texts but there * are a lot of cases that one document uses 'main font' and 'secodnary font' */ private commonFonts(doc: Document): Font[] { const allWords = doc.getElementsOfType<Word>(Word, true); const allFonts = [...allWords.map(w => w.font).filter(f => f !== undefined)]; let uniqueFonts: Font[] = []; allFonts.forEach(font => { if (uniqueFonts.filter(f => f.isEqual(font)).length === 0) { uniqueFonts.push(font); } }); // sorting the fonts by their ratios const sortedUniqueFonts = uniqueFonts.sort((fontA, fontB) => { return this.fontRatio(doc, fontB) - this.fontRatio(doc, fontA); }); // for now we return only the font with highest ratio as common font // the idea is to return 1, 2 or 3 common fonts (i.e. .slice(0, threshold)) return sortedUniqueFonts.slice(0, 1); } private pageOtherElements(page: Page): Element[] { return page.elements.filter(element => !(element instanceof Paragraph)); } private getElementsWithParagraphs(elements: Element[], withParagraphs: Element[]): Element[] { elements.forEach(element => { const paragraphs = this.getParagraphsInElement(element); if (paragraphs.length > 0) { withParagraphs.push(element); } else if (Array.isArray(element.content)) { element.content.forEach(child => { if (child.content as Element[]) { this.getElementsWithParagraphs(child.content as Element[], withParagraphs); } }); } }); return withParagraphs; } private getParagraphsInElement(element: Element): Paragraph[] { if (Array.isArray(element.content)) { return element.content .filter(item => item instanceof Paragraph) .map(paragraph => paragraph as Paragraph); } return []; } private pageParagraphs(page: Page): Paragraph[] { return page.getElementsOfType<Paragraph>(Paragraph, false); } private headingsDetected(doc: Document): boolean { let detected = false; doc.pages.forEach(page => { if (page.getElementsOfType<Heading>(Heading, true).length > 0) { detected = true; } }); return detected; } private async computeHeadingLevels(document: Document, commonFonts: Font[]) { const headings: Heading[] = document.getElementsOfType<Heading>(Heading, true); let args = ''; headings.forEach(h => { const headingFont = h.getMainFont(); const size = headingFont.size; const weight = headingFont.weight === 'bold' ? 1 : 0; const textCase = this.textCase(h.toString()); const isFontBigger = commonFonts.map(font => { return headingFont.size > font.size ? 1 : 0; }) .reduce((acc, curr) => acc && curr); const differentColor = commonFonts.map(font => { return headingFont.color !== font.color ? 1 : 0; }) .reduce((acc, curr) => acc && curr); const wordCount = h.content.length; const fontRatio = this.fontRatio(document, headingFont); args = args + [size, weight, textCase, isFontBigger, differentColor, wordCount, fontRatio].toString() + ','; }); await CommandExecuter.levelPrediction(args).then(stdout => { const predictions = stdout.split(' '); headings.forEach((h, index) => { h.level = parseInt(predictions[index]); }); }); } }
the_stack
'use strict'; import { IReducerMap } from 'chord/workbench/api/common/reducer/reducerMap'; import { showSearchView } from 'chord/workbench/parts/mainView/browser/reducer/searchView'; import { showSearchResult, addSearchSongs, addSearchAlbums, addSearchArtists, addSearchCollections, addSearchEpisodes, addSearchPodcasts, addSearchRadios, } from 'chord/workbench/parts/mainView/browser/reducer/searchResult'; import { showAlbumView } from 'chord/workbench/parts/mainView/browser/reducer/showAlbum'; import { showCollectionView } from 'chord/workbench/parts/mainView/browser/reducer/showCollection'; import { showArtistView } from 'chord/workbench/parts/mainView/browser/reducer/showArtist'; import { comebackView } from 'chord/workbench/parts/mainView/browser/reducer/comeback'; import { getMoreArtistSongs, getMoreArtistAlbums } from 'chord/workbench/parts/mainView/browser/reducer/artist'; import { showLibraryResult } from 'chord/workbench/parts/mainView/browser/reducer/libraryResult'; import { getMoreLibrarySongs, getMoreLibraryArtists, getMoreLibraryAlbums, getMoreLibraryCollections, getMoreLibraryUserProfiles, getMoreLibraryEpisodes, getMoreLibraryPodcasts, getMoreLibraryRadios, } from 'chord/workbench/parts/mainView/browser/reducer/libraryResult'; import { addLibrarySong, addLibraryArtist, addLibraryAlbum, addLibraryCollection, addLibraryUserProfile, addLibraryEpisode, addLibraryPodcast, addLibraryRadio, removeFromLibrary, } from 'chord/workbench/parts/mainView/browser/reducer/library'; import { showPreference } from 'chord/workbench/parts/mainView/browser/reducer/preference'; import { showUserProfile } from 'chord/workbench/parts/mainView/browser/reducer/showUserProfile'; import { getMoreUserFavoriteSongs, getMoreUserFavoriteAlbums, getMoreUserFavoriteArtists, getMoreUserFavoriteCollections, getMoreUserCreatedCollections, getMoreUserFollowings, } from 'chord/workbench/parts/mainView/browser/reducer/userProfile'; import { changeHomeView } from 'chord/workbench/parts/mainView/browser/reducer/home/nagivation'; import { showRecommendView } from 'chord/workbench/parts/mainView/browser/reducer/home/recommend'; import { showCollectionListOptions, showCollectionListView, getMoreCollections } from 'chord/workbench/parts/mainView/browser/reducer/home/collections'; import { showAlbumListOptions, showAlbumList, getMoreAlbums } from 'chord/workbench/parts/mainView/browser/reducer/home/albums'; import { showArtistListOptions, showArtistList } from 'chord/workbench/parts/mainView/browser/reducer/home/artists'; import { showPodcastView } from 'chord/workbench/parts/mainView/browser/reducer/showPodcast'; import { showRadioView } from 'chord/workbench/parts/mainView/browser/reducer/showRadio'; export function map(act: string): IReducerMap { switch (act) { case 'c:mainView:searchView': return { reducer: showSearchView, node: 'searchView', }; case 'c:mainView:searchInput': return { reducer: showSearchResult, node: 'searchView', }; case 'c:mainView:searchMoreSongs': return { reducer: addSearchSongs, node: 'searchView.result', }; case 'c:mainView:searchMoreAlbums': return { reducer: addSearchAlbums, node: 'searchView.result', }; case 'c:mainView:searchMoreArtists': return { reducer: addSearchArtists, node: 'searchView.result', }; case 'c:mainView:searchMoreCollections': return { reducer: addSearchCollections, node: 'searchView.result', }; case 'c:mainView:searchMoreEpisodes': return { reducer: addSearchEpisodes, node: 'searchView.result', }; case 'c:mainView:searchMorePodcasts': return { reducer: addSearchPodcasts, node: 'searchView.result', }; case 'c:mainView:searchMoreRadios': return { reducer: addSearchRadios, node: 'searchView.result', }; // show album view case 'c:mainView:showAlbumView': return { reducer: showAlbumView, node: 'albumView', }; // show collection view case 'c:mainView:showCollectionView': return { reducer: showCollectionView, node: 'collectionView', }; case 'c:mainView:comeback': return { reducer: comebackView, node: '.', }; // show artist view case 'c:mainView:showArtistView': return { reducer: showArtistView, node: 'artistView', }; // artist case 'c:mainView:getMoreArtistSongs': return { reducer: getMoreArtistSongs, node: 'artistView', }; case 'c:mainView:getMoreArtistAlbums': return { reducer: getMoreArtistAlbums, node: 'artistView', }; // library case 'c:mainView:libraryInput': return { reducer: showLibraryResult, node: 'libraryView', }; case 'c:mainView:getMoreLibrarySongs': return { reducer: getMoreLibrarySongs, node: 'libraryView.result', }; case 'c:mainView:getMoreLibraryArtists': return { reducer: getMoreLibraryArtists, node: 'libraryView.result', }; case 'c:mainView:getMoreLibraryAlbums': return { reducer: getMoreLibraryAlbums, node: 'libraryView.result', }; case 'c:mainView:getMoreLibraryCollections': return { reducer: getMoreLibraryCollections, node: 'libraryView.result', }; case 'c:mainView:getMoreLibraryUserProfiles': return { reducer: getMoreLibraryUserProfiles, node: 'libraryView.result', }; case 'c:mainView:getMoreLibraryEpisodes': return { reducer: getMoreLibraryEpisodes, node: 'libraryView.result', }; case 'c:mainView:getMoreLibraryPodcasts': return { reducer: getMoreLibraryPodcasts, node: 'libraryView.result', }; case 'c:mainView:getMoreLibraryRadios': return { reducer: getMoreLibraryRadios, node: 'libraryView.result', }; case 'c:mainView:addLibrarySong': return { reducer: addLibrarySong, node: 'libraryView.result', }; case 'c:mainView:addLibraryArtist': return { reducer: addLibraryArtist, node: 'libraryView.result', }; case 'c:mainView:addLibraryAlbum': return { reducer: addLibraryAlbum, node: 'libraryView.result', }; case 'c:mainView:addLibraryCollection': return { reducer: addLibraryCollection, node: 'libraryView.result', }; case 'c:mainView:addLibraryUserProfile': return { reducer: addLibraryUserProfile, node: 'libraryView.result', }; case 'c:mainView:addLibraryEpisode': return { reducer: addLibraryEpisode, node: 'libraryView.result', }; case 'c:mainView:addLibraryPodcast': return { reducer: addLibraryPodcast, node: 'libraryView.result', }; case 'c:mainView:addLibraryRadio': return { reducer: addLibraryRadio, node: 'libraryView.result', }; case 'c:mainView:removeFromLibrary': return { reducer: removeFromLibrary, node: 'libraryView.result', }; // preference case 'c:mainView:preferenceView': return { reducer: showPreference, node: '.', }; // user profile case 'c:mainView:showUserProfileView': return { reducer: showUserProfile, node: 'userProfileView', }; case 'c:mainView:getMoreUserFavoriteSongs': return { reducer: getMoreUserFavoriteSongs, node: 'userProfileView', }; case 'c:mainView:getMoreUserFavoriteArtists': return { reducer: getMoreUserFavoriteArtists, node: 'userProfileView', }; case 'c:mainView:getMoreUserFavoriteAlbums': return { reducer: getMoreUserFavoriteAlbums, node: 'userProfileView', }; case 'c:mainView:getMoreUserFavoriteCollections': return { reducer: getMoreUserFavoriteCollections, node: 'userProfileView', }; case 'c:mainView:getMoreUserCreatedCollections': return { reducer: getMoreUserCreatedCollections, node: 'userProfileView', }; case 'c:mainView:getMoreUserFollowings': return { reducer: getMoreUserFollowings, node: 'userProfileView', }; // Podcast case 'c:mainView:showPodcastView': return { reducer: showPodcastView, node: 'podcastView', }; case 'c:mainView:showRadioView': return { reducer: showRadioView, node: 'radioView', }; // home view case 'c:mainView:home:navigation:changeView': return { reducer: changeHomeView, node: 'homeView', }; case 'c:mainView:home:showRecommendView': return { reducer: showRecommendView, node: 'homeView', }; case 'c:mainView:home:showCollectionListOptionsView': return { reducer: showCollectionListOptions, node: 'homeView', }; case 'c:mainView:home:showCollectionListView': return { reducer: showCollectionListView, node: 'homeView.collectionsView', }; case 'c:mainView:home:collections:getMoreCollections': return { reducer: getMoreCollections, node: 'homeView.collectionsView', }; case 'c:mainView:home:showAlbumListOptionsView': return { reducer: showAlbumListOptions, node: 'homeView', }; case 'c:mainView:home:showAlbumListView': return { reducer: showAlbumList, node: 'homeView', }; case 'c:mainView:home:albums:getMoreAlbums': return { reducer: getMoreAlbums, node: 'homeView.albumsView', }; case 'c:mainView:home:showArtistListOptionsView': return { reducer: showArtistListOptions, node: 'homeView', }; case 'c:mainView:home:showArtistListView': return { reducer: showArtistList, node: 'homeView', }; default: return null; } }
the_stack
import { Inject, Injectable, forwardRef } from "@angular/core"; import { AccessToken, DataStore, ServerError } from "@batch-flask/core"; import { log } from "@batch-flask/utils"; import { TenantDetails } from "app/models"; import { AADResourceName, AzurePublic } from "client/azure-environment"; import { BatchExplorerApplication } from "client/core/batch-explorer-application"; import { BlIpcMain } from "client/core/bl-ipc-main"; import { fetch } from "client/core/fetch"; import { BatchExplorerProperties } from "client/core/properties"; import { TelemetryManager } from "client/core/telemetry"; import { Constants } from "common"; import { IpcEvent } from "common/constants"; import { Deferred } from "common/deferred"; import { dialog } from "electron"; import { BehaviorSubject, Observable } from "rxjs"; import { AADConfig } from "../aad-config"; import { defaultTenant } from "../aad-constants"; import AuthProvider from "../auth-provider"; import { AuthenticationService, AuthenticationState, AuthorizeResult, LogoutError } from "../authentication"; import { AADUser } from "./aad-user"; import { UserDecoder } from "./user-decoder"; const aadConfig: AADConfig = { tenant: "common", clientId: "04b07795-8ddb-461a-bbee-02f9e1bf7b46", // Azure CLI redirectUri: "urn:ietf:wg:oauth:2.0:oob", logoutRedirectUri: "urn:ietf:wg:oauth:2.0:oob/logout", }; @Injectable() export class AADService { public currentUser: Observable<AADUser | null>; public tenants: Observable<TenantDetails[]>; public userAuthorization: AuthenticationService; public authenticationState: Observable<AuthenticationState | null>; private _authenticationState = new BehaviorSubject<AuthenticationState | null>(null); private _userDecoder: UserDecoder; private _newAccessTokenSubject: StringMap<Deferred<AccessToken>> = {}; private _currentUser = new BehaviorSubject<AADUser | null>(null); private _tenants = new BehaviorSubject<TenantDetails[]>([]); constructor( @Inject(forwardRef(() => BatchExplorerApplication)) private app: BatchExplorerApplication, private localStorage: DataStore, private properties: BatchExplorerProperties, private telemetryManager: TelemetryManager, ipcMain: BlIpcMain ) { this._userDecoder = new UserDecoder(); this.currentUser = this._currentUser.asObservable(); this.tenants = this._tenants.asObservable(); this.userAuthorization = new AuthenticationService(this.app, aadConfig, new AuthProvider(this.app, aadConfig)); this.authenticationState = this._authenticationState.asObservable(); ipcMain.on(IpcEvent.AAD.accessTokenData, async ({ tenantId, resource }) => await this.accessTokenData(tenantId, resource)); this.userAuthorization.state.subscribe((state) => { this._authenticationState.next(state); }); } public async init() { await this._retrieveUserFromLocalStorage(); } /** * Login to azure active directory. * This will retrieve fresh tokens for all tenant and resources needed by BatchExplorer. */ public login(): { started: Promise<any>, done: Promise<any> } { const started = this._ensureTelemetryOptInNationalClouds(); return { started, done: started.then(() => this._loginInCurrentCloud()), }; } public async logout() { await this.localStorage.removeItem(Constants.localStorageKey.currentUser); this._tenants.next([]); await this._clearUserSpecificCache(); for (const [, window] of this.app.windows) { window.webContents.session.clearStorageData({ storages: ["localStorage"] }); } this.app.windows.closeAll(); await this.userAuthorization.logout(); } public async accessTokenFor(tenantId: string, resource?: AADResourceName) { return this.accessTokenData(tenantId, resource).then(x => x.access_token); } /** * * @param tenantId * @param resource */ public async accessTokenData(tenantId: string, resource?: AADResourceName): Promise<AccessToken> { return this._retrieveNewAccessToken(tenantId, resource || "arm"); } private async _loginInCurrentCloud() { try { await this.accessTokenData(defaultTenant); this._authenticationState.next(AuthenticationState.Authenticated); } catch (error) { if (error instanceof LogoutError) { throw error; } else { log.error("Error login in ", error); throw error; } } try { const tenants = await this._loadTenants(); this._tenants.next(tenants); } catch (error) { log.error("Error retrieving tenants", error); this._tenants.error(ServerError.fromARM(error)); } } /** * Look into the localStorage to see if there is a user to be loaded */ private async _retrieveUserFromLocalStorage() { const userStr = await this.localStorage.getItem<string>(Constants.localStorageKey.currentUser); if (userStr) { try { const user = JSON.parse(userStr); this._currentUser.next(user); } catch (e) { this.localStorage.removeItem(Constants.localStorageKey.currentUser); } } } /** * Retrieve a new access token. * @return Observable with access token object */ private async _retrieveNewAccessToken(tenantId: string, resource: AADResourceName): Promise<AccessToken> { const defer = new Deferred<AccessToken>(); this._newAccessTokenSubject[this._tenantResourceKey(tenantId, resource)] = defer; this._redeemNewAccessToken(tenantId, resource); return defer.promise; } private _tenantResourceKey(tenantId: string, resource: string) { return `${tenantId}|${resource}`; } /** * Load a new access token from the authorization code given at login */ private async _redeemNewAccessToken(tenantId: string, resource: AADResourceName) { const defer = this._newAccessTokenSubject[this._tenantResourceKey(tenantId, resource)]; try { const result: AuthorizeResult = await this.userAuthorization.authorizeResource( tenantId, this.properties.azureEnvironment[resource as string] ); this._processUserToken(result.idToken); delete this._newAccessTokenSubject[this._tenantResourceKey(tenantId, resource)]; defer.resolve(new AccessToken({ access_token: result.accessToken, refresh_token: null, token_type: result.tokenType, expires_in: null, expires_on: result.expiresOn, ext_expires_in: null, not_before: null, tenantId, resource })); } catch (e) { log.error(`Error redeem auth code for a token for resource ${resource}`, e); delete this._newAccessTokenSubject[this._tenantResourceKey(tenantId, resource)]; defer.reject(e); } } /** * Process IDToken return by the /authorize url to extract user information */ private _processUserToken(idToken: string) { const user = this._userDecoder.decode(idToken); const prevUser = this._currentUser.value; if (!prevUser || prevUser.username !== user.username) { this._clearUserSpecificCache(); } this._currentUser.next(user); this.localStorage.setItem(Constants.localStorageKey.currentUser, JSON.stringify(user)); } private async _loadTenants(): Promise<TenantDetails[]> { const token = await this.accessTokenData(defaultTenant); const headers = { Authorization: `${token.token_type} ${token.access_token}`, }; const options = { headers }; const url = this._tenantURL(); const response = await fetch(url, options); const { value } = await response.json(); return value; } private _tenantURL() { return this.properties.azureEnvironment.arm + `tenants?api-version=${Constants.ApiVersion.arm}`; } private async _clearUserSpecificCache() { this.localStorage.removeItem(Constants.localStorageKey.subscriptions); this.localStorage.removeItem(Constants.localStorageKey.selectedAccountId); } private async _ensureTelemetryOptInNationalClouds() { if (this.properties.azureEnvironment.id === AzurePublic.id) { return; } // If user hasn't picked a telemetry setting ask to opt in or out if (this.telemetryManager.userTelemetryEnabled == null) { const wikiLink = "https://github.com/Azure/BatchExplorer/wiki/Crash-reporting-and-telemetry"; const val = await dialog.showMessageBox({ type: "question", buttons: ["Enable", "Disable"], title: "Telemetry settings", message: "Batch Explorer collects anonymous usage data and sends it " + "to Microsoft to help improve our products and services. " + `You can learn more about what data is being sent and what it is used for at ${wikiLink}. ` + `You are login into a national cloud, do you wish to keep sending telemetry? ` + "Disabling will restart the application.", noLink: true, }); if (val.response === 0) { return this.telemetryManager.enableTelemetry({ restart: false }); } else if (val.response === 1) { return this.telemetryManager.disableTelemetry(); } } } }
the_stack
import { logger, events } from '../util' import * as app from './app' import * as charts from '../charts/core' import Client from '../client' import Dashboard from '../models/dashboard' import DashboardItem from '../models/items/item' import Container from '../models/items/container' import Query from '../models/data/query' import {transforms} from '../models/transform/transform' declare var $, URI, window, bootbox, ts, require const log = logger('manager') const axios = require('axios') class DashboardHolder { url : string element : any dashboard : Dashboard constructor(url, element) { this.url = url this.element = element this.dashboard = null } setRange(from, until) { let url = new URI(this.url) if (from) { url.setQuery('from', from) } if (until) { url.setQuery('until', until) } this.url = url.href() } } export class Manager { current: any /* DashboardHolder */ current_transform: any current_list: Dashboard[] client: Client constructor(client?: Client) { this.client = client ? client : new Client() } set_current(value) : Manager { this.current = value return this } find(href: string) : Dashboard { if (!this.current_list) return null return this.current_list.find(d => d.href === href) } /** * Register an event handler for processing a dashboard once it's * loaded and ready. */ onDashboardLoaded(handler) : Manager { events.on(this, app.Event.DASHBOARD_LOADED, handler) return this } /** * List all dashboards. */ list(path, handler) : void { this.client.dashboard_list({path: path}) .then(handler) .catch(error => { this.error(`Error listing dashboards. ${error}`) }) } // Web Components. I want Web Components. TBD. render_dashboard_list(path, element, handler?) : void { let mgr = this let fn = (data) => { if (data && data.length) { this.current_list = data if (handler) { handler(data) } $(element).html(ts.templates.listing.dashboard_list({dashboards: data})) ts.user.list_favorites().forEach(function(d) { $(`[data-ds-href="${d.href}"].ds-favorite-indicator`).html('<i class="fa fa-lg fa-star"></i>') $(`[data-ds-href="${d.href}"]`).addClass('ds-favorited') $(`tr[data-ds-href="${d.href}"]`).addClass('active') }) } } if (path instanceof Array) { fn(path) } else { this.list(path, fn) } } default_error_handler(xhr, status, error) : void { console.log(xhr) console.log(status) console.log(error) } error(message, options: any = {}) : void { options.type = options.type || 'danger' $.notify({ message: message, title: 'Error', icon: 'fa fa-exclamation-circle' }, options) } warning(message, options: any = {}) : void { options.type = options.type || 'warning' $.notify({ message: message, title: options.title || 'Warning', icon: options.icon || 'fa fa-exclamation-circle' }, options) } success(message, options: any = {}) : void { options.type = options.type || 'success' $.notify({ message: message, title: options.title || 'Success', icon: options.icon || 'fa fa-check-circle' }, options) } /** * Set up us the API call. */ _prep_url(base_url: string, options: any) : any { let url = new URI(base_url).setQuery('rendering', true) let context = app.context(url.query(true)) context.from = options.from || context.from context.until = context.until || options.until url.setQuery('from', context.from) if (context.until) { url.setQuery('until', context.until) } context.url = url.href() if (typeof(options.interactive) != 'undefined') { context.interactive = options.interactive } else if (context.params.interactive) { context.interactive = context.params.interactive != 'false' } return context } cleanup() : void { if (this.current && this.current.dashboard) { this.current.dashboard.visit(item => item.cleanup()) } } /** * Load and render a dashboard. */ load(url: string, element, options: any = {}) : Manager { log.debug('load(): ' + url) this.cleanup() let holder = new DashboardHolder(url, element) let context = this._prep_url(url, options) this.set_current(holder) axios.get(context.url) .catch(error => this.error(`Error loading dashboard. ${error}`)) .then(response => { let dashboard = new Dashboard(response.data) holder.dashboard = dashboard let r = context.variables.renderer || response.data.preferences.renderer if (typeof context.variables.interactive != 'undefined') { r = context.variables.interactive === 'false' ? 'graphite' : 'flot' } if (r) { charts.set_renderer(r) } events.fire(this, app.Event.DASHBOARD_LOADED, dashboard) // Expand any templatized queries or dashboard items dashboard.render_templates(context.variables) // Render the dashboard $(element).html(dashboard.definition.render()) let currentURL = new URI(holder.url) events.fire(this, app.Event.RANGE_CHANGED, { from: currentURL.query('from'), until: currentURL.query('until') }) if (this.current_transform) { this.apply_transform(this.current_transform.transform, this.current_transform.target, false, context) } else { // Load the queries dashboard.definition.load_all({ from: context.from, until: context.until }) } events.fire(this, app.Event.DASHBOARD_RENDERED, dashboard) if (context.params.mode) { app.switch_to_mode(context.params.mode) } else { app.refresh_mode() } }) return this } /** * Re-render a dashboard item and update its DOM representation. */ update_item_view(item) : void { let element = $(`#${item.item_id}`) // REFACTOR - unchecked global reference let visible = ts.edit.details_visibility(item) element.replaceWith(item.render()) if (visible) { // REFACTOR - unchecked global reference ts.edit.show_details(item.item_id) } item.visit((i) => { let query = i.query_override || i.query if (query && query instanceof Query) { log.debug(`update_item_view(): reloading query ${query.name}`) query.load() } }) app.refresh_mode() } /** * Execute a function with re-rendering of the DOM for dashboard * items disabled. */ without_updates(handler) : any { let fn = Manager.prototype.update_item_view Manager.prototype.update_item_view = function() { } try { return handler() } finally { Manager.prototype.update_item_view = fn } } handle_popstate(event) : void { if (!event.state) { this.current_transform = undefined this.refresh() app.switch_to_mode('standard') } else { if (event.state.transform) { let item = this.current.dashboard.get_item(event.state.target.item_id) this.apply_transform(event.state.transform.name, item, false) } else if (event.state.url) { this.current_transform = undefined this.refresh() app.switch_to_mode('standard') } } } remove_transform() : Manager { if (this.current && this.current_transform) { window.location = new URI(window.location) .path(this.current.dashboard.view_href) .href() this.current_transform = undefined } return this } apply_transform(transform, target, set_location: boolean = true, context?: any) : Manager { let dashboard = this.current.dashboard if (typeof(transform) === 'string') transform = transforms.get(transform) log.debug('apply_transform(' + transform.name + ')') if (transform.transform_type == 'dashboard' && typeof(target) === 'undefined') { target = dashboard.definition } /** * Set browser URL state */ if (set_location) { let url = new URI(window.location) if (target.item_type != 'dashboard_definition') { url.segment(target.item_id.toString()) } url.segment('transform').segment(transform.name) window.history.pushState({ url:this.current.url, element:this.current.element, transform:transform.toJSON(), target:target.toJSON() }, '', url.href()) } /** * update_item_view() reloads queries, which we don't want to do * while processing the transform. */ let result = this.without_updates(() => { return transform.transform(target) }) result.visit((item) => { item.set_dashboard(dashboard) }) dashboard.definition.queries = result.get_queries() // this could go in an observer dashboard.set_items([result]) $(`#${dashboard.definition.item_id}`).replaceWith(dashboard.render()) dashboard.render_templates(app.context().variables) if (context) { dashboard.load_all({ from: context.from, until: context.until }) } else { dashboard.load_all() } if ((transform.transform_type === 'presentation') && (app.instance.current_mode != app.Mode.EDIT)) { app.switch_to_mode('transform') this.current_transform = { transform: transform, target: target } } dashboard.dirty = false return this } refresh() : void { log.debug('refresh()') if (this.current && (app.instance.current_mode != app.Mode.EDIT)) { this.load(this.current.url, this.current.element) } else { log.debug(`skipping reload; current mode: ${app.instance.current_mode}`) } } /* ----------------------------------------------------------------------------- Time range and auto-refresh ----------------------------------------------------------------------------- */ set_time_range(from, until) : void { let uri = new URI(window.location) from ? uri.setQuery('from', from) : uri.removeQuery('from') until ? uri.setQuery('until', until) : uri.removeQuery('until') window.history.pushState({url: this.current.url, element:this.current.element}, '', uri.href()) this.current.setRange(from, until) events.fire(this, app.Event.RANGE_CHANGED, { from: from, until: until }) this.refresh() } static ranges = { // TODO - quick hack. Parse the range and generate on the fly // for maximum flexibiliy '-1h' : 'Past Hour', '-2h' : 'Past 2 Hours', '-3h' : 'Past 3 Hours', '-4h' : 'Past 4 Hours', '-6h' : 'Past 6 Hours', '-12h' : 'Past 12 Hours', '-1d' : 'Past Day', '-7d' : 'Past Week' } getRangeDescription(range: string) : string { if (range in Manager.ranges) { return Manager.ranges[range] } else { return null } } onRangeChanged(handler) : void { events.on(this, app.Event.RANGE_CHANGED, handler) } autoRefreshInterval: number intervalSeconds: number intervalId: any = null set_refresh_interval(value) : void { let intervalSeconds = parseInt(value) this.autoRefreshInterval = intervalSeconds if (this.intervalId) { log.debug('clearing auto-refresh interval; intervalId: ' + this.intervalId) window.clearInterval(this.intervalId) this.intervalId = undefined } if (intervalSeconds > 0) { this.intervalSeconds = intervalSeconds this.intervalId = window.setInterval(() => { this.refresh() }, intervalSeconds * 1000) log.debug(`set auto-refresh interval; intervalId: ${this.intervalId}; seconds: ${intervalSeconds}`) } } delete_with_confirmation(href, handler?) : void { bootbox.dialog({ message: "Are you really sure you want to delete this dashboard? Deletion is irrevocable.", title: "Confirm dashboard delete", backdrop: false, buttons: { cancel: { label: "Cancel", className: "btn-default", callback: () => { // TODO - notification } }, confirm: { label: "Delete", className: "btn-danger", callback: () => { this.delete_dashboard(href, handler) } } } }) } delete_dashboard(href, handler?) : void { let done : any = handler || (() => { window.location.href = '/dashboards' this.success(`Successfully deleted dashboard ${href}`) }) this.client.dashboard_delete(href) .then(done) .catch(error => { this.error(`Error deleting dashboard ${href}. ${error}`) }) } delete_current() : void { this.delete_with_confirmation(this.current.dashboard.href) } create(input, handler?) : void { let dashboard = null if (typeof input === 'string') { let json = JSON.parse(input) dashboard = new Dashboard(json) } else if (input instanceof Dashboard) { dashboard = input } else { dashboard = new Dashboard(input) } this.client.dashboard_create(dashboard) .then(handler) .catch(error => { this.error(`Error creating dashboard. ${error}`) }) } update(dashboard, handler?) : void { this.client.dashboard_update(dashboard) .then(handler) .then(() => { dashboard.dirty = false }) .catch(error => { this.error(`Error updating dashboard ${dashboard.title}. ${error}`) }) } update_definition(dashboard: any, handler?) : void { if (app.instance.current_mode === app.Mode.TRANSFORM) { this.warning(`Unable to save dashboad while a transform is applied. Revert to standard mode in order to save changes.`) return } this.client.dashboard_update_definition(dashboard) .then(handler) .then(() => { dashboard.dirty = false }) .catch(error => { this.error(`Error updating dashboard definition ${dashboard.title}. ${error}`) }) } duplicate(href: string, handler?) : void { let error_handler = (error) => { this.error(`Error duplicating dashboard ${href}. ${error}`) } this.client.dashboard_get(href, { definition: true }) .then((db) => { db.title = `Copy of ${db.title}` db.id = null this.client.dashboard_create(db) .then(handler) .catch(error_handler) }) .catch(error_handler) } } const manager = new Manager() events.on(DashboardItem, 'update', (e: { target: DashboardItem }) => { if (!e || !e.target) { log.warn('on:DashboardItem.update: item not bound') } else { let item = e.target log.debug(`on:DashboardItem.update: ${item.item_type} / ${item.item_id}`) if (item instanceof Container && manager.current) { manager.current.dashboard.update_index() } manager.update_item_view(item) } }) window.addEventListener('popstate', (e) => { manager.handle_popstate(e) }) app.add_mode_handler(app.Mode.STANDARD, { enter: () => { manager.remove_transform() } }) export default manager
the_stack
import { expect } from "chai"; import { describe } from "mocha"; import { IKernelEventObserver } from "../src/common/interactive/kernel"; import { KernelInvocationContext } from "../src/common/interactive/kernelInvocationContext"; import * as contracts from "../src/common/interfaces/contracts"; describe("dotnet-interactive", () => { let toDispose: contracts.Disposable[] = []; function use<T extends contracts.Disposable>(disposable: T): T { toDispose.push(disposable); return disposable; } afterEach(() => toDispose.forEach(d => d.dispose())); describe("client-side kernel invocation context", () => { let makeEventWatcher: () => { watcher: IKernelEventObserver, events: contracts.KernelEventEnvelope[] } = () => { let events: contracts.KernelEventEnvelope[] = []; return { events, watcher: (kernelEvent: contracts.KernelEventEnvelope) => events.push(kernelEvent) }; }; function makeSubmitCode(code: string): contracts.KernelCommandEnvelope { let command: contracts.SubmitCode = { code: code }; return { commandType: contracts.SubmitCodeType, command: command }; } let commadnEnvelope = makeSubmitCode("123"); it("publishes CommandHandled when Complete is called", async () => { let context = use(KernelInvocationContext.establish(commadnEnvelope)); let ew = makeEventWatcher(); context.subscribeToKernelEvents(ew.watcher); context.complete(commadnEnvelope); expect(ew.events.length).to.eql(1); expect(ew.events[0].eventType).to.eql(contracts.CommandSucceededType); }); it("does not publish CommandFailed when Complete is called", async () => { let context = use(KernelInvocationContext.establish(commadnEnvelope)); let ew = makeEventWatcher(); context.subscribeToKernelEvents(ew.watcher); context.complete(commadnEnvelope); ew.events.forEach(event => { expect(event.eventType).is.not.eq(contracts.CommandFailedType); }); }); it("completes only when child context introduced by spawned command completes", async () => { // TODO // Not clear that we can test this right now, because the C# test depends on adding // middleware to the composite kernel, and getting it to invoke the C# kernel. I'm not // even sure where the spawned child command gets created - the test only appears to // create one command explicitly. }); it("does not publish further events after Complete is called", async () => { let context = use(KernelInvocationContext.establish(commadnEnvelope)); let ew = makeEventWatcher(); context.subscribeToKernelEvents(ew.watcher); context.complete(commadnEnvelope); let ev: contracts.ErrorProduced = { message: "oops", formattedValues: null, valueId: null }; let evEnv: contracts.KernelEventEnvelope = { event: ev, eventType: contracts.ErrorProducedType, command: commadnEnvelope }; context.publish(evEnv); ew.events.forEach(event => { expect(event.eventType).is.not.eq(contracts.ErrorProducedType); }); }); it("publishes CommandFailed when Fail is called", async () => { let context = use(KernelInvocationContext.establish(commadnEnvelope)); let ew = makeEventWatcher(); context.subscribeToKernelEvents(ew.watcher); context.fail("oops!"); expect(ew.events.length).to.eql(1); expect(ew.events[0].eventType).to.eql(contracts.CommandFailedType); }); it("does not publish CommandHandled when Fail is called", async () => { let context = use(KernelInvocationContext.establish(commadnEnvelope)); let ew = makeEventWatcher(); context.subscribeToKernelEvents(ew.watcher); context.fail("oops!"); ew.events.forEach(event => { expect(event.eventType).is.not.eq(contracts.CommandSucceededType); }); }); it("does not publish further events after Fail is called", async () => { let context = use(KernelInvocationContext.establish(commadnEnvelope)); let ew = makeEventWatcher(); context.subscribeToKernelEvents(ew.watcher); context.fail("oops!"); let ev: contracts.DisplayedValueProduced = { formattedValues: null, valueId: null }; let evEnv: contracts.KernelEventEnvelope = { event: ev, eventType: contracts.DisplayedValueProducedType, command: commadnEnvelope }; context.publish(evEnv); ew.events.forEach(event => { expect(event.eventType).is.not.eq(contracts.DisplayedValueProducedType); }); }); it("completes only when child all commands complete if multiple commands are active", async () => { let outerSubmitCode = makeSubmitCode("abc"); let outer = use(KernelInvocationContext.establish(outerSubmitCode)); let ew = makeEventWatcher(); outer.subscribeToKernelEvents(ew.watcher); let innerSubmitCode = makeSubmitCode("def"); let inner = use(KernelInvocationContext.establish(innerSubmitCode)); inner.complete(innerSubmitCode); ew.events.forEach(event => { expect(event.eventType).is.not.eq(contracts.CommandSucceededType); }); }); it("publishes events from inner context if both inner and outer are in progress", async () => { let outerSubmitCode = makeSubmitCode("abc"); let outer = use(KernelInvocationContext.establish(outerSubmitCode)); let ew = makeEventWatcher(); outer.subscribeToKernelEvents(ew.watcher); let innerSubmitCode = makeSubmitCode("def"); let inner = use(KernelInvocationContext.establish(innerSubmitCode)); let ev: contracts.ErrorProduced = { message: "oops", formattedValues: null, valueId: null }; let evEnv: contracts.KernelEventEnvelope = { event: ev, eventType: contracts.ErrorProducedType, command: innerSubmitCode }; inner.publish(evEnv); expect(ew.events.length).to.eql(1); expect(ew.events[0].eventType).to.eql(contracts.ErrorProducedType); }); it("does not publish further events from inner context after outer context is completed", async () => { let outerSubmitCode = makeSubmitCode("abc"); let outer = use(KernelInvocationContext.establish(outerSubmitCode)); let ew = makeEventWatcher(); outer.subscribeToKernelEvents(ew.watcher); let innerSubmitCode = makeSubmitCode("def"); let inner = use(KernelInvocationContext.establish(innerSubmitCode)); outer.complete(outerSubmitCode); let ev: contracts.ErrorProduced = { message: "oops", formattedValues: null, valueId: null }; let evEnv: contracts.KernelEventEnvelope = { event: ev, eventType: contracts.ErrorProducedType, command: innerSubmitCode }; inner.publish(evEnv); ew.events.forEach(event => { expect(event.eventType).is.not.eq(contracts.ErrorProducedType); }); }); it("does not publish further events from inner context after it is completed", async () => { let outerSubmitCode = makeSubmitCode("abc"); let outer = use(KernelInvocationContext.establish(outerSubmitCode)); let ew = makeEventWatcher(); outer.subscribeToKernelEvents(ew.watcher); let innerSubmitCode = makeSubmitCode("def"); let inner = use(KernelInvocationContext.establish(innerSubmitCode)); inner.complete(outerSubmitCode); let ev: contracts.ErrorProduced = { message: "oops", formattedValues: null, valueId: null }; let evEnv: contracts.KernelEventEnvelope = { event: ev, eventType: contracts.ErrorProducedType, command: innerSubmitCode }; inner.publish(evEnv); ew.events.forEach(event => { expect(event.eventType).is.not.eq(contracts.ErrorProducedType); }); }); it("set current to null when disposed", async () => { let context = KernelInvocationContext.establish(commadnEnvelope); // TODO // The C# test registers a completion callback with OnComplete, but it's not // entirely clear why. It doesn't verify that the completion callback is // invoked, so I'm not sure what the relevance is to this test. context.dispose(); expect(KernelInvocationContext.current).is.null; }); it("publishes CommandFailed when inner context fails", async () => { let outerSubmitCode = makeSubmitCode("abc"); let outer = use(KernelInvocationContext.establish(outerSubmitCode)); let ew = makeEventWatcher(); outer.subscribeToKernelEvents(ew.watcher); let innerSubmitCode = makeSubmitCode("def"); let inner = use(KernelInvocationContext.establish(innerSubmitCode)); inner.fail(); expect(ew.events.length).to.eql(1); expect(ew.events[0].eventType).to.eql(contracts.CommandFailedType); expect(ew.events[0].command).to.eql(outerSubmitCode); }); it("does not publish further events after inner context fails", async () => { let outerSubmitCode = makeSubmitCode("abc"); let outer = use(KernelInvocationContext.establish(outerSubmitCode)); let ew = makeEventWatcher(); outer.subscribeToKernelEvents(ew.watcher); let innerSubmitCode = makeSubmitCode("def"); let inner = use(KernelInvocationContext.establish(innerSubmitCode)); inner.fail(); let ev: contracts.ErrorProduced = { message: "oops", formattedValues: null, valueId: null }; let evEnv: contracts.KernelEventEnvelope = { event: ev, eventType: contracts.ErrorProducedType, command: innerSubmitCode }; inner.publish(evEnv); ew.events.forEach(event => { expect(event.eventType).is.not.eq(contracts.ErrorProducedType); }); }); }); });
the_stack
class Component { openFhirServiceUrl = 'https://sb-fhir-stu3.smarthealthit.org/smartstu3/open'; closedFhirServiceUrl = 'https://sb-fhir-stu3.smarthealthit.org/smartstu3/data'; clientSettings: FHIR.SMART.OAuth2ClientSettings = { client_id: '50a7f6ca-075a-47de-ab83-152814c3edb2', scope: 'launch/patient user/*.* openid profile', state: 'RandomStateOverride' }; oauth2Configuration: FHIR.SMART.OAuth2Configuration = { client: this.clientSettings, server: this.closedFhirServiceUrl }; authContext: FHIR.SMART.AuthContext = { type: 'none' }; context: FHIR.SMART.Context = { serviceUrl: this.openFhirServiceUrl, auth: this.authContext, userId: 'tTFt1mD0vgox9npTe2ZA', // Patient name: Abernathy,Francine patientId: 'a509406a-5098-478c-b183-037d68a953d9' }; observationEntry: FHIR.SMART.Entry = { resource: { 'resourceType': 'Observation', 'id': 'c179f87f-e7d2-49b0-8838-c7cbf9b0da27', 'meta': { 'versionId': '1', 'lastUpdated': '2018-01-12T19:22:57.000+00:00', 'profile': [ 'http://standardhealthrecord.org/fhir/StructureDefinition/shr-observation-Observation' ], 'tag': [ { 'system': 'https://smarthealthit.org/tags', 'code': 'synthea-7-2017' } ] }, 'status': 'final', 'category': [ { 'coding': [ { 'system': 'http://hl7.org/fhir/observation-category' } ] } ], 'code': { 'coding': [ { 'system': 'http://loinc.org', 'code': '69453-9', 'display': 'Cause of Death [US Standard Certificate of Death]' } ], 'text': 'Cause of Death [US Standard Certificate of Death]' }, 'subject': { 'reference': 'Patient/a509406a-5098-478c-b183-037d68a953d9' }, 'context': { 'reference': 'Encounter/fbebfcf2-86d8-4c56-9539-314be0ce5bed' }, 'effectiveDateTime': '1989-07-26T17:51:45-04:00', 'issued': '1989-07-26T17:51:45-04:00', 'valueCodeableConcept': { 'coding': [ { 'system': 'http://snomed.info/sct', 'code': '185086009', 'display': 'Chronic obstructive bronchitis (disorder)' } ], 'text': 'Chronic obstructive bronchitis (disorder)' } } }; weightObservationEntry: FHIR.SMART.Entry = { 'resource': { 'id': 'RandomId', 'resourceType': 'Observation', 'text': { 'status': 'generated', 'div': '<div>Human readable form</div>' }, 'status': 'final', 'category': [ { 'coding': [ { 'system': 'http://hl7.org/fhir/observation-category', 'code': 'vital-signs', 'display': 'Vital Signs' } ] } ], 'code': { 'coding': [ { 'system': 'http://loinc.org', 'code': '29463-7', 'display': 'Body Weight' }, { 'system': 'http://loinc.org', 'code': '3141-9', 'display': 'Body weight Measured' }, { 'system': 'http://snomed.info/sct', 'code': '27113001', 'display': 'Body weight' }, { 'system': 'http://acme.org/devices/clinical-codes', 'code': 'body-weight', 'display': 'Body Weight' } ] }, 'subject': { 'reference': 'Patient/example' }, 'context': { 'reference': 'Encounter/example' }, 'effectiveDateTime': '2016-03-28', 'valueQuantity': { 'value': 185, 'unit': 'lbs', 'system': 'http://unitsofmeasure.org', 'code': '[lb_us]' } } }; bundle: FHIR.SMART.Bundle = { bundle: { 'resourceType': 'Bundle', 'id': '936286e3-cf22-44c8-be9f-b8d1b950a9a3', 'meta': { 'lastUpdated': '2018-05-22T22:08:19.000+00:00' }, 'type': 'searchset', 'total': 1, 'link': [ { 'relation': 'self', // tslint:disable-next-line:max-line-length 'url': 'https://sb-fhir-stu3.smarthealthit.org/smartstu3/open?_getpages=8bbd1c3c-a90f-49c6-8394-ca7524b46774&_getpagesoffset=10&_count=10&_pretty=true&_bundletype=searchset' }, { 'relation': 'next', // tslint:disable-next-line:max-line-length 'url': 'https://sb-fhir-stu3.smarthealthit.org/smartstu3/open?_getpages=8bbd1c3c-a90f-49c6-8394-ca7524b46774&_getpagesoffset=20&_count=10&_format=json&_pretty=true&_bundletype=searchset' }, { 'relation': 'prev', // tslint:disable-next-line:max-line-length 'url': 'https://sb-fhir-stu3.smarthealthit.org/smartstu3/open?_getpages=8bbd1c3c-a90f-49c6-8394-ca7524b46774&_getpagesoffset=0&_count=10&_format=json&_pretty=true&_bundletype=searchset' } ], 'entry': [ { 'fullUrl': 'https://sb-fhir-stu3.smarthealthit.org/smartstu3/open/Observation/152759', 'resource': { 'resourceType': 'Observation', 'id': '152759', 'meta': { 'versionId': '1', 'lastUpdated': '2018-05-22T20:42:56.000+00:00', 'profile': [ 'http://standardhealthrecord.org/fhir/StructureDefinition/shr-observation-Observation' ], 'tag': [ { 'system': 'https://smarthealthit.org/tags', 'code': 'synthea-7-2017' } ] }, 'status': 'final', 'category': [ { 'coding': [ { 'system': 'http://hl7.org/fhir/observation-category' } ] } ], 'code': { 'coding': [ { 'system': 'http://loinc.org', 'code': '69453-9', 'display': 'Cause of Death [US Standard Certificate of Death]' } ], 'text': 'Cause of Death [US Standard Certificate of Death]' }, 'subject': { 'reference': 'Patient/a509406a-5098-478c-b183-037d68a953d9' }, 'context': { 'reference': 'Encounter/fbebfcf2-86d8-4c56-9539-314be0ce5bed' }, 'effectiveDateTime': '1989-07-26T17:51:45-04:00', 'issued': '1989-07-26T17:51:45-04:00', 'valueCodeableConcept': { 'coding': [ { 'system': 'http://snomed.info/sct', 'code': '185086009', 'display': 'Chronic obstructive bronchitis (disorder)' } ], 'text': 'Chronic obstructive bronchitis (disorder)' } }, 'search': { 'mode': 'match' } } ] } }; heightObservation: FHIR.SMART.Resource = { 'resourceType': 'Observation', 'id': 'body-height', 'meta': { 'profile': [ 'http://hl7.org/fhir/StructureDefinition/vitalsigns' ] }, 'text': { 'status': 'generated', 'div': '<div>Test</div>' }, 'status': 'final', 'category': [ { 'coding': [ { 'system': 'http://hl7.org/fhir/observation-category', 'code': 'vital-signs', 'display': 'Vital Signs' } ], 'text': 'Vital Signs' } ], 'code': { 'coding': [ { 'system': 'http://loinc.org', 'code': '8302-2', 'display': 'Body height' } ], 'text': 'Body height' }, 'subject': { 'reference': 'Patient/example' }, 'effectiveDateTime': '1999-07-02', 'valueQuantity': { 'value': 66.899999999999991, 'unit': 'in', 'system': 'http://unitsofmeasure.org', 'code': '[in_i]' } }; transactionBundle: FHIR.SMART.Bundle = { bundle: { 'resourceType': 'Bundle', 'id': '936286e3-cf22-44c8-be9f-b8d1b950a9a3', 'meta': { 'lastUpdated': '2018-05-22T22:08:19.000+00:00' }, 'type': 'transaction', 'total': 1, 'link': [ { 'relation': 'self', // tslint:disable-next-line:max-line-length 'url': 'https://sb-fhir-stu3.smarthealthit.org/smartstu3/open?_getpages=8bbd1c3c-a90f-49c6-8394-ca7524b46774&_getpagesoffset=10&_count=10&_pretty=true&_bundletype=searchset' }, { 'relation': 'next', // tslint:disable-next-line:max-line-length 'url': 'https://sb-fhir-stu3.smarthealthit.org/smartstu3/open?_getpages=8bbd1c3c-a90f-49c6-8394-ca7524b46774&_getpagesoffset=20&_count=10&_format=json&_pretty=true&_bundletype=searchset' }, { 'relation': 'prev', // tslint:disable-next-line:max-line-length 'url': 'https://sb-fhir-stu3.smarthealthit.org/smartstu3/open?_getpages=8bbd1c3c-a90f-49c6-8394-ca7524b46774&_getpagesoffset=0&_count=10&_format=json&_pretty=true&_bundletype=searchset' } ], 'entry': [ { 'fullUrl': 'https://sb-fhir-stu3.smarthealthit.org/smartstu3/open/Observation/152759', 'resource': { 'resourceType': 'Observation', 'id': '152759', 'meta': { 'versionId': '1', 'lastUpdated': '2018-05-22T20:42:56.000+00:00', 'profile': [ 'http://standardhealthrecord.org/fhir/StructureDefinition/shr-observation-Observation' ], 'tag': [ { 'system': 'https://smarthealthit.org/tags', 'code': 'synthea-7-2017' } ] }, 'status': 'final', 'category': [ { 'coding': [ { 'system': 'http://hl7.org/fhir/observation-category' } ] } ], 'code': { 'coding': [ { 'system': 'http://loinc.org', 'code': '69453-9', 'display': 'Cause of Death [US Standard Certificate of Death]' } ], 'text': 'Cause of Death [US Standard Certificate of Death]' }, 'subject': { 'reference': 'Patient/a509406a-5098-478c-b183-037d68a953d9' }, 'context': { 'reference': 'Encounter/fbebfcf2-86d8-4c56-9539-314be0ce5bed' }, 'effectiveDateTime': '1989-07-26T17:51:45-04:00', 'issued': '1989-07-26T17:51:45-04:00', 'valueCodeableConcept': { 'coding': [ { 'system': 'http://snomed.info/sct', 'code': '185086009', 'display': 'Chronic obstructive bronchitis (disorder)' } ], 'text': 'Chronic obstructive bronchitis (disorder)' } }, 'request': { 'method': 'POST' }, 'search': { 'mode': 'match' } } ] } }; searchParameter: FHIR.SMART.SearchParams = { type: 'Observation', query: { code: '69453-9' } }; patientSpecificSearchParams: FHIR.SMART.SearchParams = { patient: 'a509406a-5098-478c-b183-037d68a953d9', type: 'Observation', query: { code: '69453-9' } }; resolveParameter: string[] = ['Observation.subject']; historyParameter: FHIR.SMART.HistoryParams = { id: '152768', type: 'Observation', count: 10, params: { _extraParam: 'extraParamValue' } }; resourceType: FHIR.SMART.ResourceType = { type: 'Observation' }; readParameter: FHIR.SMART.ReadParams = { type: 'Observation', id: '152768' }; vreadParameter: FHIR.SMART.VersionReadParams = { type: 'Observation', id: '152768', versionId: '1' }; resolveParameter2: FHIR.SMART.ResolveParams = { reference: this.observationEntry.resource.subject, resource: this.observationEntry.resource, bundle: this.bundle.bundle }; resourceParameter: FHIR.SMART.ResourceParameter = { resource: 'Patient', id: 'a509406a-5098-478c-b183-037d68a953d9' }; oauth2ReadyCallback = (smartClient: FHIR.SMART.SMARTClient) => { // Client interacting after a successful OAuth2 authorization workflow const api: FHIR.SMART.Api = smartClient.api; // FHIR API methods exposed by fhir.js api.conformance(this.context).then(this.apiSuccess, this.apiError); api.create(this.observationEntry).then(this.apiSuccess, this.apiError); api.delete(this.observationEntry).then(this.apiSuccess, this.apiError); api.document(this.observationEntry).then(this.apiSuccess, this.apiError); api.drain(this.searchParameter, this.drainProcess, this.drainDone, this.apiError); api.fetchAll(this.searchParameter).then(this.fetchAllSuccess, this.apiError); api.fetchAllWithReferences(this.searchParameter, this.resolveParameter) .then(this.fetchAllWithReferencesSuccess, this.apiError); api.history(this.historyParameter).then(this.apiSuccess, this.apiError); api.nextPage(this.bundle).then(this.apiSuccess, this.apiError); api.prevPage(this.bundle).then(this.apiSuccess, this.apiError); api.profile(this.resourceType).then(this.apiSuccess, this.apiError); api.read(this.readParameter).then(this.apiSuccess, this.apiError); api.resolve(this.resolveParameter2).then(this.apiSuccess, this.apiError); api.resourceHistory(this.historyParameter).then(this.apiSuccess, this.apiError); api.search(this.searchParameter).then(this.apiSuccess, this.apiError); api.search(this.patientSpecificSearchParams).then(this.apiSuccess, this.apiError); api.transaction(this.transactionBundle).then(this.apiSuccess, this.apiError); api.typeHistory(this.historyParameter).then(this.apiSuccess, this.apiError); api.update(this.observationEntry).then(this.apiSuccess, this.apiError); api.validate(this.observationEntry).then(this.apiSuccess, this.apiError); api.vread(this.vreadParameter).then(this.apiSuccess, this.apiError); const objectPopulatedWithHeader = smartClient.authenticated({}); smartClient.fetchBinary(this.observationEntry.resource.subject.reference).then(this.fetchBinarySuccess, this.apiError); smartClient.get(this.resourceParameter).then(this.apiSuccess, this.apiError); smartClient.getBinary(this.observationEntry.resource.subject.reference).then(this.fetchBinarySuccess, this.apiError); // Patient scoped FHIR API calls if (smartClient.patient) { const patient: FHIR.SMART.Patient = smartClient.patient; const patientId: string = patient.id; const patientApi: FHIR.SMART.Api = patient.api; patientApi.conformance(this.context).then(this.apiSuccess, this.apiError); patientApi.create(this.observationEntry).then(this.apiSuccess, this.apiError); patientApi.delete(this.observationEntry).then(this.apiSuccess, this.apiError); patientApi.document(this.observationEntry).then(this.apiSuccess, this.apiError); patientApi.drain(this.searchParameter, this.drainProcess, this.drainDone, this.apiError); patientApi.fetchAll(this.searchParameter).then(this.fetchAllSuccess, this.apiError); patientApi.fetchAllWithReferences(this.searchParameter, this.resolveParameter) .then(this.fetchAllWithReferencesSuccess, this.apiError); patientApi.history(this.historyParameter).then(this.apiSuccess, this.apiError); patientApi.nextPage(this.bundle).then(this.apiSuccess, this.apiError); patientApi.prevPage(this.bundle).then(this.apiSuccess, this.apiError); patientApi.profile(this.resourceType).then(this.apiSuccess, this.apiError); patientApi.read(this.readParameter).then(this.apiSuccess, this.apiError); patientApi.resolve(this.resolveParameter2).then(this.apiSuccess, this.apiError); patientApi.resourceHistory(this.historyParameter).then(this.apiSuccess, this.apiError); patientApi.search(this.searchParameter).then(this.apiSuccess, this.apiError); patientApi.search(this.patientSpecificSearchParams).then(this.apiSuccess, this.apiError); patientApi.transaction(this.transactionBundle).then(this.apiSuccess, this.apiError); patientApi.typeHistory(this.historyParameter).then(this.apiSuccess, this.apiError); patientApi.update(this.observationEntry).then(this.apiSuccess, this.apiError); patientApi.validate(this.observationEntry).then(this.apiSuccess, this.apiError); patientApi.vread(this.vreadParameter).then(this.apiSuccess, this.apiError); patient.read().then(this.apiSuccess, this.apiError); } // SMART client context helpers const context: FHIR.SMART.Context = smartClient.server; if (smartClient.server.auth) { const auth: FHIR.SMART.AuthContext = smartClient.server.auth; } if (smartClient.server.patientId) { const patientIdInContext: string = smartClient.server.patientId; } const fhirServiceUrl = smartClient.server.serviceUrl; if (smartClient.server.userId) { const userIdInContext: string = smartClient.server.userId; } const state: FHIR.SMART.OAuth2Configuration = smartClient.state; const tokenResponse = smartClient.tokenResponse; // User in context const userId = smartClient.userId; const userInContext = smartClient.user; smartClient.user.read().then(this.apiSuccess, this.apiError); // SMART client helper methods // Observation helpers const observationByCodesFn = smartClient.byCodes(this.observationEntry.resource, 'code'); const observations = observationByCodesFn('29463-7'); const observationsByCodes: FHIR.SMART.ObservationsByCode = smartClient.byCode(this.observationEntry.resource, 'code'); // Unit helpers const numericValue = smartClient.units.any(this.heightObservation.valueQuantity); const convertedHeightValueInCm = smartClient.units.cm(this.heightObservation.valueQuantity); const convertedWeightValueInKg = smartClient.units.kg(this.weightObservationEntry.resource.valueQuantity); } oauth2ReadyErrback = (error: any) => { FHIR.oauth2.authorize(this.oauth2Configuration, (authError) => { console.log(authError); }); } oauth2ResolveAuthTypeCallback = (type: string) => { console.log(type); } oauth2ResolveAuthTypeErrback = (error: any) => { console.log(error); } apiSuccess = (response: FHIR.SMART.Response) => { console.log('Response from the FHIR server:'); console.log(response); } apiError = (response: FHIR.SMART.Response) => { console.log('Error response from the FHIR server:'); console.log(response); } drainProcess = (entries: FHIR.SMART.Entry[]) => { console.log('Drain Process:'); console.log(entries); } drainDone = () => { console.log('Drain Done'); } fetchAllSuccess = (entries: FHIR.SMART.Entry[]) => { console.log('Fetch all success:'); console.log(entries); } fetchAllWithReferencesSuccess = (entries: FHIR.SMART.Entry[], resolvedReferences: FHIR.SMART.ResolveFn) => { console.log('Fetch all with references success:'); console.log(entries); console.log('Resolved References'); console.log(resolvedReferences(this.observationEntry.resource, this.observationEntry.resource.subject)); } genericCallback = (data: any) => { console.log(data); } fetchBinarySuccess = (blob: any) => { // const reader = new FileReader(); // reader.addEventListener('loadend', function () { // console.log('Blob content'); // console.log(reader.result); // }); // reader.readAsArrayBuffer(blob); } openSmartFhir(): void { // Open SMART on FHIR server interaction const openSmartClient: FHIR.SMART.Client = FHIR.client(this.context); const api: FHIR.SMART.Api = openSmartClient.api; api.conformance(this.context).then(this.apiSuccess, this.apiError); api.create(this.observationEntry).then(this.apiSuccess, this.apiError); api.delete(this.observationEntry).then(this.apiSuccess, this.apiError); api.document(this.observationEntry).then(this.apiSuccess, this.apiError); api.drain(this.searchParameter, this.drainProcess, this.drainDone, this.apiError); api.fetchAll(this.searchParameter).then(this.fetchAllSuccess, this.apiError); api.fetchAllWithReferences(this.searchParameter, this.resolveParameter) .then(this.fetchAllWithReferencesSuccess, this.apiError); api.history(this.historyParameter).then(this.apiSuccess, this.apiError); api.nextPage(this.bundle).then(this.apiSuccess, this.apiError); api.prevPage(this.bundle).then(this.apiSuccess, this.apiError); api.profile(this.resourceType).then(this.apiSuccess, this.apiError); api.read(this.readParameter).then(this.apiSuccess, this.apiError); api.resolve(this.resolveParameter2).then(this.apiSuccess, this.apiError); api.resourceHistory(this.historyParameter).then(this.apiSuccess, this.apiError); api.search(this.searchParameter).then(this.apiSuccess, this.apiError); api.search(this.patientSpecificSearchParams).then(this.apiSuccess, this.apiError); api.transaction(this.transactionBundle).then(this.apiSuccess, this.apiError); api.typeHistory(this.historyParameter).then(this.apiSuccess, this.apiError); api.update(this.observationEntry).then(this.apiSuccess, this.apiError); api.validate(this.observationEntry).then(this.apiSuccess, this.apiError); api.vread(this.vreadParameter).then(this.apiSuccess, this.apiError); openSmartClient.fetchBinary(this.observationEntry.resource.subject.reference).then(this.fetchBinarySuccess, this.apiError); openSmartClient.get(this.resourceParameter).then(this.apiSuccess, this.apiError); openSmartClient.getBinary(this.observationEntry.resource.subject.reference).then(this.fetchBinarySuccess, this.apiError); if (openSmartClient.patient) { const patient: FHIR.SMART.Patient = openSmartClient.patient; const patientApi: FHIR.SMART.Api = patient.api; const patientId: string = patient.id; patientApi.conformance(this.context).then(this.apiSuccess, this.apiError); patientApi.create(this.observationEntry).then(this.apiSuccess, this.apiError); patientApi.delete(this.observationEntry).then(this.apiSuccess, this.apiError); patientApi.document(this.observationEntry).then(this.apiSuccess, this.apiError); patientApi.drain(this.searchParameter, this.drainProcess, this.drainDone, this.apiError); patientApi.fetchAll(this.searchParameter).then(this.fetchAllSuccess, this.apiError); patientApi.fetchAllWithReferences(this.searchParameter, this.resolveParameter) .then(this.fetchAllWithReferencesSuccess, this.apiError); patientApi.history(this.historyParameter).then(this.apiSuccess, this.apiError); patientApi.nextPage(this.bundle).then(this.apiSuccess, this.apiError); patientApi.prevPage(this.bundle).then(this.apiSuccess, this.apiError); patientApi.profile(this.resourceType).then(this.apiSuccess, this.apiError); patientApi.read(this.readParameter).then(this.apiSuccess, this.apiError); patientApi.resolve(this.resolveParameter2).then(this.apiSuccess, this.apiError); patientApi.resourceHistory(this.historyParameter).then(this.apiSuccess, this.apiError); patientApi.search(this.searchParameter).then(this.apiSuccess, this.apiError); patientApi.search(this.patientSpecificSearchParams).then(this.apiSuccess, this.apiError); patientApi.transaction(this.transactionBundle).then(this.apiSuccess, this.apiError); patientApi.typeHistory(this.historyParameter).then(this.apiSuccess, this.apiError); patientApi.update(this.observationEntry).then(this.apiSuccess, this.apiError); patientApi.validate(this.observationEntry).then(this.apiSuccess, this.apiError); patientApi.vread(this.vreadParameter).then(this.apiSuccess, this.apiError); patient.read().then(this.apiSuccess, this.apiError); } const context: FHIR.SMART.Context = openSmartClient.server; if (openSmartClient.server.auth) { const auth: FHIR.SMART.AuthContext = openSmartClient.server.auth; } if (openSmartClient.server.patientId) { const patientIdInContext: string = openSmartClient.server.patientId; } const fhirServiceUrl = openSmartClient.server.serviceUrl; if (openSmartClient.server.userId) { const userIdInContext: string = openSmartClient.server.userId; } const userId = openSmartClient.userId; const userInContext = openSmartClient.user; openSmartClient.user.read().then(this.apiSuccess, this.apiError); const observationByCodesFn = openSmartClient.byCodes(this.observationEntry.resource, 'code'); const observations = observationByCodesFn('29463-7'); const observationsByCodes: FHIR.SMART.ObservationsByCode = openSmartClient.byCode(this.observationEntry.resource, 'code'); const numericValue = openSmartClient.units.any(this.heightObservation.valueQuantity); const convertedHeightValueInCm = openSmartClient.units.cm(this.heightObservation.valueQuantity); const convertedWeightValueInKg = openSmartClient.units.kg(this.weightObservationEntry.resource.valueQuantity); } closedSmartOnFhir() { // Closed FHIR server which requires user authorization FHIR.oauth2.ready(this.oauth2ReadyCallback, this.oauth2ReadyErrback); FHIR.oauth2.resolveAuthType(this.closedFhirServiceUrl, this.oauth2ResolveAuthTypeCallback, this.oauth2ResolveAuthTypeErrback); } } let component = new Component(); // Perform the API interactions on the Open SMART on FHIR sandbox server component.openSmartFhir(); // Perform the API interactions on the Closed SMART on FHIR sandbox server(Requires user authorization) component.closedSmartOnFhir();
the_stack
import {Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Output} from '@angular/core'; import {Store} from '@ngrx/store'; import {KELLY_COLORS} from 'org_xprof/frontend/app/common/constants/constants'; import {AllReduceOpInfo, ChannelInfo, PodStatsRecord, PodViewerTopology, StepBreakdownEvent} from 'org_xprof/frontend/app/common/interfaces/data_table'; import * as utils from 'org_xprof/frontend/app/common/utils/utils'; import {getActivePodViewerInfoState} from 'org_xprof/frontend/app/store/selectors'; import {ReplaySubject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; interface ColorInfo { color: string; label: string; } interface ElementInfo { id?: string; rid?: number; x: number; y: number; } interface ArrowElementInfo extends ElementInfo { rotate?: number; scale?: number; } const BORDER_WIDTH = 1; const CONTAINER_MARGIN = 4; const CHIP_PADDING = 4; const HOST_MARGIN = 5; const HOST_PADDING = 5; const LABEL_HEIGHT = 14; const LABEL_PADDING = 5; const LABEL_WIDTH = 20; const NODE_HEIGHT = 30; const NODE_WIDTH = 15; const TOOLTIP_OFFSET_X = 20; const TOOLTIP_OFFSET_Y = 35; const NODE_COLORS = [ '#ffffd9', '#edf8b1', '#c7e9b4', '#7fcdbb', '#41b6c4', '#1d91c0', '#225ea8', '#253494', '#081d58' ]; /** A topology graph view component. */ @Component({ selector: 'topology-graph', templateUrl: './topology_graph.ng.html', styleUrls: ['./topology_graph.scss'] }) export class TopologyGraph implements OnChanges, OnDestroy { /** The channel dababase. */ @Input() channelDb?: ChannelInfo[]; /** The replica id map with core id as key. */ @Input() coreIdToReplicaIdMap?: {[key: /* uint32 */ string]: /* uint32 */ number}; /** The metric list. */ @Input() metricList: StepBreakdownEvent[] = []; /** The pod stats per core. */ @Input() podStatsPerCore?: {[key: string]: PodStatsRecord}; /** The topology of the system to draw. */ @Input() topology?: PodViewerTopology; /** The device type of the system, e.g. TPU, GPU. */ @Input() deviceType?: string; /** The event when the selection of the channel is changed. */ @Output() selected = new EventEmitter<number>(); /** Handles on-destroy Subject, used to unsubscribe. */ private readonly destroyed = new ReplaySubject<void>(1); hosts: ElementInfo[] = []; labels: ElementInfo[] = []; nodes: ElementInfo[] = []; colorInfos: ColorInfo[] = []; channels: number[] = []; arrows: ArrowElementInfo[] = []; xDimension = 0; yDimension = 0; containerHeight = 0; containerWidth = 0; hostColumns = 0; hostRows = 0; hostHeight = 0; hostXStride = 1; hostYStride = 1; hostWidth = 0; nodesPerChip = 2; selectedMetric = 0; selectedMetricLabel = ''; channelCount = 0; firstChannel = 0; lastChannel = 0; selectedChannelIndex = 0; selectedChannelId = 0; tooltipText = ''; tooltipX = 0; tooltipY = 0; info?: AllReduceOpInfo|ChannelInfo|PodStatsRecord; constructor( private readonly elRef: ElementRef, private readonly store: Store<{}>) { this.createColorInfos(); this.store.select(getActivePodViewerInfoState) .pipe(takeUntil(this.destroyed)) .subscribe((info) => { this.updateReplicaGroupColoring(info as AllReduceOpInfo); }); } ngOnChanges() { this.update(); } private createColorInfos() { const len = NODE_COLORS.length; this.colorInfos = NODE_COLORS.map( (color, index) => ({color, label: (index / len).toFixed(1)})); } private getNodeColor(value: number): string { let colorIndex = Math.floor((value || 0) * NODE_COLORS.length); colorIndex = Math.min(colorIndex, NODE_COLORS.length - 1); return NODE_COLORS[colorIndex]; } private getNodePosition(chipId: number, nodeId: number): ElementInfo { const hostWidthWithPadding = HOST_PADDING + BORDER_WIDTH + this.hostWidth + BORDER_WIDTH + HOST_PADDING; const hostHeightWithPadding = HOST_PADDING + BORDER_WIDTH + this.hostHeight + BORDER_WIDTH + HOST_PADDING; const chipWidthWithPadding = CHIP_PADDING + (BORDER_WIDTH + NODE_WIDTH) * this.nodesPerChip + BORDER_WIDTH + CHIP_PADDING; const chipHeightWithPadding = CHIP_PADDING + BORDER_WIDTH + NODE_HEIGHT + BORDER_WIDTH + CHIP_PADDING; let x = CONTAINER_MARGIN + LABEL_PADDING + LABEL_WIDTH + LABEL_PADDING; let y = CONTAINER_MARGIN + LABEL_PADDING + LABEL_HEIGHT + LABEL_PADDING; x += hostWidthWithPadding * Math.floor( (chipId % (this.hostColumns * this.hostXStride)) / this.hostXStride); x += HOST_PADDING + BORDER_WIDTH + HOST_MARGIN; x += chipWidthWithPadding * (chipId % this.hostXStride); x += CHIP_PADDING + (BORDER_WIDTH + NODE_WIDTH) * nodeId; y += hostHeightWithPadding * Math.floor( Math.floor(chipId / (this.hostColumns * this.hostXStride)) / this.hostYStride); y += HOST_PADDING + BORDER_WIDTH + HOST_MARGIN; y += chipHeightWithPadding * (Math.floor(chipId / (this.hostColumns * this.hostXStride)) % this.hostYStride); y += CHIP_PADDING; return {x, y}; } private getNodeRotate(srcX: number, srcY: number, dstX: number, dstY: number): number { const dx = dstX - srcX; const dy = dstY - srcY; return Math.atan2(dy, dx); } private getNodeScale(srcX: number, srcY: number, dstX: number, dstY: number): number { const dx = srcX - dstX; const dy = srcY - dstY; return Math.sqrt(dx * dx + dy * dy) / 100; } private updateArrows() { this.arrows = []; if (!this.topology || !this.podStatsPerCore || !this.channelDb) { return; } const channelInfo = this.channelDb[this.selectedChannelIndex]; if (!channelInfo || !channelInfo.srcCoreIds || !channelInfo.dstCoreIds) { return; } const len = Math.min(channelInfo.srcCoreIds.length, channelInfo.dstCoreIds.length); for (let i = 0; i < len; i++) { const srcId = channelInfo.srcCoreIds[i] || 0; const dstId = channelInfo.dstCoreIds[i] || 0; const srcNodeInfo = this.getNodePosition(Math.floor(srcId / 2), srcId & 1); const dstNodeInfo = this.getNodePosition(Math.floor(dstId / 2), dstId & 1); this.arrows.push({ x: dstNodeInfo.x + BORDER_WIDTH + (NODE_WIDTH / 2), y: dstNodeInfo.y + BORDER_WIDTH + (NODE_HEIGHT / 2), scale: this.getNodeScale( srcNodeInfo.x, srcNodeInfo.y, dstNodeInfo.x, dstNodeInfo.y), rotate: this.getNodeRotate( srcNodeInfo.x, srcNodeInfo.y, dstNodeInfo.x, dstNodeInfo.y), }); } } private updateChannels() { if (!this.topology || !this.podStatsPerCore || !this.channelDb) { this.channelCount = 0; this.firstChannel = 0; this.lastChannel = 0; this.selectedChannelIndex = 0; this.selectedChannelId = 0; return; } this.channels = this.channelDb.map(channelInfo => Number(channelInfo.channelId || 0)); this.channelCount = this.channelDb.length - 1; this.firstChannel = this.channels[0]; this.lastChannel = this.channels[this.channelCount]; this.selectedChannelIndex = 0; this.selectedChannelId = this.channels[0]; this.updateArrows(); this.selected.emit(0); } private updateHosts() { this.hosts = []; if (!this.topology) return; const xOffset = CONTAINER_MARGIN + LABEL_PADDING + LABEL_WIDTH + LABEL_PADDING; const yOffset = CONTAINER_MARGIN + LABEL_PADDING + LABEL_HEIGHT + LABEL_PADDING; const hostWidthWithPadding = HOST_PADDING + BORDER_WIDTH + this.hostWidth + BORDER_WIDTH + HOST_PADDING; const hostHeightWithPadding = HOST_PADDING + BORDER_WIDTH + this.hostHeight + BORDER_WIDTH + HOST_PADDING; for (let i = 0; i < this.hostRows; i++) { for (let j = 0; j < this.hostColumns; j++) { this.hosts.push({ x: xOffset + HOST_PADDING + (hostWidthWithPadding * j), y: yOffset + HOST_PADDING + (hostHeightWithPadding * i), }); } } } private updateLabels() { this.labels = []; if (!this.topology) return; let xOffset = CONTAINER_MARGIN + LABEL_PADDING + LABEL_WIDTH + LABEL_PADDING; let yOffset = CONTAINER_MARGIN + LABEL_PADDING + LABEL_HEIGHT / 2; for (let i = 0; i < this.xDimension; i++) { if (i % this.hostXStride === 0) { xOffset += HOST_PADDING + BORDER_WIDTH + HOST_MARGIN; } xOffset += CHIP_PADDING + BORDER_WIDTH + NODE_WIDTH; this.labels.push({ id: i.toString(), x: xOffset, y: yOffset, }); xOffset += BORDER_WIDTH + NODE_WIDTH + BORDER_WIDTH + CHIP_PADDING; if (i % this.hostXStride === this.hostXStride - 1) { xOffset += HOST_MARGIN + BORDER_WIDTH + HOST_PADDING; } } xOffset = CONTAINER_MARGIN + LABEL_PADDING + LABEL_WIDTH / 2; yOffset = CONTAINER_MARGIN + LABEL_PADDING + LABEL_HEIGHT + LABEL_PADDING; for (let i = 0; i < this.yDimension; i++) { if (i % this.hostYStride === 0) { yOffset += HOST_PADDING + BORDER_WIDTH + HOST_MARGIN; } yOffset += CHIP_PADDING + BORDER_WIDTH + NODE_HEIGHT / 2; this.labels.push({ id: i.toString(), x: xOffset, y: yOffset, }); yOffset += NODE_HEIGHT / 2 + BORDER_WIDTH + CHIP_PADDING; if (i % this.hostYStride === this.hostYStride - 1) { yOffset += HOST_MARGIN + BORDER_WIDTH + HOST_PADDING; } } } private updateNodes() { this.nodes = []; if (!this.topology || !this.podStatsPerCore) { return; } Object.keys(this.podStatsPerCore).forEach(coreId => { const podStatsRecord = this.podStatsPerCore![coreId]; const chipId = podStatsRecord.chipId || 0; const nodeId = podStatsRecord.nodeId || 0; const nodeInfo = this.getNodePosition(chipId, nodeId); nodeInfo.id = 'node-' + chipId.toString() + '-' + nodeId.toString(); if (this.coreIdToReplicaIdMap && this.coreIdToReplicaIdMap[coreId] !== undefined) { nodeInfo.rid = this.coreIdToReplicaIdMap[coreId]; } this.nodes.push(nodeInfo); }); } private updateSystemInfo() { if (!this.topology) { this.xDimension = 0; this.yDimension = 0; this.containerWidth = 0; this.containerHeight = 0; this.hostColumns = 0; this.hostRows = 0; this.hostWidth = 0; this.hostHeight = 0; return; } this.xDimension = this.topology.xDimension || 0; this.yDimension = this.topology.yDimension || 0; this.hostXStride = this.topology.hostXStride || 1; this.hostYStride = this.topology.hostYStride || 1; this.nodesPerChip = this.topology.numCoresPerChip || 1; const chipWidth = CHIP_PADDING + ((BORDER_WIDTH + NODE_WIDTH) * this.nodesPerChip) + BORDER_WIDTH + CHIP_PADDING; const chipHeight = CHIP_PADDING + BORDER_WIDTH + NODE_HEIGHT + BORDER_WIDTH + CHIP_PADDING; this.hostWidth = HOST_MARGIN + (chipWidth * this.hostXStride) + HOST_MARGIN; this.hostHeight = HOST_MARGIN + (chipHeight * this.hostYStride) + HOST_MARGIN; const hostWidthWithPadding = HOST_PADDING + BORDER_WIDTH + this.hostWidth + HOST_PADDING + BORDER_WIDTH; const hostHeightWithPadding = HOST_PADDING + BORDER_WIDTH + this.hostHeight + HOST_PADDING + BORDER_WIDTH; this.hostColumns = Math.floor(this.xDimension / this.hostXStride); if (this.xDimension % this.hostXStride !== 0) { this.hostColumns++; } this.containerWidth = CONTAINER_MARGIN + LABEL_PADDING + LABEL_WIDTH + LABEL_PADDING + (hostWidthWithPadding * this.hostColumns) + CONTAINER_MARGIN; this.hostRows = Math.floor(this.yDimension / this.hostYStride); if (this.yDimension % this.hostYStride !== 0) { this.hostRows++; } this.containerHeight = CONTAINER_MARGIN + LABEL_PADDING + LABEL_HEIGHT + LABEL_PADDING + (hostHeightWithPadding * this.hostRows) + CONTAINER_MARGIN; } hideTooltip() { this.tooltipText = ''; } selectMetric(key: number, label: string) { if (!label) { this.selectedMetric = 0; this.selectedMetricLabel = 'Please select a metric'; return; } this.selectedMetric = key; this.selectedMetricLabel = 'Color: ' + label; if (!this.podStatsPerCore) { return; } Object.values(this.podStatsPerCore).forEach(podStatsRecord => { const chipId = podStatsRecord.chipId || 0; const nodeId = podStatsRecord.nodeId || 0; const id = 'node-' + chipId.toString() + '-' + nodeId.toString(); const nodeEl = this.elRef.nativeElement.querySelector('#' + id); if (nodeEl) { let value = utils.getPodStatsRecordBreakdownProperty( podStatsRecord, key.toString()); value = podStatsRecord.totalDurationUs ? value / podStatsRecord.totalDurationUs : 0; nodeEl.style.backgroundColor = this.getNodeColor(value); } }); } showTooltip(id: string) { this.tooltipText = ''; let podStatsRecord: PodStatsRecord|null = null; let coreId = ''; const found = Object.entries(this.podStatsPerCore || {}).find(([, value]) => { const chipId = value.chipId || 0; const nodeId = value.nodeId || 0; return id === 'node-' + chipId.toString() + '-' + nodeId.toString(); }); if (!found || found.length !== 2) { return; } coreId = found[0]; podStatsRecord = found[1]; if (!podStatsRecord) { return; } const chipId = podStatsRecord.chipId || 0; const nodeId = podStatsRecord.nodeId || 0; this.tooltipText += 'pos: ('; this.tooltipText += (chipId % (this.hostColumns * this.hostXStride)).toString(); this.tooltipText += ','; this.tooltipText += Math.floor(chipId / (this.hostColumns * this.hostXStride)).toString(); this.tooltipText += ')\n'; this.tooltipText += 'host: ' + (podStatsRecord.hostName || '') + '\n'; this.tooltipText += 'chip id: ' + chipId.toString() + '\n'; this.tooltipText += 'node id: ' + nodeId.toString() + '\n'; if (this.coreIdToReplicaIdMap && this.coreIdToReplicaIdMap[coreId] !== undefined) { this.tooltipText += 'replica id: ' + this.coreIdToReplicaIdMap[coreId].toString() + '\n'; } if (this.selectedMetric && this.selectedMetricLabel) { const value: number = utils.getPodStatsRecordBreakdownProperty( podStatsRecord, this.selectedMetric.toString()); this.tooltipText += this.selectedMetricLabel.replace('Color: ', ''); this.tooltipText += ' spends '; this.tooltipText += value.toFixed(2); this.tooltipText += 'us in total, '; this.tooltipText += 'taking '; this.tooltipText += podStatsRecord.totalDurationUs ? (100 * value / podStatsRecord.totalDurationUs).toFixed(2) : '0.00'; this.tooltipText += '% of a step.'; } const nodeInfo = this.getNodePosition(chipId, nodeId); this.tooltipX = nodeInfo.x + TOOLTIP_OFFSET_X; this.tooltipY = nodeInfo.y + TOOLTIP_OFFSET_Y; } updateChannelId(id: number) { if (id < this.selectedChannelId) { let i = this.selectedChannelIndex - 1; while (i >= 0) { if (this.channels[i] <= id) { break; } i--; } this.updateChannelIndex(Math.max(0, i)); } else if (id > this.selectedChannelId) { let i = this.selectedChannelIndex + 1; while (i <= this.channelCount) { if (this.channels[i] >= id) { break; } i++; } this.updateChannelIndex(Math.min(this.channelCount, i)); } } updateChannelIndex(index: number) { this.selectedChannelIndex = index; this.selectedChannelId = this.channels[index]; this.updateArrows(); this.selected.emit(index || 0); } updateReplicaGroupColoring(info: AllReduceOpInfo) { if (!info || !info.replicaGroups || !info.replicaGroups.length) return; // Colors the nodes within the same replica group to the same color. for (let i = 0; i < info.replicaGroups.length; i++) { const group = info.replicaGroups[i].replicaIds; if (!group) continue; for (let j = 0; j < group.length; j++) { const groupEl = this.elRef.nativeElement.querySelectorAll( '[rid="' + group[j] + '"]'); groupEl.forEach((el: HTMLElement) => { el.style.backgroundColor = KELLY_COLORS[i % 20]; }); } } this.selectedMetric = 0; } update() { this.updateSystemInfo(); this.updateLabels(); this.updateHosts(); this.updateNodes(); this.selectMetric(0, ''); this.updateChannels(); } ngOnDestroy() { // Unsubscribes all pending subscriptions. this.destroyed.next(); this.destroyed.complete(); } }
the_stack
import './DataRuns.css' import * as React from "react"; import GraphViewContainer from '../../container/GraphViewContainer'; import ControlPanelContainer from '../../container/ControlPanelContainer'; import { getGraphInfo, getModelList, getModelInfo, getSubgraphList, getSubgraphInfo } from '../../service/dataService'; import GridLayout from "react-grid-layout"; export interface IProps { dataset_id : number | null, contentWidth:number, contentHeight:number, NLabelList : any, eweightList: any, changeEnableForceDirected : any, changeNLabelOptions: any, changeEWeightOptions: any, changeNLabel: any, changeEWeight: any, changeShowSource: any, } export interface IState { graph_object : any, model_list : any, model_nlabels : any, model_eweights: any, model_nweights: any, subg_list : any, subgs : any, layout_config: any, screenWidth: number, screenHeight: number } export default class DataRuns extends React.Component<IProps, IState>{ public GraphViewRef:any; public ControlPanelRef: any; constructor(props:IProps) { super(props); this.onResizeStop = this.onResizeStop.bind(this); this.getLayoutConfigWithName = this.getLayoutConfigWithName.bind(this); this.getCurrentLayoutConfig = this.getCurrentLayoutConfig.bind(this); this.GraphViewRef = React.createRef(); this.ControlPanelRef = React.createRef(); let m_to_eweights: Record<string, Array<number>> = {}; this.state = { graph_object:{ model : -1, graph : -1, }, model_list: null, model_nlabels: null, model_eweights: m_to_eweights, model_nweights: null, subg_list: [], subgs: null, layout_config: null, screenWidth : 0, screenHeight: 0 } // show_mode_specification // 1 -> graph_input // 2 -> graph_target // 3 -> graph_output // 4 -> Explain_mode // Explained_node, default for 0. //this.resize.bind(this); // Flow: // 1. Constructor // 2. componentWillMount() // 3. render() // 4. componentDidMount() // If props update: // 4.1 componentWillReceiveProps(nextProps : IProps), then goto 5. // If States update // 5. shouldComponentUpdate() if return false, then no rerendering. // 6. if True, then componentWillUpdate // 7. render() // 8. componentDidUpdate // If Unmount, then componentWillUnmount() } // When the view is mounted, it will be executed. componentDidMount(){ //window.addEventListener('resize', this.onResize) this.setState({ layout_config: this.getWholeLayoutConfig(), screenHeight: window.innerHeight, screenWidth: window.innerWidth }) } // Get graph data. public async getGraphBundledData(dataset_id:number){ let data = await getGraphInfo(dataset_id); let m_to_eweights: Record<string, Array<number>> = {}; if(data["success"] === true){ data["graph_obj"]["bundle_id"] = dataset_id; for (var head in data["graph_obj"]["eweights"]) { let mname = "Graph/".concat(head); m_to_eweights[mname] = data["graph_obj"]["eweights"][head] } data["graph_obj"]["eweights"] = m_to_eweights this.setState({ graph_object: data["graph_obj"] }) this.props.changeEnableForceDirected(true); this.props.changeNLabelOptions([]); this.props.changeNLabelOptions([]); this.props.changeNLabel([]); this.props.changeEWeight([]); this.props.changeShowSource(false); } } // Get associated model list and model data. public async getModelData(dataset_id:number){ let mlist = await getModelList(dataset_id); if(mlist["success"] === true){ let m_to_nlabels: Record<string, Array<number>> = {}; let m_to_eweights: Record<string, Array<number>> = {}; // let m_to_nweights: Record<string, Array<number>> = {}; for (var model_info of mlist["models"]) { let mdata = await getModelInfo(dataset_id, model_info["id"]); m_to_nlabels[mdata["model_obj"]["name"]] = mdata["model_obj"]["nlabels"]; // m_to_eweights[mdata["model_obj"]["name"]] = mdata["model_obj"]["eweight"]; // m_to_nweights[mdata["model_obj"]["name"]] = mdata["model_obj"]["nweight"]; for (var head in mdata["model_obj"]["eweights"]) { let mname = mdata["model_obj"]["name"].concat("/"); m_to_eweights[mname.concat(head)]= mdata["model_obj"]["eweights"][head]; } } this.setState({ model_list: mlist["models"], model_nlabels: m_to_nlabels, model_eweights: m_to_eweights, // TODO // model_nweights: m_to_nweights// TODO }) } } // Get associated subgraph list and subgraph data. public async getSubgraphData(dataset_id:number){ let slist = await getSubgraphList(dataset_id); if(slist["success"] === true){ // Name to subgraphs let n_to_subgs: Record<string, any> = {}; for (var subg_info of slist["subgraphs"]) { let sdata = await getSubgraphInfo(dataset_id, subg_info["id"]); n_to_subgs[sdata["name"]] = sdata["node_subgraphs"]; } this.setState({ subg_list: slist["subgraphs"].map((d:any)=>(d["name"])), subgs: n_to_subgs }) } } // Get width and height from view name. public getLayoutConfigWithName(name:string){ let width = 0; let height = 0; if(name === "GraphView"){ if(this.GraphViewRef){ width = this.GraphViewRef.current.offsetWidth; height = this.GraphViewRef.current.offsetHeight; } }else if(name === "ControlPanel"){ if(this.ControlPanelRef){ width = this.ControlPanelRef.current.offsetWidth; height = this.ControlPanelRef.current.offsetHeight; } } return { "width":width, "height":height } } // Get the whole layout config. public getWholeLayoutConfig(){ let viewName = ["GraphView", "ControlPanel"]; let layout_config:any = {}; viewName.forEach((d:any)=>{ layout_config[d] = this.getLayoutConfigWithName(d); }) return layout_config; } // Get layout config from view name. public getCurrentLayoutConfig(name:string){ let layout_config = this.state.layout_config; if(layout_config){ if(layout_config[name]){ return layout_config[name]; }else{ return null; } }else{ return null; } } // Handling the changing of states or props. componentDidUpdate(prevProps:IProps, prevState:IState) { //console.log('Component did update!') // If the dataset_id has been changed. if(prevProps.dataset_id !== this.props.dataset_id){ // If the id is valid. if( this.props.dataset_id && this.props.dataset_id>=0){ // Get the graph data. this.getGraphBundledData(this.props.dataset_id); // Get the model data associated with the graph. this.getModelData(this.props.dataset_id); // Get the subgraph data associated with the graph. this.getSubgraphData(this.props.dataset_id); }else{ // Set to a dummy case. this.setState({ graph_object:{ model : -1, graph : -1, } }) } } // If the window is resized, update the layout config. if(prevProps.contentHeight!==this.props.contentHeight || prevProps.contentWidth !== this.props.contentWidth){ this.setState({ layout_config: this.getWholeLayoutConfig() }) } } // RESERVED: handling the layout change. public onLayoutChange(layout:any){} // For react-grid-layout, when the resizing is fixed, the layout configuration should be updated. public onResizeStop(layout:any){ console.log("onResizeStop", layout); console.log("Layout", this.getWholeLayoutConfig()); this.setState({ layout_config : this.getWholeLayoutConfig() }) //var width = document.getElementById('a').offsetWidth; } public render() { // Rendering. let {graph_object, model_nlabels, model_eweights} = this.state; let dataset_id = -1; if(graph_object.bundle_id){ dataset_id = graph_object.bundle_id; let nlabel_options: any[] = []; console.log('graph_object', graph_object); if (graph_object.nlabels.length !== 0) { nlabel_options.push("ground_truth"); } if (model_nlabels !== null) { nlabel_options = nlabel_options.concat(Object.keys(model_nlabels)); } this.props.changeNLabelOptions(nlabel_options); let eweight_options: any[] = []; eweight_options = Object.keys(graph_object.eweights); if (model_eweights !== null) { eweight_options = eweight_options.concat(Object.keys(model_eweights)); } this.props.changeEWeightOptions(eweight_options); } // Generate Graph View. let generateGraphView = (graph_object: any, model_nlabels: any, model_eweights: any, model_nweights: any, subgs: any, NLabelList: any, eweightList: any, subgList: any, width:number, height:number) => { return <GraphViewContainer graph_object={graph_object} model_nlabels={model_nlabels} model_eweights={model_eweights} model_nweights={model_nweights} subgs={subgs} NLabelList={NLabelList} eweightList={eweightList} subgList={subgList} width={width} height={height} /> } // Generate Control Panel let generateControlPanel = () => { return <ControlPanelContainer/> } // layout is an array of objects, see the demo for more complete usage let enableStatic = true; // If enabled static, the layout cannot be manually configured. let max_row_num = Math.floor(this.props.contentHeight / 40); // Maximum rows in the screen. // small width, height: 1707 724 // big width, height: 2560 1175 let ControlPanelH = max_row_num; let GraphViewPanelH = max_row_num; let layout = [ {i: 'b', x: 5, y: 0, w: 19, h: GraphViewPanelH, static:enableStatic}, // Graph View {i: 'd', x: 0, y: 0, w: 5, h: ControlPanelH, static:enableStatic} // Control Panel ]; // Generate Whole Layout. let generateWholeView = () =>{ let screenwidth = window.innerWidth; //let screenheight = window.innerHeight; return <div><GridLayout className="layout" layout={layout} cols={24} rowHeight={30} width={screenwidth} onLayoutChange={this.onLayoutChange} onResizeStop={this.onResizeStop}> <div className="PanelBox" key="b" ref={this.GraphViewRef}> {(dataset_id>=0 && this.getCurrentLayoutConfig("GraphView"))?generateGraphView(graph_object, this.state.model_nlabels, this.state.model_eweights, this.state.model_nweights, this.state.subgs, this.props.NLabelList, this.props.eweightList, this.state.subg_list, this.getCurrentLayoutConfig("GraphView")["width"], this.getCurrentLayoutConfig("GraphView")["height"]):<div />} </div> <div className="PanelBox" key="d" ref={this.ControlPanelRef}> {generateControlPanel()} </div> </GridLayout> </div> } return generateWholeView(); } }
the_stack