text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { IExecuteFunctions, } from 'n8n-core'; import { ICredentialsDecrypted, ICredentialTestFunctions, IDataObject, ILoadOptionsFunctions, INodeExecutionData, INodeType, INodeTypeDescription, NodeCredentialTestResult, } from 'n8n-workflow'; import { formatFeed, formatResults, formatSearch, getId, populate, setCount, splunkApiRequest, toUnixEpoch, } from './GenericFunctions'; import { firedAlertOperations, searchConfigurationFields, searchConfigurationOperations, searchJobFields, searchJobOperations, searchResultFields, searchResultOperations, userFields, userOperations, } from './descriptions'; import { SplunkCredentials, SplunkFeedResponse, } from './types'; import { OptionsWithUri, } from 'request'; export class Splunk implements INodeType { description: INodeTypeDescription = { displayName: 'Splunk', name: 'splunk', icon: 'file:splunk.svg', group: ['transform'], version: 1, subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', description: 'Consume the Splunk Enterprise API', defaults: { name: 'Splunk', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'splunkApi', required: true, testedBy: 'splunkApiTest', }, ], properties: [ { displayName: 'Resource', name: 'resource', type: 'options', noDataExpression: true, options: [ { name: 'Fired Alert', value: 'firedAlert', }, { name: 'Search Configuration', value: 'searchConfiguration', }, { name: 'Search Job', value: 'searchJob', }, { name: 'Search Result', value: 'searchResult', }, { name: 'User', value: 'user', }, ], default: 'searchJob', }, ...firedAlertOperations, ...searchConfigurationOperations, ...searchConfigurationFields, ...searchJobOperations, ...searchJobFields, ...searchResultOperations, ...searchResultFields, ...userOperations, ...userFields, ], }; methods = { loadOptions: { async getRoles(this: ILoadOptionsFunctions) { const endpoint = '/services/authorization/roles'; const responseData = await splunkApiRequest.call(this, 'GET', endpoint) as SplunkFeedResponse; const { entry: entries } = responseData.feed; return Array.isArray(entries) ? entries.map(entry => ({ name: entry.title, value: entry.title })) : [{ name: entries.title, value: entries.title }]; }, }, credentialTest: { async splunkApiTest( this: ICredentialTestFunctions, credential: ICredentialsDecrypted, ): Promise<NodeCredentialTestResult> { const { authToken, baseUrl, allowUnauthorizedCerts, } = credential.data as SplunkCredentials; const endpoint = '/services/alerts/fired_alerts'; const options: OptionsWithUri = { headers: { 'Authorization': `Bearer ${authToken}`, 'Content-Type': 'application/x-www-form-urlencoded', }, method: 'GET', form: {}, qs: {}, uri: `${baseUrl}${endpoint}`, json: true, rejectUnauthorized: !allowUnauthorizedCerts, }; try { await this.helpers.request(options); return { status: 'OK', message: 'Authentication successful', }; } catch (error) { return { status: 'Error', message: error.message, }; } }, }, }; async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const items = this.getInputData(); const returnData: IDataObject[] = []; const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; let responseData; for (let i = 0; i < items.length; i++) { try { if (resource === 'firedAlert') { // ********************************************************************** // firedAlert // ********************************************************************** if (operation === 'getReport') { // ---------------------------------------- // firedAlert: getReport // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/latest/RESTREF/RESTsearch#alerts.2Ffired_alerts const endpoint = '/services/alerts/fired_alerts'; responseData = await splunkApiRequest.call(this, 'GET', endpoint).then(formatFeed); } } else if (resource === 'searchConfiguration') { // ********************************************************************** // searchConfiguration // ********************************************************************** if (operation === 'delete') { // ---------------------------------------- // searchConfiguration: delete // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTsearch#saved.2Fsearches.2F.7Bname.7D const partialEndpoint = '/services/saved/searches/'; const searchConfigurationId = getId.call( this, i, 'searchConfigurationId', '/search/saved/searches/', ); // id endpoint differs from operation endpoint const endpoint = `${partialEndpoint}/${searchConfigurationId}`; responseData = await splunkApiRequest.call(this, 'DELETE', endpoint); } else if (operation === 'get') { // ---------------------------------------- // searchConfiguration: get // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTsearch#saved.2Fsearches.2F.7Bname.7D const partialEndpoint = '/services/saved/searches/'; const searchConfigurationId = getId.call( this, i, 'searchConfigurationId', '/search/saved/searches/', ); // id endpoint differs from operation endpoint const endpoint = `${partialEndpoint}/${searchConfigurationId}`; responseData = await splunkApiRequest.call(this, 'GET', endpoint).then(formatFeed); } else if (operation === 'getAll') { // ---------------------------------------- // searchConfiguration: getAll // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTsearch#saved.2Fsearches const qs = {} as IDataObject; const options = this.getNodeParameter('options', i) as IDataObject; populate(options, qs); setCount.call(this, qs); const endpoint = '/services/saved/searches'; responseData = await splunkApiRequest.call(this, 'GET', endpoint, {}, qs).then(formatFeed); } } else if (resource === 'searchJob') { // ********************************************************************** // searchJob // ********************************************************************** if (operation === 'create') { // ---------------------------------------- // searchJob: create // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTsearch#search.2Fjobs const body = { search: this.getNodeParameter('search', i), } as IDataObject; const { earliest_time, latest_time, index_earliest, index_latest, ...rest } = this.getNodeParameter('additionalFields', i) as IDataObject & { earliest_time?: string; latest_time?: string; index_earliest?: string, index_latest?: string, }; populate({ ...earliest_time && { earliest_time: toUnixEpoch(earliest_time) }, ...latest_time && { latest_time: toUnixEpoch(latest_time) }, ...index_earliest && { index_earliest: toUnixEpoch(index_earliest) }, ...index_latest && { index_latest: toUnixEpoch(index_latest) }, ...rest, }, body); const endpoint = '/services/search/jobs'; responseData = await splunkApiRequest.call(this, 'POST', endpoint, body); const getEndpoint = `/services/search/jobs/${responseData.response.sid}`; responseData = await splunkApiRequest.call(this, 'GET', getEndpoint).then(formatSearch); } else if (operation === 'delete') { // ---------------------------------------- // searchJob: delete // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTsearch#search.2Fjobs.2F.7Bsearch_id.7D const partialEndpoint = '/services/search/jobs/'; const searchJobId = getId.call(this, i, 'searchJobId', partialEndpoint); const endpoint = `${partialEndpoint}/${searchJobId}`; responseData = await splunkApiRequest.call(this, 'DELETE', endpoint); } else if (operation === 'get') { // ---------------------------------------- // searchJob: get // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTsearch#search.2Fjobs.2F.7Bsearch_id.7D const partialEndpoint = '/services/search/jobs/'; const searchJobId = getId.call(this, i, 'searchJobId', partialEndpoint); const endpoint = `${partialEndpoint}/${searchJobId}`; responseData = await splunkApiRequest.call(this, 'GET', endpoint).then(formatSearch); } else if (operation === 'getAll') { // ---------------------------------------- // searchJob: getAll // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTsearch#search.2Fjobs const qs = {} as IDataObject; const options = this.getNodeParameter('options', i) as IDataObject; populate(options, qs); setCount.call(this, qs); const endpoint = '/services/search/jobs'; responseData = await splunkApiRequest.call(this, 'GET', endpoint, {}, qs) as SplunkFeedResponse; responseData = formatFeed(responseData); } } else if (resource === 'searchResult') { // ********************************************************************** // searchResult // ********************************************************************** if (operation === 'getAll') { // ---------------------------------------- // searchResult: getAll // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/latest/RESTREF/RESTsearch#search.2Fjobs.2F.7Bsearch_id.7D.2Fresults const searchJobId = this.getNodeParameter('searchJobId', i); const qs = {} as IDataObject; const filters = this.getNodeParameter('filters', i) as IDataObject & { keyValueMatch?: { keyValuePair?: { key: string; value: string; } } }; const options = this.getNodeParameter('options', i) as IDataObject; const keyValuePair = filters?.keyValueMatch?.keyValuePair; if (keyValuePair?.key && keyValuePair?.value) { qs.search = `search ${keyValuePair.key}=${keyValuePair.value}`; } populate(options, qs); setCount.call(this, qs); const endpoint = `/services/search/jobs/${searchJobId}/results`; responseData = await splunkApiRequest.call(this, 'GET', endpoint, {}, qs).then(formatResults); } } else if (resource === 'user') { // ********************************************************************** // user // ********************************************************************** if (operation === 'create') { // ---------------------------------------- // user: create // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTaccess#authentication.2Fusers const roles = this.getNodeParameter('roles', i) as string[]; const body = { name: this.getNodeParameter('name', i), roles, password: this.getNodeParameter('password', i), } as IDataObject; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; populate(additionalFields, body); const endpoint = '/services/authentication/users'; responseData = await splunkApiRequest.call(this, 'POST', endpoint, body) as SplunkFeedResponse; responseData = formatFeed(responseData); } else if (operation === 'delete') { // ---------------------------------------- // user: delete // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTaccess#authentication.2Fusers.2F.7Bname.7D const partialEndpoint = '/services/authentication/users'; const userId = getId.call(this, i, 'userId', partialEndpoint); const endpoint = `${partialEndpoint}/${userId}`; await splunkApiRequest.call(this, 'DELETE', endpoint); responseData = { success: true }; } else if (operation === 'get') { // ---------------------------------------- // user: get // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTaccess#authentication.2Fusers.2F.7Bname.7D const partialEndpoint = '/services/authentication/users/'; const userId = getId.call(this, i, 'userId', '/services/authentication/users/'); const endpoint = `${partialEndpoint}/${userId}`; responseData = await splunkApiRequest.call(this, 'GET', endpoint).then(formatFeed); } else if (operation === 'getAll') { // ---------------------------------------- // user: getAll // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTaccess#authentication.2Fusers const qs = {} as IDataObject; setCount.call(this, qs); const endpoint = '/services/authentication/users'; responseData = await splunkApiRequest.call(this, 'GET', endpoint, {}, qs).then(formatFeed); } else if (operation === 'update') { // ---------------------------------------- // user: update // ---------------------------------------- // https://docs.splunk.com/Documentation/Splunk/8.2.2/RESTREF/RESTaccess#authentication.2Fusers.2F.7Bname.7D const body = {} as IDataObject; const { roles, ...rest } = this.getNodeParameter('updateFields', i) as IDataObject & { roles: string[]; }; populate({ ...roles && { roles }, ...rest, }, body); const partialEndpoint = '/services/authentication/users/'; const userId = getId.call(this, i, 'userId', partialEndpoint); const endpoint = `${partialEndpoint}/${userId}`; responseData = await splunkApiRequest.call(this, 'POST', endpoint, body).then(formatFeed); } } } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.cause.error }); continue; } throw error; } Array.isArray(responseData) ? returnData.push(...responseData) : returnData.push(responseData as IDataObject); } return [this.helpers.returnJsonArray(returnData)]; } }
the_stack
import { ArrowFunction, Block, ConstructorDeclaration, FunctionDeclaration, FunctionExpression, ModifierFlags, ParameterDeclaration, SyntaxKind, } from 'typescript'; import { emptyArray, ILogger, } from '@aurelia/kernel'; import { Realm, ExecutionContext, } from '../realm.js'; import { $EnvRec, $DeclarativeEnvRec, $FunctionEnvRec, } from '../types/environment-record.js'; import { $String, } from '../types/string.js'; import { $Undefined, } from '../types/undefined.js'; import { $Function, } from '../types/function.js'; import { $Any, CompletionType, $AnyNonEmpty, $PropertyKey, } from '../types/_shared.js'; import { $Object, } from '../types/object.js'; import { $Empty, } from '../types/empty.js'; import { $CreateUnmappedArgumentsObject, $ArgumentsExoticObject, } from '../exotics/arguments.js'; import { $CreateListIteratorRecord, $IteratorRecord, $IteratorStep, $IteratorValue, } from '../globals/iteration.js'; import { $Error, } from '../types/error.js'; import { I$Node, Context, $$ESDeclaration, $NodeWithStatements, modifiersToModifierFlags, hasBit, $identifier, $$AssignmentExpressionOrHigher, $assignmentExpression, $AssignmentExpressionNode, $$TSDeclaration, $$BindingName, $$bindingName, $AnyParentNode, GetDirectivePrologue, $decoratorList, $i, $$ESVarDeclaration, FunctionKind, } from './_shared.js'; import { ExportEntryRecord, $$ESModuleOrScript, } from './modules.js'; import { $Identifier, $Decorator, } from './expressions.js'; import { $ClassDeclaration, $ClassExpression, } from './classes.js'; import { $Block, DirectivePrologue, } from './statements.js'; import { $MethodDeclaration, $SetAccessorDeclaration, $GetAccessorDeclaration, } from './methods.js'; import { $DefinePropertyOrThrow, } from '../operations.js'; import { $PropertyDescriptor, } from '../types/property-descriptor.js'; import { $Boolean, } from '../types/boolean.js'; import { $List, } from '../types/list.js'; export type $$Function = ( $FunctionDeclaration | $FunctionExpression | $MethodDeclaration | $ConstructorDeclaration | $SetAccessorDeclaration | $GetAccessorDeclaration | $ArrowFunction ); export class $FormalParameterList extends Array<$ParameterDeclaration> { // http://www.ecma-international.org/ecma-262/#sec-destructuring-binding-patterns-static-semantics-boundnames // 13.3.3.1 Static Semantics: BoundNames // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-boundnames // 14.1.3 Static Semantics: BoundNames public readonly BoundNames: readonly $String[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-containsexpression // 14.1.5 Static Semantics: ContainsExpression public readonly ContainsExpression: boolean = false; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-expectedargumentcount // 14.1.7 Static Semantics: ExpectedArgumentCount public readonly ExpectedArgumentCount: number = 0; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-hasinitializer // 14.1.8 Static Semantics: HasInitializer public readonly HasInitializer: boolean = false; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-issimpleparameterlist // 14.1.13 Static Semantics: IsSimpleParameterList public readonly IsSimpleParameterList: boolean = true; public readonly hasDuplicates: boolean = false; public constructor( nodes: readonly ParameterDeclaration[] | undefined, parent: $$Function, ctx: Context, ) { super(); if (nodes === void 0) { this.BoundNames = emptyArray; } else { const BoundNames = this.BoundNames = [] as $String[]; const seenNames = new Set<string>(); let boundNamesLen = 0; let cur: $ParameterDeclaration; let curBoundNames: readonly $String[]; let curBoundName: $String; for (let i = 0, ii = nodes.length; i < ii; ++i) { cur = super[i] = new $ParameterDeclaration(nodes[i], parent, ctx, i); curBoundNames = cur.BoundNames; for (let j = 0, jj = curBoundNames.length; j < jj; ++j) { curBoundName = curBoundNames[j]; if (seenNames.has(curBoundName['[[Value]]'])) { this.hasDuplicates = true; } else { seenNames.add(curBoundName['[[Value]]']); } BoundNames[boundNamesLen++] = curBoundName; } if (cur.ContainsExpression && !this.ContainsExpression) { this.ContainsExpression = true; } if (cur.HasInitializer && !this.HasInitializer) { this.HasInitializer = true; this.ExpectedArgumentCount = i; } if (!cur.IsSimpleParameterList && this.IsSimpleParameterList) { this.IsSimpleParameterList = false; } } if (!this.HasInitializer) { this.ExpectedArgumentCount = nodes.length; } } } } export class $FunctionExpression implements I$Node { public get $kind(): SyntaxKind.FunctionExpression { return SyntaxKind.FunctionExpression; } public readonly modifierFlags: ModifierFlags; public readonly $name: $Identifier | undefined; public readonly $parameters: $FormalParameterList; public readonly $body: $Block; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-boundnames // 14.1.3 Static Semantics: BoundNames public readonly BoundNames: readonly $String[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-containsusestrict // 14.1.6 Static Semantics: ContainsUseStrict public readonly ContainsUseStrict: boolean; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-hasname // 14.1.9 Static Semantics: HasName public readonly HasName: boolean; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-isconstantdeclaration // 14.1.11 Static Semantics: IsConstantDeclaration public readonly IsConstantDeclaration: false = false; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-isfunctiondefinition // 14.1.12 Static Semantics: IsFunctionDefinition public readonly IsFunctionDefinition: true = true; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-lexicallydeclarednames // 14.1.14 Static Semantics: LexicallyDeclaredNames public readonly LexicallyDeclaredNames: readonly $String[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-lexicallyscopeddeclarations // 14.1.15 Static Semantics: LexicallyScopedDeclarations public readonly LexicallyScopedDeclarations: readonly $$ESDeclaration[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-vardeclarednames // 14.1.16 Static Semantics: VarDeclaredNames public readonly VarDeclaredNames: readonly $String[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-varscopeddeclarations // 14.1.17 Static Semantics: VarScopedDeclarations public readonly VarScopedDeclarations: readonly $$ESVarDeclaration[]; public readonly DirectivePrologue: DirectivePrologue; public readonly TypeDeclarations: readonly $$TSDeclaration[] = emptyArray; public readonly IsType: false = false; public readonly functionKind: FunctionKind.normal | FunctionKind.generator | FunctionKind.async | FunctionKind.asyncGenerator; public constructor( public readonly node: FunctionExpression, public readonly parent: $AnyParentNode, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.FunctionExpression`, ) { const modifierFlags = this.modifierFlags = modifiersToModifierFlags(node.modifiers); const DirectivePrologue = this.DirectivePrologue = GetDirectivePrologue(node.body!.statements); if (DirectivePrologue.ContainsUseStrict) { ctx |= Context.InStrictMode; } const $name = this.$name = $identifier(node.name, this, ctx, -1); this.$parameters = new $FormalParameterList(node.parameters, this, ctx); const $body = this.$body = new $Block(node.body, this, ctx, -1); this.BoundNames = emptyArray; this.ContainsUseStrict = DirectivePrologue.ContainsUseStrict === true; this.HasName = $name !== void 0; this.LexicallyDeclaredNames = $body.TopLevelLexicallyDeclaredNames; this.LexicallyScopedDeclarations = $body.TopLevelLexicallyScopedDeclarations; this.VarDeclaredNames = $body.TopLevelVarDeclaredNames; this.VarScopedDeclarations = $body.TopLevelVarScopedDeclarations; if (!hasBit(modifierFlags, ModifierFlags.Async)) { if (node.asteriskToken === void 0) { this.functionKind = FunctionKind.normal; } else { this.functionKind = FunctionKind.generator; } } else if (node.asteriskToken === void 0) { this.functionKind = FunctionKind.async; } else { this.functionKind = FunctionKind.asyncGenerator; } } // http://www.ecma-international.org/ecma-262/#sec-function-definitions-runtime-semantics-evaluatebody // 14.1.18 Runtime Semantics: EvaluateBody public EvaluateBody( ctx: ExecutionContext<$FunctionEnvRec, $FunctionEnvRec>, functionObject: $Function, argumentsList: $List<$AnyNonEmpty>, ): $Any { return EvaluateBody(this, ctx, functionObject, argumentsList); } public Evaluate( ctx: ExecutionContext, ): $Function | $Error { switch (this.functionKind) { case FunctionKind.normal: return this.$Evaluate(ctx); case FunctionKind.generator: return this.$EvaluateGenerator(ctx); case FunctionKind.asyncGenerator: return this.$EvaluateAsyncGenerator(ctx); case FunctionKind.async: return this.$EvaluateAsync(ctx); } } // http://www.ecma-international.org/ecma-262/#sec-function-definitions-runtime-semantics-evaluation // 14.1.22 Runtime Semantics: Evaluation private $Evaluate( ctx: ExecutionContext, ): $Function | $Error { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`${this.path}.$Evaluate(#${ctx.id})`); // FunctionExpression : // function ( FormalParameters ) { FunctionBody } // 1. If the function code for FunctionExpression is strict mode code, let strict be true. Otherwise let strict be false. // 2. Let scope be the LexicalEnvironment of the running execution context. // 3. Let closure be FunctionCreate(Normal, FormalParameters, FunctionBody, scope, strict). // 4. Perform MakeConstructor(closure). // 5. Set closure.[[SourceText]] to the source text matched by FunctionExpression. // 6. Return closure. // FunctionExpression : // function BindingIdentifier ( FormalParameters ) { FunctionBody } // 1. If the function code for FunctionExpression is strict mode code, let strict be true. Otherwise let strict be false. const strict = new $Boolean(realm, this.DirectivePrologue.ContainsUseStrict === true); // 2. Let scope be the running execution context's LexicalEnvironment. const scope = ctx.LexicalEnvironment; // 3. Let funcEnv be NewDeclarativeEnvironment(scope). const funcEnv = new $DeclarativeEnvRec(this.logger, realm, scope); // 4. Let envRec be funcEnv's EnvironmentRecord. // 5. Let name be StringValue of BindingIdentifier. const name = this.$name?.StringValue ?? void 0; if (name !== void 0) { // 6. Perform envRec.CreateImmutableBinding(name, false). funcEnv.CreateImmutableBinding(ctx, name, intrinsics.false); } // 7. Let closure be FunctionCreate(Normal, FormalParameters, FunctionBody, funcEnv, strict). const closure = $Function.FunctionCreate(ctx, 'normal', this, funcEnv, strict); // 8. Perform MakeConstructor(closure). closure.MakeConstructor(ctx); if (name !== void 0) { // 9. Perform SetFunctionName(closure, name). closure.SetFunctionName(ctx, name); } // 10. Set closure.[[SourceText]] to the source text matched by FunctionExpression. closure['[[SourceText]]'] = new $String(realm, this.node.getText(this.mos.node)); if (name !== void 0) { // 11. Perform envRec.InitializeBinding(name, closure). funcEnv.InitializeBinding(ctx, name, closure); } // 12. Return closure. return closure; } // http://www.ecma-international.org/ecma-262/#sec-generator-function-definitions-runtime-semantics-evaluation // 14.4.14 Runtime Semantics: Evaluation private $EvaluateGenerator( ctx: ExecutionContext, ): $Function | $Error { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`${this.path}.$EvaluateGenerator(#${ctx.id})`); // GeneratorExpression : // function * ( FormalParameters ) { GeneratorBody } // 1. If the function code for this GeneratorExpression is strict mode code, let strict be true. Otherwise let strict be false. // 2. Let scope be the LexicalEnvironment of the running execution context. // 3. Let closure be GeneratorFunctionCreate(Normal, FormalParameters, GeneratorBody, scope, strict). // 4. Let prototype be ObjectCreate(%GeneratorPrototype%). // 5. Perform DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }). // 6. Set closure.[[SourceText]] to the source text matched by GeneratorExpression. // 7. Return closure. // GeneratorExpression : // function * BindingIdentifier ( FormalParameters ) { GeneratorBody } // 1. If the function code for this GeneratorExpression is strict mode code, let strict be true. Otherwise let strict be false. const strict = new $Boolean(realm, this.DirectivePrologue.ContainsUseStrict === true); // 2. Let scope be the running execution context's LexicalEnvironment. const scope = ctx.LexicalEnvironment; // 3. Let funcEnv be NewDeclarativeEnvironment(scope). const funcEnv = new $DeclarativeEnvRec(this.logger, realm, scope); // 4. Let envRec be funcEnv's EnvironmentRecord. // 5. Let name be StringValue of BindingIdentifier. const name = this.$name?.StringValue ?? void 0; if (name !== void 0) { // 6. Perform envRec.CreateImmutableBinding(name, false). funcEnv.CreateImmutableBinding(ctx, name, intrinsics.false); } // 7. Let closure be GeneratorFunctionCreate(Normal, FormalParameters, GeneratorBody, funcEnv, strict). const closure = $Function.GeneratorFunctionCreate(ctx, 'normal', this, funcEnv, strict); // 8. Let prototype be ObjectCreate(%GeneratorPrototype%). const prototype = $Object.ObjectCreate(ctx, 'Generator', intrinsics['%GeneratorPrototype%']); // 9. Perform DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }). const $DefinePropertyOrThrowResult = $DefinePropertyOrThrow( ctx, closure, intrinsics.$prototype, new $PropertyDescriptor( realm, intrinsics.$prototype, { '[[Value]]': prototype, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.false, }, ), ); if ($DefinePropertyOrThrowResult.isAbrupt) { return $DefinePropertyOrThrowResult.enrichWith(ctx, this); } if (name !== void 0) { // 10. Perform SetFunctionName(closure, name). closure.SetFunctionName(ctx, name); // 11. Perform envRec.InitializeBinding(name, closure). funcEnv.InitializeBinding(ctx, name, closure); } // 12. Set closure.[[SourceText]] to the source text matched by GeneratorExpression. closure['[[SourceText]]'] = new $String(realm, this.node.getText(this.mos.node)); // 13. Return closure. return closure; } // http://www.ecma-international.org/ecma-262/#sec-asyncgenerator-definitions-evaluation // 14.5.14 Runtime Semantics: Evaluation private $EvaluateAsyncGenerator( ctx: ExecutionContext, ): $Function | $Error { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`${this.path}.$EvaluateAsyncGenerator(#${ctx.id})`); // AsyncGeneratorExpression : // async function * ( FormalParameters ) { AsyncGeneratorBody } // 1. If the function code for this AsyncGeneratorExpression is strict mode code, let strict be true. Otherwise let strict be false. // 2. Let scope be the LexicalEnvironment of the running execution context. // 3. Let closure be ! AsyncGeneratorFunctionCreate(Normal, FormalParameters, AsyncGeneratorBody, scope, strict). // 4. Let prototype be ! ObjectCreate(%AsyncGeneratorPrototype%). // 5. Perform ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }). // 6. Set closure.[[SourceText]] to the source text matched by AsyncGeneratorExpression. // 7. Return closure. // AsyncGeneratorExpression : // async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } // 1. If the function code for this AsyncGeneratorExpression is strict mode code, let strict be true. Otherwise let strict be false. const strict = new $Boolean(realm, this.DirectivePrologue.ContainsUseStrict === true); // 2. Let scope be the running execution context's LexicalEnvironment. const scope = ctx.LexicalEnvironment; // 3. Let funcEnv be ! NewDeclarativeEnvironment(scope). const funcEnv = new $DeclarativeEnvRec(this.logger, realm, scope); // 4. Let envRec be funcEnv's EnvironmentRecord. // 5. Let name be StringValue of BindingIdentifier. const name = this.$name?.StringValue ?? void 0; if (name !== void 0) { // 6. Perform ! envRec.CreateImmutableBinding(name). funcEnv.CreateImmutableBinding(ctx, name, intrinsics.false); // TODO: we sure about this? } // 7. Let closure be ! AsyncGeneratorFunctionCreate(Normal, FormalParameters, AsyncGeneratorBody, funcEnv, strict). const closure = $Function.AsyncGeneratorFunctionCreate(ctx, 'normal', this, funcEnv, strict); // 8. Let prototype be ! ObjectCreate(%AsyncGeneratorPrototype%). const prototype = $Object.ObjectCreate(ctx, 'AsyncGenerator', intrinsics['%AsyncGeneratorPrototype%']); // 9. Perform ! DefinePropertyOrThrow(closure, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }). const $DefinePropertyOrThrowResult = $DefinePropertyOrThrow( ctx, closure, intrinsics.$prototype, new $PropertyDescriptor( realm, intrinsics.$prototype, { '[[Value]]': prototype, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.false, }, ), ); if ($DefinePropertyOrThrowResult.isAbrupt) { return $DefinePropertyOrThrowResult.enrichWith(ctx, this); } if (name !== void 0) { // 10. Perform SetFunctionName(closure, name). closure.SetFunctionName(ctx, name); // 11. Perform envRec.InitializeBinding(name, closure). funcEnv.InitializeBinding(ctx, name, closure); } // 12. Set closure.[[SourceText]] to the source text matched by AsyncGeneratorExpression. closure['[[SourceText]]'] = new $String(realm, this.node.getText(this.mos.node)); // 13. Return closure. return closure; } // http://www.ecma-international.org/ecma-262/#sec-async-function-definitions-runtime-semantics-evaluation // 14.7.14 Runtime Semantics: Evaluation private $EvaluateAsync( ctx: ExecutionContext, ): $Function | $Error { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`${this.path}.$EvaluateAsync(#${ctx.id})`); // AsyncFunctionExpression : // async function ( FormalParameters ) { AsyncFunctionBody } // 1. If the function code for AsyncFunctionExpression is strict mode code, let strict be true. Otherwise let strict be false. // 2. Let scope be the LexicalEnvironment of the running execution context. // 3. Let closure be ! AsyncFunctionCreate(Normal, FormalParameters, AsyncFunctionBody, scope, strict). // 4. Set closure.[[SourceText]] to the source text matched by AsyncFunctionExpression. // 5. Return closure. // AsyncFunctionExpression : // async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } // 1. If the function code for AsyncFunctionExpression is strict mode code, let strict be true. Otherwise let strict be false. const strict = new $Boolean(realm, this.DirectivePrologue.ContainsUseStrict === true); // 2. Let scope be the LexicalEnvironment of the running execution context. const scope = ctx.LexicalEnvironment; // 3. Let funcEnv be ! NewDeclarativeEnvironment(scope). const funcEnv = new $DeclarativeEnvRec(this.logger, realm, scope); // 4. Let envRec be funcEnv's EnvironmentRecord. // 5. Let name be StringValue of BindingIdentifier. const name = this.$name?.StringValue ?? void 0; if (name !== void 0) { // 6. Perform ! envRec.CreateImmutableBinding(name). funcEnv.CreateImmutableBinding(ctx, name, intrinsics.false); // TODO: we sure about this? } // 7. Let closure be ! AsyncFunctionCreate(Normal, FormalParameters, AsyncFunctionBody, funcEnv, strict). const closure = $Function.AsyncFunctionCreate(ctx, 'normal', this, funcEnv, strict); if (name !== void 0) { // 8. Perform ! SetFunctionName(closure, name). closure.SetFunctionName(ctx, name); // 9. Perform ! envRec.InitializeBinding(name, closure). funcEnv.InitializeBinding(ctx, name, closure); } // 10. Set closure.[[SourceText]] to the source text matched by AsyncFunctionExpression. closure['[[SourceText]]'] = new $String(realm, this.node.getText(this.mos.node)); // 11. Return closure. return closure; } public EvaluateNamed( ctx: ExecutionContext, name: $String, ): $Function | $Error { ctx.checkTimeout(); // http://www.ecma-international.org/ecma-262/#sec-function-definitions-runtime-semantics-namedevaluation // 14.1.21 Runtime Semantics: NamedEvaluation // FunctionExpression : // function ( FormalParameters ) { FunctionBody } // http://www.ecma-international.org/ecma-262/#sec-generator-function-definitions-runtime-semantics-namedevaluation // 14.4.13 Runtime Semantics: NamedEvaluation // GeneratorExpression : // function * ( FormalParameters ) { GeneratorBody } // http://www.ecma-international.org/ecma-262/#sec-asyncgenerator-definitions-namedevaluation // 14.5.13 Runtime Semantics: NamedEvaluation // AsyncGeneratorExpression : // async function * ( FormalParameters ) { AsyncGeneratorBody } // http://www.ecma-international.org/ecma-262/#sec-async-function-definitions-runtime-semantics-namedevaluation // 14.7.13 Runtime Semantics: NamedEvaluation // AsyncFunctionExpression : // async function ( FormalParameters ) { AsyncFunctionBody } // FunctionExpression : function ( FormalParameters ) { FunctionBody } // 1. Let closure be the result of evaluating this FunctionExpression. // 1. Let closure be the result of evaluating this GeneratorExpression. // 1. Let closure be the result of evaluating this AsyncGeneratorExpression. // 1. Let closure be the result of evaluating this AsyncFunctionExpression. const closure = this.Evaluate(ctx); if (closure.isAbrupt) { return closure.enrichWith(ctx, this); } // 2. Perform SetFunctionName(closure, name). closure.SetFunctionName(ctx, name); // 3. Return closure. return closure; } } export class $FunctionDeclaration implements I$Node { public get $kind(): SyntaxKind.FunctionDeclaration { return SyntaxKind.FunctionDeclaration; } public readonly modifierFlags: ModifierFlags; public readonly $decorators: readonly $Decorator[]; public readonly $name: $Identifier | undefined; public readonly $parameters: $FormalParameterList; public readonly $body: $Block; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-boundnames // 14.1.3 Static Semantics: BoundNames // http://www.ecma-international.org/ecma-262/#sec-generator-function-definitions-static-semantics-boundnames // 14.4.2 Static Semantics: BoundNames // http://www.ecma-international.org/ecma-262/#sec-async-generator-function-definitions-static-semantics-boundnames // 14.5.2 Static Semantics: BoundNames // http://www.ecma-international.org/ecma-262/#sec-async-function-definitions-static-semantics-BoundNames // 14.7.2 Static Semantics: BoundNames public readonly BoundNames: readonly [$String | $String<'*default*'>] | readonly $String[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-containsusestrict // 14.1.6 Static Semantics: ContainsUseStrict public readonly ContainsUseStrict: boolean; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-hasname // 14.1.9 Static Semantics: HasName // http://www.ecma-international.org/ecma-262/#sec-generator-function-definitions-static-semantics-hasname // 14.4.6 Static Semantics: HasName // http://www.ecma-international.org/ecma-262/#sec-async-generator-function-definitions-static-semantics-hasname // 14.5.6 Static Semantics: HasName // http://www.ecma-international.org/ecma-262/#sec-async-function-definitions-static-semantics-HasName // 14.7.6 Static Semantics: HasName public readonly HasName: boolean; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-isconstantdeclaration // 14.1.11 Static Semantics: IsConstantDeclaration // http://www.ecma-international.org/ecma-262/#sec-generator-function-definitions-static-semantics-isconstantdeclaration // 14.4.7 Static Semantics: IsConstantDeclaration // http://www.ecma-international.org/ecma-262/#sec-async-generator-function-definitions-static-semantics-isconstantdeclaration // 14.5.7 Static Semantics: IsConstantDeclaration // http://www.ecma-international.org/ecma-262/#sec-async-function-definitions-static-semantics-IsConstantDeclaration // 14.7.7 Static Semantics: IsConstantDeclaration public readonly IsConstantDeclaration: false = false; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-isfunctiondefinition // 14.1.12 Static Semantics: IsFunctionDefinition // http://www.ecma-international.org/ecma-262/#sec-generator-function-definitions-static-semantics-isfunctiondefinition // 14.4.8 Static Semantics: IsFunctionDefinition // http://www.ecma-international.org/ecma-262/#sec-async-generator-function-definitions-static-semantics-isfunctiondefinition // 14.5.8 Static Semantics: IsFunctionDefinition // http://www.ecma-international.org/ecma-262/#sec-async-function-definitions-static-semantics-IsFunctionDefinition // 14.7.8 Static Semantics: IsFunctionDefinition public readonly IsFunctionDefinition: true = true; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-lexicallydeclarednames // 14.1.14 Static Semantics: LexicallyDeclaredNames public readonly LexicallyDeclaredNames: readonly $String[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-lexicallyscopeddeclarations // 14.1.15 Static Semantics: LexicallyScopedDeclarations public readonly LexicallyScopedDeclarations: readonly $$ESDeclaration[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-vardeclarednames // 14.1.16 Static Semantics: VarDeclaredNames public readonly VarDeclaredNames: readonly $String[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-varscopeddeclarations // 14.1.17 Static Semantics: VarScopedDeclarations public readonly VarScopedDeclarations: readonly $$ESVarDeclaration[]; // http://www.ecma-international.org/ecma-262/#sec-generator-function-definitions-static-semantics-propname // 14.4.9 Static Semantics: PropName // http://www.ecma-international.org/ecma-262/#sec-async-generator-function-definitions-static-semantics-propname // 14.5.9 Static Semantics: PropName // http://www.ecma-international.org/ecma-262/#sec-async-function-definitions-static-semantics-PropName // 14.7.9 Static Semantics: PropName public readonly PropName: $String | $Undefined; public readonly DirectivePrologue: DirectivePrologue; // http://www.ecma-international.org/ecma-262/#sec-exports-static-semantics-exportedbindings // 15.2.3.3 Static Semantics: ExportedBindings public readonly ExportedBindings: readonly $String[]; // http://www.ecma-international.org/ecma-262/#sec-exports-static-semantics-exportednames // 15.2.3.4 Static Semantics: ExportedNames public readonly ExportedNames: readonly $String[]; // http://www.ecma-international.org/ecma-262/#sec-exports-static-semantics-exportentries // 15.2.3.5 Static Semantics: ExportEntries public readonly ExportEntries: readonly ExportEntryRecord[]; // http://www.ecma-international.org/ecma-262/#sec-exports-static-semantics-modulerequests // 15.2.3.9 Static Semantics: ModuleRequests public readonly ModuleRequests: readonly $String[] = emptyArray; public readonly TypeDeclarations: readonly $$TSDeclaration[] = emptyArray; public readonly IsType: false = false; public readonly functionKind: FunctionKind.normal | FunctionKind.generator | FunctionKind.async | FunctionKind.asyncGenerator; public constructor( public readonly node: FunctionDeclaration, public readonly parent: $NodeWithStatements, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.FunctionDeclaration`, ) { const intrinsics = realm['[[Intrinsics]]']; const modifierFlags = this.modifierFlags = modifiersToModifierFlags(node.modifiers); if (hasBit(modifierFlags, ModifierFlags.Export)) { ctx |= Context.InExport; } const DirectivePrologue = this.DirectivePrologue = GetDirectivePrologue(node.body!.statements); if (this.DirectivePrologue.ContainsUseStrict) { ctx |= Context.InStrictMode; } this.$decorators = $decoratorList(node.decorators, this, ctx); const $name = this.$name = $identifier(node.name, this, ctx, -1); this.$parameters = new $FormalParameterList(node.parameters, this, ctx); const $body = this.$body = new $Block(node.body!, this, ctx, -1); this.ContainsUseStrict = DirectivePrologue.ContainsUseStrict === true; const HasName = this.HasName = $name !== void 0; this.LexicallyDeclaredNames = $body.TopLevelLexicallyDeclaredNames; this.LexicallyScopedDeclarations = $body.TopLevelLexicallyScopedDeclarations; this.VarDeclaredNames = $body.TopLevelVarDeclaredNames; this.VarScopedDeclarations = $body.TopLevelVarScopedDeclarations; if ($name === void 0) { this.PropName = new $Undefined(realm); } else { this.PropName = $name.PropName; } if (hasBit(ctx, Context.InExport)) { if (hasBit(this.modifierFlags, ModifierFlags.Default)) { if (HasName) { const [localName] = $name!.BoundNames; const BoundNames = this.BoundNames = [localName, intrinsics['*default*']]; this.ExportedBindings = BoundNames; this.ExportedNames = [intrinsics['default']]; this.ExportEntries = [ new ExportEntryRecord( /* source */this, /* ExportName */intrinsics['default'], /* ModuleRequest */intrinsics.null, /* ImportName */intrinsics.null, /* LocalName */localName, ), ]; } else { const BoundNames = this.BoundNames = [intrinsics['*default*']]; this.ExportedBindings = BoundNames; this.ExportedNames = [intrinsics['default']]; this.ExportEntries = [ new ExportEntryRecord( /* source */this, /* ExportName */intrinsics['default'], /* ModuleRequest */intrinsics.null, /* ImportName */intrinsics.null, /* LocalName */intrinsics['*default*'], ), ]; } } else { // Must have a name, so we assume it does const BoundNames = this.BoundNames = $name!.BoundNames; const [localName] = BoundNames; this.ExportedBindings = BoundNames; this.ExportedNames = BoundNames; this.ExportEntries = [ new ExportEntryRecord( /* source */this, /* ExportName */localName, /* ModuleRequest */intrinsics.null, /* ImportName */intrinsics.null, /* LocalName */localName, ), ]; } } else { // Must have a name, so we assume it does this.BoundNames = $name!.BoundNames; this.ExportedBindings = emptyArray; this.ExportedNames = emptyArray; this.ExportEntries = emptyArray; } if (!hasBit(modifierFlags, ModifierFlags.Async)) { if (node.asteriskToken === void 0) { this.functionKind = FunctionKind.normal; } else { this.functionKind = FunctionKind.generator; } } else if (node.asteriskToken === void 0) { this.functionKind = FunctionKind.async; } else { this.functionKind = FunctionKind.asyncGenerator; } } public InstantiateFunctionObject( ctx: ExecutionContext, Scope: $EnvRec, ): $Function | $Error { switch (this.functionKind) { case FunctionKind.normal: return this.$InstantiateFunctionObject(ctx, Scope); case FunctionKind.generator: return this.$InstantiateGeneratorFunctionObject(ctx, Scope); case FunctionKind.asyncGenerator: return this.$InstantiateAsyncGeneratorFunctionObject(ctx, Scope); case FunctionKind.async: return this.$InstantiateAsyncFunctionObject(ctx, Scope); } } // http://www.ecma-international.org/ecma-262/#sec-function-definitions-runtime-semantics-instantiatefunctionobject // 14.1.20 Runtime Semantics: InstantiateFunctionObject private $InstantiateFunctionObject( ctx: ExecutionContext, Scope: $EnvRec, ): $Function | $Error { ctx.checkTimeout(); this.logger.debug(`${this.path}.$InstantiateFunctionObject(#${ctx.id})`); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // FunctionDeclaration : // function ( FormalParameters ) { FunctionBody } // 1. Let F be FunctionCreate(Normal, FormalParameters, FunctionBody, scope, true). // 2. Perform MakeConstructor(F). // 3. Perform SetFunctionName(F, "default"). // 4. Set F.[[SourceText]] to the source text matched by FunctionDeclaration. // 5. Return F. // FunctionDeclaration : // function BindingIdentifier ( FormalParameters ) { FunctionBody } // 1. If the function code for FunctionDeclaration is strict mode code, let strict be true. Otherwise let strict be false. const strict = new $Boolean(realm, this.DirectivePrologue.ContainsUseStrict === true); // 2. Let name be StringValue of BindingIdentifier. const name = this.$name === void 0 ? intrinsics.default : this.$name.StringValue; // 3. Let F be FunctionCreate(Normal, FormalParameters, FunctionBody, scope, strict). const F = $Function.FunctionCreate(ctx, 'normal', this, Scope, strict); // 4. Perform MakeConstructor(F). F.MakeConstructor(ctx); // 5. Perform SetFunctionName(F, name). F.SetFunctionName(ctx, name); // 6. Set F.[[SourceText]] to the source text matched by FunctionDeclaration. F['[[SourceText]]'] = new $String(realm, this.node.getText(this.mos.node)); // 7. Return F. return F; } // http://www.ecma-international.org/ecma-262/#sec-generator-function-definitions-runtime-semantics-instantiatefunctionobject // 14.4.11 Runtime Semantics: InstantiateFunctionObject private $InstantiateGeneratorFunctionObject( ctx: ExecutionContext, Scope: $EnvRec, ): $Function | $Error { ctx.checkTimeout(); this.logger.debug(`${this.path}.$InstantiateFunctionObject(#${ctx.id})`); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // GeneratorDeclaration : // function * ( FormalParameters ) { GeneratorBody } // 1. Let F be GeneratorFunctionCreate(Normal, FormalParameters, GeneratorBody, scope, true). // 2. Let prototype be ObjectCreate(%GeneratorPrototype%). // 3. Perform DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }). // 4. Perform SetFunctionName(F, "default"). // 5. Set F.[[SourceText]] to the source text matched by GeneratorDeclaration. // 6. Return F. // GeneratorDeclaration : // function * BindingIdentifier ( FormalParameters ) { GeneratorBody } // 1. If the function code for GeneratorDeclaration is strict mode code, let strict be true. Otherwise let strict be false. const strict = new $Boolean(realm, this.DirectivePrologue.ContainsUseStrict === true); // 2. Let name be StringValue of BindingIdentifier. const name = this.$name === void 0 ? intrinsics.default : this.$name.StringValue; // 3. Let F be GeneratorFunctionCreate(Normal, FormalParameters, GeneratorBody, scope, strict). const F = $Function.GeneratorFunctionCreate(ctx, 'normal', this, Scope, strict); // 4. Let prototype be ObjectCreate(%GeneratorPrototype%). const prototype = $Object.ObjectCreate(ctx, 'Generator', intrinsics['%GeneratorPrototype%']); // 5. Perform DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }). const $DefinePropertyOrThrowResult = $DefinePropertyOrThrow( ctx, F, intrinsics.$prototype, new $PropertyDescriptor( realm, intrinsics.$prototype, { '[[Value]]': prototype, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.false, }, ), ); if ($DefinePropertyOrThrowResult.isAbrupt) { return $DefinePropertyOrThrowResult.enrichWith(ctx, this); } // 6. Perform SetFunctionName(F, name). F.SetFunctionName(ctx, name); // 7. Set F.[[SourceText]] to the source text matched by GeneratorDeclaration. F['[[SourceText]]'] = new $String(realm, this.node.getText(this.mos.node)); // 8. Return F. return F; } // http://www.ecma-international.org/ecma-262/#sec-asyncgenerator-definitions-instantiatefunctionobject // 14.5.11 Runtime Semantics: InstantiateFunctionObject private $InstantiateAsyncGeneratorFunctionObject( ctx: ExecutionContext, Scope: $EnvRec, ): $Function | $Error { ctx.checkTimeout(); this.logger.debug(`${this.path}.$InstantiateFunctionObject(#${ctx.id})`); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // AsyncGeneratorDeclaration : // async function * ( FormalParameters ) { AsyncGeneratorBody } // 1. If the function code for AsyncGeneratorDeclaration is strict mode code, let strict be true. Otherwise let strict be false. // 2. Let F be AsyncGeneratorFunctionCreate(Normal, FormalParameters, AsyncGeneratorBody, scope, strict). // 3. Let prototype be ObjectCreate(%AsyncGeneratorPrototype%). // 4. Perform DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }). // 5. Perform SetFunctionName(F, "default"). // 6. Set F.[[SourceText]] to the source text matched by AsyncGeneratorDeclaration. // 7. Return F. // AsyncGeneratorDeclaration : // async function * BindingIdentifier ( FormalParameters ) { AsyncGeneratorBody } // 1. If the function code for AsyncGeneratorDeclaration is strict mode code, let strict be true. Otherwise let strict be false. const strict = new $Boolean(realm, this.DirectivePrologue.ContainsUseStrict === true); // 2. Let name be StringValue of BindingIdentifier. const name = this.$name === void 0 ? intrinsics.default : this.$name.StringValue; // 3. Let F be ! AsyncGeneratorFunctionCreate(Normal, FormalParameters, AsyncGeneratorBody, scope, strict). const F = $Function.GeneratorFunctionCreate(ctx, 'normal', this, Scope, strict); // 4. Let prototype be ! ObjectCreate(%AsyncGeneratorPrototype%). const prototype = $Object.ObjectCreate(ctx, 'AsyncGenerator', intrinsics['%AsyncGeneratorPrototype%']); // 5. Perform ! DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }). const $DefinePropertyOrThrowResult = $DefinePropertyOrThrow( ctx, F, intrinsics.$prototype, new $PropertyDescriptor( realm, intrinsics.$prototype, { '[[Value]]': prototype, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.false, }, ), ); if ($DefinePropertyOrThrowResult.isAbrupt) { return $DefinePropertyOrThrowResult.enrichWith(ctx, this); } // 6. Perform ! SetFunctionName(F, name). F.SetFunctionName(ctx, name); // 7. Set F.[[SourceText]] to the source text matched by AsyncGeneratorDeclaration. F['[[SourceText]]'] = new $String(realm, this.node.getText(this.mos.node)); // 8. Return F. return F; } // http://www.ecma-international.org/ecma-262/#sec-async-function-definitions-InstantiateFunctionObject // 14.7.10 Runtime Semantics: InstantiateFunctionObject private $InstantiateAsyncFunctionObject( ctx: ExecutionContext, Scope: $EnvRec, ): $Function | $Error { ctx.checkTimeout(); this.logger.debug(`${this.path}.$InstantiateFunctionObject(#${ctx.id})`); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // AsyncFunctionDeclaration : // async function ( FormalParameters ) { AsyncFunctionBody } // 1. If the function code for AsyncFunctionDeclaration is strict mode code, let strict be true. Otherwise, let strict be false. // 2. Let F be ! AsyncFunctionCreate(Normal, FormalParameters, AsyncFunctionBody, scope, strict). // 3. Perform ! SetFunctionName(F, "default"). // 4. Set F.[[SourceText]] to the source text matched by AsyncFunctionDeclaration. // 5. Return F. // AsyncFunctionDeclaration : // async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody } // 1. If the function code for AsyncFunctionDeclaration is strict mode code, let strict be true. Otherwise, let strict be false. const strict = new $Boolean(realm, this.DirectivePrologue.ContainsUseStrict === true); // 2. Let name be StringValue of BindingIdentifier. const name = this.$name === void 0 ? intrinsics.default : this.$name.StringValue; // 3. Let F be ! AsyncFunctionCreate(Normal, FormalParameters, AsyncFunctionBody, scope, strict). const F = $Function.GeneratorFunctionCreate(ctx, 'normal', this, Scope, strict); // 4. Perform ! SetFunctionName(F, name). F.SetFunctionName(ctx, name); // 5. Set F.[[SourceText]] to the source text matched by AsyncFunctionDeclaration. F['[[SourceText]]'] = new $String(realm, this.node.getText(this.mos.node)); // 6. Return F. return F; } // http://www.ecma-international.org/ecma-262/#sec-function-definitions-runtime-semantics-evaluatebody // 14.1.18 Runtime Semantics: EvaluateBody public EvaluateBody( ctx: ExecutionContext<$FunctionEnvRec, $FunctionEnvRec>, functionObject: $Function, argumentsList: $List<$AnyNonEmpty>, ): $Any { return EvaluateBody(this, ctx, functionObject, argumentsList); } public Evaluate( ctx: ExecutionContext, ): $Empty { ctx.checkTimeout(); this.logger.debug(`${this.path}.Evaluate(#${ctx.id})`); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-runtime-semantics-evaluation // 14.1.22 Runtime Semantics: Evaluation // FunctionDeclaration : // function BindingIdentifier ( FormalParameters ) { FunctionBody } // 1. Return NormalCompletion(empty). // FunctionDeclaration : // function ( FormalParameters ) { FunctionBody } // 1. Return NormalCompletion(empty). return new $Empty(realm, CompletionType.normal, intrinsics.empty, this); } } // http://www.ecma-international.org/ecma-262/#sec-function-definitions-runtime-semantics-evaluatebody // 14.1.18 Runtime Semantics: EvaluateBody function EvaluateBody( fn: $$Function, ctx: ExecutionContext<$FunctionEnvRec, $FunctionEnvRec>, functionObject: $Function, argumentsList: $List<$AnyNonEmpty>, ): $Any { ctx.checkTimeout(); fn.logger.debug(`${fn.path}.EvaluateBody(#${ctx.id})`); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // FunctionBody : FunctionStatementList // 1. Perform ? FunctionDeclarationInstantiation(functionObject, argumentsList). const fdiResult = $FunctionDeclarationInstantiation(ctx, functionObject, argumentsList); if (fdiResult.isAbrupt) { return fdiResult.enrichWith(ctx, fn); } // 2. Return the result of evaluating FunctionStatementList. return (fn.$body as $Block).Evaluate(ctx); // $Block is guaranteed by $ArrowFunction.EvaluateBody } // http://www.ecma-international.org/ecma-262/#sec-functiondeclarationinstantiation export function $FunctionDeclarationInstantiation( ctx: ExecutionContext<$FunctionEnvRec | $DeclarativeEnvRec>, func: $Function, argumentsList: $List<$AnyNonEmpty>, ): $Empty | $Error { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Let calleeContext be the running execution context. // 2. Let env be the LexicalEnvironment of calleeContext. // 3. Let envRec be env's EnvironmentRecord. const envRec = ctx.LexicalEnvironment; // 4. Let code be func.[[ECMAScriptCode]]. const code = func['[[ECMAScriptCode]]']; // 5. Let strict be func.[[Strict]]. const strict = func['[[Strict]]']; // 6. Let formals be func.[[FormalParameters]]. const formals = code.$parameters; // 7. Let parameterNames be the BoundNames of formals. const parameterNames = formals.BoundNames; // 8. If parameterNames has any duplicate entries, let hasDuplicates be true. Otherwise, let hasDuplicates be false. const hasDuplicates = formals.hasDuplicates; // 9. Let simpleParameterList be IsSimpleParameterList of formals. const simpleParameterList = formals.IsSimpleParameterList; // 10. Let hasParameterExpressions be ContainsExpression of formals. const hasParameterExpressions = formals.ContainsExpression; // 11. Let varNames be the VarDeclaredNames of code. const varNames = code.VarDeclaredNames; // 12. Let varDeclarations be the VarScopedDeclarations of code. const varDeclarations = code.VarScopedDeclarations; // 13. Let lexicalNames be the LexicallyDeclaredNames of code. const lexicalNames = code.LexicallyDeclaredNames; // 14. Let functionNames be a new empty List. const functionNames = [] as $String[]; // 15. Let functionsToInitialize be a new empty List. const functionsToInitialize = [] as ($FunctionDeclaration | $ArrowFunction)[]; let i = varDeclarations.length; let d: $$ESDeclaration; // 16. For each d in varDeclarations, in reverse list order, do while (--i >= 0) { d = varDeclarations[i]; // 16. a. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then if (d instanceof $FunctionDeclaration) { // 16. a. i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration. // 16. a. ii. Let fn be the sole element of the BoundNames of d. const [fn] = d.BoundNames; // 16. a. iii. If fn is not an element of functionNames, then if (!functionNames.some(x => x.is(fn))) { // 16. a. iii. 1. Insert fn as the first element of functionNames. functionNames.unshift(fn); // 16. a. iii. 2. NOTE: If there are multiple function declarations for the same name, the last declaration is used. // 16. a. iii. 3. Insert d as the first element of functionsToInitialize. functionsToInitialize.unshift(d); } } } // 17. Let argumentsObjectNeeded be true. let argumentsObjectNeeded = true; // 18. If func.[[ThisMode]] is lexical, then if (func['[[ThisMode]]'] === 'lexical') { // 18. a. NOTE: Arrow functions never have an arguments objects. // 18. b. Set argumentsObjectNeeded to false. argumentsObjectNeeded = false; } // 19. Else if "arguments" is an element of parameterNames, then else if (parameterNames.some(x => x['[[Value]]'] === 'arguments')) { // 19. a. Set argumentsObjectNeeded to false. argumentsObjectNeeded = false; } // 20. Else if hasParameterExpressions is false, then else if (!hasParameterExpressions) { // 20. a. If "arguments" is an element of functionNames or if "arguments" is an element of lexicalNames, then if (functionNames.some(x => x['[[Value]]'] === 'arguments') || lexicalNames.some(x => x['[[Value]]'] === 'arguments')) { // 20. a. i. Set argumentsObjectNeeded to false. argumentsObjectNeeded = false; } } // 21. For each String paramName in parameterNames, do for (const paramName of parameterNames) { // 21. a. Let alreadyDeclared be envRec.HasBinding(paramName). const alreadyDeclared = envRec.HasBinding(ctx, paramName); // 21. b. NOTE: Early errors ensure that duplicate parameter names can only occur in non-strict functions that do not have parameter default values or rest parameters. // 21. c. If alreadyDeclared is false, then if (alreadyDeclared.isFalsey) { // 21. c. i. Perform ! envRec.CreateMutableBinding(paramName, false). envRec.CreateMutableBinding(ctx, paramName, intrinsics.false); // 21. c. ii. If hasDuplicates is true, then if (hasDuplicates) { // 21. c. ii. 1. Perform ! envRec.InitializeBinding(paramName, undefined). envRec.InitializeBinding(ctx, paramName, intrinsics.undefined); } } } let ao: $Object | $ArgumentsExoticObject; let parameterBindings: readonly $String[]; // 22. If argumentsObjectNeeded is true, then if (argumentsObjectNeeded) { // 22. a. If strict is true or if simpleParameterList is false, then if (strict.isTruthy || !simpleParameterList) { // 22. a. i. Let ao be CreateUnmappedArgumentsObject(argumentsList). ao = $CreateUnmappedArgumentsObject(ctx, argumentsList); } // 22. b. Else, else { // 22. b. i. NOTE: mapped argument object is only provided for non-strict functions that don't have a rest parameter, any parameter default value initializers, or any destructured parameters. // 22. b. ii. Let ao be CreateMappedArgumentsObject(func, formals, argumentsList, envRec). ao = new $ArgumentsExoticObject(realm, func, formals, argumentsList, envRec); } // 22. c. If strict is true, then if (strict.isTruthy) { // 22. c. i. Perform ! envRec.CreateImmutableBinding("arguments", false). envRec.CreateImmutableBinding(ctx, intrinsics.$arguments, intrinsics.false); } // 22. d. Else, else { // 22. d. i. Perform ! envRec.CreateMutableBinding("arguments", false). envRec.CreateMutableBinding(ctx, intrinsics.$arguments, intrinsics.false); } // 22. e. Call envRec.InitializeBinding("arguments", ao). envRec.InitializeBinding(ctx, intrinsics.$arguments, ao); // 22. f. Let parameterBindings be a new List of parameterNames with "arguments" appended. parameterBindings = parameterNames.concat(intrinsics.$arguments); } // 23. Else, else { // 23. a. Let parameterBindings be parameterNames. parameterBindings = parameterNames; } // 24. Let iteratorRecord be CreateListIteratorRecord(argumentsList). const iteratorRecord = $CreateListIteratorRecord(ctx, argumentsList); // 25. If hasDuplicates is true, then if (hasDuplicates) { // 25. a. Perform ? IteratorBindingInitialization for formals with iteratorRecord and undefined as arguments. for (const formal of formals) { const result = formal.InitializeIteratorBinding(ctx, iteratorRecord, void 0); if (result?.isAbrupt) { return result; } } } // 26. Else, else { // 26. a. Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments. for (const formal of formals) { const result = formal.InitializeIteratorBinding(ctx, iteratorRecord, envRec); if (result?.isAbrupt) { return result; } } } let varEnvRec: $EnvRec; // 27. If hasParameterExpressions is false, then if (!hasParameterExpressions) { // 27. a. NOTE: Only a single lexical environment is needed for the parameters and top-level vars. // 27. b. Let instantiatedVarNames be a copy of the List parameterBindings. const instantiatedVarNames = parameterBindings.slice(); // 27. c. For each n in varNames, do for (const n of varNames) { // 27. c. i. If n is not an element of instantiatedVarNames, then if (!instantiatedVarNames.some(x => x.is(n))) { // 27. c. i. 1. Append n to instantiatedVarNames. instantiatedVarNames.push(n); // 27. c. i. 2. Perform ! envRec.CreateMutableBinding(n, false). envRec.CreateMutableBinding(ctx, n, intrinsics.false); // 27. c. i. 3. Call envRec.InitializeBinding(n, undefined). envRec.InitializeBinding(ctx, n, intrinsics.undefined); } } // 27. d. Let varEnv be env. // 27. e. Let varEnvRec be envRec. varEnvRec = envRec; } // 28. Else, else { // 28. a. NOTE: A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body. // 28. b. Let varEnv be NewDeclarativeEnvironment(env). // 28. c. Let varEnvRec be varEnv's EnvironmentRecord. varEnvRec = new $DeclarativeEnvRec(code.logger, realm, envRec); // 28. d. Set the VariableEnvironment of calleeContext to varEnv. ctx.VariableEnvironment = varEnvRec; // 28. e. Let instantiatedVarNames be a new empty List. const instantiatedVarNames = [] as $String[]; // 28. f. For each n in varNames, do for (const n of varNames) { // 28. f. i. If n is not an element of instantiatedVarNames, then if (!instantiatedVarNames.some(x => x.is(n))) { // 28. f. i. 1. Append n to instantiatedVarNames. instantiatedVarNames.push(n); // 28. f. i. 2. Perform ! varEnvRec.CreateMutableBinding(n, false). varEnvRec.CreateMutableBinding(ctx, n, intrinsics.false); let initialValue: $Any; // 28. f. i. 3. If n is not an element of parameterBindings or if n is an element of functionNames, let initialValue be undefined. if (!parameterBindings.some(x => x.is(n))) { initialValue = intrinsics.undefined; } // 28. f. i. 4. Else, else { // 28. f. i. 4. a. Let initialValue be ! envRec.GetBindingValue(n, false). initialValue = envRec.GetBindingValue(ctx, n, intrinsics.false) as $AnyNonEmpty; } // 28. f. i. 5. Call varEnvRec.InitializeBinding(n, initialValue). varEnvRec.InitializeBinding(ctx, n, initialValue); // 28. f. i. 6. NOTE: vars whose names are the same as a formal parameter, initially have the same value as the corresponding initialized parameter. } } } // 29. NOTE: Annex B.3.3.1 adds additional steps at this point. let lexEnvRec: $EnvRec; // 30. If strict is false, then if (strict.isFalsey) { // 30. a. Let lexEnv be NewDeclarativeEnvironment(varEnv). lexEnvRec = new $DeclarativeEnvRec(code.logger, realm, varEnvRec); // 30. b. NOTE: Non-strict functions use a separate lexical Environment Record for top-level lexical declarations so that a direct eval can determine whether any var scoped declarations introduced by the eval code conflict with pre-existing top-level lexically scoped declarations. This is not needed for strict functions because a strict direct eval always places all declarations into a new Environment Record. } // 31. Else, let lexEnv be varEnv. else { lexEnvRec = varEnvRec; } // 32. Let lexEnvRec be lexEnv's EnvironmentRecord. // 33. Set the LexicalEnvironment of calleeContext to lexEnv. ctx.LexicalEnvironment = lexEnvRec; // 34. Let lexDeclarations be the LexicallyScopedDeclarations of code. const lexDeclarations = code.LexicallyScopedDeclarations; // 35. For each element d in lexDeclarations, do for (const d of lexDeclarations) { // 35. a. NOTE: A lexically declared name cannot be the same as a function/generator declaration, formal parameter, or a var name. Lexically declared names are only instantiated here but not initialized. // 35. b. For each element dn of the BoundNames of d, do for (const dn of d.BoundNames) { // 35. b. i. If IsConstantDeclaration of d is true, then if (d.IsConstantDeclaration) { // 35. b. i. 1. Perform ! lexEnvRec.CreateImmutableBinding(dn, true). lexEnvRec.CreateImmutableBinding(ctx, dn, intrinsics.true); } // 35. b. ii. Else, else { // 35. b. ii. 1. Perform ! lexEnvRec.CreateMutableBinding(dn, false). lexEnvRec.CreateMutableBinding(ctx, dn, intrinsics.false); } } } // 36. For each Parse Node f in functionsToInitialize, do for (const f of functionsToInitialize) { // 36. a. Let fn be the sole element of the BoundNames of f. const [fn] = f.BoundNames; // TODO: probably not right if (f instanceof $FunctionDeclaration) { // 36. b. Let fo be the result of performing InstantiateFunctionObject for f with argument lexEnv. const fo = f.InstantiateFunctionObject(ctx, lexEnvRec); if (fo.isAbrupt) { return fo; } // 36. c. Perform ! varEnvRec.SetMutableBinding(fn, fo, false). varEnvRec.SetMutableBinding(ctx, fn, fo, intrinsics.false); } } // 37. Return NormalCompletion(empty). return new $Empty(realm, CompletionType.normal, intrinsics.empty); } export class $ArrowFunction implements I$Node { public get $kind(): SyntaxKind.ArrowFunction { return SyntaxKind.ArrowFunction; } public readonly modifierFlags: ModifierFlags; public readonly $parameters: $FormalParameterList; public readonly $body: $Block | $$AssignmentExpressionOrHigher; // http://www.ecma-international.org/ecma-262/#sec-arrow-function-definitions-static-semantics-boundnames // 14.2.2 Static Semantics: BoundNames // http://www.ecma-international.org/ecma-262/#sec-async-arrow-function-definitions-static-semantics-BoundNames // 14.8.3 Static Semantics: BoundNames public readonly BoundNames: readonly $String[] = emptyArray; // http://www.ecma-international.org/ecma-262/#sec-arrow-function-definitions-static-semantics-containsusestrict // 14.2.5 Static Semantics: ContainsUseStrict public readonly ContainsUseStrict: boolean; // http://www.ecma-international.org/ecma-262/#sec-arrow-function-definitions-static-semantics-hasname // 14.2.7 Static Semantics: HasName // http://www.ecma-international.org/ecma-262/#sec-async-arrow-function-definitions-static-semantics-HasName // 14.8.7 Static Semantics: HasName public readonly HasName: false = false; // http://www.ecma-international.org/ecma-262/#sec-static-semantics-coveredformalslist // 14.2.9 Static Semantics: CoveredFormalsList public readonly CoveredFormalsList: $FormalParameterList; // http://www.ecma-international.org/ecma-262/#sec-arrow-function-definitions-static-semantics-lexicallydeclarednames // 14.2.10 Static Semantics: LexicallyDeclaredNames // http://www.ecma-international.org/ecma-262/#sec-async-arrow-function-definitions-static-semantics-LexicallyDeclaredNames // 14.8.9 Static Semantics: LexicallyDeclaredNames public readonly LexicallyDeclaredNames: readonly $String[] = emptyArray; // http://www.ecma-international.org/ecma-262/#sec-arrow-function-definitions-static-semantics-lexicallyscopeddeclarations // 14.2.11 Static Semantics: LexicallyScopedDeclarations // http://www.ecma-international.org/ecma-262/#sec-async-arrow-function-definitions-static-semantics-LexicallyScopedDeclarations // 14.8.10 Static Semantics: LexicallyScopedDeclarations public readonly LexicallyScopedDeclarations: readonly $$ESDeclaration[] = emptyArray; // http://www.ecma-international.org/ecma-262/#sec-arrow-function-definitions-static-semantics-vardeclarednames // 14.2.12 Static Semantics: VarDeclaredNames // http://www.ecma-international.org/ecma-262/#sec-async-arrow-function-definitions-static-semantics-VarDeclaredNames // 14.8.11 Static Semantics: VarDeclaredNames public readonly VarDeclaredNames: readonly $String[] = emptyArray; // http://www.ecma-international.org/ecma-262/#sec-arrow-function-definitions-static-semantics-varscopeddeclarations // 14.2.13 Static Semantics: VarScopedDeclarations // http://www.ecma-international.org/ecma-262/#sec-async-arrow-function-definitions-static-semantics-VarScopedDeclarations // 14.8.12 Static Semantics: VarScopedDeclarations public readonly VarScopedDeclarations: readonly $$ESVarDeclaration[] = emptyArray; public readonly DirectivePrologue: DirectivePrologue; public readonly TypeDeclarations: readonly $$TSDeclaration[] = emptyArray; public readonly IsType: false = false; public readonly functionKind: FunctionKind.normal | FunctionKind.async; public constructor( public readonly node: ArrowFunction, public readonly parent: $AnyParentNode, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.ArrowFunction`, ) { const modifierFlags = this.modifierFlags = modifiersToModifierFlags(node.modifiers); if (node.body.kind === SyntaxKind.Block) { const DirectivePrologue = this.DirectivePrologue = GetDirectivePrologue((node.body as Block).statements); if (DirectivePrologue.ContainsUseStrict) { ctx |= Context.InStrictMode; this.ContainsUseStrict = true; } else { this.ContainsUseStrict = false; } this.$parameters = this.CoveredFormalsList = new $FormalParameterList(node.parameters, this as $ArrowFunction, ctx); this.$body = new $Block(node.body as Block, this, ctx, -1); } else { this.DirectivePrologue = emptyArray; this.ContainsUseStrict = false; this.$parameters = this.CoveredFormalsList = new $FormalParameterList(node.parameters, this, ctx); this.$body = $assignmentExpression(node.body as $AssignmentExpressionNode, this, ctx, -1); } this.functionKind = hasBit(modifierFlags, ModifierFlags.Async) ? FunctionKind.async : FunctionKind.normal; } // http://www.ecma-international.org/ecma-262/#sec-arrow-function-definitions-runtime-semantics-evaluation // 14.2.17 Runtime Semantics: Evaluation public Evaluate( ctx: ExecutionContext, ): $AnyNonEmpty { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`${this.path}.Evaluate(#${ctx.id})`); // ArrowFunction : ArrowParameters => ConciseBody // 1. If the function code for this ArrowFunction is strict mode code, let strict be true. Otherwise let strict be false. // 2. Let scope be the LexicalEnvironment of the running execution context. // 3. Let parameters be CoveredFormalsList of ArrowParameters. // 4. Let closure be FunctionCreate(Arrow, parameters, ConciseBody, scope, strict). // 5. Set closure.[[SourceText]] to the source text matched by ArrowFunction. // 6. Return closure. return intrinsics.undefined; // TODO: implement this } // http://www.ecma-international.org/ecma-262/#sec-arrow-function-definitions-runtime-semantics-evaluatebody // 14.2.15 Runtime Semantics: EvaluateBody public EvaluateBody( ctx: ExecutionContext<$FunctionEnvRec, $FunctionEnvRec>, functionObject: $Function, argumentsList: $List<$AnyNonEmpty>, ): $Any { ctx.checkTimeout(); if (this.$body.$kind === SyntaxKind.Block) { return $FunctionDeclaration.prototype.EvaluateBody.call(this, ctx, functionObject, argumentsList); } this.logger.debug(`${this.path}.EvaluateBody(#${ctx.id})`); // ConciseBody : AssignmentExpression // 1. Perform ? FunctionDeclarationInstantiation(functionObject, argumentsList). // 2. Let exprRef be the result of evaluating AssignmentExpression. // 3. Let exprValue be ? GetValue(exprRef). // 4. Return Completion { [[Type]]: return, [[Value]]: exprValue, [[Target]]: empty }. const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; return intrinsics.undefined; // TODO: implement this } } export class MethodDefinitionRecord { public '[[Key]]': $PropertyKey; public '[[Closure]]': $Function; public get isAbrupt(): false { return false; } public constructor( key: $PropertyKey, closure: $Function, ) { this['[[Key]]'] = key; this['[[Closure]]'] = closure; } } export class $ConstructorDeclaration implements I$Node { public get $kind(): SyntaxKind.Constructor { return SyntaxKind.Constructor; } public readonly modifierFlags: ModifierFlags; public readonly $decorators: readonly $Decorator[]; public readonly $parameters: $FormalParameterList; public readonly $body: $Block; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-lexicallydeclarednames // 14.1.14 Static Semantics: LexicallyDeclaredNames public readonly LexicallyDeclaredNames: readonly $String[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-lexicallyscopeddeclarations // 14.1.15 Static Semantics: LexicallyScopedDeclarations public readonly LexicallyScopedDeclarations: readonly $$ESDeclaration[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-vardeclarednames // 14.1.16 Static Semantics: VarDeclaredNames public readonly VarDeclaredNames: readonly $String[]; // http://www.ecma-international.org/ecma-262/#sec-function-definitions-static-semantics-varscopeddeclarations // 14.1.17 Static Semantics: VarScopedDeclarations public readonly VarScopedDeclarations: readonly $$ESVarDeclaration[]; public readonly functionKind: FunctionKind.normal = FunctionKind.normal; public constructor( public readonly node: ConstructorDeclaration, public readonly parent: $ClassDeclaration | $ClassExpression, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.ConstructorDeclaration`, ) { this.modifierFlags = modifiersToModifierFlags(node.modifiers); this.$decorators = $decoratorList(node.decorators, this, ctx); this.$parameters = new $FormalParameterList(node.parameters, this, ctx); const $body = this.$body = new $Block(node.body!, this, ctx, -1); this.LexicallyDeclaredNames = $body.TopLevelLexicallyDeclaredNames; this.LexicallyScopedDeclarations = $body.TopLevelLexicallyScopedDeclarations; this.VarDeclaredNames = $body.TopLevelVarDeclaredNames; this.VarScopedDeclarations = $body.TopLevelVarScopedDeclarations; } // http://www.ecma-international.org/ecma-262/#sec-runtime-semantics-definemethod // 14.3.7 Runtime Semantics: DefineMethod public DefineMethod( ctx: ExecutionContext, object: $Object, functionPrototype: $Object, ): MethodDefinitionRecord { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // NOTE: this logic and signature is adapted to the fact that this is always a constructor method // MethodDefinition : PropertyName ( UniqueFormalParameters ) { FunctionBody } // 1. Let propKey be the result of evaluating PropertyName. const propKey = intrinsics.$constructor; // 2. ReturnIfAbrupt(propKey). // 3. If the function code for this MethodDefinition is strict mode code, let strict be true. Otherwise let strict be false. const strict = intrinsics.true; // TODO: use static semantics // 4. Let scope be the running execution context's LexicalEnvironment. const scope = ctx.LexicalEnvironment; // 5. If functionPrototype is present as a parameter, then // 5. a. Let kind be Normal. // 5. b. Let prototype be functionPrototype. // 6. Else, // 6. a. Let kind be Method. // 6. b. Let prototype be the intrinsic object %FunctionPrototype%. // 7. Let closure be FunctionCreate(kind, UniqueFormalParameters, FunctionBody, scope, strict, prototype). const closure = $Function.FunctionCreate(ctx, 'normal', this, scope, strict, functionPrototype); // 8. Perform MakeMethod(closure, object). closure['[[HomeObject]]'] = object; // 9. Set closure.[[SourceText]] to the source text matched by MethodDefinition. closure['[[SourceText]]'] = new $String(realm, this.parent.node.getText(this.mos.node)); // 10. Return the Record { [[Key]]: propKey, [[Closure]]: closure }. return new MethodDefinitionRecord(propKey, closure); } // http://www.ecma-international.org/ecma-262/#sec-function-definitions-runtime-semantics-evaluatebody // 14.1.18 Runtime Semantics: EvaluateBody public EvaluateBody( ctx: ExecutionContext<$FunctionEnvRec, $FunctionEnvRec>, functionObject: $Function, argumentsList: $List<$AnyNonEmpty>, ): $Any { return EvaluateBody(this, ctx, functionObject, argumentsList); } } export class $ParameterDeclaration implements I$Node { public get $kind(): SyntaxKind.Parameter { return SyntaxKind.Parameter; } public readonly modifierFlags: ModifierFlags; public readonly combinedModifierFlags: ModifierFlags; public readonly $decorators: readonly $Decorator[]; public readonly $name: $$BindingName; public readonly $initializer: $$AssignmentExpressionOrHigher | undefined; // http://www.ecma-international.org/ecma-262/#sec-destructuring-binding-patterns-static-semantics-boundnames // 13.3.3.1 Static Semantics: BoundNames public readonly BoundNames: readonly $String[] | readonly [$String]; // http://www.ecma-international.org/ecma-262/#sec-destructuring-binding-patterns-static-semantics-containsexpression // 13.3.3.2 Static Semantics: ContainsExpression public readonly ContainsExpression: boolean; // http://www.ecma-international.org/ecma-262/#sec-destructuring-binding-patterns-static-semantics-hasinitializer // 13.3.3.3 Static Semantics: HasInitializer public readonly HasInitializer: boolean; // http://www.ecma-international.org/ecma-262/#sec-destructuring-binding-patterns-static-semantics-issimpleparameterlist // 13.3.3.4 Static Semantics: IsSimpleParameterList public readonly IsSimpleParameterList: boolean; public constructor( public readonly node: ParameterDeclaration, public readonly parent: $$Function, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.ParameterDeclaration`, ) { this.modifierFlags = this.combinedModifierFlags = modifiersToModifierFlags(node.modifiers); ctx |= Context.InParameterDeclaration; this.$decorators = $decoratorList(node.decorators, this, ctx); const $name = this.$name = $$bindingName(node.name, this, ctx, -1); this.BoundNames = $name.BoundNames; if (node.initializer === void 0) { this.$initializer = void 0; this.ContainsExpression = $name.ContainsExpression; this.HasInitializer = false; this.IsSimpleParameterList = $name.IsSimpleParameterList; } else { this.$initializer = $assignmentExpression(node.initializer as $AssignmentExpressionNode, this, ctx, -1); this.ContainsExpression = true; this.HasInitializer = true; this.IsSimpleParameterList = false; } } // http://www.ecma-international.org/ecma-262/#sec-function-definitions-runtime-semantics-iteratorbindinginitialization // 14.1.19 Runtime Semantics: IteratorBindingInitialization public InitializeIteratorBinding( ctx: ExecutionContext, iteratorRecord: $IteratorRecord, environment: $EnvRec | undefined, ) { ctx.checkTimeout(); this.logger.debug(`${this.path}.InitializeIteratorBinding(#${ctx.id})`); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; const BindingElement = this.$name; if (BindingElement.$kind === SyntaxKind.Identifier) { return BindingElement.InitializeIteratorBinding(ctx, iteratorRecord, environment, this.$initializer); } // FormalParameter : BindingElement if (!this.ContainsExpression) { // 1. If ContainsExpression of BindingElement is false, return the result of performing IteratorBindingInitialization for BindingElement using iteratorRecord and environment as the arguments. // http://www.ecma-international.org/ecma-262/#sec-destructuring-binding-patterns-runtime-semantics-iteratorbindinginitialization // 13.3.3.8 Runtime Semantics: IteratorBindingInitialization // NOTE: this section is duplicated in BindingElement // BindingElement : BindingPattern Initializer opt let v: $Any = intrinsics.undefined; // TODO: sure about this? // 1. If iteratorRecord.[[Done]] is false, then if (iteratorRecord['[[Done]]'].isFalsey) { // 1. a. Let next be IteratorStep(iteratorRecord). const next = $IteratorStep(ctx, iteratorRecord); // 1. b. If next is an abrupt completion, set iteratorRecord.[[Done]] to true. if (next.isAbrupt) { iteratorRecord['[[Done]]'] = intrinsics.true; // 1. c. ReturnIfAbrupt(next). if (next.isAbrupt) { return next; } } // 1. d. If next is false, set iteratorRecord.[[Done]] to true. if (next.isFalsey) { iteratorRecord['[[Done]]'] = intrinsics.true; } // 1. e. Else, else { // 1. e. i. Let v be IteratorValue(next). v = $IteratorValue(ctx, next); // 1. e. ii. If v is an abrupt completion, set iteratorRecord.[[Done]] to true. if (v.isAbrupt) { iteratorRecord['[[Done]]'] = intrinsics.true; // 1. e. iii. ReturnIfAbrupt(v). if (v.isAbrupt) { return v; } } } } // 2. If iteratorRecord.[[Done]] is true, let v be undefined. if (iteratorRecord['[[Done]]'].isTruthy) { v = intrinsics.undefined; } const initializer = this.$initializer; // 3. If Initializer is present and v is undefined, then if (initializer !== void 0 && v.isUndefined) { // 3. a. Let defaultValue be the result of evaluating Initializer. const defaultValue = initializer.Evaluate(ctx); // 3. b. Set v to ? GetValue(defaultValue). const $v = defaultValue.GetValue(ctx); if ($v.isAbrupt) { return $v.enrichWith(ctx, this); } } // 4. Return the result of performing BindingInitialization of BindingPattern with v and environment as the arguments. return BindingElement.InitializeBinding(ctx, v as $Object, environment); } // TODO: implement the rest of this // 2. Let currentContext be the running execution context. // 3. Let originalEnv be the VariableEnvironment of currentContext. // 4. Assert: The VariableEnvironment and LexicalEnvironment of currentContext are the same. // 5. Assert: environment and originalEnv are the same. // 6. Let paramVarEnv be NewDeclarativeEnvironment(originalEnv). // 7. Set the VariableEnvironment of currentContext to paramVarEnv. // 8. Set the LexicalEnvironment of currentContext to paramVarEnv. // 9. Let result be the result of performing IteratorBindingInitialization for BindingElement using iteratorRecord and environment as the arguments. // 10. Set the VariableEnvironment of currentContext to originalEnv. // 11. Set the LexicalEnvironment of currentContext to originalEnv. // 12. Return result. // FunctionRestParameter : BindingRestElement // 1. If ContainsExpression of BindingRestElement is false, return the result of performing IteratorBindingInitialization for BindingRestElement using iteratorRecord and environment as the arguments. // 2. Let currentContext be the running execution context. // 3. Let originalEnv be the VariableEnvironment of currentContext. // 4. Assert: The VariableEnvironment and LexicalEnvironment of currentContext are the same. // 5. Assert: environment and originalEnv are the same. // 6. Let paramVarEnv be NewDeclarativeEnvironment(originalEnv). // 7. Set the VariableEnvironment of currentContext to paramVarEnv. // 8. Set the LexicalEnvironment of currentContext to paramVarEnv. // 9. Let result be the result of performing IteratorBindingInitialization for BindingRestElement using iteratorRecord and environment as the arguments. // 10. Set the VariableEnvironment of currentContext to originalEnv. // 11. Set the LexicalEnvironment of currentContext to originalEnv. // 12. Return result. } }
the_stack
import React, { Component, RefObject } from 'react' import { Animated, ImageBackground, ScrollView, Share, StyleSheet, View, SafeAreaView, NativeSyntheticEvent, NativeScrollEvent } from 'react-native' import { observable, action, computed, reaction } from 'mobx' import { observer } from 'mobx-react' import { boundMethod } from 'autobind-decorator' import { CommonActions } from '@react-navigation/native' import { webUrl, appName } from '@app/config' import { HomeRoutes } from '@app/constants/routes' import { IArticle } from '@app/types/business' import { LANGUAGE_KEYS } from '@app/constants/language' import { likeStore } from '@app/stores/like' import { Iconfont } from '@app/components/common/iconfont' import { TouchableView } from '@app/components/common/touchable-view' import { AutoActivityIndicator } from '@app/components/common/activity-indicator' import { Markdown } from '@app/components/common/markdown' import { BetterModal } from '@app/components/common/modal' import { DoubleClick } from '@app/components/common/double-click' import { Text } from '@app/components/common/text' import { Comment } from '@app/components/comment' import { dateToYMD } from '@app/utils/filters' import { IPageProps } from '@app/types/props' import mixins, { getHeaderButtonStyle } from '@app/style/mixins' import sizes, { safeAreaViewBottom } from '@app/style/sizes' import i18n from '@app/services/i18n' import colors from '@app/style/colors' import fonts from '@app/style/fonts' import fetch from '@app/services/fetch' const headerHeight = sizes.gap * 3 const headerHeightCollapsed = sizes.gap * 2.5 const headerDescriptionHeight = 20 const thumbHeight = sizes.screen.width / sizes.thumbHeightRatio const footerHeight = headerHeightCollapsed export interface IArticleDetailProps extends IPageProps {} @observer export class ArticleDetail extends Component<IArticleDetailProps> { constructor(props: IArticleDetailProps) { super(props) this.fetchArticleDatail() reaction( () => this.isHeaderCollapsed, collapse => this.runHeaderAnimate(collapse), { fireImmediately: true } ) } private scrollContentElement: RefObject<ScrollView> = React.createRef() @observable isLoading: boolean = false @observable article: IArticle | null = null @observable isHeaderCollapsed: boolean = false @observable commentModalVisible: boolean = false @observable headerHeight: Animated.Value = new Animated.Value(headerHeight) @observable headerDescriptionOpacity: Animated.Value = new Animated.Value(1) @observable headerDescriptionHeight: Animated.Value = new Animated.Value(headerDescriptionHeight) @boundMethod private getParamArticle(): IArticle { return this.props.route.params?.article } @boundMethod private getArticleId(): number { const { params } = this.props.route return params?.articleId || params?.article?.id } @computed private get articleContent(): string | null { return this.article && this.article.content } @computed private get isLikedArticle(): boolean { return likeStore.articles.includes(this.getArticleId()) } private runHeaderAnimate(collapse: boolean) { Animated.parallel([ Animated.timing(this.headerHeight, { toValue: collapse ? headerHeightCollapsed : headerHeight, duration: 288 }), Animated.timing(this.headerDescriptionOpacity, { toValue: collapse ? 0 : 1, duration: 188 }), Animated.timing(this.headerDescriptionHeight, { toValue: collapse ? 0 : headerDescriptionHeight, duration: 288 }) ]).start() } @action private updateHeaderCollapsedState(collapse: boolean) { this.isHeaderCollapsed = collapse } @action private updateLoadingState(loading: boolean) { this.isLoading = loading } @action private updateCommentModalVisible(visible: boolean) { this.commentModalVisible = visible } @action private updateAndCorrectArticle(article: IArticle | null) { if (article && article.content) { const { content } = article const thumbContent = `![](${article.thumb})` const isBrStart = content.startsWith('\n') const isIncludeThumb = content && content.includes(thumbContent) if (isIncludeThumb) { article.content = article.content.replace(thumbContent, '') } if (isBrStart) { article.content = article.content.replace('\n', '') } // FIX: Lazy loading content article.content = article.content.replace(/data-src=/ig, 'src=') // FIX: Did not receive response to shouldStartLoad in time, defaulting to YES article.content = article.content.replace(/src="\/\//ig, 'src="https://') } this.article = article } @action private updateResultData(article: IArticle) { this.updateLoadingState(false) this.updateAndCorrectArticle(article) } private fetchArticleDatail(): Promise<any> { const articleId = this.getArticleId() if (!articleId) { return Promise.reject() } this.updateLoadingState(true) return fetch.get<IArticle>(`/article/${articleId}`) .then(article => { this.updateResultData(article.result) return article }) .catch(error => { this.updateLoadingState(false) console.warn('Fetch article detail error:', error) return Promise.reject(error) }) } @boundMethod private handleGoBack() { this.props.navigation.goBack(null) } @boundMethod private handleScrollToTop() { const element = this.scrollContentElement.current element && element.scrollTo({ y: 0 }) } private handleToNewArticle(article: IArticle) { this.props.navigation.dispatch( CommonActions.navigate({ key: String(article.id), name: HomeRoutes.ArticleDetail, params: { article } }) ) } @boundMethod private handleLikeArticle() { if (!this.isLikedArticle) { const articleId = this.getArticleId() const doLike = action(() => { likeStore.likeArticle(articleId) this.article && this.article.meta.likes++ }) fetch.patch<boolean>('/like/article', { article_id: articleId }) .then(doLike) .catch(error => { doLike() console.warn('Fetch like article error:', error) }) } } @boundMethod private handlePageScroll(event: NativeSyntheticEvent<NativeScrollEvent>) { const pageOffsetY = event.nativeEvent.contentOffset.y this.updateHeaderCollapsedState(pageOffsetY > headerHeight) } @boundMethod private handleOpenComment() { this.updateCommentModalVisible(true) } @boundMethod private async handleShare() { try { const title = this.article?.title || '' const result = await Share.share({ title, message: title, url: `${webUrl}/article/${this.getArticleId()}` }, { dialogTitle: `Share article: ${title}`, subject: `A article from ${appName}: ${title}` }) } catch (error) { console.warn('Share article failed:', error.message) } } render() { const { styles } = obStyles const { article, isLoading } = this const automaticArticle = this.article || this.getParamArticle() const TextSeparator = ( <Text style={styles.metaTextSeparator}>∙</Text> ) return ( <SafeAreaView style={[styles.container, styles.cardBackground]}> <View style={[styles.container, styles.article]}> <Animated.View style={[ styles.header, mixins.rowCenter, styles.cardBackground, { height: this.headerHeight } ]} > <TouchableView accessibilityLabel="返回" accessibilityHint="返回列表页" style={{ height: sizes.goldenRatioGap * 2 }} onPress={this.handleGoBack} > <Iconfont name="prev" color={colors.textTitle} {...getHeaderButtonStyle(19)} /> </TouchableView> <View style={styles.name}> <DoubleClick onDoubleClick={this.handleScrollToTop}> <Text style={styles.title} numberOfLines={1}> {automaticArticle ? automaticArticle.title : '...'} </Text> </DoubleClick> <Animated.View style={{ height: this.headerDescriptionHeight, opacity: this.headerDescriptionOpacity }} > <Text style={styles.description} numberOfLines={1}> {automaticArticle ? automaticArticle.description : '...'} </Text> </Animated.View> </View> </Animated.View> <Animated.View style={[ styles.container, { transform: [{ translateY: this.headerHeight }] } ]} > <ScrollView ref={this.scrollContentElement} style={styles.container} scrollEventThrottle={16} onScroll={this.handlePageScroll} > <ImageBackground style={styles.thumb} source={automaticArticle ? { uri: automaticArticle.thumb } : {}} /> {automaticArticle && ( <View style={[styles.meta, styles.cardBackground, styles.headerMeta]}> <Text style={styles.metaText}> {automaticArticle.meta.views} {i18n.t(LANGUAGE_KEYS.VIEWS)} </Text> {TextSeparator} <Text style={styles.metaText}> {automaticArticle.meta.likes} {i18n.t(LANGUAGE_KEYS.LIKES)} </Text> {TextSeparator} <Text style={styles.metaText}> {i18n.t(LANGUAGE_KEYS.LAST_UPDATE_AT)} {dateToYMD(automaticArticle.update_at)} </Text> </View> )} <View accessibilityLabel={`文章内容:${this.articleContent}`} style={[styles.content, styles.cardBackground]} > { isLoading ? <AutoActivityIndicator style={styles.indicator} text={i18n.t(LANGUAGE_KEYS.LOADING)} /> : <Markdown navigation={this.props.navigation} route={this.props.route} sanitize={false} style={styles.markdown} padding={sizes.goldenRatioGap} markdown={this.articleContent} /> } {article && ( <View style={[styles.cardBackground, styles.footerMeta]}> <Text style={styles.metaText}> {i18n.t(LANGUAGE_KEYS.CREATE_AT)} {dateToYMD(automaticArticle.create_at)} </Text> <View style={styles.footerMetaItems}> <Text style={styles.metaText}> { article.category.length ? `${String(article.category.map(c => c.name).join('、'))} ∙ ` : i18n.t(LANGUAGE_KEYS.EMPTY) } </Text> <Text style={styles.metaText}> { article.tag.length ? `${String(article.tag.map(t => t.name).join('、'))}` : i18n.t(LANGUAGE_KEYS.EMPTY) } </Text> </View> </View> )} </View> {article && article.related.length && ( <View style={[styles.related, styles.cardBackground]}> <Text style={styles.relatedTitle}> {i18n.t(LANGUAGE_KEYS.RELATED_ARTICLE)} </Text> {article.related.filter(a => a.id !== article.id).slice(0, 3).map((item, index) => ( <TouchableView key={`${item.id}-${index}`} style={styles.relatedItem} onPress={(() => this.handleToNewArticle(item))} > <Text style={styles.relatedItemTitle} numberOfLines={1} > {item.title} </Text> <View style={[mixins.rowCenter, styles.cardBackground]}> <Text style={styles.metaText}> {item.meta.views} {i18n.t(LANGUAGE_KEYS.VIEWS)} </Text> {TextSeparator} <Text style={styles.metaText}> {item.meta.likes} {i18n.t(LANGUAGE_KEYS.LIKES)} </Text> {TextSeparator} <Text style={styles.metaText}> {item.meta.comments} {i18n.t(LANGUAGE_KEYS.COMMENTS)} </Text> {TextSeparator} <Text style={styles.metaText}> {i18n.t(LANGUAGE_KEYS.CREATE_AT)} {dateToYMD(item.create_at)} </Text> </View> </TouchableView> ))} </View> )} </ScrollView> </Animated.View> {article && ( <View style={[styles.footer, styles.cardBackground]}> <TouchableView style={styles.footerItem} onPress={this.handleOpenComment} > <Iconfont name="comment-discussion" style={styles.footerItemIcon} /> <Text style={styles.footerItemText}> {i18n.t(LANGUAGE_KEYS.COMMENTS)} {` (${article.meta.comments})`} </Text> </TouchableView> <TouchableView style={styles.footerItem} disabled={this.isLikedArticle} onPress={this.handleLikeArticle} > <Iconfont name="like" style={[ styles.footerItemIcon, { color: this.isLikedArticle ? colors.red : styles.footerItemIcon.color } ]} /> <Text style={[ styles.footerItemText, { color: this.isLikedArticle ? colors.red : styles.footerItemText.color } ]} > {i18n.t(LANGUAGE_KEYS.LIKE)} {` (${article.meta.likes})`} </Text> </TouchableView> <TouchableView style={styles.footerItem} onPress={this.handleShare} > <Iconfont name="share1" style={styles.footerItemIcon} /> <Text style={styles.footerItemText}> {i18n.t(LANGUAGE_KEYS.SHARE)} </Text> </TouchableView> </View> )} </View> <BetterModal visible={this.commentModalVisible} onClose={() => this.updateCommentModalVisible(false)} top={this.isHeaderCollapsed ? headerHeightCollapsed : headerHeight} > <Comment postId={this.getArticleId()} /> </BetterModal> </SafeAreaView> ) } } const obStyles = observable({ get styles() { return StyleSheet.create({ container: { flex: 1, position: 'relative', backgroundColor: colors.background }, cardBackground: { backgroundColor: colors.cardBackground }, article: { paddingBottom: safeAreaViewBottom + footerHeight }, header: { position: 'absolute', top: 0, left: 0, right: 0, zIndex: 1, borderColor: colors.border, borderBottomWidth: sizes.borderWidth }, name: { justifyContent: 'center', width: sizes.screen.width - sizes.gap * 3.5 }, title: { ...fonts.h3, fontWeight: 'bold', color: colors.textTitle }, description: { ...fonts.small, marginTop: 2 }, thumb: { flex: 1, width: sizes.screen.width, height: thumbHeight, resizeMode: 'cover', backgroundColor: colors.inverse }, meta: { ...mixins.rowCenter, paddingHorizontal: sizes.goldenRatioGap }, metaText: { ...fonts.small, color: colors.textSecondary }, metaTextSeparator: { marginHorizontal: 5, color: colors.textSecondary }, headerMeta: { paddingBottom: 0, paddingTop: sizes.goldenRatioGap }, footerMeta: { paddingHorizontal: sizes.goldenRatioGap, paddingBottom: sizes.goldenRatioGap }, footerMetaItems: { ...mixins.rowCenter, marginTop: sizes.goldenRatioGap }, content: { minHeight: sizes.screen.heightSafeArea - thumbHeight - headerHeight - sizes.statusBarHeight, marginBottom: sizes.gap }, indicator: { flex: 1 }, markdown: { marginVertical: sizes.goldenRatioGap, }, related: { marginBottom: sizes.gap * 1.9 }, relatedTitle: { padding: sizes.goldenRatioGap, borderBottomColor: colors.border, borderBottomWidth: sizes.borderWidth, color: colors.textSecondary }, relatedItem: { padding: sizes.goldenRatioGap, borderTopColor: colors.border, borderTopWidth: sizes.borderWidth }, relatedItemTitle: { ...fonts.h4, marginBottom: 5 }, footer: { position: 'absolute', left: 0, bottom: 0, width: sizes.screen.width, height: footerHeight, flex: 1, ...mixins.rowCenter, justifyContent: 'space-evenly', borderTopColor: colors.border, borderTopWidth: sizes.borderWidth, opacity: 0.9 }, footerItem: { ...mixins.rowCenter, justifyContent: 'center' }, footerItemIcon: { marginRight: 5, color: colors.textDefault }, footerItemText: { color: colors.textDefault } }) } })
the_stack
import { unset, set, setWith, entries, pickBy, includes, get } from 'lodash'; import { flatStepHeight, wheelChairWashBasin, evaluateWheelmapA11y, evaluateToiletWheelmapA11y } from '../rules/WheelmapA11yRuleset'; export type KoboAttachment = { mimetype: string; download_url: string; filename: string; instance: number; id: number; xform: number; }; type YesNoResult = 'true' | 'false' | 'undefined'; type YesNoPartiallyResult = 'true' | 'partially' | 'false' | 'undefined'; export type KoboResult = { _id: number; _uuid: string; _geolocation: [number, number]; _attachments: KoboAttachment[]; _notes?: unknown[]; _tags?: unknown[]; _xform_id_string?: string; _bamboo_dataset_id?: string; simserial?: string; phonenumber?: string; username: string; 'meta/instanceID': string; 'formhub/uuid': string; today: string; end: string; start: string; _status: string; __version__: string; deviceid: string; _validation_status: unknown; _submission_time: unknown; _submitted_by: unknown | null; subscriberid: string; // actual form values 'outside/geometry_point': string; 'user/user_measuring': 'inch' | 'cm'; 'user/user_record_type': string; 'outside/category/category_sub': string; 'outside/category/category_top': string; 'outside/entrance/has_fixed_ramp': YesNoResult; 'outside/entrance/has_automatic_door': YesNoResult; 'outside/entrance/has_door': YesNoResult; 'outside/entrance/has_entrance': YesNoResult; 'outside/entrance/has_mobile_ramp': YesNoResult; 'outside/entrance/has_steps': YesNoResult; 'outside/entrance/steps_low_height': YesNoResult; 'outside/entrance/picture': string; 'outside/entrance/steps_count': string; 'outside/entrance/steps_height': string; 'outside/name': string | object; 'inside/is_well_lit': YesNoResult; 'inside/is_quiet': YesNoResult; 'inside/toilet/basin_wheelchair_fits_belows': YesNoResult; 'inside/toilet/basin_wheelchair_reachable': YesNoResult; 'inside/toilet/basin_inside_cabin': YesNoResult; 'inside/toilet/door_width': string; 'inside/toilet/free_space_front': string; 'inside/toilet/free_space_left': string; 'inside/toilet/free_space_right': string; 'inside/toilet/has_arm_rests': string; 'inside/toilet/has_basin': YesNoResult; 'inside/toilet/has_toilet': YesNoResult; 'inside/toilet/seat_height': string; 'inside/toilet/stepless_access': YesNoResult; 'inside/toilet/toilet_photo': string; 'inside/has_wide_aisles': YesNoResult; 'inquire/are_service_animals_allowed': YesNoResult; 'inquire/media/has_audio': YesNoResult; 'inquire/media/has_braille': YesNoResult; 'inquire/media/has_large_print': YesNoResult; 'inquire/staff_can_speak_sign_lang': YesNoResult; 'inquire/staff_has_disabled_training': YesNoResult; 'inquire/staff_spoken_sign_langs': string; 'feedback/feedback_matrix/questions_fits_this_place': string; 'feedback/feedback_matrix/no_interaction_problems': string; is_wheelchair_accessible: YesNoPartiallyResult; wheelchair_comment: string; has_phone_number: YesNoResult; phone_number?: string; place_phone_number: string; place_website_url: string; place_email_address: string; }; // make keys typesafe to prevent typos export type KoboKey = keyof KoboResult; type FieldTypes = 'yesno' | 'float' | 'int'; const parseValue = (data: KoboResult, field: KoboKey, type: FieldTypes) => { const rawValue = data[field]; if (rawValue === null || typeof rawValue === 'undefined') { return rawValue; } if (typeof rawValue !== 'string') { return undefined; } if (type === 'yesno') { if (rawValue === 'true') { return true; } return rawValue === 'false' ? false : undefined; } if (type === 'float') { return parseFloat(rawValue); } if (type === 'int') { return parseInt(rawValue, 10); } return undefined; }; const parseYesNo = (data: KoboResult, field: KoboKey) => { return parseValue(data, field, 'yesno'); }; const parseHasWithDefault = ( data: KoboResult, field: KoboKey, existsValue: any, doesNotExistValue: any ) => { const value = parseValue(data, field, 'yesno'); if (value === true) { return existsValue; } if (value === false) { return doesNotExistValue; } return undefined; }; const parseHasArray = (data: KoboResult, field: KoboKey) => { return parseHasWithDefault(data, field, [], null); }; const parseHasEntry = (data: KoboResult, field: KoboKey) => { return parseHasWithDefault(data, field, {}, null); }; const parseIsAnyOfWithDefault = ( data: KoboResult, field: KoboKey, list: string[], existsValue: any, doesNotExistValue: any ) => { const rawValue = data[field]; if (rawValue === null || typeof rawValue === 'undefined') { return rawValue; } return includes(list, rawValue) ? existsValue : doesNotExistValue; }; const parseIsAnyOf = (data: KoboResult, field: KoboKey, list: string[]) => { return parseIsAnyOfWithDefault(data, field, list, true, false); }; const parseIsAnyOfEntry = (data: KoboResult, field: KoboKey, list: string[]) => { return parseIsAnyOfWithDefault(data, field, list, {}, undefined); }; const parseFloatUnit = (data: KoboResult, field: KoboKey, unit: string, operator?: string) => { const value = parseValue(data, field, 'float') as number; // remove undefined values const unitValue = pickBy({ operator, unit, value }); return value && !isNaN(value) ? unitValue : undefined; }; const parseIntUnit = (data: KoboResult, field: KoboKey, unit: string, operator?: string) => { const value = parseValue(data, field, 'int') as number; // remove undefined values const unitValue = pickBy({ operator, unit, value }); return value && !isNaN(value) ? unitValue : undefined; }; const parseMultiSelect = (data: KoboResult, field: KoboKey) => { const rawValue = data[field]; if (rawValue === null || typeof rawValue === 'undefined') { return rawValue; } if (typeof rawValue !== 'string') { return undefined; } return rawValue.split(' '); }; export const transformKoboToA11y = (data: KoboResult) => { const usedLengthUnit = data['user/user_measuring'] || 'cm'; const mapping = { geometry: data._geolocation ? { coordinates: data._geolocation.reverse(), type: 'Point' } : {}, 'properties.originalId': data._id && `${data._id}`, 'properties.infoPageUrl': null, 'properties.originalData': JSON.stringify(data), // basic place data 'properties.name': data['outside/name'], 'properties.phoneNumber': data['place_phone_number'] || data['phone_number'], 'properties.emailAddress': data['place_email_address'], 'properties.placeWebsiteUrl': data['place_website_url'], 'properties.category': data['outside/category/category_top'] || data['outside/category/category_sub'] || 'undefined', 'properties.description': data['wheelchair_comment'], 'properties.accessibility.accessibleWith.wheelchair': { true: true, false: false, partially: false }[data['is_wheelchair_accessible']], 'properties.accessibility.partiallyAccessibleWith.wheelchair': data['is_wheelchair_accessible'] === 'partially' ? true : undefined, // entrances 'properties.accessibility.isWellLit': parseYesNo(data, 'inside/is_well_lit'), 'properties.accessibility.isQuiet': parseYesNo(data, 'inside/is_quiet'), 'properties.accessibility.entrances': parseHasArray(data, 'outside/entrance/has_entrance'), 'properties.accessibility.entrances.0': parseHasEntry(data, 'outside/entrance/has_entrance'), 'properties.accessibility.entrances.0.hasFixedRamp': parseYesNo( data, 'outside/entrance/has_fixed_ramp' ), // stairs 'properties.accessibility.entrances.0.stairs': parseHasArray( data, 'outside/entrance/has_steps' ), 'properties.accessibility.entrances.0.stairs.0': parseHasEntry( data, 'outside/entrance/has_steps' ), 'properties.accessibility.entrances.0.stairs.0.count': parseValue( data, 'outside/entrance/steps_count', 'int' ), 'properties.accessibility.entrances.0.stairs.0.stepHeight': parseFloatUnit(data, 'outside/entrance/steps_height', usedLengthUnit) || parseHasWithDefault(data, 'outside/entrance/steps_low_height', flatStepHeight, undefined), 'properties.accessibility.entrances.0.hasRemovableRamp': parseYesNo( data, 'outside/entrance/has_mobile_ramp' ), // doors 'properties.accessibility.entrances.0.doors': parseHasArray(data, 'outside/entrance/has_door'), 'properties.accessibility.entrances.0.doors.0': parseHasEntry( data, 'outside/entrance/has_door' ), 'properties.accessibility.entrances.0.doors.0.isAutomaticOrAlwaysOpen': parseYesNo( data, 'outside/entrance/has_automatic_door' ), // restrooms 'properties.accessibility.restrooms': parseHasArray(data, 'inside/toilet/has_toilet'), 'properties.accessibility.restrooms.0': parseHasEntry(data, 'inside/toilet/has_toilet'), // entrance 'properties.accessibility.restrooms.0.entrance.isLevel': parseYesNo( data, 'inside/toilet/stepless_access' ), 'properties.accessibility.restrooms.0.entrance.door.width': parseFloatUnit( data, 'inside/toilet/door_width', usedLengthUnit ), // toilet 'properties.accessibility.restrooms.0.toilet': parseHasEntry(data, 'inside/toilet/has_toilet'), 'properties.accessibility.restrooms.0.toilet.heightOfBase': parseFloatUnit( data, 'inside/toilet/seat_height', usedLengthUnit ), 'properties.accessibility.restrooms.0.toilet.spaceOnUsersLeftSide': parseFloatUnit( data, 'inside/toilet/free_space_left', usedLengthUnit ), 'properties.accessibility.restrooms.0.toilet.spaceOnUsersRightSide': parseFloatUnit( data, 'inside/toilet/free_space_right', usedLengthUnit ), 'properties.accessibility.restrooms.0.toilet.spaceInFront': parseFloatUnit( data, 'inside/toilet/free_space_front', usedLengthUnit ), // bars 'properties.accessibility.restrooms.0.toilet.hasGrabBars': parseIsAnyOf( data, 'inside/toilet/has_arm_rests', ['left_and_right', 'right', 'left'] ), 'properties.accessibility.restrooms.0.toilet.grabBars': parseIsAnyOfEntry( data, 'inside/toilet/has_arm_rests', ['left_and_right', 'right', 'left'] ), 'properties.accessibility.restrooms.0.toilet.grabBars.onUsersLeftSide': parseIsAnyOf( data, 'inside/toilet/has_arm_rests', ['left_and_right', 'left'] ), 'properties.accessibility.restrooms.0.toilet.grabBars.onUsersRightSide': parseIsAnyOf( data, 'inside/toilet/has_arm_rests', ['left_and_right', 'right'] ), // washBasin 'properties.accessibility.restrooms.0.washBasin': parseHasEntry( data, 'inside/toilet/has_basin' ), 'properties.accessibility.restrooms.0.washBasin.accessibleWithWheelchair': parseYesNo( data, 'inside/toilet/basin_wheelchair_reachable' ), 'properties.accessibility.restrooms.0.washBasin.spaceBelow': parseHasWithDefault( data, 'inside/toilet/basin_wheelchair_fits_belows', wheelChairWashBasin, null ), 'properties.accessibility.restrooms.0.washBasin.isLocatedInsideRestroom': parseYesNo( data, 'inside/toilet/basin_inside_cabin' ), // animal policy 'properties.accessibility.animalPolicy.allowsServiceAnimals': parseYesNo( data, 'inquire/are_service_animals_allowed' ), // staff 'properties.accessibility.staff.isTrainedForDisabilities': parseYesNo( data, 'inquire/staff_has_disabled_training' ), 'properties.accessibility.staff.spokenLanguages': parseMultiSelect( data, 'inquire/staff_spoken_sign_langs' ), 'properties.accessibility.staff.isTrainedInSigning': parseYesNo( data, 'inquire/staff_can_speak_sign_lang' ), // media 'properties.accessibility.media.isLargePrint': parseYesNo( data, 'inquire/media/has_large_print' ), 'properties.accessibility.media.isAudio': parseYesNo(data, 'inquire/media/has_audio'), 'properties.accessibility.media.isBraille': parseYesNo(data, 'inquire/media/has_braille') }; const result = { properties: { hasAccessibility: true } }; // if there is a null in the history, do not set a value const customizedSetter = (currValue: any) => (currValue === null ? null : undefined); for (const [key, value] of entries(mapping)) { if (typeof value !== 'undefined') { setWith(result, key, value, customizedSetter); } } const userDefinedA11y = data['is_wheelchair_accessible']; if (!userDefinedA11y || userDefinedA11y === 'undefined') { // rate place a11y automatically const a11y = evaluateWheelmapA11y(result); // Currently, these fields are exlusive. if (a11y === 'yes') { set(result, 'properties.accessibility.accessibleWith.wheelchair', true); unset(result, 'properties.accessibility.partiallyAccessibleWith.wheelchair'); } else if (a11y === 'partial') { unset(result, 'properties.accessibility.accessibleWith.wheelchair'); set(result, 'properties.accessibility.partiallyAccessibleWith.wheelchair', true); } else if (a11y === 'no') { set(result, 'properties.accessibility.accessibleWith.wheelchair', false); unset(result, 'properties.accessibility.partiallyAccessibleWith.wheelchair'); } } else { // ensure that only one value is set to true if (get(result, 'properties.accessibility.accessibleWith.wheelchair') === true) { unset(result, 'properties.accessibility.partiallyAccessibleWith.wheelchair'); } else if ( get(result, 'properties.accessibility.partiallyAccessibleWith.wheelchair') === true ) { unset(result, 'properties.accessibility.accessibleWith.wheelchair'); } } if (Object.keys(get(result, 'properties.accessibility.accessibleWith') || {}).length === 0) { unset(result, 'properties.accessibility.accessibleWith'); } if ( Object.keys(get(result, 'properties.accessibility.partiallyAccessibleWith') || {}).length === 0 ) { unset(result, 'properties.accessibility.partiallyAccessibleWith'); } // rate place a11y const toiletA11y = evaluateToiletWheelmapA11y(result); // rate toilet a11y // TODO this field doesn't exist in ac format! Clarify & align with wheelmap frontend & a11yjson if (toiletA11y === 'yes') { setWith( result, 'properties.accessibility.restrooms.0.isAccessibleWithWheelchair', true, customizedSetter ); } else if (toiletA11y === 'no') { setWith( result, 'properties.accessibility.restrooms.0.isAccessibleWithWheelchair', false, customizedSetter ); } return result; };
the_stack
import Vue from "vue"; import Root, { Result } from "../root/root"; import { Component } from "vue-property-decorator"; import { ddragon, mapBackground, Role } from "@/constants"; import Timer from "./timer.vue"; import Members from "./members.vue"; import PlayerSettings from "./player-settings.vue"; import SummonerPicker from "./summoner-picker.vue"; import ChampionPicker from "./champion-picker.vue"; import RuneEditor from "./rune-editor.vue"; import Bench from "./bench.vue"; import SkinPicker from "./skin-picker.vue"; import MagicBackground from "../../static/magic-background.jpg"; export interface ChampSelectMember { assignedPosition: Role | ""; // blind pick has no role playerType: string; // either PLAYER or BOT cellId: number; championId: number; championPickIntent: number; selectedSkinId: number; displayName: string; summonerId: number; spell1Id: number; spell2Id: number; team: number; // added manually isFriendly: boolean; } export interface ChampSelectAction { id: number; actorCellId: number; championId: number; completed: boolean; type: "ban" | "pick" | "ten_bans_reveal"; // might be more types, only these two are used in conventional queues } // A 'turn' is simply an array of actions that happen at the same time. // In blind pick, this is all the players picking. In draft pick, every // turn only contains a single action (since no players pick at the same time). export type ChampSelectTurn = ChampSelectAction[]; export interface ChampSelectTimer { phase: "PLANNING" | "BAN_PICK" | "FINALIZATION" | "GAME_STARTING"; // might be more isInfinite: boolean; adjustedTimeLeftInPhase: number; // time left in ms } export interface ChampSelectState { actions: ChampSelectTurn[]; localPlayerCellId: number; localPlayer: ChampSelectMember; // added manually, not actually in the payload myTeam: ChampSelectMember[]; theirTeam: ChampSelectMember[]; timer: ChampSelectTimer; trades: { id: number; cellId: number; state: string; // this is an enum. }; benchEnabled: boolean; benchChampionIds: number[]; } export interface GameflowState { map: { id: number }; gameData: { queue: { gameMode: string; gameTypeConfig: { reroll: boolean; }; }; } } export interface RerollState { numberOfRolls: number; maxRolls: number; } export interface RunePage { id: number; name: string; isEditable: boolean; isActive: boolean; order: number; primaryStyleId: number; // -1 if not selected subStyleId: number; // -1 if not selected selectedPerkIds: number[]; // 0 or not included if not selected } export interface SkinItem { championId: number; id: number; name: string; isBase: boolean; disabled: boolean; ownership: { owned: boolean }; } @Component({ components: { timer: Timer, members: Members, playerSettings: PlayerSettings, summonerPicker: SummonerPicker, championPicker: ChampionPicker, runeEditor: RuneEditor, bench: Bench, skinPicker: SkinPicker } }) export default class ChampSelect extends Vue { $root: Root; state: ChampSelectState | null = null; gameflowState: GameflowState | null = null; rerollState: RerollState = { numberOfRolls: 0, maxRolls: 2 }; runePages: RunePage[] = []; currentRunePage: RunePage | null = null; skins: SkinItem[] = []; pickingSkin = false; // These two are used to map summoner/champion id -> data. championDetails: { [id: number]: { id: string, key: string, name: string } }; summonerSpellDetails: { [id: number]: { id: string, key: string, name: string } }; // Information for the summoner spell overlay. pickingSummonerSpell = false; pickingFirstSummonerSpell = false; // Information for the champion picker. pickingChampion = false; // Information for the rune editor. showingRuneOverlay = false; // Information for the reroll bench. showingBench = false; mounted() { this.loadStatic("champion.json").then(map => { // map to { id: data } const details: any = {}; Object.keys(map.data).forEach(x => details[+map.data[x].key] = map.data[x]); this.championDetails = details; }); this.loadStatic("summoner.json").then(map => { // map to { id: data } const details: any = {}; Object.keys(map.data).forEach(x => details[+map.data[x].key] = map.data[x]); this.summonerSpellDetails = details; }); // Start observing champion select. this.$root.observe("/lol-champ-select/v1/session", this.handleChampSelectChange.bind(this)); // Keep track of reroll points for if we play ARAM. this.$root.observe("/lol-summoner/v1/current-summoner/rerollPoints", result => { this.rerollState = result.status === 200 ? result.content : { numberOfRolls: 0, maxRolls: 2 }; }); // Observe runes this.$root.observe("/lol-perks/v1/pages", response => { response.status === 200 && (this.runePages = response.content); response.status === 200 && (this.runePages.sort((a, b) => a.order - b.order)); }); this.$root.observe("/lol-perks/v1/currentpage", response => { this.currentRunePage = response.status === 200 ? response.content : null; // Update the isActive param if needed. if (this.currentRunePage) { this.runePages.forEach(x => x.isActive = x.id === this.currentRunePage!.id); } }); } /** * Handles a change to the champion select and updates the state appropriately. * Note: this cannot be an arrow function for various changes. See the lobby component for more info. */ handleChampSelectChange = async function(this: ChampSelect, result: Result) { if (result.status !== 200) { this.state = null; return; } const newState: ChampSelectState = result.content; newState.localPlayer = newState.myTeam.filter(x => x.cellId === newState.localPlayerCellId)[0]; // If we haven't loaded skins before, do so now. if (!this.skins.length) { const url = `/lol-champions/v1/inventories/${newState.localPlayer.summonerId}/skins-minimal`; this.skins = await this.$root.request(url).then(x => x.content); this.$root.observe(url, data => { this.skins = data.status === 200 ? data.content : [] }); } // For everyone on our team, request their summoner name. await Promise.all(newState.myTeam.map(async mem => { if (mem.playerType === "BOT") { mem.displayName = (this.championDetails[mem.championId] || { name: "Unknown" }).name + " Bot"; } else { const summ = (await this.$root.request("/lol-summoner/v1/summoners/" + mem.summonerId)).content; mem.displayName = summ.displayName; } mem.isFriendly = true; })); // Give enemy summoners obfuscated names, if we don't know their names newState.theirTeam.forEach((mem, idx) => { mem.displayName = "Summoner " + (idx + 1); mem.isFriendly = false; }); // If we weren't in champ select before, fetch some data. if (!this.state) { // Gameflow, which contains information about the map and gamemode we are queued up for. this.$root.request("/lol-gameflow/v1/session").then(x => { x.status === 200 && (this.gameflowState = <GameflowState>x.content); }); } const oldAction = this.state ? this.getActions(this.state.localPlayer) : undefined; this.state = newState; const newAction = this.getActions(this.state.localPlayer); // If we didn't have an action and have one now, or if the actions differ in id, present the champion picker. if ((!oldAction && newAction) || (newAction && oldAction && oldAction.id !== newAction.id)) { this.pickingChampion = true; } }; /** * @returns the map background for the current queue */ get background(): string { if (!this.gameflowState) return "background-image: url(" + MagicBackground + ")"; return mapBackground(this.gameflowState.map.id); } // TODO: Maybe unify the following two functions? /** * @returns the current turn happening, or null if no single turn is currently happening (pre and post picks) */ get currentTurn(): ChampSelectTurn | null { if (!this.state || this.state.timer.phase !== "BAN_PICK") return null; // Find the first set of actions that has at least one not completed. return this.state.actions.filter(x => x.filter(y => !y.completed).length > 0)[0]; } /** * @returns the next turn happening, or null if there is no next turn. */ get nextTurn(): ChampSelectTurn | null { if (!this.state || this.state.timer.phase !== "BAN_PICK") return null; return this.state.actions.filter(x => x.filter(y => !y.completed).length > 0)[1]; } /** * @returns the action in the current turn for the specified member, or null if the member can't do anything */ getActions(member: ChampSelectMember, future = false): ChampSelectAction | null { const turn = future ? this.nextTurn : this.currentTurn; return turn ? turn.filter(x => x.actorCellId === member.cellId)[0] || null : null; } /** * @returns the member associated with the specified cellId */ getMember(cellId: number): ChampSelectMember { if (!this.state) throw new Error("Shouldn't happen"); return this.state.myTeam.filter(x => x.cellId === cellId)[0] || this.state.theirTeam.filter(x => x.cellId === cellId)[0]; } /** * Selects the specified rune page, by setting its `current` property to true and calling the collections backend. */ selectRunePage(event: Event) { const id = +(event.target as HTMLSelectElement).value; this.runePages.forEach(r => r.isActive = r.id === id); this.$root.request("/lol-perks/v1/currentpage", "PUT", "" + id); } /** * @returns whether the local summoner still needs to pick a champion or not */ get hasLockedChampion(): boolean { return !!this.state // A state exists. && this.state.actions.filter(x => // and we cannot find a pick turn in which x.filter(y => // there exists an action... y.actorCellId === this.state!.localPlayerCellId // by the current player && y.type === "pick" // that has to pick a champion && !y.completed // and hasn't been completed yet ).length > 0).length === 0; } /** * @returns whether everyone has picked their champion already */ get hasEveryonePicked(): boolean { return !!this.state // A state exists. && this.state.actions.filter(x => // and we cannot find a pick turn in which x.filter(y => // there exists an action... y.type === "pick" // that has to pick a champion && !y.completed // and hasn't been completed yet ).length > 0).length === 0; } /** * Helper method to load the specified json name from the ddragon static data. */ public loadStatic(filename: string): Promise<any> { return new Promise(resolve => { const req = new XMLHttpRequest(); req.onreadystatechange = () => { if (req.status !== 200 || !req.responseText || req.readyState !== 4) return; const map = JSON.parse(req.responseText); resolve(map); }; req.open("GET", "https://ddragon.leagueoflegends.com/cdn/" + ddragon() + "/data/en_US/" + filename, true); req.send(); }); } }
the_stack
import type * as mongoose from 'mongoose'; import type { Severity, WhatIsIt } from './internal/constants'; /** * Get the Type of an instance of a Document with Class properties * @example * ```ts * class ClassName {} * const NameModel = getModelForClass(ClassName); * * const doc: DocumentType<ClassName> = await NameModel.create({}); * ``` */ export type DocumentType<T, QueryHelpers = BeAnObject> = (T extends { _id: unknown } ? mongoose.Document<T['_id'], QueryHelpers> & T : mongoose.Document<any, QueryHelpers> & T) & IObjectWithTypegooseFunction; /** * Used Internally for ModelTypes */ export type ModelType<T, QueryHelpers = BeAnObject> = mongoose.Model<DocumentType<T, QueryHelpers>, QueryHelpers>; /** * Any-param Constructor */ export type AnyParamConstructor<T> = new (...args: any) => T; /** * The Type of a Model that gets returned by "getModelForClass" and "setModelForClass" */ export type ReturnModelType<U extends AnyParamConstructor<any>, QueryHelpers = BeAnObject> = ModelType<InstanceType<U>, QueryHelpers> & U; export type Func = (...args: any[]) => any; /** * The Type of a function to generate a custom model name. */ export type CustomNameFunction = (options: IModelOptions) => string; /** * Defer an reference with an function (or as other projects call it "Forward declaration") * @param type This is just to comply with the common pattern of `type => ActualType` */ export type DeferredFunc<T = any> = (...args: unknown[]) => T; /** * Dynamic Functions, since mongoose 4.13 * @param doc The Document current document */ export type DynamicStringFunc<T extends AnyParamConstructor<any>> = (doc: DocumentType<T>) => string; /** * This Interface for most properties uses "mongoose.SchemaTypeOptions<any>['']", but for some special (or typegoose custom) options, it is not used * * Example: `index` is directly from mongoose, where as `type` is from typegoose */ export interface BasePropOptions { /** * include this value? * @default true (Implicitly) */ select?: mongoose.SchemaTypeOptions<any>['select']; /** * is this value required? * @default false (Implicitly) */ required?: mongoose.SchemaTypeOptions<any>['required']; /** Only accept Values from the Enum(|Array) */ enum?: string[] | BeAnObject; /** * Add "null" to the enum array * Note: Custom Typegoose Option */ addNullToEnum?: boolean; /** Give the Property a default Value */ default?: mongoose.SchemaTypeOptions<any>['default']; // i know this one does not have much of an effect, because of "any" /** Give an Validator RegExp or Function */ validate?: mongoose.SchemaTypeOptions<any>['validate']; /** * Should this property have an "unique" index? * @link https://docs.mongodb.com/manual/indexes/#unique-indexes */ unique?: mongoose.SchemaTypeOptions<any>['unique']; /** * Should this property have an index? * Note: dont use this if you want to do an compound index * @link https://docs.mongodb.com/manual/indexes */ index?: mongoose.SchemaTypeOptions<any>['index']; /** * Should this property have an "sparse" index? * @link https://docs.mongodb.com/manual/indexes/#sparse-indexes */ sparse?: mongoose.SchemaTypeOptions<any>['sparse']; /** * Should this property have an "expires" index? * @link https://docs.mongodb.com/manual/tutorial/expire-data */ expires?: mongoose.SchemaTypeOptions<any>['expires']; /** * Should this property have an "text" index? * @link https://mongoosejs.com/docs/api.html#schematype_SchemaType-text */ text?: mongoose.SchemaTypeOptions<any>['text']; /** Should subdocuments get their own id? * @default true (Implicitly) */ _id?: mongoose.SchemaTypeOptions<any>['_id']; /** * Set a Setter (Non-Virtual) to pre-process your value * (when using get/set both are required) * Please note that the option `type` is required, if get/set saves a different value than what is defined * @param value The Value that needs to get modified * @returns The Value, but modified OR anything * @example * ```ts * function setHello(val: string): string { * return val.toLowerCase() * } * function getHello(val: string): string { * return val.toUpperCase(); * } * class Dummy { * @prop({ set: setHello, get: getHello }) // many options can be used, like required * public hello: string; * } * ``` */ set?(val: any): any; /** * Set a Getter (Non-Virtual) to Post-process your value * (when using get/set both are required) * Please note that the option `type` is required, if get/set saves a different value than what is defined * @param value The Value that needs to get modified * @returns The Value, but modified OR anything * @example * ```ts * function setHello(val: string): string { * return val.toLowerCase() * } * function getHello(val: string): string { * return val.toUpperCase(); * } * class Dummy { * @prop({ set: setHello, get: getHello }) // many options can be used, like required * public hello: string; * } * ``` */ get?(val: any): any; /** * This may be needed if get/set is used * (this sets the type how it is saved to the DB) */ type?: DeferredFunc<AnyParamConstructor<any>> | DeferredFunc<unknown> | unknown; /** * Make a property read-only * @example * ```ts * class SomeClass { * @prop({ immutable: true }) * public someprop: Readonly<string>; * } * ``` */ immutable?: mongoose.SchemaTypeOptions<any>['immutable']; /** * Give the Property an alias in the output * * Note: you should include the alias as a variable in the class, but not with a prop decorator * @example * ```ts * class Dummy { * @prop({ alias: "helloWorld" }) * public hello: string; // normal, with @prop * public helloWorld: string; // is just for type Completion, will not be included in the DB * } * ``` */ alias?: mongoose.SchemaTypeOptions<any>['alias']; /** * This option as only an effect when the plugin `mongoose-autopopulate` is used */ // eslint-disable-next-line @typescript-eslint/ban-types autopopulate?: boolean | Function | KeyStringAny; /** Reference an other Document (you should use Ref<T> as Prop type) */ ref?: DeferredFunc<string | AnyParamConstructor<any> | DynamicStringFunc<any>> | string | AnyParamConstructor<any>; /** Take the Path and try to resolve it to a Model */ refPath?: string; /** * Set the Nested Discriminators * * Note: "_id: false" as an prop option dosnt work here * * Note: Custom Typegoose Option */ discriminators?: DeferredFunc<(AnyParamConstructor<any> | DiscriminatorObject)[]>; /** * Use option {@link BasePropOptions.type} * @see https://typegoose.github.io/typegoose/docs/api/decorators/prop#map-options * @see https://typegoose.github.io/typegoose/docs/api/decorators/prop#whatisit */ of?: never; /** * If true, uses Mongoose's default `_id` settings. Only allowed for ObjectIds * * Note: Copied from mongoose's "index.d.ts"#SchemaTypeOptions */ auto?: mongoose.SchemaTypeOptions<any>['auto']; /** * The default [subtype](http://bsonspec.org/spec.html) associated with this buffer when it is stored in MongoDB. Only allowed for buffer paths * * Note: Copied from mongoose's "index.d.ts"#SchemaTypeOptions */ subtype?: mongoose.SchemaTypeOptions<any>['subtype']; /** * If `true`, Mongoose will skip gathering indexes on subpaths. Only allowed for subdocuments and subdocument arrays. * * Note: Copied from mongoose's "index.d.ts"#SchemaTypeOptions */ excludeIndexes?: mongoose.SchemaTypeOptions<any>['excludeIndexes']; /** * Define a transform function for this individual schema type. * Only called when calling `toJSON()` or `toObject()`. * * Note: Copied from mongoose's "index.d.ts"#SchemaTypeOptions */ transform?: mongoose.SchemaTypeOptions<any>['transform']; // for plugins / undocumented types [extra: string]: any; } export interface InnerOuterOptions { /** * Use this to define inner-options * Use this if the auto-mapping is not correct or for plugin options * * Please open a new issue if some option is mismatched or not existing / mapped */ innerOptions?: KeyStringAny; /** * Use this to define outer-options * Use this if the auto-mapping is not correct or for plugin options * * Please open a new issue if some option is mismatched or not existing / mapped */ outerOptions?: KeyStringAny; } export interface ArrayPropOptions extends BasePropOptions, InnerOuterOptions { /** * How many dimensions this Array should have * (needs to be higher than 0) * * Note: Custom Typegoose Option * @default 1 */ dim?: number; /** * Set if Non-Array values will be cast to an array * * NOTE: This option currently only really affects "DocumentArray" and not normal arrays, https://github.com/Automattic/mongoose/issues/10398 * @see https://mongoosejs.com/docs/api/schemaarray.html#schemaarray_SchemaArray.options * @example * ```ts * new Model({ array: "string" }); * // will be cast to equal * new Model({ array: ["string"] }); * ``` * @default true */ castNonArrays?: boolean; } export interface MapPropOptions extends BasePropOptions, InnerOuterOptions {} export interface ValidateNumberOptions { /** Only allow numbers that are higher than this */ min?: mongoose.SchemaTypeOptions<any>['min']; /** Only allow numbers lower than this */ max?: mongoose.SchemaTypeOptions<any>['max']; /** Only allow Values from the enum */ enum?: number[]; } export interface ValidateStringOptions { /** Only allow values that match this RegExp */ match?: RegExp | [RegExp, string]; /** Only allow Values from the enum */ enum?: string[]; /** Only allow values that have at least this length */ minlength?: mongoose.SchemaTypeOptions<any>['minlength']; /** Only allow values that have at max this length */ maxlength?: mongoose.SchemaTypeOptions<any>['maxlength']; } export interface TransformStringOptions { /** Should it be lowercased before save? */ lowercase?: mongoose.SchemaTypeOptions<any>['lowercase']; /** Should it be uppercased before save? */ uppercase?: mongoose.SchemaTypeOptions<any>['uppercase']; /** Should it be trimmed before save? */ trim?: mongoose.SchemaTypeOptions<any>['trim']; } export interface VirtualOptions { /** Reference another Document (Ref<T> should be used as property type) */ ref: NonNullable<BasePropOptions['ref']>; /** Which property(on the current-Class) to match `foreignField` against */ localField: string | DynamicStringFunc<any>; /** Which property(on the ref-Class) to match `localField` against */ foreignField: string | DeferredFunc<string>; /** Return as One Document(true) or as Array(false) */ justOne?: mongoose.VirtualTypeOptions['justOne']; /** Return the number of Documents found instead of the actual Documents */ count?: mongoose.VirtualTypeOptions['count']; /** Extra Query Options */ options?: mongoose.VirtualTypeOptions['options']; /** Match Options */ match?: KeyStringAny | ((doc) => KeyStringAny); /** * If you set this to `true`, Mongoose will call any custom getters you defined on this virtual. * * Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions */ getters?: mongoose.VirtualTypeOptions['getters']; /** * Add a default `limit` to the `populate()` query. * * Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions */ limit?: mongoose.VirtualTypeOptions['limit']; /** * Add a default `skip` to the `populate()` query. * * Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions */ skip?: mongoose.VirtualTypeOptions['skip']; /** * For legacy reasons, `limit` with `populate()` may give incorrect results because it only * executes a single query for every document being populated. If you set `perDocumentLimit`, * Mongoose will ensure correct `limit` per document by executing a separate query for each * document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` * will execute 2 additional queries if `.find()` returns 2 documents. * * Note: Copied from mongoose's "index.d.ts"#VirtualTypeOptions */ perDocumentLimit?: mongoose.VirtualTypeOptions['perDocumentLimit']; // for plugins / undocumented types [extra: string]: any; } export type PropOptionsForNumber = BasePropOptions & ValidateNumberOptions; export type PropOptionsForString = BasePropOptions & TransformStringOptions & ValidateStringOptions; export type RefType = mongoose.RefType; /** * Reference another Model */ export type Ref< PopulatedType, RawId extends mongoose.RefType = | (PopulatedType extends { _id?: mongoose.RefType } ? NonNullable<PopulatedType['_id']> : mongoose.Types.ObjectId) | undefined > = mongoose.PopulatedDoc<PopulatedType, RawId>; /** * An Function type for a function that doesn't have any arguments and doesn't return anything */ export type EmptyVoidFn = () => void; export interface DiscriminatorObject { /** The Class to use */ type: AnyParamConstructor<any>; /** * The Name to differentiate between other classes * Mongoose JSDOC: [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. * @default {string} The output of "getName" */ value?: string; } export interface IModelOptions { /** An Existing Mongoose Connection */ existingMongoose?: mongoose.Mongoose; /** Supports all Mongoose's Schema Options */ schemaOptions?: mongoose.SchemaOptions; /** An Existing Connection */ existingConnection?: mongoose.Connection; /** Typegoose Custom Options */ options?: ICustomOptions; } export interface ICustomOptions { /** * Set the modelName of the class. * If it is a function, the function will be executed. The function will override * "automaticName". If "automaticName" is true and "customName" is a string, it * sets a *suffix* instead of the whole name. * @default schemaOptions.collection */ customName?: string | CustomNameFunction; /** * Enable Automatic Name generation of a model * Example: * class with name of "SomeClass" * and option "collection" of "SC" * * will generate the name of "SomeClass_SC" * @default false */ automaticName?: boolean; /** Allow "mongoose.Schema.Types.Mixed"? */ allowMixed?: Severity; /** Run "model.syncIndexes" when model is finished compiling? */ runSyncIndexes?: boolean; } export interface DecoratedPropertyMetadata { /** Prop Options */ options: any; /** Target Class */ target: AnyParamConstructor<any>; /** Property name */ key: string | symbol; /** What is it for a prop type? */ whatis?: WhatIsIt; } export type DecoratedPropertyMetadataMap = Map<string | symbol, DecoratedPropertyMetadata>; /** * copy-paste from mongodb package (should be same as IndexOptions from 'mongodb') */ export interface IndexOptions<T> extends mongoose.IndexOptions { /** * Mongoose-specific syntactic sugar, uses ms to convert * expires option into seconds for the expireAfterSeconds in the above link. */ expires?: string; weights?: Partial<Record<keyof T, number>>; } /** * Used for the Reflection of Indexes * @example * ```ts * const indices: IIndexArray[] = Reflect.getMetadata(DecoratorKeys.Index, target) || []); * ``` */ export interface IIndexArray<T> { fields: KeyStringAny; options?: IndexOptions<T>; } /** * Used for the Reflection of Plugins * @example * ```ts * const plugins: IPluginsArray<any>[] = Array.from(Reflect.getMetadata(DecoratorKeys.Plugins, target) ?? []); * ``` */ export interface IPluginsArray<T> { mongoosePlugin: Func; options: T; } /** * Used for the Reflection of Virtual Populates * @example * ```ts * const virtuals: VirtualPopulateMap = new Map(Reflect.getMetadata(DecoratorKeys.VirtualPopulate, target.constructor) ?? []); * ``` */ export type VirtualPopulateMap = Map<string, any & VirtualOptions>; /** * Gets the signature (parameters with their types, and the return type) of a function type. * * @description Should be used when defining an interface for a class that uses query methods. * * @example * ```ts * function sendMessage(recipient: string, sender: string, priority: number, retryIfFails: boolean) { * // some logic... * return true; * } * * // Both of the following types will be identical. * type SendMessageType = AsQueryMethod<typeof sendMessage>; * type SendMessageManualType = (recipient: string, sender: string, priority: number, retryIfFails: boolean) => boolean; * ``` */ export type AsQueryMethod<T extends (...args: any) => any> = (...args: Parameters<T>) => ReturnType<T>; /** * Used for the Reflection of Query Methods * @example * ```ts * const queryMethods: QueryMethodMap = new Map(Reflect.getMetadata(DecoratorKeys.QueryMethod, target) ?? []); * ``` */ export type QueryMethodMap = Map<string, Func>; /** * Used for the Reflection of Nested Discriminators * @example * ```ts * const disMap: NestedDiscriminatorsMap = new Map(Reflect.getMetadata(DecoratorKeys.NestedDiscriminators, target) ?? []); * ``` */ export type NestedDiscriminatorsMap = Map<string, DiscriminatorObject[]>; /** A Helper type to combine both mongoose Hook Option types */ export type HookOptionsEither = mongoose.SchemaPreOptions | mongoose.SchemaPostOptions; /** * Used for the Reflection of Hooks * @example * ```ts * const postHooks: IHooksArray[] = Array.from(Reflect.getMetadata(DecoratorKeys.HooksPost, target) ?? []); * ``` */ export interface IHooksArray { /** The Function to add as a hooks */ func: Func; /** The Method to where this hook gets triggered */ method: string | RegExp; /** * Options for Hooks * @see https://mongoosejs.com/docs/middleware.html#naming */ options: HookOptionsEither; } export interface IGlobalOptions { /** Typegoose Options */ options?: ICustomOptions; /** Schema Options that should get applied to all models */ schemaOptions?: mongoose.SchemaOptions; /** * Global Options for general Typegoose * (There are currently none) */ globalOptions?: BeAnObject; } export interface IObjectWithTypegooseFunction { typegooseName(): string; } export interface IObjectWithTypegooseName { typegooseName: string; } /** For the types that error that seemingly dont have a prototype */ export interface IPrototype { prototype?: any; } /** An Helper Interface for key: any: string */ export interface KeyStringAny { [key: string]: any; } /** * The Return Type of "utils.getType" */ export interface GetTypeReturn { type: unknown; dim: number; } /** * This type is for lint error "ban-types" */ export type BeAnObject = Record<string, any>;
the_stack
import { Session } from '@ory/kratos-client' export interface MailMessage { fromAddress: string toAddresses: Array<string> body: string subject: string } declare global { namespace Cypress { interface Chainable { /** * Delete mails from the email server. * * @param options */ deleteMail(options: { atLeast?: boolean }): Chainable<void> /** * Adds end enables a WebAuth authenticator key. */ addVirtualAuthenticator(): Chainable<any> /** * Fetch the browser's Ory Session. * * @param opts */ getSession(opts?: { expectAal?: 'aal2' | 'aal1' expectMethods?: Array< 'password' | 'webauthn' | 'lookup_secret' | 'totp' > }): Chainable<Session> /** * Expect that the browser has no valid Ory Kratos Cookie Session. */ noSession(): Chainable<Response<any>> /** * Log a user in * * @param opts */ login(opts: { email: string password: string expectSession?: boolean cookieUrl?: string }): Chainable<Response<Session | undefined>> /** * Sign up a user * * @param opts */ register(opts: { email: string password: string query?: { [key: string]: string } fields?: { [key: string]: any } }): Chainable<Response<void>> /** * Updates a user's settings using an API flow * * @param opts */ settingsApi(opts: { fields?: { [key: string]: any } }): Chainable<Response<void>> /** * Set the "privileged session lifespan" to a large value. */ longPrivilegedSessionTime(): Chainable<void> /** * Return and optionally delete an email from the fake email server. * * @param opts */ getMail(opts?: { removeMail: boolean }): Chainable<MailMessage> performEmailVerification(opts?: { expect?: { email?: string; redirectTo?: string } }): Chainable<void> /** * Sets the Ory Kratos configuration profile. * * @param profile */ useConfigProfile(profile: string): Chainable<void> /** * Register a new user with email + password via the API. * * Recommended to use if you need an Ory Session Token or alternatively the user created. * * @param opts */ registerApi(opts?: { email: string password: string fields: { [key: string]: string } }): Chainable<Session> /** * Submits a recovery flow via the API * * @param opts */ recoverApi(opts: { email: string; returnTo?: string }): Chainable<void> /** * Submits a verification flow via the API * * @param opts */ verificationApi(opts: { email: string returnTo?: string }): Chainable<void> /** * Update the config file * * @param cb */ updateConfigFile(cb: (arg: any) => any): Chainable<any> /** * Submits a verification flow via the API * * @param opts */ verificationApiExpired(opts: { email: string returnTo?: string }): Chainable<void> /** * Submits a verification flow via the Browser * * @param opts */ verificationBrowser(opts: { email: string returnTo?: string }): Chainable<void> /** * Changes the config so that the login flow lifespan is very short. * * * Useful when testing expiry of login flows. * @see longLoginLifespan() */ shortLoginLifespan(): Chainable<void> /** * Changes the config so that the login flow lifespan is very long. * * Useful when testing expiry of login flows. * * @see shortLoginLifespan() */ longLoginLifespan(): Chainable<void> /** * Change the config so that `https://www.ory.sh/` is a allowed return to URL. */ browserReturnUrlOry(): Chainable<void> /** * Change the courier recovery invalid and valid templates to remote base64 strings */ remoteCourierRecoveryTemplates(): Chainable<void> /** * Changes the config so that the registration flow lifespan is very short. * * Useful when testing expiry of registration flows. * * @see longRegisterLifespan() */ shortRegisterLifespan(): Chainable<void> /** * Changes the config so that the registration flow lifespan is very long. * * Useful when testing expiry of registration flows. * * @see shortRegisterLifespan() */ longRegisterLifespan(): Chainable<void> /** * Changes the config so that the settings privileged lifespan is very long. * * Useful when testing privileged settings flows. * * @see longPrivilegedSessionTime() */ shortPrivilegedSessionTime(): Chainable<void> /** * Re-authenticates a user. * * @param opts */ reauth(opts: { expect: { email; success?: boolean } }): Chainable<void> /** * Re-authenticates a user. * * @param opts */ reauthWithOtherAccount(opts: { previousUrl: string expect: { email; success?: boolean } type: { email?: string; password?: string } }): Chainable<void> /** * Do not require 2fa for /session/whoami */ sessionRequiresNo2fa(): Chainable<void> /** * Require 2fa for /session/whoami if available */ sessionRequires2fa(): Chainable<void> /** * Like sessionRequires2fa but sets this also for settings */ requireStrictAal(): Chainable<void> /** * Like sessionRequiresNo2fa but sets this also for settings */ useLaxAal(): Chainable<void> /** * Gets the lookup codes from the settings page */ getLookupSecrets(): Chainable<Array<string>> /** * Expect the settings to be saved. */ expectSettingsSaved(): Chainable<void> clearCookies( options?: Partial<Loggable & Timeoutable & { domain: null | string }> ): Chainable<null> /** * A workaround for cypress not being able to clear cookies properly */ clearAllCookies(): Chainable<null> /** * Submits a password form by clicking the button with method=password */ submitPasswordForm(): Chainable<null> /** * Submits a profile form by clicking the button with method=profile */ submitProfileForm(): Chainable<null> /** * Expect a CSRF error to occur * * @param opts */ shouldHaveCsrfError(opts: { app: string }): Chainable<void> /** * Expects the app to error if a return_to is used which isn't allowed. * * @param init * @param opts */ shouldErrorOnDisallowedReturnTo( init: string, opts: { app: string } ): Chainable<void> /** * Expect that the second factor login screen is shown */ shouldShow2FAScreen(): Chainable<void> /** Click a webauthn button * * @param type */ clickWebAuthButton(type: 'login' | 'register'): Chainable<void> /** * Sign up a user using Social Sign In * * @param opts */ registerOidc(opts: { email?: string website?: string scopes?: Array<string> rememberLogin?: boolean rememberConsent?: boolean acceptLogin?: boolean acceptConsent?: boolean expectSession?: boolean route?: string }): Chainable<void> /** * Sign in a user using Social Sign In * * @param opts */ loginOidc(opts: { expectSession?: boolean url?: string }): Chainable<void> /** * Triggers a Social Sign In flow for the given provider * * @param app * @param provider */ triggerOidc(app: 'react' | 'express', provider?: string): Chainable<void> /** * Changes the config so that the recovery privileged lifespan is very long. * * Useful when testing privileged recovery flows. * * @see shortPrivilegedRecoveryTime() */ longRecoveryLifespan(): Chainable<void> /** * Changes the config so that the recovery privileged lifespan is very short. * * Useful when testing privileged recovery flows. * * @see shortPrivilegedRecoveryTime() */ shortRecoveryLifespan(): Chainable<void> /** * Changes the config so that the verification privileged lifespan is very long. * * Useful when testing recovery/verification flows. * * @see shortLinkLifespan() */ longVerificationLifespan(): Chainable<void> /** * Changes the config so that the verification privileged lifespan is very short. * * Useful when testing privileged verification flows. * * @see shortPrivilegedVerificationTime() */ shortVerificationLifespan(): Chainable<void> /** * Log a user out */ logout(): Chainable<void> /** * Deletes all mail in the mail mock server. * * @param opts */ deleteMail(opts?: { atLeast?: number }): Chainable<void> /** * Changes the config so that the link lifespan is very long. * * Useful when testing recovery/verification flows. * * @see shortLinkLifespan() */ longLinkLifespan(): Chainable<void> /** * Changes the config so that the link lifespan is very short. * * Useful when testing recovery/verification flows. * * @see longLinkLifespan() */ shortLinkLifespan(): Chainable<void> /** * Expect a recovery email which is expired. * * @param opts */ recoverEmailButExpired(opts?: { expect: { email: string } }): Chainable<void> /** * Expect a verification email which is expired. * * @param opts */ verifyEmailButExpired(opts?: { expect: { password?: string; email: string } }): Chainable<string> /** * Disables verification */ disableVerification(): Chainable<void> /** * Enables verification */ enableVerification(): Chainable<void> /** * Enables recovery */ enableRecovery(): Chainable<void> /** * Disabled recovery */ disableRecovery(): Chainable<void> /** * Disables registration */ disableRegistration(): Chainable<void> /** * Enables registration */ enableRegistration(): Chainable<void> /** * Expect a recovery email which is valid. * * @param opts */ recoverEmail(opts: { expect: { email: string } shouldVisit?: boolean }): Chainable<string> /** * Expect a verification email which is valid. * * @param opts */ verifyEmail(opts: { expect: { email: string; password?: string; redirectTo?: string } shouldVisit?: boolean }): Chainable<string> /** * Configures a hook which only allows verified email addresses to sign in. */ enableLoginForVerifiedAddressOnly(): Chainable<void> /** * Sign a user in via the API and return the session. * * @param opts */ loginApi(opts: { email: string password: string }): Chainable<{ session: Session }> /** * Same as loginApi but uses dark magic to avoid cookie issues. * * @param opts */ loginApiWithoutCookies(opts: { email: string password: string }): Chainable<{ session: Session }> /** * Which app to proxy */ proxy(app: 'react' | 'express'): Chainable<void> /** * Log a user in on mobile * * @param opts */ loginMobile(opts: { email: string; password: string }): Chainable<void> /** * Set the identity schema * @param schema */ setIdentitySchema(schema: string): Chainable<void> /** * Set the default schema * @param id */ setDefaultIdentitySchema(id: string): Chainable<void> } } }
the_stack
import { Tree } from '@angular-devkit/schematics'; import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import { EOL } from 'os'; import { collectionPath } from './common'; const templateFileName = '__specFileName__.template'; describe('Option: classTemplate', () => { let treeWithCustomClassTemplate: Tree; beforeEach(() => { treeWithCustomClassTemplate = Tree.empty(); treeWithCustomClassTemplate.create( 'example.component.ts', classContent() ); treeWithCustomClassTemplate.create( templateFileName, `<% params.forEach(p => { if(p.importPath) {%>import { <%= p.type %> } from '<%= p.importPath %>'; <% }}) %>import { <%= className %> } from './<%= normalizedName %>'; import { autoSpy } from 'autoSpy'; describe('<%= className %>', () => { <% publicMethods.forEach(meth=> {if(meth != '') { %>it('when <%= meth %> is called it should', () => { // arrange const { build } = setup().default(); const <%= shorthand %> = build(); // act <%= shorthand %>.<%= meth %>(); // assert // expect(<%= shorthand %>).toEqual }); <% } else { %> it('it should construct', () => { // arrange const { build } = setup().default(); // act const <%= shorthand %> = build(); // assert // expect(<%= shorthand %>).toEqual }); <% }}) %> }); // add a comment here function setup() { <%= declaration %> const builder = { <%= builderExports %> default() { return builder; }, build() { return new <%= className %>(<%= constructorParams %>); } }; return builder; } ` ); }); it('when class template missing it should stop', async () => { // arrange const runner = new SchematicTestRunner('schematics', collectionPath); // act return await runner .runSchematicAsync( 'spec', { name: 'example.component.ts', classTemplate: 'missing-file-path' }, treeWithCustomClassTemplate ) .toPromise() // assert .then(() => fail('should throw since the template file is missing')) .catch((e) => { expect(e).toBeDefined(); expect(e.message).toMatch('Class template configuration was'); expect(e.message).toMatch('missing-file-path'); }); }); it('when class template passed in it should use it', async () => { // arrange const runner = new SchematicTestRunner('schematics', collectionPath); // act const result = await runner .runSchematicAsync( 'spec', { name: 'example.component.ts', classTemplate: '__specFileName__.template' }, treeWithCustomClassTemplate ) .toPromise(); // assert expect(result.exists('example.component.spec.ts')).toBe(true); const content = result .readContent('example.component.spec.ts') .replace(EOL, '\n') .split('\n'); let i = 0; expect(content[i++]).toEqual(`import { ADep } from '../my/relative/path';`); expect(content[i++]).toEqual(`import { DDep } from '@angular/router';`); expect(content[i++]).toEqual(`import { ExampleComponent } from './example.component';`); expect(content[i++]).toEqual(`import { autoSpy } from 'autoSpy';`); expect(content[i++]).toEqual(``); expect(content[i++]).toEqual(`describe('ExampleComponent', () => {`); expect(content[i++]).toEqual(` it('when aMethod is called it should', () => {`); expect(content[i++]).toEqual(` // arrange`); expect(content[i++]).toEqual(` const { build } = setup().default();`); expect(content[i++]).toEqual(` const e = build();`); expect(content[i++]).toEqual(` // act`); expect(content[i++]).toEqual(` e.aMethod();`); expect(content[i++]).toEqual(` // assert`); expect(content[i++]).toEqual(` // expect(e).toEqual`); expect(content[i++]).toEqual(` });`); expect(content[i++]).toEqual(` `); expect(content[i++]).toEqual(`});`); expect(content[i++]).toEqual(``); expect(content[i++]).toEqual(`// add a comment here`); expect(content[i++]).toEqual(`function setup() {`); expect(content[i++]).toEqual(` const aDep = autoSpy(ADep);`); expect(content[i++]).toEqual(`const d = autoSpy(DDep);`); expect(content[i++]).toEqual(` const builder = {`); expect(content[i++]).toMatch(` aDep,`); expect(content[i++]).toEqual(`d,`); expect(content[i++]).toEqual(` default() {`); expect(content[i++]).toEqual(` return builder;`); expect(content[i++]).toEqual(` },`); expect(content[i++]).toEqual(` build() {`); expect(content[i++]).toEqual(` return new ExampleComponent(aDep,d);`); expect(content[i++]).toEqual(` }`); expect(content[i++]).toEqual(` };`); expect(content[i++]).toEqual(``); expect(content[i++]).toEqual(` return builder;`); expect(content[i++]).toEqual(`}`); }); it('when class template in config use it', async () => { // arrange const runner = new SchematicTestRunner('schematics', collectionPath); // act const result = await runner .runSchematicAsync( 'spec', { name: 'example.component.ts', config: 'tests/spec/test-data/valid-config-valid-class-template.json' }, treeWithCustomClassTemplate ) .toPromise(); // assert expect(result.exists('example.component.spec.ts')).toBe(true); const content = result .readContent('example.component.spec.ts') .replace(EOL, '\n') .split('\n'); let i = 0; expect(content[i++]).toEqual(`import { ADep } from '../my/relative/path';`); expect(content[i++]).toEqual(`import { DDep } from '@angular/router';`); expect(content[i++]).toEqual(`import { ExampleComponent } from './example.component';`); expect(content[i++]).toEqual(`import { autoSpy } from 'autoSpy';`); expect(content[i++]).toEqual(``); expect(content[i++]).toEqual(`describe('ExampleComponent', () => {`); expect(content[i++]).toEqual(` it('when aMethod is called it should', () => {`); expect(content[i++]).toEqual(` // arrange`); expect(content[i++]).toEqual(` const { build } = setup().default();`); expect(content[i++]).toEqual(` const e = build();`); expect(content[i++]).toEqual(` // act`); expect(content[i++]).toEqual(` e.aMethod();`); expect(content[i++]).toEqual(` // assert`); expect(content[i++]).toEqual(` // expect(e).toEqual`); expect(content[i++]).toEqual(` });`); expect(content[i++]).toEqual(` `); expect(content[i++]).toEqual(`});`); expect(content[i++]).toEqual(``); expect(content[i++]).toEqual(`// add a comment here`); expect(content[i++]).toEqual(`function setup() {`); expect(content[i++]).toEqual(` const aDep = autoSpy(ADep);`); expect(content[i++]).toEqual(`const d = autoSpy(DDep);`); expect(content[i++]).toEqual(` const builder = {`); expect(content[i++]).toMatch(` aDep,`); expect(content[i++]).toEqual(`d,`); expect(content[i++]).toEqual(` default() {`); expect(content[i++]).toEqual(` return builder;`); expect(content[i++]).toEqual(` },`); expect(content[i++]).toEqual(` build() {`); expect(content[i++]).toEqual(` return new ExampleComponent(aDep,d);`); expect(content[i++]).toEqual(` }`); expect(content[i++]).toEqual(` };`); expect(content[i++]).toEqual(``); expect(content[i++]).toEqual(` return builder;`); expect(content[i++]).toEqual(`}`); }); it('when class template has update templates - skip them from create result', async () => { // arrange const runner = new SchematicTestRunner('schematics', collectionPath); // act treeWithCustomClassTemplate.overwrite(templateFileName, templateWithCustomUpdateTemplates()); const result = await runner .runSchematicAsync( 'spec', { name: 'example.component.ts', config: 'tests/spec/test-data/valid-config-valid-class-template.json' }, treeWithCustomClassTemplate ) .toPromise(); // assert expect(result.exists('example.component.spec.ts')).toBe(true); const content = result .readContent('example.component.spec.ts') .replace(EOL, '\n') .split('\n'); let i = 0; expect(content[i++]).toEqual(`import { ADep } from '../my/relative/path';`); expect(content[i++]).toEqual(`import { DDep } from '@angular/router';`); expect(content[i++]).toEqual(`import { ExampleComponent } from './example.component';`); expect(content[i++]).toEqual(`import { autoSpy } from 'autoSpy';`); expect(content[i++]).toEqual(``); expect(content[i++]).toEqual(`describe('ExampleComponent', () => {`); expect(content[i++]).toEqual(` it('when aMethod is called it should', () => {`); expect(content[i++]).toEqual(` // arrange`); expect(content[i++]).toEqual(` const { build } = setup().default();`); expect(content[i++]).toEqual(` const e = build();`); expect(content[i++]).toEqual(` // act`); expect(content[i++]).toEqual(` e.aMethod();`); expect(content[i++]).toEqual(` // assert`); expect(content[i++]).toEqual(` // expect(e).toEqual`); expect(content[i++]).toEqual(` });`); expect(content[i++]).toEqual(` `); expect(content[i++]).toEqual(`});`); expect(content[i++]).toEqual(``); expect(content[i++]).toEqual(`// add a comment here`); expect(content[i++]).toEqual(`function setup() {`); expect(content[i++]).toEqual(` const aDep = autoSpy(ADep);`); expect(content[i++]).toEqual(`const d = autoSpy(DDep);`); expect(content[i++]).toEqual(` const builder = {`); expect(content[i++]).toMatch(` aDep,`); expect(content[i++]).toEqual(`d,`); expect(content[i++]).toEqual(` default() {`); expect(content[i++]).toEqual(` return builder;`); expect(content[i++]).toEqual(` },`); expect(content[i++]).toEqual(` build() {`); expect(content[i++]).toEqual(` return new ExampleComponent(aDep,d);`); expect(content[i++]).toEqual(` }`); expect(content[i++]).toEqual(` };`); expect(content[i++]).toEqual(``); expect(content[i++]).toEqual(` return builder;`); expect(content[i++]).toEqual(`}`); }); it('should be able to use functions in the spec file name', async () => { // arrange const runner = new SchematicTestRunner('schematics', collectionPath); const templateFile = 'templates/spec/__name@dasherize__.spec.ts.template'; // act treeWithCustomClassTemplate.create(templateFile, templateWithCustomUpdateTemplates()); const result = await runner .runSchematicAsync( 'spec', { name: 'example.component.ts', classTemplate: templateFile }, treeWithCustomClassTemplate ) .toPromise(); // assert expect(result.exists('./example-component.spec.ts')).toBe(true); }); it('should be able to use multiple functions in the spec file name', async () => { // arrange const runner = new SchematicTestRunner('schematics', collectionPath); const templateFile = 'templates/spec/__name@dasherize@camelize__.spec.ts.template'; // act treeWithCustomClassTemplate.create(templateFile, templateWithCustomUpdateTemplates()); const result = await runner .runSchematicAsync( 'spec', { name: 'example.component.ts', classTemplate: templateFile }, treeWithCustomClassTemplate ) .toPromise(); // assert expect(result.exists('./exampleComponent.spec.ts')).toBe(true); }); it('should be able to use folderfy to match the file path', async () => { // arrange const className = '.\\my\\class\\location\\example-test.component.ts'; const specName = './my/class/location/example_component.custom.ts' const templateName = 'templates/spec/__name@underscore__.custom.ts.template'; const runner = new SchematicTestRunner('schematics', collectionPath); // act treeWithCustomClassTemplate.create(className, classContent()) treeWithCustomClassTemplate.create(templateName, templateWithCustomUpdateTemplates()); const result = await runner .runSchematicAsync( 'spec', { name: className, classTemplate: templateName }, treeWithCustomClassTemplate ) .toPromise(); // assert expect(result.exists(specName)).toBe(true); }); it('when both config classTemplate and command line arg classTemplate passed in it should use CLI arg', async () => { // arrange const runner = new SchematicTestRunner('schematics', collectionPath); treeWithCustomClassTemplate.create('just.template', 'CLI Args take precedence'); // act const result = await runner .runSchematicAsync( 'spec', { name: 'example.component.ts', config: 'tests/spec/test-data/valid-config-valid-class-template.json', classTemplate: 'just.template' }, treeWithCustomClassTemplate ) .toPromise(); // assert expect(result.exists('just')).toBe(true); expect(result.readContent('just')).toEqual('CLI Args take precedence'); }); }); function classContent(): string | Buffer { return `import { ADep } from '../my/relative/path'; import { DDep } from '@angular/router'; export class ExampleComponent { constructor( private aDep: ADep, private d: DDep, ) {} aMethod(); }`; } function templateWithCustomUpdateTemplates() { return `<% params.forEach(p => { if(p.importPath) {%>import { <%= p.type %> } from '<%= p.importPath %>'; <% }}) %>import { <%= className %> } from './<%= normalizedName %>'; import { autoSpy } from 'autoSpy'; describe('<%= className %>', () => { <% publicMethods.forEach(meth=> {if(meth != '') { %>it('when <%= meth %> is called it should', () => { // arrange const { build } = setup().default(); const <%= shorthand %> = build(); // act <%= shorthand %>.<%= meth %>(); // assert // expect(<%= shorthand %>).toEqual }); <% } else { %> it('it should construct', () => { // arrange const { build } = setup().default(); // act const <%= shorthand %> = build(); // assert // expect(<%= shorthand %>).toEqual }); <% }}) %> }); // add a comment here function setup() { <%= declaration %> const builder = { <%= builderExports %> default() { return builder; }, build() { return new <%= className %>(<%= constructorParams %>); } }; return builder; } /** scuri:template:lets:<%params.forEach(p => {%>let <%= camelize(p.type) %>Spy: <%= p.type %>; <% }) %>*/ /** scuri:template:injectables:<%params.forEach(p => {%>{ provide: <%= p.type %>, useClass: autoSpy(<%= p.type %>, '<%= p.type %>') }, <% }) %>*/ /** scuri:template:get-instances:<%params.forEach(p => {%><%= camelize(p.type) %>Spy = spyInject<<%= p.type %>>(TestBed.inject(<%= p.type %>)); <% }) %>*/ /** scuri:template:methods-skipDeDupe:<% publicMethods.forEach(meth=> {if(meth != '') { %>it('when <%= meth %> is called it should', () => { // arrange // act <%= shorthand %>.<%= meth %>(); // assert // expect(<%= shorthand %>).toEqual }); <% }}) %>*/` }
the_stack
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { VersionListComponent } from './version-list.component'; import { setupTestBed } from '@alfresco/adf-core'; import { MatDialog } from '@angular/material/dialog'; import { of } from 'rxjs'; import { Node, VersionPaging, VersionEntry, NodeEntry } from '@alfresco/js-api'; import { ContentTestingModule } from '../testing/content.testing.module'; import { TranslateModule } from '@ngx-translate/core'; import { ContentVersionService } from './content-version.service'; describe('VersionListComponent', () => { let component: VersionListComponent; let fixture: ComponentFixture<VersionListComponent>; let dialog: MatDialog; let contentVersionService: ContentVersionService; const nodeId = 'test-id'; const versionId = '1.0'; const versionTest = [ <VersionEntry> { entry: { name: 'test-file-name', id: '1.0', versionComment: 'test-version-comment' } }, <VersionEntry> { entry: { name: 'test-file-name-two', id: '1.0', versionComment: 'test-version-comment' } } ]; setupTestBed({ imports: [ TranslateModule.forRoot(), ContentTestingModule ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }); afterEach(() => { fixture.destroy(); TestBed.resetTestingModule(); }); beforeEach(() => { fixture = TestBed.createComponent(VersionListComponent); dialog = TestBed.inject(MatDialog); contentVersionService = TestBed.inject(ContentVersionService); component = fixture.componentInstance; component.node = <Node> { id: nodeId, allowableOperations: ['update'] }; spyOn(component, 'downloadContent').and.stub(); spyOn(component['nodesApi'], 'getNode').and.returnValue(Promise.resolve(<NodeEntry> { entry: { id: 'nodeInfoId' } })); }); it('should raise confirmation dialog on delete', () => { fixture.detectChanges(); component.versions = versionTest; spyOn(dialog, 'open').and.returnValue({ afterClosed() { return of(false); } } as any); component.deleteVersion('1'); expect(dialog.open).toHaveBeenCalled(); }); it('should delete the version if user confirms', () => { fixture.detectChanges(); component.versions = versionTest; spyOn(dialog, 'open').and.returnValue({ afterClosed() { return of(true); } } as any); spyOn(component['versionsApi'], 'deleteVersion').and.returnValue(Promise.resolve(true)); component.deleteVersion(versionId); expect(dialog.open).toHaveBeenCalled(); expect(component['versionsApi'].deleteVersion).toHaveBeenCalledWith(nodeId, versionId); }); it('should not delete version if user rejects', () => { component.versions = versionTest; spyOn(dialog, 'open').and.returnValue({ afterClosed() { return of(false); } } as any); spyOn(component['versionsApi'], 'deleteVersion').and.returnValue(Promise.resolve(true)); component.deleteVersion(versionId); expect(dialog.open).toHaveBeenCalled(); expect(component['versionsApi'].deleteVersion).not.toHaveBeenCalled(); }); it('should reload and raise deleted event', (done) => { spyOn(component, 'loadVersionHistory').and.stub(); component.deleted.subscribe(() => { expect(component.loadVersionHistory).toHaveBeenCalled(); done(); }); fixture.detectChanges(); component.onVersionDeleted({}); }); describe('Version history fetching', () => { it('should use loading bar', () => { spyOn(component['versionsApi'], 'listVersionHistory').and .callFake(() => Promise.resolve({ list: { entries: versionTest } })); let loadingProgressBar = fixture.debugElement.query(By.css('[data-automation-id="version-history-loading-bar"]')); expect(loadingProgressBar).toBeNull(); component.ngOnChanges(); fixture.detectChanges(); loadingProgressBar = fixture.debugElement.query(By.css('[data-automation-id="version-history-loading-bar"]')); expect(loadingProgressBar).not.toBeNull(); }); it('should load the versions for a given id', () => { spyOn(component['versionsApi'], 'listVersionHistory').and .callFake(() => Promise.resolve({ list: { entries: versionTest } })); component.ngOnChanges(); fixture.detectChanges(); expect(component['versionsApi'].listVersionHistory).toHaveBeenCalledWith(nodeId); }); it('should show the versions after loading', (done) => { fixture.detectChanges(); spyOn(component['versionsApi'], 'listVersionHistory').and.callFake(() => { return Promise.resolve(new VersionPaging({ list: { entries: [ { entry: { name: 'test-file-name', id: '1.0', versionComment: 'test-version-comment' } } ] } })); }); component.ngOnChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); const versionFileName = fixture.debugElement.query(By.css('.adf-version-list-item-name')).nativeElement.innerText; const versionIdText = fixture.debugElement.query(By.css('.adf-version-list-item-version')).nativeElement.innerText; const versionComment = fixture.debugElement.query(By.css('.adf-version-list-item-comment')).nativeElement.innerText; expect(versionFileName).toBe('test-file-name'); expect(versionIdText).toBe('1.0'); expect(versionComment).toBe('test-version-comment'); done(); }); }); it('should NOT show the versions comments if input property is set not to show them', (done) => { spyOn(component['versionsApi'], 'listVersionHistory').and .callFake(() => Promise.resolve( new VersionPaging({ list: { entries: [ { entry: { name: 'test-file-name', id: '1.0', versionComment: 'test-version-comment' } } ] } }) )); component.showComments = false; fixture.detectChanges(); component.ngOnChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); const versionCommentEl = fixture.debugElement.query(By.css('.adf-version-list-item-comment')); expect(versionCommentEl).toBeNull(); done(); }); }); it('should be able to download a version', () => { const versionEntry = { entry: { name: 'test-file-name', id: '1.0', versionComment: 'test-version-comment' } }; spyOn(component['versionsApi'], 'listVersionHistory').and.returnValue(Promise.resolve(new VersionPaging({ list: { entries: [versionEntry] } }))); spyOn(contentVersionService.contentApi, 'getContentUrl').and.returnValue('the/download/url'); fixture.detectChanges(); component.downloadVersion('1.0'); expect(contentVersionService.contentApi.getContentUrl).toHaveBeenCalledWith(nodeId, true); }); it('should be able to view a version', () => { spyOn(component.viewVersion, 'emit'); component.onViewVersion('1.0'); fixture.detectChanges(); expect(component.viewVersion.emit).toHaveBeenCalledWith('1.0'); }); it('should NOT be able to download a version if configured so', () => { const versionEntry = { entry: { name: 'test-file-name', id: '1.0', versionComment: 'test-version-comment' } }; spyOn(component['versionsApi'], 'listVersionHistory').and .callFake(() => Promise.resolve(new VersionPaging({ list: { entries: [versionEntry] } }))); const spyOnDownload = spyOn(component['contentApi'], 'getContentUrl').and.stub(); component.allowDownload = false; fixture.detectChanges(); component.downloadVersion('1.0'); expect(spyOnDownload).not.toHaveBeenCalled(); }); }); describe('Version restoring', () => { it('should restore version only when restore allowed', () => { component.node.allowableOperations = []; spyOn(component['versionsApi'], 'revertVersion').and.stub(); component.restore('1'); expect(component['versionsApi'].revertVersion).not.toHaveBeenCalled(); }); it('should load the versions for a given id', () => { fixture.detectChanges(); component.versions = versionTest; const spyOnRevertVersion = spyOn(component['versionsApi'], 'revertVersion').and .callFake(() => Promise.resolve(new VersionEntry( { entry: { name: 'test-file-name', id: '1.0', versionComment: 'test-version-comment' } }))); component.restore(versionId); expect(spyOnRevertVersion).toHaveBeenCalledWith(nodeId, versionId, { majorVersion: true, comment: '' }); }); it('should get node info after restoring the node', fakeAsync(() => { fixture.detectChanges(); component.versions = versionTest; spyOn(component['versionsApi'], 'listVersionHistory') .and.callFake(() => Promise.resolve({ list: { entries: versionTest } })); spyOn(component['versionsApi'], 'revertVersion') .and.callFake(() => Promise.resolve(new VersionEntry( { entry: { name: 'test-file-name', id: '1.0', versionComment: 'test-version-comment' } }))); component.restore(versionId); fixture.detectChanges(); tick(); expect(component['nodesApi'].getNode).toHaveBeenCalled(); })); it('should emit with node info data', fakeAsync(() => { fixture.detectChanges(); component.versions = versionTest; spyOn(component['versionsApi'], 'listVersionHistory') .and.callFake(() => Promise.resolve({ list: { entries: versionTest } })); spyOn(component['versionsApi'], 'revertVersion') .and.callFake(() => Promise.resolve(new VersionEntry( { entry: { name: 'test-file-name', id: '1.0', versionComment: 'test-version-comment' } }))); spyOn(component.restored, 'emit'); component.restore(versionId); fixture.detectChanges(); tick(); expect(component.restored.emit).toHaveBeenCalledWith(<Node> { id: 'nodeInfoId' }); })); it('should reload the version list after a version restore', fakeAsync(() => { fixture.detectChanges(); component.versions = versionTest; const spyOnListVersionHistory = spyOn(component['versionsApi'], 'listVersionHistory').and .callFake(() => Promise.resolve({ list: { entries: versionTest } })); spyOn(component['versionsApi'], 'revertVersion').and.callFake(() => Promise.resolve(null)); component.restore(versionId); fixture.detectChanges(); tick(); expect(spyOnListVersionHistory).toHaveBeenCalledTimes(1); })); }); describe('Actions buttons', () => { describe('showActions', () => { beforeEach(() => { fixture.detectChanges(); component.node = new Node({ id: nodeId }); spyOn(component['versionsApi'], 'listVersionHistory').and.callFake(() => { return Promise.resolve(new VersionPaging({ list: { entries: [ { entry: { name: 'test-file-name', id: '1.0', versionComment: 'test-version-comment' } } ] } })); }); component.ngOnChanges(); }); it('should show Actions if showActions is true', (done) => { component.versions = versionTest; component.showActions = true; fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); const menuButton = fixture.nativeElement.querySelector('[id="adf-version-list-action-menu-button-1.0"]'); expect(menuButton).not.toBeNull(); done(); }); }); it('should hide Actions if showActions is false', (done) => { component.showActions = false; fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); const menuButton = fixture.nativeElement.querySelector('[id="adf-version-list-action-menu-button-1.0"]'); expect(menuButton).toBeNull(); done(); }); }); }); describe('disabled', () => { beforeEach(() => { fixture.detectChanges(); component.node = <Node> { id: nodeId }; spyOn(component['versionsApi'], 'listVersionHistory').and.callFake(() => { return Promise.resolve(new VersionPaging({ list: { entries: [ { entry: { name: 'test-file-two', id: '1.1', versionComment: 'test-version-comment' } }, { entry: { name: 'test-file-name', id: '1.0', versionComment: 'test-version-comment' } } ] } })); }); component.ngOnChanges(); }); it('should disable delete action if is not allowed', (done) => { fixture.whenStable().then(() => { fixture.detectChanges(); const menuButton = fixture.nativeElement.querySelector('[id="adf-version-list-action-menu-button-1.1"]'); menuButton.click(); const deleteButton: any = document.querySelector('[id="adf-version-list-action-delete-1.1"]'); expect(deleteButton.disabled).toBe(true); done(); }); }); it('should disable restore action if is not allowed', (done) => { fixture.whenStable().then(() => { fixture.detectChanges(); const menuButton = fixture.nativeElement.querySelector('[id="adf-version-list-action-menu-button-1.1"]'); menuButton.click(); const restoreButton: any = document.querySelector('[id="adf-version-list-action-restore-1.1"]'); expect(restoreButton.disabled).toBe(true); done(); }); }); }); describe('enabled', () => { beforeEach(() => { fixture.detectChanges(); component.node = <Node> { id: nodeId, allowableOperations: ['update', 'delete'] }; spyOn(component['versionsApi'], 'listVersionHistory').and.callFake(() => { return Promise.resolve(new VersionPaging({ list: { entries: [ { entry: { name: 'test-file-name', id: '1.1', versionComment: 'test-version-comment' } }, { entry: { name: 'test-file-name', id: '1.0', versionComment: 'test-version-comment' } } ] } })); }); component.ngOnChanges(); }); it('should enable delete action if is allowed', (done) => { fixture.whenStable().then(() => { fixture.detectChanges(); const menuButton = fixture.nativeElement.querySelector('[id="adf-version-list-action-menu-button-1.1"]'); menuButton.click(); const deleteButton: any = document.querySelector('[id="adf-version-list-action-delete-1.1"]'); expect(deleteButton.disabled).toBe(false); done(); }); }); it('should enable restore action if is allowed', (done) => { fixture.whenStable().then(() => { fixture.detectChanges(); const menuButton = fixture.nativeElement.querySelector('[id="adf-version-list-action-menu-button-1.1"]'); menuButton.click(); const restoreButton: any = document.querySelector('[id="adf-version-list-action-restore-1.1"]'); expect(restoreButton.disabled).toBe(false); done(); }); }); }); }); });
the_stack
import {assert} from '../../platform/chai-web.js'; import {ChangeType, VersionMap, CollectionOpTypes, CRDTCollection, CollectionOperation} from '../lib-crdt.js'; import {isEmptyChange} from '../internal/crdt.js'; import {simplifyFastForwardOp} from '../internal/crdt-collection.js'; /** Creates an Add operation. */ function addOp(id: string, actor: string, versionMap: VersionMap): CollectionOperation<{id: string}> { return {type: CollectionOpTypes.Add, added: {id}, versionMap, actor}; } /** Creates an Remove operation. */ function removeOp(id: string, actor: string, versionMap: VersionMap): CollectionOperation<{id: string}> { return {type: CollectionOpTypes.Remove, removed: {id}, versionMap, actor}; } describe('CRDTCollection', () => { it('initially is empty', () => { const set = new CRDTCollection<{id: string}>(); assert.strictEqual(set.getParticleView().size, 0); }); it('can add two different items from the same actor', () => { const set = new CRDTCollection<{id: string}>(); set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'one'}, versionMap: {me: 1}, actor: 'me' }); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'two'}, versionMap: {me: 2}, actor: 'me' })); assert.sameMembers([...set.getParticleView()].map(a => a.id), ['one', 'two']); }); it('can add the same value from two actors', () => { const set = new CRDTCollection<{id: string}>(); set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'one'}, versionMap: {me: 1}, actor: 'me' }); set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'one'}, versionMap: {them: 1}, actor: 'them' }); assert.sameMembers([...set.getParticleView()].map(a => a.id), ['one']); }); it('can add the same id twice keeping the first value', () => { const set = new CRDTCollection<{id: string, value: number}>(); set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'one', value: 1}, versionMap: {me: 1}, actor: 'me' }); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'one', value: 2}, versionMap: {me: 2}, actor: 'me' })); assert.sameMembers([...set.getParticleView()].map(a => a.value), [1]); }); it('rejects add operations not in sequence', () => { const set = new CRDTCollection<{id: string}>(); set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'one'}, versionMap: {me: 1}, actor: 'me' }); assert.isFalse(set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'two'}, versionMap: {me: 0}, actor: 'me' })); assert.isFalse(set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'two'}, versionMap: {me: 1}, actor: 'me' })); assert.isFalse(set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'two'}, versionMap: {me: 3}, actor: 'me' })); }); it('can remove an item', () => { const set = new CRDTCollection<{id: string}>(); set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'one'}, versionMap: {me: 1}, actor: 'me' }); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.Remove, removed: {id: 'one'}, versionMap: {me: 1}, actor: 'me' })); assert.strictEqual(set.getParticleView().size, 0); }); it('rejects remove operations if version mismatch', () => { const set = new CRDTCollection<{id: string}>(); set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'one'}, versionMap: {me: 1}, actor: 'me' }); assert.isFalse(set.applyOperation({ type: CollectionOpTypes.Remove, removed: {id: 'one'}, versionMap: {me: 2}, actor: 'me' })); assert.isFalse(set.applyOperation({ type: CollectionOpTypes.Remove, removed: {id: 'one'}, versionMap: {me: 0}, actor: 'me' })); }); it('rejects remove value not in collection', () => { const set = new CRDTCollection<{id: string}>(); set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'one'}, versionMap: {me: 1}, actor: 'me' }); assert.isFalse(set.applyOperation({ type: CollectionOpTypes.Remove, removed: {id: 'two'}, versionMap: {me: 1}, actor: 'me' })); }); it('rejects remove version too old', () => { const set = new CRDTCollection<{id: string}>(); set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'one'}, versionMap: {me: 1}, actor: 'me' }); set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'two'}, versionMap: {you: 1}, actor: 'you' }); // This succeeds because the op versionMap is up to date wrt to the value "one" (whose version is me:1). assert.isTrue(set.applyOperation({ type: CollectionOpTypes.Remove, removed: {id: 'one'}, versionMap: {me: 1}, actor: 'them' })); // This fails because the op versionMap is not up to date wrt to the actor "you" (whose version is you:1). assert.isFalse(set.applyOperation({ type: CollectionOpTypes.Remove, removed: {id: 'two'}, versionMap: {me: 1}, actor: 'them' })); }); it('allows removal by single actors who are up to date', () => { const set = new CRDTCollection<{id: string}>(); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'x'}, versionMap: {a: 1}, actor: 'a' })); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.Remove, removed: {id: 'x'}, versionMap: {a: 1}, actor: 'a' })); }); it('allows removal by actors who are up to date', () => { const set = new CRDTCollection<{id: string}>(); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'x'}, versionMap: {a: 1}, actor: 'a' })); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'x'}, versionMap: {c: 1}, actor: 'c' })); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.Remove, removed: {id: 'x'}, versionMap: {a: 1, c: 1}, actor: 'a' })); // This does not cause an update, as the removal has already been applied. assert.isFalse(set.applyOperation({ type: CollectionOpTypes.Remove, removed: {id: 'x'}, versionMap: {a: 1, c: 1}, actor: 'c' })); }); it('refuses removal by actors who are not up to date', () => { const set = new CRDTCollection<{id: string}>(); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'x'}, versionMap: {a: 1}, actor: 'a' })); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.Add, added: {id: 'x'}, versionMap: {c: 1}, actor: 'c' })); assert.isFalse(set.applyOperation({ type: CollectionOpTypes.Remove, removed: {id: 'x'}, versionMap: {a: 1}, actor: 'a' })); assert.isFalse(set.applyOperation({ type: CollectionOpTypes.Remove, removed: {id: 'x'}, versionMap: {c: 1}, actor: 'c' })); }); it('rejects values with missing IDs', () => { const set = new CRDTCollection<{id: string}>(); const valuesWithMissingIDs: {id: string}[] = [ {} as {id: string}, {id: null}, {id: ''}, ]; valuesWithMissingIDs.forEach(value => { assert.throws( () => set.applyOperation({type: CollectionOpTypes.Add, added: value, actor: 'a', versionMap: {a: 1}}), 'CRDT value must have an ID.'); assert.throws( () => set.applyOperation({type: CollectionOpTypes.Remove, removed: value, actor: 'a', versionMap: {a: 1}}), 'CRDT value must have an ID.'); }); }); it('can merge two models', () => { // Original set of data common to both sets. Say that actor c added them all. const originalOps = [ addOp('kept by both', 'c', {c: 1}), addOp('removed by a', 'c', {c: 2}), addOp('removed by b', 'c', {c: 3}), addOp('removed by a added by b', 'c', {c: 4}), addOp('removed by b added by a', 'c', {c: 5}), ]; const set1 = new CRDTCollection<{id: string}>(); const set2 = new CRDTCollection<{id: string}>(); originalOps.forEach(op => assert.isTrue(set1.applyOperation(op))); originalOps.forEach(op => assert.isTrue(set2.applyOperation(op))); assert.isTrue(set1.applyOperation(removeOp('removed by a', 'a', {a: 0, c: 5}))); assert.isTrue(set1.applyOperation(addOp('added by a', 'a', {a: 1, c: 5}))); assert.isTrue(set1.applyOperation(addOp('added by both', 'a', {a: 2, c: 5}))); assert.isTrue(set1.applyOperation(addOp('removed by b added by a', 'a', {a: 3, c: 5}))); assert.isTrue(set1.applyOperation(removeOp('removed by a added by b', 'a', {a: 3, c: 5}))); assert.isTrue(set2.applyOperation(addOp('added by both', 'b', {b: 1, c: 5}))); assert.isTrue(set2.applyOperation(addOp('added by b', 'b', {b: 2, c: 5}))); assert.isTrue(set2.applyOperation(removeOp('removed by b', 'b', {b: 2, c: 5}))); assert.isTrue(set2.applyOperation(removeOp('removed by b added by a', 'b', {b: 2, c: 5}))); assert.isTrue(set2.applyOperation(addOp('removed by a added by b', 'b', {b: 3, c: 5}))); const {modelChange, otherChange} = set1.merge(set2.getData()); const expectedVersion = {a: 3, b: 3, c: 5}; assert.deepEqual(modelChange, { changeType: ChangeType.Model, modelPostChange: { values: { 'kept by both': {value: {id: 'kept by both'}, version: {c: 1}}, 'removed by a added by b': {value: {id: 'removed by a added by b'}, version: {b: 3, c: 5}}, 'removed by b added by a': {value: {id: 'removed by b added by a'}, version: {a: 3, c: 5}}, 'added by a': {value: {id: 'added by a'}, version: {a: 1, c: 5}}, 'added by b': {value: {id: 'added by b'}, version: {b: 2, c: 5}}, 'added by both': {value: {id: 'added by both'}, version: {a: 2, b: 1, c: 5}}, }, version: expectedVersion }, }); if (otherChange.changeType === ChangeType.Operations) { assert.deepEqual(otherChange, { changeType: ChangeType.Operations, operations: [{ type: CollectionOpTypes.FastForward, added: [ [{id: 'added by both'}, {a: 2, b: 1, c: 5}], [{id: 'removed by b added by a'}, {a: 3, c: 5}], [{id: 'added by a'}, {a: 1, c: 5}], ], removed: [ {id: 'removed by a'}, ], oldVersionMap: {b: 3, c: 5}, newVersionMap: expectedVersion, }], }); assert.isTrue(set2.applyOperation(otherChange.operations[0])); if (modelChange.changeType === ChangeType.Model) { assert.deepEqual(set2.getData(), modelChange.modelPostChange); } else { assert.fail('Expected modelChange.changeType to be ChangeType.Model'); } } else { assert.fail('Expected otherChange.changeType to be ChangeType.Operations'); } }); it('can merge additions by two actors', () => { const set1 = new CRDTCollection<{id: string}>(); const set2 = new CRDTCollection<{id: string}>(); assert.isTrue(set1.applyOperation(addOp('added by a', 'a', {a: 1}))); assert.isTrue(set2.applyOperation(addOp('added by b', 'b', {b: 1}))); const {modelChange, otherChange} = set1.merge(set2.getData()); const expectedVersion = {a: 1, b: 1}; assert.deepEqual(modelChange, { changeType: ChangeType.Model, modelPostChange: { values: { 'added by a': {value: {id: 'added by a'}, version: {a: 1}}, 'added by b': {value: {id: 'added by b'}, version: {b: 1}} }, version: expectedVersion }, }); assert.deepEqual(otherChange, { changeType: ChangeType.Operations, operations: [{ type: CollectionOpTypes.Add, added: {id: 'added by a'}, actor: 'a', versionMap: {a: 1} }] }); }); it('can simplify single-actor add ops in merges', () => { const set1 = new CRDTCollection<{id: string}>(); const set2 = new CRDTCollection<{id: string}>(); const originalOps = [ addOp('zero', 'a', {a: 1}), addOp('one', 'b', {b: 1}), ]; originalOps.forEach(op => assert.isTrue(set1.applyOperation(op))); originalOps.forEach(op => assert.isTrue(set2.applyOperation(op))); // Add a bunch of things to set2. const set2AddOps = [ addOp('two', 'b', {a: 1, b: 2}), addOp('three', 'b', {a: 1, b: 3}), addOp('four', 'b', {a: 1, b: 4}), addOp('five', 'b', {a: 1, b: 5}), ]; set2AddOps.forEach(op => assert.isTrue(set2.applyOperation(op))); const {modelChange, otherChange} = set2.merge(set1.getData()); // Check that add ops are produced (not a fast-forward op). assert.deepEqual(otherChange, { changeType: ChangeType.Operations, operations: set2AddOps, }); }); it('can simplify single-actor add ops in merges for previously unseen actors', () => { const set1 = new CRDTCollection<{id: string}>(); const set2 = new CRDTCollection<{id: string}>(); const originalOps = [ addOp('zero', 'a', {a: 1}) ]; originalOps.forEach(op => assert.isTrue(set1.applyOperation(op))); originalOps.forEach(op => assert.isTrue(set2.applyOperation(op))); // Add a bunch of things to set2. const set2AddOps = [ addOp('one', 'b', {b: 1}), addOp('two', 'b', {b: 2}), addOp('three', 'b', {b: 3}), ]; set2AddOps.forEach(op => assert.isTrue(set2.applyOperation(op))); const {modelChange, otherChange} = set2.merge(set1.getData()); // Check that add ops are produced (not a fast-forward op). assert.deepEqual(otherChange, { changeType: ChangeType.Operations, operations: set2AddOps, }); }); describe('fast-forward operations', () => { it('rejects fast-forward ops which begin in the future', () => { const set = new CRDTCollection<{id: string}>(); assert.isFalse(set.applyOperation({ type: CollectionOpTypes.FastForward, added: [], removed: [], oldVersionMap: {a: 5}, // > 0 newVersionMap: {a: 10}, })); }); it('accepts (but does not apply) fast-forward ops which end in the past', () => { const set = new CRDTCollection<{id: string}>(); // Add some initial elements. assert.isTrue(set.applyOperation(addOp('one', 'me', {me: 1}))); assert.isTrue(set.applyOperation(addOp('two', 'me', {me: 2}))); assert.isTrue(set.applyOperation(addOp('three', 'me', {me: 3}))); // Check it accepts the operation (returns true), but does not add the new // element. assert.isTrue(set.applyOperation({ type: CollectionOpTypes.FastForward, added: [ [{id: 'four'}, {me: 2}], ], removed: [], oldVersionMap: {me: 1}, newVersionMap: {me: 2}, // < 3 })); assert.doesNotHaveAnyKeys(set.getData().values, ['four']); }); it('advances the versionMap', () => { const set = new CRDTCollection<{id: string}>(); // Add some initial elements. assert.isTrue(set.applyOperation(addOp('one', 'a', {a: 1}))); assert.isTrue(set.applyOperation(addOp('two', 'a', {a: 2}))); assert.isTrue(set.applyOperation(addOp('three', 'b', {b: 1}))); assert.isTrue(set.applyOperation(addOp('four', 'c', {c: 1}))); assert.deepEqual(set.getData().version, {a: 2, b: 1, c: 1}); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.FastForward, added: [], removed: [], oldVersionMap: {a: 2, b: 1}, newVersionMap: {a: 27, b: 45}, })); assert.deepEqual(set.getData().version, {a: 27, b: 45, c: 1}); }); it('can add elements', () => { const set = new CRDTCollection<{id: string}>(); // Add some initial elements. assert.isTrue(set.applyOperation(addOp('one', 'a', {a: 1}))); assert.isTrue(set.applyOperation(addOp('two', 'b', {b: 1}))); // This is the point where the fast-forward was computed. assert.isTrue(set.applyOperation({ type: CollectionOpTypes.FastForward, added: [ [{id: 'one'}, {a: 1, b: 7}], [{id: 'four'}, {a: 1, b: 9}], ], removed: [], oldVersionMap: {a: 1, b: 1}, newVersionMap: {a: 1, b: 9}, })); // Model has since been updated. assert.isTrue(set.applyOperation(removeOp('two', 'a', {a: 1, b: 1}))); assert.isTrue(set.applyOperation(addOp('three', 'a', {a: 2, b: 1}))); // one should be merged with the new version, two was removed and // shouldn't be added back again, three was existing and shouldn't be // deleted, and four is new. assert.deepEqual(set.getData(), { values: { 'one': {value: {id: 'one'}, version: {a: 1, b: 7}}, // Merged. 'three': {value: {id: 'three'}, version: {a: 2, b: 1}}, // Existing. 'four': {value: {id: 'four'}, version: {a: 1, b: 9}}, // Added. }, version: {a: 2, b: 9}, }); }); it('can remove elements', () => { const set = new CRDTCollection<{id: string}>(); // Add some initial elements. assert.isTrue(set.applyOperation(addOp('one', 'a', {a: 1}))); assert.isTrue(set.applyOperation(addOp('two', 'a', {a: 2}))); assert.isTrue(set.applyOperation(addOp('three', 'b', {b: 1}))); assert.isTrue(set.applyOperation({ type: CollectionOpTypes.FastForward, added: [], removed: [ {id: 'one'}, {id: 'two'}, ], oldVersionMap: {a: 1, b: 1}, newVersionMap: {a: 1, b: 5}, })); // one should be removed, but two should not, because it's version is not // dominated by newVersionMap above. assert.hasAllKeys(set.getData().values, ['two', 'three']); assert.deepEqual(set.getData().version, {a: 2, b: 5}); }); }); describe('simplifyFastForwardOp', () => { it(`simplifies single add op from a single actor`, () => { assert.deepEqual(simplifyFastForwardOp({ type: CollectionOpTypes.FastForward, added: [[{id: 'one'}, {a: 2, b: 1}]], removed: [], oldVersionMap: {a: 1, b: 1}, newVersionMap: {a: 2, b: 1}, }), [{ type: CollectionOpTypes.Add, added: {id: 'one'}, actor: 'a', versionMap: {a: 2, b: 1}, }]); }); it(`simplifies multiple add ops from a single actor`, () => { assert.deepEqual(simplifyFastForwardOp({ type: CollectionOpTypes.FastForward, added: [ [{id: 'two'}, {a: 3, b: 1}], [{id: 'one'}, {a: 2, b: 1}], ], removed: [], oldVersionMap: {a: 1, b: 1}, newVersionMap: {a: 3, b: 1}, }), [ { type: CollectionOpTypes.Add, added: {id: 'one'}, actor: 'a', versionMap: {a: 2, b: 1}, }, { type: CollectionOpTypes.Add, added: {id: 'two'}, actor: 'a', versionMap: {a: 3, b: 1}, }, ]); }); it(`doesn't simplify remove ops`, () => { assert.isNull(simplifyFastForwardOp({ type: CollectionOpTypes.FastForward, added: [], removed: [[{id: 'one'}, {a: 1}]], oldVersionMap: {a: 1}, newVersionMap: {a: 1}, })); }); it(`doesn't simplify pure version bumps`, () => { assert.isNull(simplifyFastForwardOp({ type: CollectionOpTypes.FastForward, added: [], removed: [], oldVersionMap: {a: 1}, newVersionMap: {a: 5}, })); }); it(`doesn't simplify add ops from a single actor with version jumps`, () => { assert.isNull(simplifyFastForwardOp({ type: CollectionOpTypes.FastForward, added: [ [{id: 'one'}, {a: 1}], [{id: 'two'}, {a: 2}], [{id: 'four'}, {a: 4}], ], removed: [], oldVersionMap: {a: 0}, newVersionMap: {a: 4}, })); }); it(`doesn't simplify add ops from multiple actors`, () => { assert.isNull(simplifyFastForwardOp({ type: CollectionOpTypes.FastForward, added: [[{id: 'one'}, {a: 2, b: 2}]], removed: [], oldVersionMap: {a: 1, b: 1}, newVersionMap: {a: 2, b: 2}, })); }); it(`doesn't simplify add ops with a version jump at the end`, () => { assert.isNull(simplifyFastForwardOp({ type: CollectionOpTypes.FastForward, added: [[{id: 'one'}, {a: 2}]], removed: [], oldVersionMap: {a: 1}, newVersionMap: {a: 3}, // Fails because it's > 2 })); }); it('returns an empty change when merging identical models', () => { const set = new CRDTCollection<{id: string}>(); const {modelChange, otherChange} = set.merge(set.getData()); assert.isTrue(isEmptyChange(modelChange)); assert.isTrue(isEmptyChange(otherChange)); set.applyOperation({type: CollectionOpTypes.Add, actor: 'a', added: {id: 'foo'}, versionMap: {'a': 1}}); set.applyOperation({type: CollectionOpTypes.Add, actor: 'b', added: {id: 'bar'}, versionMap: {'a': 1, 'b': 1}}); const {modelChange: modelChange2, otherChange: otherChange2} = set.merge(set.getData()); assert.isTrue(isEmptyChange(modelChange2)); assert.isTrue(isEmptyChange(otherChange2)); const set2 = new CRDTCollection<{id: string}>(); set2.merge(set.getData()); set.applyOperation({type: CollectionOpTypes.Remove, actor: 'a', removed: {id: 'foo'}, versionMap: {'a': 1, 'b': 1}}); set2.applyOperation({type: CollectionOpTypes.Remove, actor: 'a', removed: {id: 'bar'}, versionMap: {'a': 1, 'b': 1}}); const {modelChange: modelChange3, otherChange: otherChange3} = set.merge(set2.getData()); assert.isFalse(isEmptyChange(modelChange3)); assert.isFalse(isEmptyChange(otherChange3)); }); it('returns empty other change when merging into empty model', () => { const set = new CRDTCollection<{id: string}>(); const set2 = new CRDTCollection<{id: string}>(); set2.applyOperation({type: CollectionOpTypes.Add, actor: 'a', added: {id: 'foo'}, versionMap: {'a': 1}}); const {modelChange: modelChange, otherChange: otherChange} = set.merge(set2.getData()); assert.isFalse(isEmptyChange(modelChange)); assert.isTrue(isEmptyChange(otherChange)); }); }); }); // Note: if/when adding more tests to this file, please, also update CrdtSetTest.kt
the_stack
// ==================================================== // GraphQL query operation: GetCustomer // ==================================================== export interface GetCustomer_getCustomer_createdBy { __typename: "User"; name: string | null; } export interface GetCustomer_getCustomer_addresses { __typename: "Address"; id: string; isPrimary: boolean; street: string | null; city: string | null; postNumber: string | null; } export interface GetCustomer_getCustomer { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; taxIdentificationNumber: string | null; personName: string | null; email: string | null; phone: string | null; note: string | null; allowedBankPayments: boolean; createdBy: GetCustomer_getCustomer_createdBy; createdAt: any; updatedAt: any; addresses: GetCustomer_getCustomer_addresses[]; } export interface GetCustomer { getCustomer: GetCustomer_getCustomer | null; } export interface GetCustomerVariables { id: string; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: UpdateCustomer // ==================================================== export interface UpdateCustomer_updateCustomer_createdBy { __typename: "User"; name: string | null; } export interface UpdateCustomer_updateCustomer_addresses { __typename: "Address"; id: string; isPrimary: boolean; street: string | null; city: string | null; postNumber: string | null; } export interface UpdateCustomer_updateCustomer { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; taxIdentificationNumber: string | null; personName: string | null; email: string | null; phone: string | null; note: string | null; allowedBankPayments: boolean; createdBy: UpdateCustomer_updateCustomer_createdBy; createdAt: any; updatedAt: any; addresses: UpdateCustomer_updateCustomer_addresses[]; } export interface UpdateCustomer { updateCustomer: UpdateCustomer_updateCustomer; } export interface UpdateCustomerVariables { input: UpdateCustomerInput; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: DeleteCustomer // ==================================================== export interface DeleteCustomer_deleteCustomer { __typename: "Customer"; id: string; } export interface DeleteCustomer { deleteCustomer: DeleteCustomer_deleteCustomer; } export interface DeleteCustomerVariables { id: string; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL query operation: GetOrder // ==================================================== export interface GetOrder_getOrderByNumber_customer { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; } export interface GetOrder_getOrderByNumber_createdBy { __typename: "User"; id: string; name: string | null; } export interface GetOrder_getOrderByNumber_items_material { __typename: "Material"; id: string; name: string; } export interface GetOrder_getOrderByNumber_items { __typename: "OrderItem"; id: string; material: GetOrder_getOrderByNumber_items_material | null; name: string | null; width: number | null; height: number | null; pieces: number | null; printedPieces: number; producedPieces: number; totalPrice: number; totalTax: number; } export interface GetOrder_getOrderByNumber { __typename: "Order"; id: string; number: number; customer: GetOrder_getOrderByNumber_customer | null; status: OrderStatus; note: string | null; urgency: number; totalPrice: number; totalTax: number; createdAt: any; updatedAt: any; createdBy: GetOrder_getOrderByNumber_createdBy; items: GetOrder_getOrderByNumber_items[]; } export interface GetOrder { getOrderByNumber: GetOrder_getOrderByNumber | null; } export interface GetOrderVariables { number: number; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: UpdateOrder // ==================================================== export interface UpdateOrder_updateOrder_customer { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; } export interface UpdateOrder_updateOrder_createdBy { __typename: "User"; id: string; name: string | null; } export interface UpdateOrder_updateOrder_items_material { __typename: "Material"; id: string; name: string; } export interface UpdateOrder_updateOrder_items { __typename: "OrderItem"; id: string; material: UpdateOrder_updateOrder_items_material | null; name: string | null; width: number | null; height: number | null; pieces: number | null; printedPieces: number; producedPieces: number; totalPrice: number; totalTax: number; } export interface UpdateOrder_updateOrder { __typename: "Order"; id: string; number: number; customer: UpdateOrder_updateOrder_customer | null; status: OrderStatus; note: string | null; urgency: number; totalPrice: number; totalTax: number; createdAt: any; updatedAt: any; createdBy: UpdateOrder_updateOrder_createdBy; items: UpdateOrder_updateOrder_items[]; } export interface UpdateOrder { updateOrder: UpdateOrder_updateOrder; } export interface UpdateOrderVariables { id: string; input: UpdateOrderInput; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: DeleteOrder // ==================================================== export interface DeleteOrder_deleteOrder { __typename: "Order"; id: string; } export interface DeleteOrder { deleteOrder: DeleteOrder_deleteOrder; } export interface DeleteOrderVariables { id: string; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: AddProductionLog // ==================================================== export interface AddProductionLog_addProductionLog_productionLog_createdBy { __typename: "User"; id: string; name: string | null; } export interface AddProductionLog_addProductionLog_productionLog { __typename: "ProductionLog"; id: string; action: ProductionLogType; pieces: number; createdAt: any; createdBy: AddProductionLog_addProductionLog_productionLog_createdBy; } export interface AddProductionLog_addProductionLog { __typename: "OrderItem"; id: string; printedPieces: number; producedPieces: number; productionLog: AddProductionLog_addProductionLog_productionLog[]; } export interface AddProductionLog { addProductionLog: AddProductionLog_addProductionLog; } export interface AddProductionLogVariables { orderItemId: string; action: ProductionLogType; pieces: number; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: UpdateOrderNote // ==================================================== export interface UpdateOrderNote_updateOrderNote_customer { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; } export interface UpdateOrderNote_updateOrderNote_createdBy { __typename: "User"; id: string; name: string | null; } export interface UpdateOrderNote_updateOrderNote_items_material { __typename: "Material"; id: string; name: string; } export interface UpdateOrderNote_updateOrderNote_items { __typename: "OrderItem"; id: string; material: UpdateOrderNote_updateOrderNote_items_material | null; name: string | null; width: number | null; height: number | null; pieces: number | null; printedPieces: number; producedPieces: number; totalPrice: number; totalTax: number; } export interface UpdateOrderNote_updateOrderNote { __typename: "Order"; id: string; number: number; customer: UpdateOrderNote_updateOrderNote_customer | null; status: OrderStatus; note: string | null; urgency: number; totalPrice: number; totalTax: number; createdAt: any; updatedAt: any; createdBy: UpdateOrderNote_updateOrderNote_createdBy; items: UpdateOrderNote_updateOrderNote_items[]; } export interface UpdateOrderNote { updateOrderNote: UpdateOrderNote_updateOrderNote; } export interface UpdateOrderNoteVariables { id: string; note?: string | null; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: UpdateOrderStatus // ==================================================== export interface UpdateOrderStatus_updateOrderStatus_customer { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; } export interface UpdateOrderStatus_updateOrderStatus_createdBy { __typename: "User"; id: string; name: string | null; } export interface UpdateOrderStatus_updateOrderStatus_items_material { __typename: "Material"; id: string; name: string; } export interface UpdateOrderStatus_updateOrderStatus_items { __typename: "OrderItem"; id: string; material: UpdateOrderStatus_updateOrderStatus_items_material | null; name: string | null; width: number | null; height: number | null; pieces: number | null; printedPieces: number; producedPieces: number; totalPrice: number; totalTax: number; } export interface UpdateOrderStatus_updateOrderStatus { __typename: "Order"; id: string; number: number; customer: UpdateOrderStatus_updateOrderStatus_customer | null; status: OrderStatus; note: string | null; urgency: number; totalPrice: number; totalTax: number; createdAt: any; updatedAt: any; createdBy: UpdateOrderStatus_updateOrderStatus_createdBy; items: UpdateOrderStatus_updateOrderStatus_items[]; } export interface UpdateOrderStatus { updateOrderStatus: UpdateOrderStatus_updateOrderStatus; } export interface UpdateOrderStatusVariables { id: string; status: OrderStatus; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL query operation: GetAllCustomers // ==================================================== export interface GetAllCustomers_getAllCustomers_items { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; personName: string | null; email: string | null; phone: string | null; } export interface GetAllCustomers_getAllCustomers { __typename: "CustomerPaginated"; totalCount: number; items: GetAllCustomers_getAllCustomers_items[]; } export interface GetAllCustomers { getAllCustomers: GetAllCustomers_getAllCustomers; } export interface GetAllCustomersVariables { first?: number | null; skip?: number | null; search?: string | null; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL query operation: GetAllOrders // ==================================================== export interface GetAllOrders_getAllOrders_items_customer { __typename: "Customer"; id: string; name: string | null; } export interface GetAllOrders_getAllOrders_items_items_material { __typename: "Material"; id: string; name: string; } export interface GetAllOrders_getAllOrders_items_items { __typename: "OrderItem"; material: GetAllOrders_getAllOrders_items_items_material | null; pieces: number | null; } export interface GetAllOrders_getAllOrders_items { __typename: "Order"; id: string; number: number; status: OrderStatus; urgency: number; customer: GetAllOrders_getAllOrders_items_customer | null; createdAt: any; totalPrice: number; totalTax: number; totalSize: number; items: GetAllOrders_getAllOrders_items_items[]; } export interface GetAllOrders_getAllOrders { __typename: "OrderPaginated"; totalCount: number; items: GetAllOrders_getAllOrders_items[]; } export interface GetAllOrders { getAllOrders: GetAllOrders_getAllOrders; } export interface GetAllOrdersVariables { first?: number | null; skip?: number | null; status?: OrderStatus | null; orderByUrgency?: OrderByArg | null; customerId?: string | null; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: LoginMutation // ==================================================== export interface LoginMutation_login_user { __typename: "User"; name: string | null; id: string; email: string; role: UserRole; } export interface LoginMutation_login { __typename: "AuthPayload"; user: LoginMutation_login_user; token: string; } export interface LoginMutation { login: LoginMutation_login; } export interface LoginMutationVariables { email: string; password: string; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL query operation: MeQuery // ==================================================== export interface MeQuery_me { __typename: "User"; id: string; name: string | null; email: string; role: UserRole; } export interface MeQuery { me: MeQuery_me; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL query operation: GetAllMaterials // ==================================================== export interface GetAllMaterials_getAllMaterials { __typename: "Material"; id: string; name: string; price: number; updatedAt: any; } export interface GetAllMaterials { getAllMaterials: GetAllMaterials_getAllMaterials[]; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: UpdateMaterial // ==================================================== export interface UpdateMaterial_updateMaterial { __typename: "Material"; id: string; name: string; price: number; updatedAt: any; } export interface UpdateMaterial { updateMaterial: UpdateMaterial_updateMaterial; } export interface UpdateMaterialVariables { id: string; name?: string | null; price?: number | null; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: DeleteMaterial // ==================================================== export interface DeleteMaterial_deleteMaterial { __typename: "Material"; id: string; } export interface DeleteMaterial { deleteMaterial: DeleteMaterial_deleteMaterial; } export interface DeleteMaterialVariables { id: string; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: CreateMaterial // ==================================================== export interface CreateMaterial_createMaterial { __typename: "Material"; id: string; name: string; price: number; updatedAt: any; } export interface CreateMaterial { createMaterial: CreateMaterial_createMaterial; } export interface CreateMaterialVariables { name: string; price: number; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: CreateCustomerMutation // ==================================================== export interface CreateCustomerMutation_createCustomer { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; personName: string | null; email: string | null; phone: string | null; } export interface CreateCustomerMutation { createCustomer: CreateCustomerMutation_createCustomer; } export interface CreateCustomerMutationVariables { input: CreateCustomerInput; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL query operation: GetCustomerHelperInfo // ==================================================== export interface GetCustomerHelperInfo_getCustomerHelperInfo { __typename: "CustomerHelperInfo"; identificationNumber: string | null; taxIdentificationNumber: string | null; name: string | null; city: string | null; street: string | null; postNumber: string | null; } export interface GetCustomerHelperInfo { getCustomerHelperInfo: GetCustomerHelperInfo_getCustomerHelperInfo; } export interface GetCustomerHelperInfoVariables { partialIdentificationNumber: string; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL query operation: GetHighestOrderNumber // ==================================================== export interface GetHighestOrderNumber { getHighestOrderNumber: number | null; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: CreateOrder // ==================================================== export interface CreateOrder_createOrder { __typename: "Order"; id: string; number: number; } export interface CreateOrder { createOrder: CreateOrder_createOrder; } export interface CreateOrderVariables { number: number; input: OrderInput; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL query operation: FindCustomerQuery // ==================================================== export interface FindCustomerQuery_getAllCustomers_items { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; personName: string | null; email: string | null; phone: string | null; } export interface FindCustomerQuery_getAllCustomers { __typename: "CustomerPaginated"; totalCount: number; items: FindCustomerQuery_getAllCustomers_items[]; } export interface FindCustomerQuery { getAllCustomers: FindCustomerQuery_getAllCustomers; } export interface FindCustomerQueryVariables { search?: string | null; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: ChangePasswordMutation // ==================================================== export interface ChangePasswordMutation_changePassword { __typename: "User"; id: string; name: string | null; } export interface ChangePasswordMutation { changePassword: ChangePasswordMutation_changePassword; } export interface ChangePasswordMutationVariables { oldPassword: string; newPassword: string; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL query operation: GetAllUsers // ==================================================== export interface GetAllUsers_getAllUsers { __typename: "User"; id: string; email: string; name: string | null; role: UserRole; } export interface GetAllUsers { getAllUsers: GetAllUsers_getAllUsers[]; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: CreateUser // ==================================================== export interface CreateUser_addUser { __typename: "User"; id: string; email: string; name: string | null; role: UserRole; } export interface CreateUser { addUser: CreateUser_addUser; } export interface CreateUserVariables { input: CreateUserInput; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: UpdateUser // ==================================================== export interface UpdateUser_updateUser { __typename: "User"; id: string; email: string; name: string | null; role: UserRole; } export interface UpdateUser { updateUser: UpdateUser_updateUser; } export interface UpdateUserVariables { id: string; input: UpdateUserInput; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL mutation operation: DeleteUser // ==================================================== export interface DeleteUser_deleteUser { __typename: "User"; id: string; } export interface DeleteUser { deleteUser: DeleteUser_deleteUser; } export interface DeleteUserVariables { id: string; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL fragment: CustomerDetails // ==================================================== export interface CustomerDetails_createdBy { __typename: "User"; name: string | null; } export interface CustomerDetails_addresses { __typename: "Address"; id: string; isPrimary: boolean; street: string | null; city: string | null; postNumber: string | null; } export interface CustomerDetails { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; taxIdentificationNumber: string | null; personName: string | null; email: string | null; phone: string | null; note: string | null; allowedBankPayments: boolean; createdBy: CustomerDetails_createdBy; createdAt: any; updatedAt: any; addresses: CustomerDetails_addresses[]; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL fragment: OrderFragment // ==================================================== export interface OrderFragment_customer { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; } export interface OrderFragment_createdBy { __typename: "User"; id: string; name: string | null; } export interface OrderFragment_items_material { __typename: "Material"; id: string; name: string; } export interface OrderFragment_items { __typename: "OrderItem"; id: string; material: OrderFragment_items_material | null; name: string | null; width: number | null; height: number | null; pieces: number | null; printedPieces: number; producedPieces: number; totalPrice: number; totalTax: number; } export interface OrderFragment { __typename: "Order"; id: string; number: number; customer: OrderFragment_customer | null; status: OrderStatus; note: string | null; urgency: number; totalPrice: number; totalTax: number; createdAt: any; updatedAt: any; createdBy: OrderFragment_createdBy; items: OrderFragment_items[]; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL fragment: ProductionLogFragment // ==================================================== export interface ProductionLogFragment_createdBy { __typename: "User"; id: string; name: string | null; } export interface ProductionLogFragment { __typename: "ProductionLog"; id: string; action: ProductionLogType; pieces: number; createdAt: any; createdBy: ProductionLogFragment_createdBy; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. // ==================================================== // GraphQL fragment: CustomerFragment // ==================================================== export interface CustomerFragment { __typename: "Customer"; id: string; name: string | null; identificationNumber: string | null; personName: string | null; email: string | null; phone: string | null; } /* tslint:disable */ /* eslint-disable */ // @generated // This file was automatically generated and should not be edited. //============================================================== // START Enums and Input Objects //============================================================== export enum OrderByArg { asc = "asc", desc = "desc", } export enum OrderStatus { DONE = "DONE", NEW = "NEW", READY_TO_PRINT = "READY_TO_PRINT", TO_BE_SHIPPED = "TO_BE_SHIPPED", WAITING_FOR_CALCULATION = "WAITING_FOR_CALCULATION", WAITING_FOR_PRODUCTION = "WAITING_FOR_PRODUCTION", } export enum ProductionLogType { PRINT = "PRINT", PRODUCTION = "PRODUCTION", } export enum UserRole { ADMINISTRATION = "ADMINISTRATION", EXECUTIVE = "EXECUTIVE", FACTORY = "FACTORY", } export interface AddressInput { city?: string | null; isPrimary?: boolean | null; number?: string | null; postNumber?: string | null; state?: string | null; street?: string | null; } export interface CreateCustomerInput { addresses?: AddressInput[] | null; allowedBankPayments?: boolean | null; email?: string | null; identificationNumber?: string | null; name?: string | null; note?: string | null; personName?: string | null; phone?: string | null; taxIdentificationNumber?: string | null; } export interface CreateUserInput { email: string; name?: string | null; password: string; role?: UserRole | null; } export interface OrderInput { customerId?: string | null; items: OrderItemInput[]; note?: string | null; status?: OrderStatus | null; totalPrice: number; totalTax: number; urgency?: number | null; } export interface OrderItemInput { height?: number | null; materialId?: string | null; name?: string | null; pieces?: number | null; totalPrice: number; totalTax: number; width?: number | null; } export interface UpdateAddressInput { city?: string | null; id?: string | null; isPrimary?: boolean | null; number?: string | null; postNumber?: string | null; state?: string | null; street?: string | null; } export interface UpdateCustomerInput { addresses?: UpdateAddressInput[] | null; allowedBankPayments?: boolean | null; email?: string | null; id?: string | null; identificationNumber?: string | null; name?: string | null; note?: string | null; personName?: string | null; phone?: string | null; taxIdentificationNumber?: string | null; } export interface UpdateOrderInput { customerId?: string | null; items?: UpdateOrderItemInput[] | null; note?: string | null; status?: OrderStatus | null; totalPrice?: number | null; totalTax?: number | null; urgency?: number | null; } export interface UpdateOrderItemInput { height?: number | null; id?: string | null; materialId?: string | null; name?: string | null; pieces?: number | null; totalPrice: number; totalTax: number; width?: number | null; } export interface UpdateUserInput { email: string; name?: string | null; password?: string | null; role?: UserRole | null; } //============================================================== // END Enums and Input Objects //==============================================================
the_stack
import Conditions from '../../../../../resources/conditions'; import NetRegexes from '../../../../../resources/netregexes'; import { Responses } from '../../../../../resources/responses'; import ZoneId from '../../../../../resources/zone_id'; import { RaidbossData } from '../../../../../types/data'; import { TriggerSet } from '../../../../../types/trigger'; export interface Data extends RaidbossData { calledWildSpeed?: boolean; calledUseCannon?: boolean; } const triggerSet: TriggerSet<Data> = { zoneId: ZoneId.CastrumAbania, timelineFile: 'castrum_abania.txt', triggers: [ { id: 'CastrumAbania Magna Roader Fire III', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Magna Roader', id: '1F16', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Magna Rotula', id: '1F16', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Magna Rouleur Magitek', id: '1F16', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: '魔導マグナローダー', id: '1F16', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '魔导机车大魔', id: '1F16', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '마도 마그나로더', id: '1F16', capture: false }), response: Responses.aoe(), run: (data) => data.calledWildSpeed = data.calledUseCannon = false, }, { id: 'CastrumAbania Magna Roader Wild Speed', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Magna Roader', id: '207E', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Magna Rotula', id: '207E', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Magna Rouleur Magitek', id: '207E', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: '魔導マグナローダー', id: '207E', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '魔导机车大魔', id: '207E', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '마도 마그나로더', id: '207E', capture: false }), // This repeats indefinitely, so only call the first one per Wild Speed phase. condition: (data) => !data.calledWildSpeed, delaySeconds: 6, response: Responses.killAdds(), run: (data) => data.calledWildSpeed = true, }, { id: 'CastrumAbania Magna Roader Mark XLIII Mini Cannon', type: 'NameToggle', netRegex: NetRegexes.nameToggle({ name: 'Mark XLIII Mini Cannon', toggle: '01', capture: false }), netRegexDe: NetRegexes.nameToggle({ name: 'Kleingeschütz Xliii', toggle: '01', capture: false }), netRegexFr: NetRegexes.nameToggle({ name: 'Mortier Type Xliii', toggle: '01', capture: false }), netRegexJa: NetRegexes.nameToggle({ name: 'Xliii式小臼砲', toggle: '01', capture: false }), netRegexCn: NetRegexes.nameToggle({ name: '43式小迫击炮', toggle: '01', capture: false }), netRegexKo: NetRegexes.nameToggle({ name: 'Xliii식 소형 박격포', toggle: '01', capture: false }), // There's two cannons, so only say something when the first one is targetable. condition: (data) => !data.calledUseCannon, delaySeconds: 6, infoText: (_data, _matches, output) => output.text!(), run: (data) => data.calledUseCannon = true, outputStrings: { text: { en: 'Fire cannon at boss', de: 'Feuere Kanonen auf den Boss', fr: 'Tirez le canon sur le boss', cn: '用炮射BOSS', ko: '보스 파동탄 맞추기', }, }, }, { id: 'CastrumAbania Number XXIV Stab', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Number XXIV', id: '1F1B' }), netRegexDe: NetRegexes.startsUsing({ source: 'Nummer Xxiv', id: '1F1B' }), netRegexFr: NetRegexes.startsUsing({ source: 'Numéro Xxiv', id: '1F1B' }), netRegexJa: NetRegexes.startsUsing({ source: 'ナンバーXxiv', id: '1F1B' }), netRegexCn: NetRegexes.startsUsing({ source: '024号', id: '1F1B' }), netRegexKo: NetRegexes.startsUsing({ source: 'Xxiv호', id: '1F1B' }), response: Responses.tankBuster(), }, { id: 'CastrumAbania Number XXIV Barrier Shift Fire', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Number XXIV', id: '1F21', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Nummer Xxiv', id: '1F21', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Numéro Xxiv', id: '1F21', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'ナンバーXxiv', id: '1F21', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '024号', id: '1F21', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: 'Xxiv호', id: '1F21', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Get Fire Buff', de: 'Nimm Feuer Buff', fr: 'Obtenez le buff de Feu', cn: '去火BUFF', ko: '화염 속성 버프 얻기', }, }, }, { id: 'CastrumAbania Number XXIV Barrier Shift Ice', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Number XXIV', id: '1F22', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Nummer Xxiv', id: '1F22', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Numéro Xxiv', id: '1F22', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'ナンバーXxiv', id: '1F22', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '024号', id: '1F22', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: 'Xxiv호', id: '1F22', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Get Ice Buff', de: 'Nimm Eis Buff', fr: 'Obtenez le buff de Glace', cn: '去冰BUFF', ko: '빙결 속성 버프 얻기', }, }, }, { id: 'CastrumAbania Number XXIV Barrier Shift Lightning', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Number XXIV', id: '1F23', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Nummer Xxiv', id: '1F23', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Numéro Xxiv', id: '1F23', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'ナンバーXxiv', id: '1F23', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '024号', id: '1F23', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: 'Xxiv호', id: '1F23', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Get Lightning Buff', de: 'Nimm Blitz Buff', fr: 'Obtenez le buff d\'Éclair', cn: '去雷BUFF', ko: '뇌격 속성 버프 얻기', }, }, }, { id: 'CastrumAbania Inferno Ketu Slash', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Inferno', id: ['1F26', '208B', '208C'] }), netRegexDe: NetRegexes.startsUsing({ source: 'Inferno', id: ['1F26', '208B', '208C'] }), netRegexFr: NetRegexes.startsUsing({ source: 'Inferno', id: ['1F26', '208B', '208C'] }), netRegexJa: NetRegexes.startsUsing({ source: 'インフェルノ', id: ['1F26', '208B', '208C'] }), netRegexCn: NetRegexes.startsUsing({ source: '炼狱炎魔', id: ['1F26', '208B', '208C'] }), netRegexKo: NetRegexes.startsUsing({ source: '인페르노', id: ['1F26', '208B', '208C'] }), response: Responses.tankBuster(), }, { id: 'CastrumAbania Inferno Adds', type: 'AddedCombatant', netRegex: NetRegexes.addedCombatantFull({ npcNameId: '6270', capture: false }), response: Responses.killAdds(), }, { id: 'CastrumAbania Inferno Rahu Ray', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '004A' }), condition: Conditions.targetIsYou(), response: Responses.spread(), }, { id: 'CastrumAbania Inferno Rahu Comet', type: 'StartsUsing', // Rahu Comet (1F2B) does not do knockback until it has been empowered at least once. netRegex: NetRegexes.startsUsing({ source: 'Inferno', id: ['2088', '2089'], capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Inferno', id: ['2088', '2089'], capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Inferno', id: ['2088', '2089'], capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'インフェルノ', id: ['2088', '2089'], capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '炼狱炎魔', id: ['2088', '2089'], capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '인페르노', id: ['2088', '2089'], capture: false }), infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { // Knockback comes from the proximity marker, not the boss. en: 'Small comet knockback', de: 'Kleiner Kometenrückstoß', fr: 'Poussée de la petite comète', cn: '小彗星击退', ko: '작은 혜성 넉백', }, }, }, ], timelineReplace: [ { 'locale': 'de', 'replaceSync': { 'Inferno': 'Inferno', 'Magna Roader': 'Magna Rotula', 'Mark XLIII Mini Cannon': 'Kleingeschütz Xliii', 'Number XXIV': 'Nummer XXIV', 'Project Aegis': 'Projekt Aegis', 'Terrestrial Weaponry': 'Bodenwaffenentwicklung', 'The Assessment Grounds': 'Evaluationsgelände', }, 'replaceText': { '--adds--': '--Adds--', 'Barrier Shift': 'Barrierewechsel', 'Gale Cut': 'Sturmschnitt', 'Ketu & Rahu': 'Ketoh & Rahu', 'Ketu Cut': 'Ketoh-Schnitt', 'Ketu Slash': 'Ketoh-Hieb', 'Magitek Fire II(?!I)': 'Magitek-Feura', 'Magitek Fire III': 'Magitek-Feuga', 'Rahu Blaster': 'Rahu-Blaster', 'Rahu Cut': 'Rahu-Schnitt', 'Stab': 'Durchstoß', 'Towers': 'Türme', 'Wheel': 'Rad', 'Wild Speed': 'Heißlaufen', }, }, { 'locale': 'fr', 'missingTranslations': true, 'replaceSync': { 'Inferno': 'Inferno', 'Magna Roader': 'magna rouleur magitek', 'Mark XLIII Mini Cannon': 'Mortier Type Xliii', 'Number XXIV': 'Numéro XXIV', 'Project Aegis': 'Projet Aegis', 'Terrestrial Weaponry': 'Armement terrestre', 'The Assessment Grounds': 'Terrain d\'évaluation', }, 'replaceText': { 'Barrier Shift': 'Change-Barrière', 'Gale Cut': 'Chute de pointes', 'Ketu & Rahu': 'Ketu et Rahu', 'Ketu Cut': 'Dépassement Ketu', 'Ketu Slash': 'Taillade Ketu', 'Magitek Fire II(?!I)': 'Extra Feu magitek', 'Magitek Fire III': 'Méga Feu magitek', 'Rahu Blaster': 'Canon Rahu', 'Rahu Cut': 'Dépassement Rahu', 'Stab': 'Poignardage', 'Wheel': 'Roue', 'Wild Speed': 'Course folle', }, }, { 'locale': 'ja', 'missingTranslations': true, 'replaceSync': { 'Inferno': 'インフェルノ', 'Magna Roader': '魔導マグナローダー', 'Mark XLIII Mini Cannon': 'Xliii式小臼砲', 'Number XXIV': 'ナンバーXXIV', 'Project Aegis': '強化実験房', 'Terrestrial Weaponry': '陸戦兵器開発房', 'The Assessment Grounds': '性能試験場', }, 'replaceText': { 'Barrier Shift': 'バリアチェンジ', 'Gale Cut': '烈風殺', 'Ketu & Rahu': 'ケトゥ&ラフ', 'Ketu Cut': 'ケトゥ・リミッターカット', 'Ketu Slash': 'ケトゥ・スラッシュ', 'Magitek Fire II(?!I)': '魔導ファイラ', 'Magitek Fire III': '魔導ファイガ', 'Rahu Blaster': 'ラフ・ブラスター', 'Rahu Cut': 'ラフ・リミッターカット', 'Stab': '刺突', 'Wheel': 'ホイール', 'Wild Speed': '暴走', }, }, { 'locale': 'cn', 'replaceSync': { 'Inferno': '炼狱炎魔', 'Magna Roader': '魔导机车大魔', 'Mark XLIII Mini Cannon': '43式小迫击炮', 'Number XXIV': '024号', 'Project Aegis': '强化实验室', 'Terrestrial Weaponry': '陆战兵器开发室', 'The Assessment Grounds': '性能试验场', }, 'replaceText': { '--adds--': '--小怪--', 'Barrier Shift': '护盾转换', 'Gale Cut': '烈风杀', 'Ketu & Rahu': '罗睺计都', 'Ketu Cut': '计都限制器减档', 'Ketu Slash': '计都挥', 'Magitek Fire II(?!I)': '魔导烈炎', 'Magitek Fire III': '魔导爆炎', 'Rahu Blaster': '罗睺冲击波', 'Rahu Cut': '罗睺限制器减档', 'Stab': '突刺', 'Towers': '塔', 'Wheel': '车轮', 'Wild Speed': '猛冲', }, }, { 'locale': 'ko', 'replaceSync': { 'Inferno': '인페르노', 'Magna Roader': '마도 마그나로더', 'Mark XLIII Mini Cannon': 'Xliii식 소형 박격포', 'Number XXIV': 'XXIV호', 'Project Aegis': '강화실험실', 'Terrestrial Weaponry': '지상 병기 개발실', 'The Assessment Grounds': '성능 시험장', }, 'replaceText': { '--adds--': '--쫄--', 'Barrier Shift': '보호막 변환', 'Gale Cut': '열풍살', 'Ketu & Rahu': '케투와 라후', 'Ketu Cut': '케투 리미터 해제', 'Ketu Slash': '케투 난도질', 'Magitek Fire II(?!I)': '마도 파이라', 'Magitek Fire III': '마도 파이가', 'Rahu Blaster': '라후 폭파', 'Rahu Cut': '라후 리미터 해제', 'Stab': '찌르기', 'Towers': '기둥', 'Wheel': '바퀴', 'Wild Speed': '폭주', }, }, ], }; export default triggerSet;
the_stack
import * as angular from 'angular'; import {moduleName} from './module-name'; import {IDGenerator} from '../common/utils/IDGenerator'; export default class HttpService{ cancelPendingHttpRequests: any; getJson: any; AbortableRequestBuilder: any; getAllRequestBuilder: any; get: any; newRequestBuilder: any; getAndTransform: any; getAll: any; appendTransform: any; constructor(private $q: any, private $http: any){ /** * Cancel all Pending Requests. * This is useful when changing views */ this.cancelPendingHttpRequests = function () { angular.forEach($http.pendingRequests, function (request: any) { if (request.cancel && request.timeout) { request.cancel.resolve(); } }); } this.getJson = function (url: any) { return $http.get(url, {headers: {'Content-type': 'application/json'}}); } this.AbortableRequestBuilder = function (url: any) { var builder = this; this.successFn; this.errorFn; this.finallyFn; this.transformFn; this.params; this.url = url; return { params: function (getParameters: any) { if (getParameters) { builder.params = getParameters; } return this; }, transform: function (fn: any) { if (fn) { builder.transformFn = fn; } return this; }, success: function (fn: any) { if (fn) { builder.successFn = fn; } return this; }, error: function (fn: any) { if (fn) { builder.errorFn = fn; } return this; }, finally: function (fn: any) { if (fn) { builder.finallyFn = fn; } return this; }, build: function () { var canceller: any = { resolve: function () { } };//$q.defer(); var options: any = {}//timeout: canceller.promise, cancel: canceller}; if (builder.params) { options.params = builder.params; } if (builder.transformFn) { // options.transformResponse = this.appendTransform($http.defaults.transformResponse,function(value){ // return transformResponseFn(value); // }) options.transformResponse = builder.transformFn; } var promise: any = $http.get(builder.url, options); if (builder.successFn) { promise.then(builder.successFn); } if (builder.errorFn) { promise.catch(builder.errorFn); } promise.finally(function () { if (builder.finallyFn) { builder.finallyFn(); } }); return { promise: promise, cancel: canceller, abort: function () { if (this.cancel != null) { this.cancel.resolve('Aborted'); } this.cancel = null; this.promise = null; } }; } } } /** * Creates an Abortable Request Builder for multiple Urls and allows you to listen for the final * success return * @param urls * @returns {{success: Function, error: Function, finally: Function, build: Function}} */ this.getAllRequestBuilder = function (urls: any) { this.id = IDGenerator.generateId('requestBuilder'); var builder: any = this; this.urls = urls; this.requestBuilders = []; this.finalSuccessFn; this.finalErrorFn; this.finallyFn; this.allData = []; var successFn = function (data: any) { if (data.length === undefined) { data = [data]; } if (data.length > 0) { builder.allData.push.apply(builder.allData, data); } }; var errorFn = function (data: any, status: any, headers: any, config: any) { if (status && status == 0) { //cancelled request } else { console.log("Failed to execute query ", data, status, headers, config); } }; for (var i = 0; i < urls.length; i++) { var rqst: any = new this.AbortableRequestBuilder(urls[i]).success(successFn).error(errorFn); builder.requestBuilders.push(rqst); } return { success: function (fn: any) { if (fn) { builder.finalSuccessFn = fn; } return this; }, error: function (fn: any) { if (fn) { builder.finalErrorFn = fn; } return this; }, finally: function (fn: any) { if (fn) { builder.finallyFn = fn; } return this; }, build: function () { var deferred = $q.defer(); var promises = []; var requests = []; for (var i = 0; i < builder.requestBuilders.length; i++) { var rqst = builder.requestBuilders[i].build(); requests.push(rqst); promises.push(rqst.promise); } deferred.promise.then(function (data: any) { if (builder.finalSuccessFn) { builder.finalSuccessFn(data); } }, function () { if (builder.finalErrorFn) { builder.finalErrorFn(); } }).finally(function () { if (builder.finallyFn) { builder.finallyFn(); } }); $q.all(promises).then(function (returnData: any) { deferred.resolve(builder.allData); }, function (e: any) { if (e && e.status && e.status == 0) { //cancelled request... dont log } else { console.log("Error occurred", e); } }); return { requests: requests, promise: deferred.promise, abort: function () { if (this.requests) { for (var i = 0; i < this.requests.length; i++) { this.requests[i].abort('Aborted'); } } } } } } } /** * Return an Abortable Request * Usage: * var rqst = HttpService.get("/feed/" + feed + "/exitCode/" + exitCode); * rqst.promise.success(function(data){ ..}) * .error(function() { ...}) * .finally(function() { ... }); * //to abort: * rqst.abort(); * * @param url * @returns {*|{promise, cancel, abort}|{requests, promise, abort}} */ this.get = function (url: any) { return this.newRequestBuilder(url).build(); } /** * creates a new AbortableRequestBuilder * This needs to call build to execute. * Example: * HttpService.newRequestBuilder(url).build(); * @param url * @returns {AbortableRequestBuilder} */ this.newRequestBuilder = function (url: any) { return new this.AbortableRequestBuilder(url); } this.getAndTransform = function (url: any, transformFn: any) { return this.newRequestBuilder(url).transform(transformFn).build(); } /** * Example Usage: * 1. pass in callbacks: * var rqst = HttpService.getAll(urls,successFn,errorFn,finallyFn); * //to abort * rqst.abort() * 2. add callbacks * var rqst = HttpService.getAll(urls); * rqst.promise.then(successFn,errorFn).finally(finallyFn); * //to abort * rqst.abort(); * * @param urls * @param successFunction * @param errorFunction * @param finallyFunction * @returns {*|{promise, cancel, abort}|{requests, promise, abort}} */ this.getAll = function (urls: any, successFunction: any, errorFunction: any, finallyFunction: any) { return new this.getAllRequestBuilder(urls).success(successFunction).error(errorFunction).finally(finallyFunction).build(); } this.appendTransform = function (defaults: any, transform: any) { // We can't guarantee that the default transformation is an array defaults = angular.isArray(defaults) ? defaults : [defaults]; // Append the new transformation to the defaults return defaults.concat(transform); } } } angular.module(moduleName).service('HttpService', ['$q', '$http', HttpService]);
the_stack
import querystring from 'querystring'; import { Readable } from 'stream'; import AxiosError from 'axios-error'; import axios, { AxiosInstance, AxiosError as BaseAxiosError } from 'axios'; import imageType from 'image-type'; import invariant from 'ts-invariant'; import warning from 'warning'; import { OnRequestFunction, createRequestInterceptor, } from 'messaging-api-common'; import * as Line from './Line'; import * as LineTypes from './LineTypes'; function handleError( err: BaseAxiosError<{ message: string; details: { property: string; message: string; }[]; }> ): never { if (err.response && err.response.data) { const { message, details } = err.response.data; let msg = `LINE API - ${message}`; if (details && details.length > 0) { details.forEach((detail) => { msg += `\n- ${detail.property}: ${detail.message}`; }); } throw new AxiosError(msg, err); } throw new AxiosError(err.message, err); } /** * LineClient is a client for LINE API calls. */ export default class LineClient { /** * @deprecated Use `new LineClient(...)` instead. */ static connect(config: LineTypes.ClientConfig): LineClient { warning( false, '`LineClient.connect(...)` is deprecated. Use `new LineClient(...)` instead.' ); return new LineClient(config); } /** * The underlying axios instance. */ readonly axios: AxiosInstance; /** * The underlying axios instance for api-data.line.me APIs. */ readonly dataAxios: AxiosInstance; /** * The access token used by the client */ readonly accessToken: string; /** * The channel secret used by the client */ readonly channelSecret: string | undefined; /** * The callback to be called when receiving requests. */ private onRequest?: OnRequestFunction; /** * Constructor of LineClient * * Usage: * ```ts * new LineClient({ * accessToken: ACCESS_TOKEN, * }) * ``` * * @param config - [[ClientConfig]] */ constructor(config: LineTypes.ClientConfig) { invariant( typeof config !== 'string', `LineClient: do not allow constructing client with ${config} string. Use object instead.` ); this.accessToken = config.accessToken; this.channelSecret = config.channelSecret; this.onRequest = config.onRequest; const { origin, dataOrigin } = config; this.axios = axios.create({ baseURL: `${origin || 'https://api.line.me'}/`, headers: { Authorization: `Bearer ${this.accessToken}`, 'Content-Type': 'application/json', }, }); this.axios.interceptors.request.use( createRequestInterceptor({ onRequest: this.onRequest }) ); this.dataAxios = axios.create({ baseURL: `${dataOrigin || 'https://api-data.line.me'}/`, headers: { Authorization: `Bearer ${this.accessToken}`, 'Content-Type': 'application/json', }, }); this.dataAxios.interceptors.request.use( createRequestInterceptor({ onRequest: this.onRequest }) ); } /** * Gets a bot's basic information. * * [Official document](https://developers.line.biz/en/reference/messaging-api/#get-bot-info) * * @returns Returns status code 200 and a JSON object with the bot information. */ getBotInfo(): Promise<LineTypes.BotInfoResponse> { return this.axios .get<LineTypes.BotInfoResponse>('/v2/bot/info') .then((res) => res.data, handleError); } /** * Gets information on a webhook endpoint. * * [Official document](https://developers.line.biz/en/reference/messaging-api/#get-webhook-endpoint-information) * * @returns Returns status code 200 and a JSON object with the webhook information. */ getWebhookEndpointInfo(): Promise<LineTypes.WebhookEndpointInfoResponse> { return this.axios .get<LineTypes.WebhookEndpointInfoResponse>( '/v2/bot/channel/webhook/endpoint' ) .then((res) => res.data, handleError); } /** * Sets the webhook endpoint URL. It may take up to 1 minute for changes to take place due to caching. * * [Official document](https://developers.line.biz/en/reference/messaging-api/#get-webhook-endpoint-information) * * @param endpoint - Webhook URL. * * @returns Returns status code `200` and an empty JSON object. */ setWebhookEndpointUrl( endpoint: string ): Promise<LineTypes.MutationSuccessResponse> { return this.axios .put<LineTypes.MutationSuccessResponse>( '/v2/bot/channel/webhook/endpoint', { endpoint } ) .then((res) => res.data, handleError); } /** * Checks if the configured webhook endpoint can receive a test webhook event. * * [Official document](https://developers.line.biz/en/reference/messaging-api/#test-webhook-endpoint) * * @returns Returns status code 200 and a JSON object with the webhook information. */ testWebhookEndpoint(): Promise<LineTypes.TestWebhookEndpointResponse> { return this.axios .post<LineTypes.TestWebhookEndpointResponse>( '/v2/bot/channel/webhook/test' ) .then((res) => res.data, handleError); } /** * Reply Message * Sends a reply message in response to an event from a user, group, or room. * * To send reply messages, you must have a reply token which is included in a webhook event object. * * [Webhooks](https://developers.line.biz/en/reference/messaging-api/#webhooks) are used to notify you when an event occurs. For events that you can respond to, a reply token is issued for replying to messages. * * Because the reply token becomes invalid after a certain period of time, responses should be sent as soon as a message is received. Reply tokens can only be used once. * * [Official document](https://developers.line.biz/en/reference/messaging-api/#send-reply-message) * * @param body - Request body * @param body.replyToken - Reply token received via webhook * @param body.messages - Messages to send (Max: 5) * * @returns Returns status code `200` and an empty JSON object. */ replyRawBody(body: { replyToken: string; messages: LineTypes.Message[]; }): Promise<LineTypes.MutationSuccessResponse> { return this.axios .post<LineTypes.MutationSuccessResponse>('/v2/bot/message/reply', body) .then((res) => res.data, handleError); } /** * Reply Message * * Sends a reply message in response to an event from a user, group, or room. * * To send reply messages, you must have a reply token which is included in a webhook event object. * * [Webhooks](https://developers.line.biz/en/reference/messaging-api/#webhooks) are used to notify you when an event occurs. For events that you can respond to, a reply token is issued for replying to messages. * * Because the reply token becomes invalid after a certain period of time, responses should be sent as soon as a message is received. Reply tokens can only be used once. * * [Official document - send reply message](https://developers.line.biz/en/reference/messaging-api/#send-reply-message) * * @param replyToken - Reply token received via webhook * @param messages - Messages to send (Max: 5) * @returns Returns status code `200` and an empty JSON object. */ reply( replyToken: string, messages: LineTypes.Message[] ): Promise<LineTypes.MutationSuccessResponse> { return this.replyRawBody({ replyToken, messages }); } /** * Reply Message * * Sends a reply message in response to an event from a user, group, or room. * * To send reply messages, you must have a reply token which is included in a webhook event object. * * [Webhooks](https://developers.line.biz/en/reference/messaging-api/#webhooks) are used to notify you when an event occurs. For events that you can respond to, a reply token is issued for replying to messages. * * Because the reply token becomes invalid after a certain period of time, responses should be sent as soon as a message is received. Reply tokens can only be used once. * * [Official document - send reply message](https://developers.line.biz/en/reference/messaging-api/#send-reply-message) * * @param replyToken - Reply token received via webhook * @param messages - Messages to send (Max: 5) * @returns Returns status code `200` and an empty JSON object. */ replyMessages( replyToken: string, messages: LineTypes.Message[] ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, messages); } /** * Reply Text Message * * [Official document - text message](https://developers.line.biz/en/reference/messaging-api/#text-message) * * @param replyToken - Reply token received via webhook * @param text - Message text. * * You can include the following emoji: * - Unicode emoji * - LINE original emoji [(Unicode code point table for LINE original emoji)](https://developers.line.biz/media/messaging-api/emoji-list.pdf) * * Max character limit: 2000 * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ replyText( replyToken: string, text: string, options?: LineTypes.MessageOptions & { emojis?: LineTypes.Emoji[] } ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [Line.createText(text, options)]); } /** * Reply Image Message * * [Official document - image message](https://developers.line.biz/en/reference/messaging-api/#image-message) * * @param replyToken - Reply token received via webhook * @param image - Image * @param options - Common properties for messages * @param image.originalContentUrl - Image URL * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - JPEG * - Max: 4096 x 4096 * - Max: 1 MB * @param image.previewImageUrl - Preview image URL * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - JPEG * - Max: 240 x 240 * - Max: 1 MB * @returns Returns status code `200` and an empty JSON object. */ replyImage( replyToken: string, image: { originalContentUrl: string; previewImageUrl?: string; }, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [Line.createImage(image, options)]); } /** * Reply Video Message * * [Official document - video message](https://developers.line.biz/en/reference/messaging-api/#video-message) * * @param replyToken - Reply token received via webhook * @param video - Video * @param options - Common properties for messages * @param video.originalContentUrl - URL of video file * * A very wide or tall video may be cropped when played in some environments. * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - mp4 * - Max: 1 minute * - Max: 10 MB * * @param video.previewImageUrl - URL of preview image * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - JPEG * - Max: 240 x 240 * - Max: 1 MB * @returns Returns status code `200` and an empty JSON object. */ replyVideo( replyToken: string, video: { originalContentUrl: string; previewImageUrl: string; }, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [Line.createVideo(video, options)]); } /** * Reply Audio Message * * [Official document - audio message](https://developers.line.biz/en/reference/messaging-api/#audio-message) * * @param replyToken - Reply token received via webhook * @param audio - Audio * @param options - Common properties for messages * @param audio.originalContentUrl - URL of audio file * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - m4a * - Max: 1 minute * - Max: 10 MB * @param audio.duration - Length of audio file (milliseconds) * @returns Returns status code `200` and an empty JSON object. */ replyAudio( replyToken: string, audio: { originalContentUrl: string; duration: number; }, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [Line.createAudio(audio, options)]); } /** * Reply Location Message * * [Official document - location message](https://developers.line.biz/en/reference/messaging-api/#location-message) * * @param replyToken - Reply token received via webhook * @param location - Location * * location.title: * - Max character limit: 100 * * location.address: * - Max character limit: 100 * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ replyLocation( replyToken: string, location: LineTypes.Location, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [Line.createLocation(location, options)]); } /** * Reply Sticker Message * * [Official document - sticker message](https://developers.line.biz/en/reference/messaging-api/#sticker-message) * * @param replyToken - Reply token received via webhook * @param sticker - Sticker * * sticker.packageId: * - Package ID for a set of stickers. For information on package IDs, see the [Sticker list](https://developers.line.biz/media/messaging-api/sticker_list.pdf). * * sticker.stickerId: * - Sticker ID. For a list of sticker IDs for stickers that can be sent with the Messaging API, see the [Sticker list](https://developers.line.biz/media/messaging-api/sticker_list.pdf). * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ replySticker( replyToken: string, sticker: Omit<LineTypes.StickerMessage, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [Line.createSticker(sticker, options)]); } /** * Reply Imagemap Message * * Imagemap messages are messages configured with an image that has multiple tappable areas. You can assign one tappable area for the entire image or different tappable areas on divided areas of the image. * * You can also play a video on the image and display a label with a hyperlink after the video is finished. * * [Official document - imagemap message](https://developers.line.biz/en/reference/messaging-api/#imagemap-message) * * @param replyToken - Reply token received via webhook * @param altText - Alternative text * @param imagemap - Imagemap * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ replyImagemap( replyToken: string, altText: string, imagemap: Omit<LineTypes.ImagemapMessage, 'type' | 'altText'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [ Line.createImagemap(altText, imagemap, options), ]); } /** * Reply Flex Message * * Flex Messages are messages with a customizable layout. * You can customize the layout freely based on the specification for [CSS Flexible Box (CSS Flexbox)](https://www.w3.org/TR/css-flexbox-1/). * For more information, see [Sending Flex Messages](https://developers.line.biz/en/docs/messaging-api/using-flex-messages/) in the API documentation. * * [Official document - flex message](https://developers.line.biz/en/reference/messaging-api/#flex-message) * * @param replyToken - Reply token received via webhook * @param altText - Alternative text * @param flex - Flex Message [container](https://developers.line.biz/en/reference/messaging-api/#container) * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ replyFlex( replyToken: string, altText: string, flex: LineTypes.FlexContainer, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [Line.createFlex(altText, flex, options)]); } /** * Reply Template Message * * Template messages are messages with predefined layouts which you can customize. For more information, see [Template messages](https://developers.line.biz/en/docs/messaging-api/message-types/#template-messages). * * The following template types are available: * - [Buttons](https://developers.line.biz/en/reference/messaging-api/#buttons) * - [Confirm](https://developers.line.biz/en/reference/messaging-api/#confirm) * - [Carousel](https://developers.line.biz/en/reference/messaging-api/#carousel) * - [Image carousel](https://developers.line.biz/en/reference/messaging-api/#image-carousel) * * [Official document - template message](https://developers.line.biz/en/reference/messaging-api/#template-messages) * * @param replyToken - Reply token received via webhook * @param altText - Alternative text * @param template - A [Buttons](https://developers.line.biz/en/reference/messaging-api/#buttons), [Confirm](https://developers.line.biz/en/reference/messaging-api/#confirm), [Carousel](https://developers.line.biz/en/reference/messaging-api/#carousel), or [Image carousel](https://developers.line.biz/en/reference/messaging-api/#image-carousel) object. * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ replyTemplate( replyToken: string, altText: string, template: LineTypes.Template, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [ Line.createTemplate(altText, template, options), ]); } /** * Reply Button Template Message * * Template with an image, title, text, and multiple action buttons. * * [Official document - button template message](https://developers.line.biz/en/reference/messaging-api/#buttons) * * @param replyToken - Reply token received via webhook * @param altText - Alternative text * @param buttonTemplate - Button template object * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ replyButtonTemplate( replyToken: string, altText: string, buttonTemplate: Omit<LineTypes.ButtonsTemplate, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [ Line.createButtonTemplate(altText, buttonTemplate, options), ]); } /** * Reply Button Template Message * * Template with an image, title, text, and multiple action buttons. * * Because of the height limitation for buttons template messages, the lower part of the text display area will get cut off if the height limitation is exceeded. For this reason, depending on the character width, the message text may not be fully displayed even when it is within the character limits. * * [Official document - button template message](https://developers.line.biz/en/reference/messaging-api/#buttons) * * @param replyToken - Reply token received via webhook * @param altText - Alternative text * @param buttonTemplate - Button template object * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ replyButtonsTemplate( replyToken: string, altText: string, buttonTemplate: Omit<LineTypes.ButtonsTemplate, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.replyButtonTemplate( replyToken, altText, buttonTemplate, options ); } /** * Reply Confirm Template Message * * Template with two action buttons. * * Because of the height limitation for confirm template messages, the lower part of the text display area will get cut off if the height limitation is exceeded. For this reason, depending on the character width, the message text may not be fully displayed even when it is within the character limits. * * [Official document - confirm template message](https://developers.line.biz/en/reference/messaging-api/#confirm) * * @param replyToken - Reply token received via webhook * @param altText - Alternative text * @param confirmTemplate - Confirm template object * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ replyConfirmTemplate( replyToken: string, altText: string, confirmTemplate: Omit<LineTypes.ConfirmTemplate, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [ Line.createConfirmTemplate(altText, confirmTemplate, options), ]); } /** * Reply Carousel Template Message * * Template with multiple columns which can be cycled like a carousel. The columns are shown in order when scrolling horizontally. * * [Official document - carousel template message](https://developers.line.biz/en/reference/messaging-api/#carousel) * * @param replyToken - Reply token received via webhook * @param altText - Alternative text * @param columns - Array of columns for carousel * * Max columns: 10 * * @param options - Carousel template options * @returns Returns status code `200` and an empty JSON object. */ replyCarouselTemplate( replyToken: string, altText: string, columns: LineTypes.ColumnObject[], options: LineTypes.CarouselTemplateOptions = {} ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [ Line.createCarouselTemplate(altText, columns, options), ]); } /** * Reply Image Carousel Template Message * * Template with multiple images which can be cycled like a carousel. The images are shown in order when scrolling horizontally. * * [Official document - image carousel template message](https://developers.line.biz/en/reference/messaging-api/#image-carousel) * * @param replyToken - Reply token received via webhook * @param altText - Alternative text * @param columns - Array of columns for image carousel * * Max columns: 10 * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ replyImageCarouselTemplate( replyToken: string, altText: string, columns: LineTypes.ImageCarouselColumnObject[], options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.reply(replyToken, [ Line.createImageCarouselTemplate(altText, columns, options), ]); } /** * Push Message * * Sends a push message to a user, group, or room at any time. * * Note: LINE\@ accounts under the free or basic plan cannot call this API endpoint. * * [Official document - send push message](https://developers.line.biz/en/reference/messaging-api/#send-push-message) * * @param body - Request body * @param body.to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param body.messages - Messages to send (Max: 5) * @returns Returns status code `200` and an empty JSON object. */ pushRawBody(body: { to: string; messages: LineTypes.Message[]; }): Promise<LineTypes.MutationSuccessResponse> { return this.axios .post<LineTypes.MutationSuccessResponse>('/v2/bot/message/push', body) .then((res) => res.data, handleError); } /** * Push Message * * Sends a push message to a user, group, or room at any time. * * Note: LINE\@ accounts under the free or basic plan cannot call this API endpoint. * * [Official document - send push message](https://developers.line.biz/en/reference/messaging-api/#send-push-message) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param messages - Messages to send (Max: 5) * @returns Returns status code `200` and an empty JSON object. */ push( to: string, messages: LineTypes.Message[] ): Promise<LineTypes.MutationSuccessResponse> { return this.pushRawBody({ to, messages }); } /** * Push Message * * Sends a push message to a user, group, or room at any time. * * Note: LINE\@ accounts under the free or basic plan cannot call this API endpoint. * * [Official document - send push message](https://developers.line.biz/en/reference/messaging-api/#send-push-message) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param messages - Messages to send (Max: 5) * @returns Returns status code `200` and an empty JSON object. */ pushMessages( to: string, messages: LineTypes.Message[] ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, messages); } /** * Push Text Message * * [Official document - text message](https://developers.line.biz/en/reference/messaging-api/#text-message) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param text - Message text. * * You can include the following emoji: * - Unicode emoji * - LINE original emoji [(Unicode code point table for LINE original emoji)](https://developers.line.biz/media/messaging-api/emoji-list.pdf) * * Max character limit: 2000 * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ pushText( to: string, text: string, options?: LineTypes.MessageOptions & { emojis?: LineTypes.Emoji[] } ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [Line.createText(text, options)]); } /** * Push Image Message * * [Official document - image message](https://developers.line.biz/en/reference/messaging-api/#image-message) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param image - Image * @param options - Common properties for messages * @param image.originalContentUrl - Image URL * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - JPEG * - Max: 4096 x 4096 * - Max: 1 MB * @param image.previewImageUrl - Preview image URL * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - JPEG * - Max: 240 x 240 * - Max: 1 MB * @returns Returns status code `200` and an empty JSON object. */ pushImage( to: string, image: { originalContentUrl: string; previewImageUrl?: string; }, options: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [Line.createImage(image, options)]); } /** * Push Video Message * * [Official document - video message](https://developers.line.biz/en/reference/messaging-api/#video-message) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param video - Video * @param options - Common properties for messages * @param video.originalContentUrl - URL of video file * * A very wide or tall video may be cropped when played in some environments. * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - mp4 * - Max: 1 minute * - Max: 10 MB * * @param video.previewImageUrl - URL of preview image * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - JPEG * - Max: 240 x 240 * - Max: 1 MB * @returns Returns status code `200` and an empty JSON object. */ pushVideo( to: string, video: { originalContentUrl: string; previewImageUrl: string; }, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [Line.createVideo(video, options)]); } /** * Push Audio Message * * [Official document - audio message](https://developers.line.biz/en/reference/messaging-api/#audio-message) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param audio - Audio * @param options - Common properties for messages * @param audio.originalContentUrl - URL of audio file * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - m4a * - Max: 1 minute * - Max: 10 MB * @param audio.duration - Length of audio file (milliseconds) * @returns Returns status code `200` and an empty JSON object. */ pushAudio( to: string, audio: { originalContentUrl: string; duration: number; }, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [Line.createAudio(audio, options)]); } /** * Push Location Message * * [Official document - location message](https://developers.line.biz/en/reference/messaging-api/#location-message) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param location - Location * * location.title: * - Max character limit: 100 * * location.address: * - Max character limit: 100 * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ pushLocation( to: string, location: LineTypes.Location, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [Line.createLocation(location, options)]); } /** * Push Sticker Message * * [Official document - sticker message](https://developers.line.biz/en/reference/messaging-api/#sticker-message) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param sticker - Sticker * * sticker.packageId: * - Package ID for a set of stickers. For information on package IDs, see the [Sticker list](https://developers.line.biz/media/messaging-api/sticker_list.pdf). * * sticker.stickerId: * - Sticker ID. For a list of sticker IDs for stickers that can be sent with the Messaging API, see the [Sticker list](https://developers.line.biz/media/messaging-api/sticker_list.pdf). * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ pushSticker( to: string, sticker: Omit<LineTypes.StickerMessage, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [Line.createSticker(sticker, options)]); } /** * Push Imagemap Message * * Imagemap messages are messages configured with an image that has multiple tappable areas. You can assign one tappable area for the entire image or different tappable areas on divided areas of the image. * * You can also play a video on the image and display a label with a hyperlink after the video is finished. * * [Official document - imagemap message](https://developers.line.biz/en/reference/messaging-api/#imagemap-message) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param altText - Alternative text * @param imagemap - Imagemap * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ pushImagemap( to: string, altText: string, imagemap: Omit<LineTypes.ImagemapMessage, 'type' | 'altText'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [Line.createImagemap(altText, imagemap, options)]); } /** * Push Flex Message * * Flex Messages are messages with a customizable layout. * You can customize the layout freely based on the specification for [CSS Flexible Box (CSS Flexbox)](https://www.w3.org/TR/css-flexbox-1/). * For more information, see [Sending Flex Messages](https://developers.line.biz/en/docs/messaging-api/using-flex-messages/) in the API documentation. * * [Official document - flex message](https://developers.line.biz/en/reference/messaging-api/#flex-message) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param altText - Alternative text * @param flex - Flex Message [container](https://developers.line.biz/en/reference/messaging-api/#container) * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ pushFlex( to: string, altText: string, flex: LineTypes.FlexContainer, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [Line.createFlex(altText, flex, options)]); } /** * Push Template Message * * Template messages are messages with predefined layouts which you can customize. For more information, see [Template messages](https://developers.line.biz/en/docs/messaging-api/message-types/#template-messages). * * The following template types are available: * - [Buttons](https://developers.line.biz/en/reference/messaging-api/#buttons) * - [Confirm](https://developers.line.biz/en/reference/messaging-api/#confirm) * - [Carousel](https://developers.line.biz/en/reference/messaging-api/#carousel) * - [Image carousel](https://developers.line.biz/en/reference/messaging-api/#image-carousel) * * [Official document - template message](https://developers.line.biz/en/reference/messaging-api/#template-messages) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param altText - Alternative text * @param template - A [Buttons](https://developers.line.biz/en/reference/messaging-api/#buttons), [Confirm](https://developers.line.biz/en/reference/messaging-api/#confirm), [Carousel](https://developers.line.biz/en/reference/messaging-api/#carousel), or [Image carousel](https://developers.line.biz/en/reference/messaging-api/#image-carousel) object. * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ pushTemplate( to: string, altText: string, template: LineTypes.Template, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [Line.createTemplate(altText, template, options)]); } /** * Push Button Template Message * * Template with an image, title, text, and multiple action buttons. * * [Official document - button template message](https://developers.line.biz/en/reference/messaging-api/#buttons) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param altText - Alternative text * @param buttonTemplate - Button template object * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ pushButtonTemplate( to: string, altText: string, buttonTemplate: Omit<LineTypes.ButtonsTemplate, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [ Line.createButtonTemplate(altText, buttonTemplate, options), ]); } /** * Push Button Template Message * * Template with an image, title, text, and multiple action buttons. * * Because of the height limitation for buttons template messages, the lower part of the text display area will get cut off if the height limitation is exceeded. For this reason, depending on the character width, the message text may not be fully displayed even when it is within the character limits. * * [Official document - button template message](https://developers.line.biz/en/reference/messaging-api/#buttons) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param altText - Alternative text * @param buttonTemplate - Button template object * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ pushButtonsTemplate( to: string, altText: string, buttonTemplate: Omit<LineTypes.ButtonsTemplate, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.pushButtonTemplate(to, altText, buttonTemplate, options); } /** * Push Confirm Template Message * * Template with two action buttons. * * Because of the height limitation for confirm template messages, the lower part of the text display area will get cut off if the height limitation is exceeded. For this reason, depending on the character width, the message text may not be fully displayed even when it is within the character limits. * * [Official document - confirm template message](https://developers.line.biz/en/reference/messaging-api/#confirm) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param altText - Alternative text * @param confirmTemplate - Confirm template object * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ pushConfirmTemplate( to: string, altText: string, confirmTemplate: Omit<LineTypes.ConfirmTemplate, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [ Line.createConfirmTemplate(altText, confirmTemplate, options), ]); } /** * Push Carousel Template Message * * Template with multiple columns which can be cycled like a carousel. The columns are shown in order when scrolling horizontally. * * [Official document - carousel template message](https://developers.line.biz/en/reference/messaging-api/#carousel) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param altText - Alternative text * @param columns - Array of columns for carousel * * Max columns: 10 * * @param options - Carousel template options * @returns Returns status code `200` and an empty JSON object. */ pushCarouselTemplate( to: string, altText: string, columns: LineTypes.ColumnObject[], options: LineTypes.CarouselTemplateOptions = {} ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [ Line.createCarouselTemplate(altText, columns, options), ]); } /** * Push Image Carousel Template Message * * Template with multiple images which can be cycled like a carousel. The images are shown in order when scrolling horizontally. * * [Official document - image carousel template message](https://developers.line.biz/en/reference/messaging-api/#image-carousel) * * @param to - ID of the target recipient. Use a userId, groupId, or roomId value returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use the LINE ID found on LINE. * @param altText - Alternative text * @param columns - Array of columns for image carousel * * Max columns: 10 * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ pushImageCarouselTemplate( to: string, altText: string, columns: LineTypes.ImageCarouselColumnObject[], options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.push(to, [ Line.createImageCarouselTemplate(altText, columns, options), ]); } /** * Multicast Message * * Sends push messages to multiple users at any time. Messages cannot be sent to groups or rooms. * * Note: LINE\@ accounts under the free or basic plan cannot call this API endpoint. * * [Official document - send multicast message](https://developers.line.biz/en/reference/messaging-api/#send-multicast-message) * * @param body - Request body * @param body.to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param body.messages - Messages to send (Max: 5) * @returns Returns status code `200` and an empty JSON object. */ multicastRawBody(body: { to: string[]; messages: LineTypes.Message[]; }): Promise<LineTypes.MutationSuccessResponse> { return this.axios .post<LineTypes.MutationSuccessResponse>( '/v2/bot/message/multicast', body ) .then((res) => res.data, handleError); } /** * Multicast Message * * Sends push messages to multiple users at any time. Messages cannot be sent to groups or rooms. * * Note: LINE\@ accounts under the free or basic plan cannot call this API endpoint. * * [Official document - send multicast message](https://developers.line.biz/en/reference/messaging-api/#send-multicast-message) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param messages - Messages to send (Max: 5) * @returns Returns status code `200` and an empty JSON object. */ multicast( to: string[], messages: LineTypes.Message[] ): Promise<LineTypes.MutationSuccessResponse> { return this.multicastRawBody({ to, messages }); } /** * Multicast Message * * Sends push messages to multiple users at any time. Messages cannot be sent to groups or rooms. * * Note: LINE\@ accounts under the free or basic plan cannot call this API endpoint. * * [Official document - send multicast message](https://developers.line.biz/en/reference/messaging-api/#send-multicast-message) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param messages - Messages to send (Max: 5) * @returns Returns status code `200` and an empty JSON object. */ multicastMessages( to: string[], messages: LineTypes.Message[] ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, messages); } /** * Multicast Text Message * * [Official document - text message](https://developers.line.biz/en/reference/messaging-api/#text-message) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param text - Message text. * * You can include the following emoji: * - Unicode emoji * - LINE original emoji [(Unicode code point table for LINE original emoji)](https://developers.line.biz/media/messaging-api/emoji-list.pdf) * * Max character limit: 2000 * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ multicastText( to: string[], text: string, options?: LineTypes.MessageOptions & { emojis?: LineTypes.Emoji[] } ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [Line.createText(text, options)]); } /** * Multicast Image Message * * [Official document - image message](https://developers.line.biz/en/reference/messaging-api/#image-message) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param image - Image * @param options - Common properties for messages * @param image.originalContentUrl - Image URL * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - JPEG * - Max: 4096 x 4096 * - Max: 1 MB * @param image.previewImageUrl - Preview image URL * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - JPEG * - Max: 240 x 240 * - Max: 1 MB * @returns Returns status code `200` and an empty JSON object. */ multicastImage( to: string[], image: { originalContentUrl: string; previewImageUrl?: string; }, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [Line.createImage(image, options)]); } /** * Multicast Video Message * * [Official document - video message](https://developers.line.biz/en/reference/messaging-api/#video-message) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param video - Video * @param options - Common properties for messages * @param video.originalContentUrl - URL of video file * * A very wide or tall video may be cropped when played in some environments. * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - mp4 * - Max: 1 minute * - Max: 10 MB * * @param video.previewImageUrl - URL of preview image * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - JPEG * - Max: 240 x 240 * - Max: 1 MB * @returns Returns status code `200` and an empty JSON object. */ multicastVideo( to: string[], video: { originalContentUrl: string; previewImageUrl: string; }, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [Line.createVideo(video, options)]); } /** * Multicast Audio Message * * [Official document - audio message](https://developers.line.biz/en/reference/messaging-api/#audio-message) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param audio - Audio * @param options - Common properties for messages * @param audio.originalContentUrl - URL of audio file * - Max character limit: 1000 * - HTTPS over TLS 1.2 or later * - m4a * - Max: 1 minute * - Max: 10 MB * @param audio.duration - Length of audio file (milliseconds) * @returns Returns status code `200` and an empty JSON object. */ multicastAudio( to: string[], audio: { originalContentUrl: string; duration: number; }, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [Line.createAudio(audio, options)]); } /** * Multicast Location Message * * [Official document - location message](https://developers.line.biz/en/reference/messaging-api/#location-message) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param location - Location * * location.title: * - Max character limit: 100 * * location.address: * - Max character limit: 100 * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ multicastLocation( to: string[], location: LineTypes.Location, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [Line.createLocation(location, options)]); } /** * Multicast Sticker Message * * [Official document - sticker message](https://developers.line.biz/en/reference/messaging-api/#sticker-message) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param sticker - Sticker * * sticker.packageId: * - Package ID for a set of stickers. For information on package IDs, see the [Sticker list](https://developers.line.biz/media/messaging-api/sticker_list.pdf). * * sticker.stickerId: * - Sticker ID. For a list of sticker IDs for stickers that can be sent with the Messaging API, see the [Sticker list](https://developers.line.biz/media/messaging-api/sticker_list.pdf). * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ multicastSticker( to: string[], sticker: Omit<LineTypes.StickerMessage, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [Line.createSticker(sticker, options)]); } /** * Multicast Imagemap Message * * Imagemap messages are messages configured with an image that has multiple tappable areas. You can assign one tappable area for the entire image or different tappable areas on divided areas of the image. * * You can also play a video on the image and display a label with a hyperlink after the video is finished. * * [Official document - imagemap message](https://developers.line.biz/en/reference/messaging-api/#imagemap-message) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param altText - Alternative text * @param imagemap - Imagemap * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ multicastImagemap( to: string[], altText: string, imagemap: Omit<LineTypes.ImagemapMessage, 'type' | 'altText'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [ Line.createImagemap(altText, imagemap, options), ]); } /** * Multicast Flex Message * * Flex Messages are messages with a customizable layout. * You can customize the layout freely based on the specification for [CSS Flexible Box (CSS Flexbox)](https://www.w3.org/TR/css-flexbox-1/). * For more information, see [Sending Flex Messages](https://developers.line.biz/en/docs/messaging-api/using-flex-messages/) in the API documentation. * * [Official document - flex message](https://developers.line.biz/en/reference/messaging-api/#flex-message) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param altText - Alternative text * @param flex - Flex Message [container](https://developers.line.biz/en/reference/messaging-api/#container) * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ multicastFlex( to: string[], altText: string, flex: LineTypes.FlexContainer, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [Line.createFlex(altText, flex, options)]); } /** * Multicast Template Message * * Template messages are messages with predefined layouts which you can customize. For more information, see [Template messages](https://developers.line.biz/en/docs/messaging-api/message-types/#template-messages). * * The following template types are available: * - [Buttons](https://developers.line.biz/en/reference/messaging-api/#buttons) * - [Confirm](https://developers.line.biz/en/reference/messaging-api/#confirm) * - [Carousel](https://developers.line.biz/en/reference/messaging-api/#carousel) * - [Image carousel](https://developers.line.biz/en/reference/messaging-api/#image-carousel) * * [Official document - template message](https://developers.line.biz/en/reference/messaging-api/#template-messages) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param altText - Alternative text * @param template - A [Buttons](https://developers.line.biz/en/reference/messaging-api/#buttons), [Confirm](https://developers.line.biz/en/reference/messaging-api/#confirm), [Carousel](https://developers.line.biz/en/reference/messaging-api/#carousel), or [Image carousel](https://developers.line.biz/en/reference/messaging-api/#image-carousel) object. * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ multicastTemplate( to: string[], altText: string, template: LineTypes.Template, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [ Line.createTemplate(altText, template, options), ]); } /** * Multicast Button Template Message * * Template with an image, title, text, and multiple action buttons. * * [Official document - button template message](https://developers.line.biz/en/reference/messaging-api/#buttons) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param altText - Alternative text * @param buttonTemplate - Button template object * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ multicastButtonTemplate( to: string[], altText: string, buttonTemplate: Omit<LineTypes.ButtonsTemplate, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [ Line.createButtonTemplate(altText, buttonTemplate, options), ]); } /** * Multicast Button Template Message * * Template with an image, title, text, and multiple action buttons. * * Because of the height limitation for buttons template messages, the lower part of the text display area will get cut off if the height limitation is exceeded. For this reason, depending on the character width, the message text may not be fully displayed even when it is within the character limits. * * [Official document - button template message](https://developers.line.biz/en/reference/messaging-api/#buttons) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param altText - Alternative text * @param buttonTemplate - Button template object * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ multicastButtonsTemplate( to: string[], altText: string, buttonTemplate: Omit<LineTypes.ButtonsTemplate, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicastButtonTemplate(to, altText, buttonTemplate, options); } /** * Multicast Confirm Template Message * * Template with two action buttons. * * Because of the height limitation for confirm template messages, the lower part of the text display area will get cut off if the height limitation is exceeded. For this reason, depending on the character width, the message text may not be fully displayed even when it is within the character limits. * * [Official document - confirm template message](https://developers.line.biz/en/reference/messaging-api/#confirm) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param altText - Alternative text * @param confirmTemplate - Confirm template object * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ multicastConfirmTemplate( to: string[], altText: string, confirmTemplate: Omit<LineTypes.ConfirmTemplate, 'type'>, options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [ Line.createConfirmTemplate(altText, confirmTemplate, options), ]); } /** * Multicast Carousel Template Message * * Template with multiple columns which can be cycled like a carousel. The columns are shown in order when scrolling horizontally. * * [Official document - carousel template message](https://developers.line.biz/en/reference/messaging-api/#carousel) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param altText - Alternative text * @param columns - Array of columns for carousel * * Max columns: 10 * * @param options - Carousel template options * @returns Returns status code `200` and an empty JSON object. */ multicastCarouselTemplate( to: string[], altText: string, columns: LineTypes.ColumnObject[], options: LineTypes.CarouselTemplateOptions = {} ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [ Line.createCarouselTemplate(altText, columns, options), ]); } /** * Multicast Image Carousel Template Message * * Template with multiple images which can be cycled like a carousel. The images are shown in order when scrolling horizontally. * * [Official document - image carousel template message](https://developers.line.biz/en/reference/messaging-api/#image-carousel) * * @param to - Array of user IDs. Use userId values which are returned in [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#common-properties). Do not use LINE IDs found on LINE. * - Max: 150 user IDs * @param altText - Alternative text * @param columns - Array of columns for image carousel * * Max columns: 10 * * @param options - Common properties for messages * @returns Returns status code `200` and an empty JSON object. */ multicastImageCarouselTemplate( to: string[], altText: string, columns: LineTypes.ImageCarouselColumnObject[], options?: LineTypes.MessageOptions ): Promise<LineTypes.MutationSuccessResponse> { return this.multicast(to, [ Line.createImageCarouselTemplate(altText, columns, options), ]); } /** * Broadcast Message * * Sends push messages to multiple users at any time. * * [Official document](https://developers.line.biz/en/reference/messaging-api/#send-broadcast-message) * * @param body - Request body * @param body.messages - Messages to send (Max: 5) * * @returns Returns status code `200` and an empty JSON object. */ broadcastRawBody(body: { messages: LineTypes.Message[]; }): Promise<LineTypes.MutationSuccessResponse> { return this.axios .post<LineTypes.MutationSuccessResponse>( '/v2/bot/message/broadcast', body ) .then((res) => res.data, handleError); } /** * Broadcast Message * * Sends push messages to multiple users at any time. * * [Official document - send broadcast message](https://developers.line.biz/en/reference/messaging-api/#send-reply-message) * * @param messages - Messages to send (Max: 5) * @returns Returns status code `200` and an empty JSON object. */ broadcast( messages: LineTypes.Message[] ): Promise<LineTypes.MutationSuccessResponse> { return this.broadcastRawBody({ messages }); } /** * Get Message Content * * Gets images, videos, audio, and files sent by users. * * 【No API for retrieving text】 * * You can't use the Messaging API to retrieve text sent by users. * * [Official document - get content](https://developers.line.biz/en/reference/messaging-api/#get-content) * * @param messageId - Message ID * @returns Returns status code `200` and the content in binary. * * Content is automatically deleted after a certain period from when the message was sent. There is no guarantee for how long content is stored. */ getMessageContent(messageId: string): Promise<Buffer> { return this.dataAxios .get(`/v2/bot/message/${messageId}/content`, { responseType: 'arraybuffer', }) .then((res) => res.data, handleError); } getMessageContentStream(messageId: string): Promise<Readable> { return this.dataAxios .get(`/v2/bot/message/${messageId}/content`, { responseType: 'stream', }) .then((res) => res.data, handleError); } /** * `retrieveMessageContent` is deprecated. Use `getMessageContent` instead. */ retrieveMessageContent(messageId: string): Promise<Buffer> { warning( false, '`retrieveMessageContent` is deprecated. Use `getMessageContent` instead.' ); return this.getMessageContent(messageId); } /** * Get User Profile * * Gets user profile information. * * [Official document - get user profile](https://developers.line.biz/en/reference/messaging-api/#get-profile) * * @param userId - User ID that is returned in a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). Do not use the LINE ID found on LINE.Message IDUser ID that is returned in a webhook event object. Do not use the LINE ID found on LINE. * @returns Returns status code `200` and a JSON object with the following information. * * displayName: * - User's display name * * userId: * - User ID * * pictureUrl: * - Profile image URL. "https" image URL. Not included in the response if the user doesn't have a profile image. * * statusMessage: * - User's status message. Not included in the response if the user doesn't have a status message. */ getUserProfile(userId: string): Promise<LineTypes.User> { return this.axios .get(`/v2/bot/profile/${userId}`) .then((res) => res.data, handleError) .catch((err) => { if (err.response && err.response.status === 404) { return null; } return handleError(err); }); } /** * Get Group Member Profile * * Gets the user profile of a member of a group that the LINE Official Account is in if the user ID of the group member is known. You can get user profiles of users who have not added the LINE Official Account as a friend or have blocked the LINE Official Account. * * [Official document - get group member profile](https://developers.line.biz/en/reference/messaging-api/#get-group-member-profile) * * @param groupId - Group ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * @param userId - User ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). Do not use the LINE ID used in LINE. * @returns Returns status code `200` and a JSON object with the following information. * * displayName: * - User's display name * * userId: * - User ID * * pictureUrl: * - Profile image URL. "https" image URL. Not included in the response if the user doesn't have a profile image. */ getGroupMemberProfile( groupId: string, userId: string ): Promise<LineTypes.User> { return this.axios .get(`/v2/bot/group/${groupId}/member/${userId}`) .then((res) => res.data, handleError); } /** * Get Room Member Profile * * Gets the user profile of a member of a room that the LINE Official Account is in if the user ID of the room member is known. You can get user profiles of users who have not added the LINE Official Account as a friend or have blocked the LINE Official Account. * * [Official document - get room member profile](https://developers.line.biz/en/reference/messaging-api/#get-room-member-profile) * * @param roomId - Room ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * @param userId - User ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). Do not use the LINE ID used in LINE. * @returns Returns status code `200` and a JSON object with the following information. * * displayName: * - User's display name * * userId: * - User ID * * pictureUrl: * - Profile image URL. "https" image URL. Not included in the response if the user doesn't have a profile image. */ getRoomMemberProfile( roomId: string, userId: string ): Promise<LineTypes.User> { return this.axios .get(`/v2/bot/room/${roomId}/member/${userId}`) .then((res) => res.data, handleError); } /** * Get Group Summary * * Gets the group ID, group name, and group icon URL of a group where the LINE Official Account is a member. * * [Official document - get group summary](https://developers.line.biz/en/reference/messaging-api/#get-group-summary) * * @param groupId - Group ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * @returns Returns status code `200` and a JSON object with the following information. * * groupId: * - Group ID * * groupName: * - Group name * * pictureUrl: * - Group icon URL */ getGroupSummary(groupId: string): Promise<LineTypes.Group> { return this.axios .get(`/v2/bot/group/${groupId}/summary`) .then((res) => res.data, handleError); } /** * Get Members In Group Count * * Gets the count of members in a group. You can get the member in group count even if the user hasn't added the LINE Official Account as a friend or has blocked the LINE Official Account. * * [Official document - get members in group count](https://developers.line.biz/en/reference/messaging-api/#get-members-group-count) * * @param groupId - Group ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * @returns Returns status code `200` and a number representing group member count. * * count: * - The count of members in the group. The number returned excludes the LINE Official Account. */ getGroupMembersCount(groupId: string): Promise<number> { return this.axios .get(`/v2/bot/group/${groupId}/members/count`) .then((res) => res.data.count, handleError); } /** * Get Group Member Ids * * Gets the user IDs of the members of a group that the bot is in. This includes the user IDs of users who have not added the LINE Official Account as a friend or has blocked the LINE Official Account. * * This feature is available only to verified or premium accounts. For more information about account types, see the [LINE Account Connect](https://www.linebiz.com/jp-en/service/line-account-connect/) page on the LINE for Business website. * * [Official document - get group member profile](https://developers.line.biz/en/reference/messaging-api/#get-group-member-profile) * * @param groupId - Group ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * @param start - Value of the continuation token found in the `next` property of the JSON object returned in the [response](https://developers.line.biz/en/reference/messaging-api/#get-group-member-user-ids-response). Include this parameter to get the next array of user IDs for the members of the group. * @returns Returns status code `200` and a JSON object with the following information. * * memberIds: * - List of user IDs of members in the group. Users of LINE version 7.4.x or earlier are not included in `memberIds`. For more information, see [User consent](https://developers.line.biz/en/docs/messaging-api/user-consent/). * - Max: 100 user IDs * * next: * - A continuation token to get the next array of user IDs of the members in the group. Returned only when there are remaining user IDs that were not returned in `memberIds` in the original request. */ getGroupMemberIds( groupId: string, start?: string ): Promise<{ memberIds: string[]; next?: string }> { return this.axios .get( `/v2/bot/group/${groupId}/members/ids${start ? `?start=${start}` : ''}` ) .then((res) => res.data, handleError); } /** * Get All Member Ids in the Group * * Gets the user IDs of the members of a group that the bot is in. This includes the user IDs of users who have not added the LINE Official Account as a friend or has blocked the LINE Official Account. * * This feature is available only to verified or premium accounts. For more information about account types, see the [LINE Account Connect](https://www.linebiz.com/jp-en/service/line-account-connect/) page on the LINE for Business website. * * [Official document - get group member profile](https://developers.line.biz/en/reference/messaging-api/#get-group-member-profile) * * @param groupId - Group ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * @returns Returns status code `200` and a JSON object with the following information. * * memberIds: * - List of user IDs of members in the group. Users of LINE version 7.4.x or earlier are not included in `memberIds`. For more information, see [User consent](https://developers.line.biz/en/docs/messaging-api/user-consent/). */ async getAllGroupMemberIds(groupId: string): Promise<string[]> { let allMemberIds: string[] = []; let continuationToken; do { const { memberIds, next, }: // eslint-disable-next-line no-await-in-loop { memberIds: string[]; next?: string } = await this.getGroupMemberIds( groupId, continuationToken ); allMemberIds = allMemberIds.concat(memberIds); continuationToken = next; } while (continuationToken); return allMemberIds; } /** * Get Members In Room Count * * Gets the count of members in a room. You can get the member in room count even if the user hasn't added the LINE Official Account as a friend or has blocked the LINE Official Account. * * [Official document - get members in room count](https://developers.line.biz/en/reference/messaging-api/#get-members-room-count) * * @param roomId - Room ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * @returns Returns status code `200` and a number representing room member count. * * count: * - The count of members in the group. The number returned excludes the LINE Official Account. */ getRoomMembersCount(roomId: string): Promise<number> { return this.axios .get(`/v2/bot/room/${roomId}/members/count`) .then((res) => res.data.count, handleError); } /** * Get Room Member Ids * * Gets the user IDs of the members of a room that the LINE Official Account is in. This includes the user IDs of users who have not added the LINE Official Account as a friend or have blocked the LINE Official Account. * * This feature is available only to verified or premium accounts. For more information about account types, see the [LINE Account Connect](https://www.linebiz.com/jp-en/service/line-account-connect/) page on the LINE for Business website. * * [Official document - get room member profile](https://developers.line.biz/en/reference/messaging-api/#get-room-member-user-ids) * * @param roomId - Room ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * @param start - Value of the continuation token found in the `next` property of the JSON object returned in the [response](https://developers.line.biz/en/reference/messaging-api/#get-room-member-user-ids-response). Include this parameter to get the next array of user IDs for the members of the group. * @returns Returns status code `200` and a JSON object with the following information. * * memberIds: * - List of user IDs of members in the room. Users of LINE version 7.4.x or earlier are not included in `memberIds`. For more information, see [User consent](https://developers.line.biz/en/docs/messaging-api/user-consent/). * - Max: 100 user IDs * * next: * - A continuation token to get the next array of user IDs of the members in the room. Returned only when there are remaining user IDs that were not returned in `memberIds` in the original request. */ getRoomMemberIds( roomId: string, start?: string ): Promise<{ memberIds: string[]; next?: string }> { return this.axios .get( `/v2/bot/room/${roomId}/members/ids${start ? `?start=${start}` : ''}` ) .then((res) => res.data, handleError); } /** * Get All Member Ids in the Room * * Gets the user IDs of the members of a room that the LINE Official Account is in. This includes the user IDs of users who have not added the LINE Official Account as a friend or have blocked the LINE Official Account. * * This feature is available only to verified or premium accounts. For more information about account types, see the [LINE Account Connect](https://www.linebiz.com/jp-en/service/line-account-connect/) page on the LINE for Business website. * * [Official document - get room member profile](https://developers.line.biz/en/reference/messaging-api/#get-room-member-user-ids) * * @param roomId - Room ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * @returns Returns status code `200` and a JSON object with the following information. * * memberIds: * - List of user IDs of members in the room. Users of LINE version 7.4.x or earlier are not included in `memberIds`. For more information, see [User consent](https://developers.line.biz/en/docs/messaging-api/user-consent/). */ async getAllRoomMemberIds(roomId: string): Promise<string[]> { let allMemberIds: string[] = []; let continuationToken; do { const { memberIds, next, }: // eslint-disable-next-line no-await-in-loop { memberIds: string[]; next?: string } = await this.getRoomMemberIds( roomId, continuationToken ); allMemberIds = allMemberIds.concat(memberIds); continuationToken = next; } while (continuationToken); return allMemberIds; } /** * Leave Group * * Leaves a [group](https://developers.line.biz/en/docs/messaging-api/group-chats/#group). * * [Official document - leave group](https://developers.line.biz/en/reference/messaging-api/#leave-group) * * @param groupId - Group ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * @returns Returns status code `200` and an empty JSON object. */ leaveGroup(groupId: string): Promise<LineTypes.MutationSuccessResponse> { return this.axios .post(`/v2/bot/group/${groupId}/leave`) .then((res) => res.data, handleError); } /** * Leave Room * * Leaves a [room](https://developers.line.biz/en/docs/messaging-api/group-chats/#room). * * [Official document - leave room](https://developers.line.biz/en/reference/messaging-api/#leave-room) * * @param roomId - Room ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * @returns Returns status code `200` and an empty JSON object. */ leaveRoom(roomId: string): Promise<LineTypes.MutationSuccessResponse> { return this.axios .post(`/v2/bot/room/${roomId}/leave`) .then((res) => res.data, handleError); } /** * Get Rich Menu List * * Gets a list of the rich menu response object of all rich menus created by [Create a rich menu](https://developers.line.biz/en/reference/messaging-api/#create-rich-menu). * * You can't retrieve rich menus created with LINE Official Account Manager. * * [Official document - get rich menu list](https://developers.line.biz/en/reference/messaging-api/#get-rich-menu-list) * * @returns Returns status code `200` and a list of [rich menu response objects](https://developers.line.biz/en/reference/messaging-api/#rich-menu-response-object). * * richmenus: * Array of [rich menu response objects](https://developers.line.biz/en/reference/messaging-api/#rich-menu-response-object) */ getRichMenuList(): Promise<LineTypes.RichMenu[]> { return this.axios .get('/v2/bot/richmenu/list') .then((res) => res.data.richmenus, handleError); } /** * Get Rich Menu * * Gets a rich menu via a rich menu ID. * * [Official document - get rich menu](https://developers.line.biz/en/reference/messaging-api/#get-rich-menu) * * @param richMenuId - ID of a rich menu * @returns Returns status code `200` and a [rich menu response objects](https://developers.line.biz/en/reference/messaging-api/#rich-menu-response-object). * * richmenus: * Array of [rich menu response objects](https://developers.line.biz/en/reference/messaging-api/#rich-menu-response-object) */ getRichMenu(richMenuId: string): Promise<LineTypes.RichMenu> { return this.axios .get(`/v2/bot/richmenu/${richMenuId}`) .then((res) => res.data) .catch((err) => { if (err.response && err.response.status === 404) { return null; } return handleError(err); }); } /** * Create Rich Menu * * Creates a rich menu. * * You must [upload a rich menu image](https://developers.line.biz/en/reference/messaging-api/#upload-rich-menu-image), and [set the rich menu as the default rich menu](https://developers.line.biz/en/reference/messaging-api/#set-default-rich-menu) or [link the rich menu to a user](https://developers.line.biz/en/reference/messaging-api/#link-rich-menu-to-user) for the rich menu to be displayed. You can create up to 1000 rich menus for one LINE Official Account with the Messaging API. * * [Official document - create rich menu](https://developers.line.biz/en/reference/messaging-api/#create-rich-menu) * * @param richMenu - The rich menu represented as a rich menu object. * @returns Returns status code `200` and a JSON object with the rich menu ID. */ createRichMenu( richMenu: LineTypes.RichMenu ): Promise<{ richMenuId: string }> { return this.axios .post('/v2/bot/richmenu', richMenu) .then((res) => res.data, handleError); } /** * Delete Rich Menu * * Deletes a rich menu. * * If you have reached the maximum of 1,000 rich menus with the Messaging API for your LINE Official Account, you must delete a rich menu before you can create a new one. * * [Official document - delete rich menu](https://developers.line.biz/en/reference/messaging-api/#delete-rich-menu) * * @param richMenuId - ID of a rich menu * @returns Returns status code `200` and an empty JSON object. */ deleteRichMenu( richMenuId: string ): Promise<LineTypes.MutationSuccessResponse> { return this.axios .delete(`/v2/bot/richmenu/${richMenuId}`) .then((res) => res.data, handleError); } /** * Get Linked Rich Menu * * Gets the ID of the rich menu linked to a user. * * [Official document - get rich menu id of user](https://developers.line.biz/en/reference/messaging-api/#get-rich-menu-id-of-user) * * @param userId - User ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). Do not use the LINE ID used in LINE. * @returns Returns status code `200` and a JSON object with the rich menu ID. */ getLinkedRichMenu(userId: string): Promise<{ richMenuId: string }> { return this.axios .get(`/v2/bot/user/${userId}/richmenu`) .then((res) => res.data) .catch((err) => { if (err.response && err.response.status === 404) { return null; } return handleError(err); }); } /** * Link Rich Menu * * Links a rich menu to a user. Only one rich menu can be linked to a user at one time. If a user already has a rich menu linked, calling this endpoint replaces the existing rich menu with the one specified in your request. * * The rich menu is displayed in the following order of priority (highest to lowest): * * 1. The per-user rich menu set with the Messaging API * 2. The [default rich menu set with the Messaging API](https://developers.line.biz/en/reference/messaging-api/#set-default-rich-menu) * 3. The [default rich menu set with LINE Official Account Manager](https://developers.line.biz/en/docs/messaging-api/using-rich-menus/#creating-a-rich-menu-with-the-line-manager) * * [Official document - link rich menu to user](https://developers.line.biz/en/reference/messaging-api/#link-rich-menu-to-user) * * @param userId - User ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). Do not use the LINE ID used in LINE. * @param richMenuId - ID of a rich menu * @returns Returns status code `200` and an empty JSON object. */ linkRichMenu( userId: string, richMenuId: string ): Promise<LineTypes.MutationSuccessResponse> { return this.axios .post(`/v2/bot/user/${userId}/richmenu/${richMenuId}`) .then((res) => res.data, handleError); } /** * Unlink Rich Menu * * Unlinks a rich menu from a user. * * [Official document - unlink rich menu from user](https://developers.line.biz/en/reference/messaging-api/#unlink-rich-menu-from-user) * * @param userId - User ID. Found in the `source` object of [webhook event objects](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). Do not use the LINE ID used in LINE. * @returns Returns status code `200` and an empty JSON object. */ unlinkRichMenu(userId: string): Promise<LineTypes.MutationSuccessResponse> { return this.axios .delete(`/v2/bot/user/${userId}/richmenu`) .then((res) => res.data, handleError); } /** * Get Default Rich Menu * * Gets the ID of the default rich menu set with the Messaging API. * * [Official document - get default rich menu id](https://developers.line.biz/en/reference/messaging-api/#get-default-rich-menu-id) * * @returns Returns status code `200` and a JSON object with the rich menu ID. */ getDefaultRichMenu(): Promise<{ richMenuId: string }> { return this.axios .get(`/v2/bot/user/all/richmenu`) .then((res) => res.data) .catch((err) => { if (err.response && err.response.status === 404) { return null; } return handleError(err); }); } /** * Set Default Rich Menu * * Sets the default rich menu. The default rich menu is displayed to all users who have added your LINE Official Account as a friend and are not linked to any per-user rich menu. If a default rich menu has already been set, calling this endpoint replaces the current default rich menu with the one specified in your request. * * The rich menu is displayed in the following order of priority (highest to lowest): * * 1. [The per-user rich menu set with the Messaging API](https://developers.line.biz/en/reference/messaging-api/#link-rich-menu-to-user) * 2. The default rich menu set with the Messaging API * 3. [The default rich menu set with LINE Official Account Manager](https://developers.line.biz/en/docs/messaging-api/using-rich-menus/#creating-a-rich-menu-with-the-line-manager) * * [Official document - set default rich menu](https://developers.line.biz/en/reference/messaging-api/#set-default-rich-menu) * * @param richMenuId - ID of a rich menu * @returns Returns status code `200` and an empty JSON object. */ setDefaultRichMenu( richMenuId: string ): Promise<LineTypes.MutationSuccessResponse> { return this.axios .post(`/v2/bot/user/all/richmenu/${richMenuId}`) .then((res) => res.data, handleError); } /** * Delete Default Rich Menu * * Cancels the default rich menu set with the Messaging API. * * [Official document - cancel default rich menu](https://developers.line.biz/en/reference/messaging-api/#cancel-default-rich-menu) * * @returns Returns status code `200` and a JSON object with the rich menu ID. */ deleteDefaultRichMenu(): Promise<{ richMenuId: string }> { return this.axios .delete(`/v2/bot/user/all/richmenu`) .then((res) => res.data, handleError); } /** * Upload Rich Menu Image * * Uploads and attaches an image to a rich menu. * * You can use rich menu images with the following specifications: * * - Image format: JPEG or PNG * - Image size (pixels): 2500x1686, 2500x843, 1200x810, 1200x405, 800x540, 800x270 * - Max file size: 1 MB * * Note: You cannot replace an image attached to a rich menu. To update your rich menu image, create a new rich menu object and upload another image. * * [Official document - upload rich menu image](https://developers.line.biz/en/reference/messaging-api/#upload-rich-menu-image) * * @param richMenuId - The ID of the rich menu to attach the image to * @param image - image * @returns Returns status code `200` and an empty JSON object. */ uploadRichMenuImage( richMenuId: string, image: Buffer ): Promise<LineTypes.MutationSuccessResponse> { const type = imageType(image); invariant( type && (type.mime === 'image/jpeg' || type.mime === 'image/png'), 'Image must be `image/jpeg` or `image/png`' ); return this.dataAxios .post(`/v2/bot/richmenu/${richMenuId}/content`, image, { headers: { 'Content-Type': (type as { mime: string }).mime, }, }) .then((res) => res.data, handleError); } /** * Download Rich Menu Image * * Downloads an image associated with a rich menu. * * [Official document - download rich menu image](https://developers.line.biz/en/reference/messaging-api/#download-rich-menu-image) * * @param richMenuId - ID of the rich menu with the image to be downloaded * @returns Returns status code `200` and the binary data of the rich menu image. The image can be downloaded as shown in the example request. */ downloadRichMenuImage(richMenuId: string): Promise<Buffer | undefined> { return this.dataAxios .get(`/v2/bot/richmenu/${richMenuId}/content`, { responseType: 'arraybuffer', }) .then((res) => Buffer.from(res.data)) .catch((err) => { if (err.response && err.response.status === 404) { return undefined; } return handleError(err); }); } /** * `issueLinkToken` is deprecated. Use `getLinkToken` instead. Note: It returns a string instead of an object. */ issueLinkToken(userId: string): Promise<{ linkToken: string }> { warning( false, '`issueLinkToken` is deprecated. Use `getLinkToken` instead. Note: It returns a string instead of an object.' ); return this.axios .post<{ linkToken: string }>(`/v2/bot/user/${userId}/linkToken`) .then((res) => res.data, handleError); } /** * Get Account link * * Issues a link token used for the [account link](https://developers.line.biz/en/docs/messaging-api/linking-accounts/) feature. * * [Official document - issue link token](https://developers.line.biz/en/reference/messaging-api/#issue-link-token) * * @param userId - User ID for the LINE account to be linked. Found in the `source` object of [account link event objects](https://developers.line.biz/en/reference/messaging-api/#account-link-event). Do not use the LINE ID used in LINE. * @returns Returns status code `200` and a link token. Link tokens are valid for 10 minutes and can only be used once. * * Note: The validity period may change without notice. */ getLinkToken(userId: string): Promise<string> { return this.axios .post<{ linkToken: string }>(`/v2/bot/user/${userId}/linkToken`) .then((res) => res.data.linkToken, handleError); } /** * LINE Front-end Framework (LIFF) */ /** * Get LIFF App List (LIFF v1) * * Gets information on all the LIFF apps registered in the channel. * * [Official document - get all liff apps](https://developers.line.biz/en/reference/liff-v1/#get-all-liff-apps) * * @returns Returns status code `200` and a JSON object with the following properties. */ getLiffAppList(): Promise<LineTypes.LiffApp[]> { return this.axios .get('/liff/v1/apps') .then((res) => res.data.apps, handleError); } /** * Create LIFF App (LIFF v1) * * Adds the LIFF app to a channel. You can add up to 30 LIFF apps on one channel. * * [Official document - add liff app](https://developers.line.biz/en/reference/liff-v1/#add-liff-app) * * @param liffApp - LIFF app settings * @returns Returns status code `200` and a JSON object with the following properties. * * liffId: * - LIFF app ID */ createLiffApp(liffApp: LineTypes.LiffApp): Promise<{ liffId: string }> { return this.axios .post('/liff/v1/apps', liffApp) .then((res) => res.data, handleError); } /** * Update LIFF App (LIFF v1) * * Partially updates LIFF app settings. * * [Official document - update liff app](https://developers.line.biz/en/reference/liff-v1/#update-liff-app) * * @param liffId - ID of the LIFF app to be updated * @param liffApp - Partial LIFF app settings. Only the properties specified in the request body are updated. * @returns Status code `200` is returned. */ updateLiffApp( liffId: string, liffApp: LineTypes.PartialLiffApp ): Promise<void> { return this.axios .put(`/liff/v1/apps/${liffId}/view`, liffApp) .then((res) => res.data, handleError); } /** * Delete LIFF App (LIFF v1) * * Deletes a LIFF app from a channel. * * [Official document - delete liff app](https://developers.line.biz/en/reference/liff-v1/#delete-liff-app) * * @param liffId - ID of the LIFF app to be deleted * @returns Status code `200` is returned. */ deleteLiffApp(liffId: string): Promise<void> { return this.axios .delete(`/liff/v1/apps/${liffId}`) .then((res) => res.data, handleError); } /** * Get number of messages sent * */ /** * Get Target Limit For Additional Messages * * Gets the target limit for additional messages in the current month. * * The number of messages retrieved by this operation includes the number of messages sent from LINE Official Account Manager. * * Set a target limit with LINE Official Account Manager. For the procedures, refer to the LINE Official Account Manager manual. * * Note: LINE\@ accounts cannot call this API endpoint. * * [Official document - get quota](https://developers.line.biz/en/reference/messaging-api/#get-quota) * * @returns Returns status code `200` and a [[TargetLimitForAdditionalMessages]]. */ getTargetLimitForAdditionalMessages(): Promise<LineTypes.TargetLimitForAdditionalMessages> { return this.axios .get<LineTypes.TargetLimitForAdditionalMessages>('/v2/bot/message/quota') .then((res) => res.data, handleError); } /** * Get Number of Messages Sent This Month * * Gets the number of messages sent in the current month. * * The number of messages retrieved by this operation includes the number of messages sent from LINE Official Account Manager. * * The number of messages retrieved by this operation is approximate. To get the correct number of sent messages, use LINE Official Account Manager or execute API operations for getting the number of sent messages. * * Note: LINE\@ accounts cannot call this API endpoint. * * [Official document - get consumption](https://developers.line.biz/en/reference/messaging-api/#get-consumption) * * @returns Returns status code `200` and a [[NumberOfMessagesSentThisMonth]]. */ getNumberOfMessagesSentThisMonth(): Promise<LineTypes.NumberOfMessagesSentThisMonth> { return this.axios .get<LineTypes.NumberOfMessagesSentThisMonth>( '/v2/bot/message/quota/consumption' ) .then((res) => res.data, handleError); } /** * Get Number of Sent Reply Messages * * Gets the number of messages sent with the `/bot/message/reply` endpoint. * * The number of messages retrieved by this operation does not include the number of messages sent from LINE Official Account Manager. * * [Official document - get number of reply messages](https://developers.line.biz/en/reference/messaging-api/#get-number-of-reply-messages) * * @param date - Date the messages were sent * * - Format: yyyyMMdd (Example: 20191231) * - Timezone: UTC+9 * * @returns Returns status code `200` and a [[NumberOfMessagesSentResponse]]. */ getNumberOfSentReplyMessages( date: string ): Promise<LineTypes.NumberOfMessagesSentResponse> { return this.axios .get<LineTypes.NumberOfMessagesSentResponse>( '/v2/bot/message/delivery/reply', { params: { date, }, } ) .then((res) => res.data, handleError); } /** * Get Number of Sent Push Messages * * Gets the number of messages sent with the `/bot/message/push` endpoint. * * The number of messages retrieved by this operation does not include the number of messages sent from LINE Official Account Manager. * * Note: LINE\@ accounts under the free or basic plan cannot call this API endpoint. * * [Official document - get number of push messages](https://developers.line.biz/en/reference/messaging-api/#get-number-of-push-messages) * * @param date - Date the messages were sent * * - Format: yyyyMMdd (Example: 20191231) * - Timezone: UTC+9 * * @returns Returns status code `200` and a [[NumberOfMessagesSentResponse]]. */ getNumberOfSentPushMessages( date: string ): Promise<LineTypes.NumberOfMessagesSentResponse> { return this.axios .get<LineTypes.NumberOfMessagesSentResponse>( '/v2/bot/message/delivery/push', { params: { date, }, } ) .then((res) => res.data, handleError); } /** * Get Number of Sent Multicast Messages * * Gets the number of messages sent with the `/bot/message/multicast` endpoint. * * The number of messages retrieved by this operation does not include the number of messages sent from LINE Official Account Manager. * * Note: LINE\@ accounts under the free or basic plan cannot call this API endpoint. * * [Official document - get number of multicast messages](https://developers.line.biz/en/reference/messaging-api/#get-number-of-multicast-messages) * * @param date - Date the messages were sent * * - Format: yyyyMMdd (Example: 20191231) * - Timezone: UTC+9 * * @returns Returns status code `200` and a [[NumberOfMessagesSentResponse]]. */ getNumberOfSentMulticastMessages( date: string ): Promise<LineTypes.NumberOfMessagesSentResponse> { return this.axios .get<LineTypes.NumberOfMessagesSentResponse>( '/v2/bot/message/delivery/multicast', { params: { date, }, } ) .then((res) => res.data, handleError); } /** * Get Number of Sent Broadcast Messages * * Gets the number of messages sent with the `/bot/message/broadcast` endpoint. * * The number of messages retrieved by this operation does not include the number of messages sent from LINE Official Account Manager. * * 【LINE Official Account migration】 * * You can't call this API with a LINE\@ account or LINE Official Account that hasn't been migrated to the account plans implemented on April 18, 2019. Please migrate your account first. For more information, see [Migration of LINE\@ accounts](https://developers.line.biz/en/docs/messaging-api/migrating-line-at/). * * [Official document - get number of broadcast messages](https://developers.line.biz/en/reference/messaging-api/#get-number-of-broadcast-messages) * * @param date - Date the messages were sent * * - Format: yyyyMMdd (Example: 20191231) * - Timezone: UTC+9 * * @returns Returns status code `200` and a [[NumberOfMessagesSentResponse]]. */ getNumberOfSentBroadcastMessages( date: string ): Promise<LineTypes.NumberOfMessagesSentResponse> { return this.axios .get<LineTypes.NumberOfMessagesSentResponse>( '/v2/bot/message/delivery/broadcast', { params: { date, }, } ) .then((res) => res.data, handleError); } /** * Insight * https://developers.line.biz/en/reference/messaging-api/#get-insight */ /** * Get Number of Delivery Messages * * Returns the number of messages sent from LINE Official Account on a specified day. * * 【LINE Official Account migration】 * * You can't call this API with a LINE\@ account or LINE Official Account that hasn't been migrated to the account plans implemented on April 18, 2019. Please migrate your account first. For more information, see [Migration of LINE\@ accounts](https://developers.line.biz/en/docs/messaging-api/migrating-line-at/). * * [Official document - get number of delivery messages](https://developers.line.biz/en/reference/messaging-api/#get-number-of-delivery-messages) * * @param date - Date for which to retrieve number of sent messages. * * - Format: yyyyMMdd (Example: 20191231) * - Timezone: UTC+9 * * @returns Returns status code `200` and a [[NumberOfMessageDeliveriesResponse]]. */ getNumberOfMessageDeliveries( date: string ): Promise<LineTypes.NumberOfMessageDeliveriesResponse> { return this.axios .get<LineTypes.NumberOfMessageDeliveriesResponse>( '/v2/bot/insight/message/delivery', { params: { date, }, } ) .then((res) => res.data, handleError); } /** * Get Number of Followers * * Returns the number of users who have added the LINE Official Account on or before a specified date. * * 【LINE Official Account migration】 * * You can't call this API with a LINE\@ account or LINE Official Account that hasn't been migrated to the account plans implemented on April 18, 2019. Please migrate your account first. For more information, see [Migration of LINE\@ accounts](https://developers.line.biz/en/docs/messaging-api/migrating-line-at/). * * [Official document - get number of followers](https://developers.line.biz/en/reference/messaging-api/#get-number-of-followers) * * @param date - Date for which to retrieve the number of followers. * * - Format: yyyyMMdd (Example: 20191231) * - Timezone: UTC+9 * * @returns Returns status code `200` and a [[NumberOfFollowersResponse]]. */ getNumberOfFollowers( date: string ): Promise<LineTypes.NumberOfFollowersResponse> { return this.axios .get<LineTypes.NumberOfFollowersResponse>('/v2/bot/insight/followers', { params: { date, }, }) .then((res) => res.data, handleError); } /** * Get Friend Demographics * * Retrieves the demographic attributes for a LINE Official Account's friends. You can only retrieve information about friends for LINE Official Accounts created by users in Japan (JP), Thailand (TH) and Taiwan (TW). * * 【LINE Official Account migration】 * * You can't call this API with a LINE\@ account or LINE Official Account that hasn't been migrated to the account plans implemented on April 18, 2019. Please migrate your account first. For more information, see [Migration of LINE\@ accounts](https://developers.line.biz/en/docs/messaging-api/migrating-line-at/). * * Not real-time data * * It can take up to 3 days for demographic information to be calculated. This means the information the API returns may be 3 days old. Furthermore, your ["Target reach"](https://developers.line.biz/en/docs/glossary/#target-reach) number must be at least 20 to retrieve demographic information. * * [Official document - get number of followers](https://developers.line.biz/en/reference/messaging-api/#get-demographic) * * @returns Returns status code `200` and a [[FriendDemographics]]. */ getFriendDemographics(): Promise<LineTypes.FriendDemographics> { return this.axios .get<LineTypes.FriendDemographics>('/v2/bot/insight/demographic') .then((res) => res.data, handleError); } /** * Narrowcast Message */ /** * Send Narrowcast Message * * Sends a push message to multiple users. You can specify recipients using attributes (such as age, gender, OS, and region) or by retargeting (audiences). Messages cannot be sent to groups or rooms. * * LINE Official Account migration * * You can't call this API with a LINE\@ account or LINE Official Account that hasn't been migrated to the account plans implemented on April 18, 2019. Please migrate your account first. For more information, see [Migration of LINE\@ accounts](https://developers.line.biz/en/docs/messaging-api/migrating-line-at/). * * [Official document - send narrowcast message](https://developers.line.biz/en/reference/messaging-api/#send-narrowcast-message) * * @param body - Request body * @param body.messages - Messages to send * - Max: 5 * @param body.recipient - [[RecipientObject]]. You can specify recipients of the message using up to 10 audiences. * * If this is omitted, messages will be sent to all users who have added your LINE Official Account as a friend. * @param body.filter - demographic: * - [[DemographicFilterObject]]. * - You can use friends' attributes to filter the list of recipients. * * If this is omitted, messages are sent to everyone—including users with attribute values of "unknown". * @param body.limit - max: * - The maximum number of narrowcast messages to send. * - Use this parameter to limit the number of narrowcast messages sent. The recipients will be chosen at random. * * @returns Returns the `202` HTTP status code and a JSON object with the following information. * * requestId: string * - The narrowcast message's request ID * * For more information on how to check the status of a narrowcast message, see [Get narrowcast message status](https://developers.line.biz/en/reference/messaging-api/#get-narrowcast-progress-status). */ narrowcastRawBody(body: { messages: LineTypes.Message[]; recipient?: LineTypes.RecipientObject; filter?: { demographic: LineTypes.DemographicFilterObject }; limit?: { max: number; }; }): Promise<{ requestId: string }> { return this.axios.post('/v2/bot/message/narrowcast', body).then((res) => { return { requestId: res.headers['x-line-request-id'], ...res.data, }; }, handleError); } /** * Send Narrowcast Message * * Sends a push message to multiple users. You can specify recipients using attributes (such as age, gender, OS, and region) or by retargeting (audiences). Messages cannot be sent to groups or rooms. * * LINE Official Account migration * * You can't call this API with a LINE\@ account or LINE Official Account that hasn't been migrated to the account plans implemented on April 18, 2019. Please migrate your account first. For more information, see [Migration of LINE\@ accounts](https://developers.line.biz/en/docs/messaging-api/migrating-line-at/). * * [Official document - send narrowcast message](https://developers.line.biz/en/reference/messaging-api/#send-narrowcast-message) * * @param messages - Messages to send * - Max: 5 * @param options - Narrowcast options * @returns Returns the `202` HTTP status code and a JSON object with the following information. * * requestId: string * - The narrowcast message's request ID * * For more information on how to check the status of a narrowcast message, see [Get narrowcast message status](https://developers.line.biz/en/reference/messaging-api/#get-narrowcast-progress-status). */ narrowcast( messages: LineTypes.Message[], options?: LineTypes.NarrowcastOptions ): Promise<{ requestId: string }> { const filter = options?.demographic ? { demographic: options.demographic, } : undefined; const limit = options?.max ? { max: options?.max, } : undefined; return this.narrowcastRawBody({ messages, recipient: options?.recipient, filter, limit, }); } /** * Send Narrowcast Message * * Sends a push message to multiple users. You can specify recipients using attributes (such as age, gender, OS, and region) or by retargeting (audiences). Messages cannot be sent to groups or rooms. * * LINE Official Account migration * * You can't call this API with a LINE\@ account or LINE Official Account that hasn't been migrated to the account plans implemented on April 18, 2019. Please migrate your account first. For more information, see [Migration of LINE\@ accounts](https://developers.line.biz/en/docs/messaging-api/migrating-line-at/). * * [Official document - send narrowcast message](https://developers.line.biz/en/reference/messaging-api/#send-narrowcast-message) * * @param messages - Messages to send * - Max: 5 * @param options - Narrowcast options * @returns Returns the `202` HTTP status code and a JSON object with the following information. * * requestId: string * - The narrowcast message's request ID * * For more information on how to check the status of a narrowcast message, see [Get narrowcast message status](https://developers.line.biz/en/reference/messaging-api/#get-narrowcast-progress-status). */ narrowcastMessages( messages: LineTypes.Message[], options?: LineTypes.NarrowcastOptions ): Promise<{ requestId: string }> { return this.narrowcast(messages, options); } /** * Get Narrowcast Message Status * * Gets the status of a narrowcast message. * * 【LINE Official Account migration】 * * You can't call this API with a LINE\@ account or LINE Official Account that hasn't been migrated to the account plans implemented on April 18, 2019. Please migrate your account first. For more information, see [Migration of LINE\@ accounts](https://developers.line.biz/en/docs/messaging-api/migrating-line-at/). * * 【Messages must have a minimum number of recipients】 * * Narrowcast messages cannot be sent when the number of recipients is below a certain minimum amount, to prevent someone from guessing the recipients' attributes. The minimum number of recipients is a private value defined by the LINE Platform. * * 【Window of availability for status requests】 * * You can get the status of a narrowcast message for up to 7 days after you have requested that it be sent. * * [Official document - get narrowcast progress status](https://developers.line.biz/en/reference/messaging-api/#get-narrowcast-progress-status) * * @param requestId - The narrowcast message's request ID. Each Messaging API request has a request ID. * @returns Returns a `200` HTTP status code and a [[NarrowcastProgressResponse]] */ getNarrowcastProgress( requestId: string ): Promise<LineTypes.NarrowcastProgressResponse> { return this.axios .get(`/v2/bot/message/progress/narrowcast?requestId=${requestId}`) .then((res) => res.data, handleError); } /** * Audience * */ /** * Create Upload Audience Group * * Creates an audience for uploading user IDs. You can create up to 1,000 audiences. * * Get user IDs via these methods: * * - Use the `source` property of a [webhook event object](https://developers.line.biz/en/reference/messaging-api/#webhook-event-objects). * - [Get group member user IDs](https://developers.line.biz/en/reference/messaging-api/#get-group-member-user-ids) * - [Get room member user IDs](https://developers.line.biz/en/reference/messaging-api/#get-room-member-user-ids) * * 【You must complete additional application forms to specify recipients using Identifiers for Advertisers (IFAs)】 * * You must complete some additional application forms before you can use IFAs to specify recipients. For more information, contact your LINE representative or submit an inquiry through the [LINE for Business](https://www.linebiz.com/) website. * * [Official document - create upload audience group](https://developers.line.biz/en/reference/messaging-api/#create-upload-audience-group) * * @param description - The audience's name. Audience names must be unique. Note that comparisons are case-insensitive, so the names `AUDIENCE` and `audience` are considered identical. * - Max character limit: 120 * @param isIfaAudience - If this is `false` (default), recipients are specified by user IDs. If `true`, recipients must be specified by IFAs. * @param audiences - An array of up to 10,000 user IDs or IFAs. * @param options - Create upload audience group options. * @returns Returns an [[UploadAudienceGroup]] along with the `202` HTTP status code. */ createUploadAudienceGroup( description: string, isIfaAudience: boolean, audiences: LineTypes.Audience[], options: LineTypes.CreateUploadAudienceGroupOptions = {} ): Promise<LineTypes.UploadAudienceGroup> { return this.axios .post('/v2/bot/audienceGroup/upload', { description, isIfaAudience, audiences, ...options, }) .then((res) => res.data, handleError); } /** * Create Upload Audience Group * * Adds new user IDs or IFAs to an audience for uploading user IDs. * * 【Request timeout values】 * * We strongly recommend using request timeout values of 30 seconds or more. * * 【You can't switch between user IDs and IFAs】 * * Add the same type of data (user IDs or IFAs) to an audience for uploading user IDs as you originally specified when creating that audience. For example, you can't add user IDs to an audience that originally used IFAs when it was created. * * You can use an audience's `isIfaAudience` property to determine which type of recipient (user IDs or IFAs) was specified when the audience was created. For more details, see [Get audience data](https://developers.line.biz/en/reference/messaging-api/#get-audience-group). * * 【You can't delete user IDs or IFAs】 * * You cannot delete a user ID or IFA after adding it. * * [Official document - update upload audience group](https://developers.line.biz/en/reference/messaging-api/#update-upload-audience-group) * * @param audienceGroupId - The audience ID. * @param audiences - An array of up to 10,000 user IDs or IFAs. * @param options - Update upload audience group options. * @returns Returns the HTTP `202` status code. */ updateUploadAudienceGroup( audienceGroupId: number, audiences: LineTypes.Audience[], options: LineTypes.UpdateUploadAudienceGroupOptions = {} ): Promise<LineTypes.MutationSuccessResponse> { return this.axios .put('/v2/bot/audienceGroup/upload', { audienceGroupId, audiences, ...options, }) .then((res) => res.data, handleError); } /** * Create Click Audience Group * * Creates an audience for click-based retargeting. You can create up to 1,000 audiences. * * A click-based retargeting audience is a collection of users who have clicked a URL contained in a broadcast or narrowcast message. * * Use a request ID to identify the message. The message is sent to any user who has clicked at least one link. * * [Official document - create click audience group](https://developers.line.biz/en/reference/messaging-api/#create-click-audience-group) * * @param description - The audience's name. Audience names must be unique. This is case-insensitive, meaning `AUDIENCE` and `audience` are considered identical. * - Max character limit: 120 * @param requestId - The request ID of a broadcast or narrowcast message sent in the past 60 days. Each Messaging API request has a request ID. * @param options - create click audience group options * @returns Returns a [[ClickAudienceGroup]] along with the `202` HTTP status code. */ createClickAudienceGroup( description: string, requestId: string, options: LineTypes.CreateClickAudienceGroupOptions = {} ): Promise<LineTypes.ClickAudienceGroup> { return this.axios .post('/v2/bot/audienceGroup/click', { description, requestId, ...options, }) .then((res) => res.data, handleError); } /** * Create Impression-based Audience Group * * Creates an audience for impression-based retargeting. You can create up to 1,000 audiences. * * An impression-based retargeting audience is a collection of users who have viewed a broadcast or narrowcast message. * * Use a request ID to specify the message. The audience will include any user who has viewed at least one message bubble. * * [Official document - create imp audience group](https://developers.line.biz/en/reference/messaging-api/#create-imp-audience-group) * * @param description - The audience's name. Audience names must be unique. This is case-insensitive, meaning `AUDIENCE` and `audience` are considered identical. * - Max character limit: 120 * @param requestId - The request ID of a broadcast or narrowcast message sent in the past 60 days. Each Messaging API request has a request ID. * @returns Returns an [[ImpAudienceGroup]] along with the `202` HTTP status code. */ createImpAudienceGroup( description: string, requestId: string ): Promise<LineTypes.ImpAudienceGroup> { return this.axios .post('/v2/bot/audienceGroup/imp', { description, requestId, }) .then((res) => res.data, handleError); } /** * Set Description of Audience Group * * Renames an existing audience. * * [Official document - set description audience group](https://developers.line.biz/en/reference/messaging-api/#set-description-audience-group) * * @param description - The audience's name. Audience names must be unique. This is case-insensitive, meaning `AUDIENCE` and `audience` are considered identical. * - Max character limit: 120 * @param audienceGroupId - The audience ID. * @returns Returns the `200` HTTP status code. */ setDescriptionAudienceGroup( description: string, audienceGroupId: number ): Promise<void> { return this.axios .put(`/v2/bot/audienceGroup/${audienceGroupId}/updateDescription`, { description, }) .then((res) => res.data, handleError); } /** * Deletes Audience Group * * Deletes an audience. * * You can't undo deleting an audience * * Make sure that an audience is no longer in use before you delete it. * * [Official document - delete audience group](https://developers.line.biz/en/reference/messaging-api/#delete-audience-group) * * @param audienceGroupId - The audience ID. * @returns Returns the `200` HTTP status code. */ deleteAudienceGroup( audienceGroupId: number ): Promise<LineTypes.MutationSuccessResponse> { return this.axios .delete(`/v2/bot/audienceGroup/${audienceGroupId}`) .then((res) => res.data, handleError); } /** * Get Audience Group * * Gets audience data. * * [Official document - get audience group](https://developers.line.biz/en/reference/messaging-api/#get-audience-group) * * @param audienceGroupId - The audience ID. * @returns Returns a `200` HTTP status code and an [[AudienceGroupWithJob]]. */ getAudienceGroup( audienceGroupId: number ): Promise<LineTypes.AudienceGroupWithJob> { return this.axios .get(`/v2/bot/audienceGroup/${audienceGroupId}`) .then((res) => res.data, handleError); } /** * Get Audience Groups * * Gets data for more than one audience. * * [Official document - get audience groups](https://developers.line.biz/en/reference/messaging-api/#get-audience-groups) * * @param options - get audience groups options * @returns Returns a `200` HTTP status code and an [[AudienceGroups]]. */ getAudienceGroups( options: LineTypes.GetAudienceGroupsOptions = {} ): Promise<LineTypes.AudienceGroups> { const query = querystring.stringify({ page: 1, ...options, }); return this.axios .get(`/v2/bot/audienceGroup/list?${query}`) .then((res) => res.data, handleError); } /** * Get Audience Group Authority Level * * Get the authority level of the audience * * [Official document - get authority level](https://developers.line.biz/en/reference/messaging-api/#get-authority-level) * * @returns Returns status code `200` and an [[AudienceGroupAuthorityLevel]]. */ getAudienceGroupAuthorityLevel(): Promise<LineTypes.AudienceGroupAuthorityLevel> { return this.axios .get(`/v2/bot/audienceGroup/authorityLevel`) .then((res) => res.data, handleError); } /** * Change the authority level of all audiences created in the same channel. * * - Audiences set to `PUBLIC` will be available in channels other than the one where you created the audience. For example, it will be available in [LINE Official Account Manager](https://manager.line.biz/), [LINE Ad Manager](https://admanager.line.biz/), and all channels the bot is linked to. * - Audiences set to `PRIVATE` will be available only in the channel where you created the audience. * * [Official document - change authority level](https://developers.line.biz/en/reference/messaging-api/#change-authority-level) * * @param authorityLevel - The authority level for all audiences linked to a channel * - `PUBLIC`: The default authority level. Audiences will be available in channels other than the one where you created the audience. For example, it will be available in [LINE Official Account Manager](https://manager.line.biz/), [LINE Ad Manager](https://admanager.line.biz/), and all channels the bot is linked to. * - `PRIVATE`: Audiences will be available only in the channel where you created the audience. * @returns Returns the HTTP `200` status code. */ changeAudienceGroupAuthorityLevel( authorityLevel: 'PUBLIC' | 'PRIVATE' ): Promise<LineTypes.MutationSuccessResponse> { return this.axios .put(`/v2/bot/audienceGroup/authorityLevel`, { authorityLevel, }) .then((res) => res.data, handleError); } }
the_stack
import { ConnectorBase } from "../internal/ConnectorBase"; import { IWebCommunicator } from "./internal/IWebCommunicator"; import { Invoke } from "../../components/Invoke"; import { IHeaderWrapper } from "../internal/IHeaderWrapper"; import { once } from "../internal/once"; import { DomainError } from "tstl/exception/DomainError"; import { WebError } from "./WebError"; import { is_node } from "tstl/utility/node"; import { sleep_for } from "tstl/thread/global"; /** * Web Socket Connector. * * The `WebConnector` is a communicator class who can connect to websocket server and * interact with it using RFC (Remote Function Call). * * You can connect to the websocket server using {@link connect}() method. The interaction * would be started if the server is opened by {@link WebServer.open}() and the server * accepts your connection by {@link WebAcceptor.accept}(). * * Note that, after you business has been completed, please close the connection using * {@link close}() or let the server to {@link WebAcceptor.close close itself}. If you don't * close the connection in time, it may waste vulnerable resources of the server. * * Also, when declaring this {@link WebConnector} type, you've to define two template arguments, * *Header* and *Provider*. The *Header* type repersents an initial data gotten from the remote * client after the connection. I hope you and client not to omit it and utilize it as an * activation tool to enhance security. * * The second template argument *Provider* represents the features provided for the remote system. * If you don't have any plan to provide any feature to the remote system, just declare it as * `null`. * * @template Header Type of the header containing initial data. * @template Provider Type of features provided for the remote system. * @author Jeongho Nam - https://github.com/samchon */ export class WebConnector<Header, Provider extends object | null> extends ConnectorBase<Header, Provider> implements IWebCommunicator { /** * @hidden */ private socket_?: WebSocket; /* ---------------------------------------------------------------- CONNECTION ---------------------------------------------------------------- */ /** * Connect to remote websocket server. * * Try connection to the remote websocket server with its address and waiting for the * server to accept the trial. If the server rejects your connection, then exception * would be thrown (in *Promise.catch*, as `WebError`). * * After the connection and your business has been completed, don't forget to closing the * connection in time to prevent waste of the server resource. * * @param url URL address to connect. * @param options Detailed options like timeout. */ public async connect ( url: string, options: Partial<WebConnector.IConnectOptions> = {} ): Promise<void> { // TEST CONDITION if (this.socket_ && this.state !== WebConnector.State.CLOSED) if (this.socket_.readyState === WebConnector.State.CONNECTING) throw new DomainError("Error on WebConnector.connect(): already connecting."); else if (this.socket_.readyState === WebConnector.State.OPEN) throw new DomainError("Error on WebConnector.connect(): already connected."); else throw new DomainError("Error on WebConnector.connect(): already closing."); //---- // CONNECTION //---- // PREPARE ASSETS this.state_ = WebConnector.State.CONNECTING; try { // DO CONNNECT this.socket_ = new g.WebSocket(url); await this._Wait_connection(); // SEND HEADERS this.socket_!.send(JSON.stringify( IHeaderWrapper.wrap(this.header) )); // PROMISED HANDSHAKE if (await this._Handshake(options.timeout) !== WebConnector.State.OPEN.toString()) throw new WebError(1008, "Error on WebConnector.connect(): target server may not be opened by TGrid. It's not following the TGrid's own handshake rule."); // SUCCESS this.state_ = WebConnector.State.OPEN; { this.socket_!.onmessage = this._Handle_message.bind(this); this.socket_!.onclose = this._Handle_close.bind(this); this.socket_!.onerror = () => {}; } } catch (exp) { this.state_ = WebConnector.State.NONE; if (this.socket_!.readyState === WebConnector.State.OPEN) { this.socket_!.onclose = () => {}; this.socket_!.close(); } throw exp; } } /** * @hidden */ private _Wait_connection(): Promise<WebSocket> { return new Promise((resolve, reject) => { this.socket_!.onopen = () => resolve(this.socket_!); this.socket_!.onclose = once(evt => { reject(new WebError(evt.code, evt.reason)); }); this.socket_!.onerror = once(() => { reject( new WebError(1006, "Connection refused.")); }); }); } /** * @inheritDoc */ public async close(code?: number, reason?: string): Promise<void> { // TEST CONDITION const error: Error | null = this.inspectReady("close"); if (error) throw error; //---- // CLOSE WITH JOIN //---- // PREPARE JOINER const ret: Promise<void> = this.join(); // DO CLOSE this.state_ = WebConnector.State.CLOSING; this.socket_!.close(code, reason); // LAZY RETURN await ret; } /** * @hidden */ private _Handshake(timeout?: number): Promise<string> { return new Promise((resolve, reject) => { let completed: boolean = false; let expired: boolean = false; // TIMEOUT if (timeout !== undefined) sleep_for(timeout).then(() => { if (completed === false) { reject(new WebError(1008, `Error on WebConnector.connect(): target server is not sending handshake data over ${timeout} milliseconds.`)); expired = true; } }); // EVENT LISTENRES this.socket_!.onmessage = once(evt => { if (expired === false) { completed = true; resolve(evt.data); } }); this.socket_!.onclose = once(evt => { if (expired === false) { completed = true; reject(new WebError(evt.code, evt.reason)); } }); this.socket_!.onerror = once(() => { if (expired === false) { completed = true; reject( new WebError(1006, "Connection refused.") ); } }); }); } /* ---------------------------------------------------------------- ACCESSORS ---------------------------------------------------------------- */ /** * Connection URL. */ public get url(): string | undefined { return this.socket_ ? this.socket_.url : undefined; } /** * Get state. * * Get current state of connection state with the websocket server. * * List of values are such like below: * * - `NONE`: The {@link WebConnector} instance is newly created, but did nothing yet. * - `CONNECTING`: The {@link WebConnector.connect} method is on running. * - `OPEN`: The connection is online. * - `CLOSING`: The {@link WebConnector.close} method is on running. * - `CLOSED`: The connection is offline. */ public get state(): WebConnector.State { return this.state_; } /* ---------------------------------------------------------------- COMMUNICATOR ---------------------------------------------------------------- */ /** * @hidden */ protected sendData(invoke: Invoke): void { this.socket_!.send(JSON.stringify(invoke)); } /** * @hidden */ private _Handle_message(evt: MessageEvent): void { if (typeof evt.data === "string") { const invoke: Invoke = JSON.parse(evt.data); this.replyData(invoke); } } /** * @hidden */ private async _Handle_close(event: CloseEvent): Promise<void> { const error: WebError | undefined = (!event.code || event.code !== 1000) ? new WebError(event.code, event.reason) : undefined; this.state_ = WebConnector.State.CLOSED; await this.destructor(error); } } /** * */ export namespace WebConnector { /** * Current state of the {@link WebConnector}. */ export import State = ConnectorBase.State; /** * Connection options for the {@link WebConnector.connect}. */ export interface IConnectOptions { /** * Milliseconds to wait the web-socket server to accept or reject it. If omitted, the waiting would be forever. */ timeout: number; } } //---- // POLYFILL //---- /** * @hidden */ const g: IFeature = is_node() ? require("./internal/websocket-polyfill") : <any>self; /** * @hidden */ interface IFeature { WebSocket: WebSocket & { new(url: string, protocols?: string | string[]): WebSocket; }; }
the_stack
import { NewExpression, Identifier, TemplateString, ArrayLiteral, CastExpression, BooleanLiteral, StringLiteral, NumericLiteral, CharacterLiteral, PropertyAccessExpression, Expression, ElementAccessExpression, BinaryExpression, UnresolvedCallExpression, ConditionalExpression, InstanceOfExpression, ParenthesizedExpression, RegexLiteral, UnaryExpression, UnaryType, MapLiteral, NullLiteral, AwaitExpression, UnresolvedNewExpression, UnresolvedMethodCallExpression, InstanceMethodCallExpression, NullCoalesceExpression, GlobalFunctionCallExpression, StaticMethodCallExpression, LambdaCallExpression, IMethodCallExpression } from "../One/Ast/Expressions"; import { Statement, ReturnStatement, UnsetStatement, ThrowStatement, ExpressionStatement, VariableDeclaration, BreakStatement, ForeachStatement, IfStatement, WhileStatement, ForStatement, DoStatement, ContinueStatement, ForVariable, TryStatement, Block } from "../One/Ast/Statements"; import { Class, IClassMember, SourceFile, IMethodBase, Constructor, IVariable, Lambda, IImportable, UnresolvedImport, Interface, Enum, IInterface, Field, Property, MethodParameter, IVariableWithInitializer, Visibility, IAstNode, GlobalFunction, Package, SourcePath, IHasAttributesAndTrivia, ExportedScope, ExportScopeRef } from "../One/Ast/Types"; import { VoidType, ClassType, InterfaceType, EnumType, AnyType, LambdaType, NullType, GenericsType } from "../One/Ast/AstTypes"; import { ThisReference, EnumReference, ClassReference, MethodParameterReference, VariableDeclarationReference, ForVariableReference, ForeachVariableReference, SuperReference, StaticFieldReference, StaticPropertyReference, InstanceFieldReference, InstancePropertyReference, EnumMemberReference, CatchVariableReference, GlobalFunctionReference, StaticThisReference, Reference, VariableReference } from "../One/Ast/References"; import { GeneratedFile } from "./GeneratedFile"; import { TSOverviewGenerator } from "../Utils/TSOverviewGenerator"; import { IGeneratorPlugin } from "./IGeneratorPlugin"; import { NameUtils } from "./NameUtils"; import { IExpression, IType } from "../One/Ast/Interfaces"; import { IGenerator } from "./IGenerator"; import { ITransformer } from "../One/ITransformer"; import { IVMValue } from "../VM/Values"; import { ExpressionValue, LambdaValue, TemplateFileGeneratorPlugin } from "./TemplateFileGeneratorPlugin"; import { StringValue } from "../VM/Values"; export class PythonGenerator implements IGenerator { tmplStrLevel = 0; package: Package; currentFile: SourceFile; imports: Set<string>; importAllScopes: Set<string>; currentClass: IInterface; reservedWords: string[] = ["from", "async", "global", "lambda", "cls", "import", "pass", "class"]; fieldToMethodHack: string[] = []; plugins: IGeneratorPlugin[] = []; constructor() { } getLangName(): string { return "Python"; } getExtension(): string { return "py"; } getTransforms(): ITransformer[] { return []; } addInclude(include: string): void { this.imports.add(`import ${include}`); } addPlugin(plugin: IGeneratorPlugin) { this.plugins.push(plugin); if (plugin instanceof TemplateFileGeneratorPlugin) { plugin.modelGlobals["escape"] = new LambdaValue(args => new StringValue(this.escape(args[0]))); plugin.modelGlobals["escapeBackslash"] = new LambdaValue(args => new StringValue(this.escapeBackslash(args[0]))); } } escape(value: IVMValue): string { if (value instanceof ExpressionValue && value.value instanceof RegexLiteral) return JSON.stringify(value.value.pattern); else if (value instanceof StringValue) return JSON.stringify(value.value); throw new Error(`Not supported VMValue for escape()`); } escapeBackslash(value: IVMValue): string { if (value instanceof ExpressionValue && value.value instanceof StringLiteral) return JSON.stringify(value.value.stringValue.replace(/\\/g, "\\\\")); throw new Error(`Not supported VMValue for escape()`); } type(type: IType) { if (type instanceof ClassType) { if (type.decl.name === "TsString") return "str"; else if (type.decl.name === "TsBoolean") return "bool"; else if (type.decl.name === "TsNumber") return "int"; else return this.clsName(type.decl); } else { debugger; return "NOT-HANDLED-TYPE"; } } splitName(name: string): string[] { const nameParts: string[] = []; let partStartIdx = 0; for (let i = 1; i < name.length; i++) { const prevChrCode = name.charCodeAt(i - 1); const chrCode = name.charCodeAt(i); if (65 <= chrCode && chrCode <= 90 && !(65 <= prevChrCode && prevChrCode <= 90)) { // 'A' .. 'Z' nameParts.push(name.substring(partStartIdx, i).toLowerCase()); partStartIdx = i; } else if (chrCode === 95) { // '-' nameParts.push(name.substring(partStartIdx, i)); partStartIdx = i + 1; } } nameParts.push(name.substr(partStartIdx).toLowerCase()); return nameParts; } name_(name: string) { if (this.reservedWords.includes(name)) name += "_"; if (this.fieldToMethodHack.includes(name)) name += "()"; return this.splitName(name).join("_"); } calcImportedName(exportScope: ExportScopeRef, name: string): string { if (this.importAllScopes.has(exportScope.getId())) return name; else return this.calcImportAlias(exportScope) + "." + name; } enumName(enum_: Enum, isDecl = false) { let name = this.name_(enum_.name).toUpperCase(); if (isDecl || enum_.parentFile.exportScope === null || enum_.parentFile === this.currentFile) return name; return this.calcImportedName(enum_.parentFile.exportScope, name); } enumMemberName(name: string) { return this.name_(name).toUpperCase(); } clsName(cls: IInterface, isDecl = false): string { // TODO: hack if (cls.name === "Set") return "dict"; if (isDecl || cls.parentFile.exportScope === null || cls.parentFile === this.currentFile) return cls.name; return this.calcImportedName(cls.parentFile.exportScope, cls.name); } leading(item: Statement) { let result = ""; if (item.leadingTrivia !== null && item.leadingTrivia.length > 0) result += item.leadingTrivia.replace(/\/\//g, "#"); //if (item.attributes !== null) // result += Object.keys(item.attributes).map(x => `// @${x} ${item.attributes[x]}\n`).join(""); return result; } preArr(prefix: string, value: string[]) { return value.length > 0 ? `${prefix}${value.join(", ")}` : ""; } preIf(prefix: string, condition: boolean) { return condition ? prefix : ""; } pre(prefix: string, value: string) { return value !== null ? `${prefix}${value}` : ""; } isTsArray(type: IType) { return type instanceof ClassType && type.decl.name == "TsArray"; } vis(v: Visibility) { return v === Visibility.Private ? "__" : v === Visibility.Protected ? "_" : v === Visibility.Public ? "" : "/* TODO: not set */public"; } varWoInit(v: IVariable, attr: IHasAttributesAndTrivia) { return this.name_(v.name); } var(v: IVariableWithInitializer, attrs: IHasAttributesAndTrivia) { return `${this.varWoInit(v, attrs)}${v.initializer !== null ? ` = ${this.expr(v.initializer)}` : ""}`; } exprCall(args: Expression[]) { return `(${args.map(x => this.expr(x)).join(", ")})`; } callParams(args: Expression[]) { const argReprs: string[] = []; for (let i = 0; i < args.length; i++) argReprs.push(this.expr(args[i])); return `(${argReprs.join(", ")})`; } methodCall(expr: IMethodCallExpression) { return this.name_(expr.method.name) + this.callParams(expr.args); } expr(expr: IExpression): string { for (const plugin of this.plugins) { const result = plugin.expr(expr); if (result !== null) return result; } let res = "UNKNOWN-EXPR"; if (expr instanceof NewExpression) { // TODO: hack if (expr.cls.decl.name === "Set") res = expr.args.length === 0 ? "dict()" : `dict.fromkeys${this.callParams(expr.args)}`; else res = `${this.clsName(expr.cls.decl)}${this.callParams(expr.args)}`; } else if (expr instanceof UnresolvedNewExpression) { res = `/* TODO: UnresolvedNewExpression */ ${expr.cls.typeName}(${expr.args.map(x => this.expr(x)).join(", ")})`; } else if (expr instanceof Identifier) { res = `/* TODO: Identifier */ ${expr.text}`; } else if (expr instanceof PropertyAccessExpression) { res = `/* TODO: PropertyAccessExpression */ ${this.expr(expr.object)}.${expr.propertyName}`; } else if (expr instanceof UnresolvedCallExpression) { res = `/* TODO: UnresolvedCallExpression */ ${this.expr(expr.func)}${this.exprCall(expr.args)}`; } else if (expr instanceof UnresolvedMethodCallExpression) { res = `/* TODO: UnresolvedMethodCallExpression */ ${this.expr(expr.object)}.${expr.methodName}${this.exprCall(expr.args)}`; } else if (expr instanceof InstanceMethodCallExpression) { res = `${this.expr(expr.object)}.${this.methodCall(expr)}`; } else if (expr instanceof StaticMethodCallExpression) { //const parent = expr.method.parentInterface === this.currentClass ? "cls" : this.clsName(expr.method.parentInterface); const parent = this.clsName(expr.method.parentInterface); res = `${parent}.${this.methodCall(expr)}`; } else if (expr instanceof GlobalFunctionCallExpression) { this.imports.add("from onelang_core import *"); res = `${this.name_(expr.func.name)}${this.exprCall(expr.args)}`; } else if (expr instanceof LambdaCallExpression) { res = `${this.expr(expr.method)}(${expr.args.map(x => this.expr(x)).join(", ")})`; } else if (expr instanceof BooleanLiteral) { res = `${expr.boolValue ? "True" : "False"}`; } else if (expr instanceof StringLiteral) { res = `${JSON.stringify(expr.stringValue)}`; } else if (expr instanceof NumericLiteral) { res = `${expr.valueAsText}`; } else if (expr instanceof CharacterLiteral) { res = `'${expr.charValue}'`; } else if (expr instanceof ElementAccessExpression) { res = `${this.expr(expr.object)}[${this.expr(expr.elementExpr)}]`; } else if (expr instanceof TemplateString) { const parts: string[] = []; for (const part of expr.parts) { if (part.isLiteral) { let lit = ""; for (let i = 0; i < part.literalText.length; i++) { const chr = part.literalText[i]; if (chr === '\n') lit += "\\n"; else if (chr === '\r') lit += "\\r"; else if (chr === '\t') lit += "\\t"; else if (chr === '\\') lit += "\\\\"; else if (chr === '\'') lit += "\\'"; else if (chr === '{') lit += "{{"; else if (chr === '}') lit += "}}"; else { const chrCode = chr.charCodeAt(0); if (32 <= chrCode && chrCode <= 126) lit += chr; else throw new Error(`invalid char in template string (code=${chrCode})`); } } parts.push(lit); } else { this.tmplStrLevel++; const repr = this.expr(part.expression); this.tmplStrLevel--; parts.push(part.expression instanceof ConditionalExpression ? `{(${repr})}` : `{${repr}}`); } } res = this.tmplStrLevel === 1 ? `f'${parts.join('')}'` : `f'''${parts.join('')}'''`; } else if (expr instanceof BinaryExpression) { const op = expr.operator === "&&" ? "and" : expr.operator === "||" ? "or" : expr.operator; res = `${this.expr(expr.left)} ${op} ${this.expr(expr.right)}`; } else if (expr instanceof ArrayLiteral) { res = `[${expr.items.map(x => this.expr(x)).join(', ')}]`; } else if (expr instanceof CastExpression) { res = `${this.expr(expr.expression)}`; } else if (expr instanceof ConditionalExpression) { res = `${this.expr(expr.whenTrue)} if ${this.expr(expr.condition)} else ${this.expr(expr.whenFalse)}`; } else if (expr instanceof InstanceOfExpression) { res = `isinstance(${this.expr(expr.expr)}, ${this.type(expr.checkType)})`; } else if (expr instanceof ParenthesizedExpression) { res = `(${this.expr(expr.expression)})`; } else if (expr instanceof RegexLiteral) { res = `RegExp(${JSON.stringify(expr.pattern)})`; } else if (expr instanceof Lambda) { let body: string = "INVALID-BODY"; if (expr.body.statements.length === 1 && expr.body.statements[0] instanceof ReturnStatement) body = this.expr((<ReturnStatement>expr.body.statements[0]).expression); else { console.error(`Multi-line lambda is not yet supported for Python: ${TSOverviewGenerator.preview.nodeRepr(expr)}`); debugger; } const params = expr.parameters.map(x => this.name_(x.name)); res = `lambda ${params.join(", ")}: ${body}`; } else if (expr instanceof UnaryExpression && expr.unaryType === UnaryType.Prefix) { const op = expr.operator === "!" ? "not " : expr.operator; if (op === "++") res = `${this.expr(expr.operand)} = ${this.expr(expr.operand)} + 1`; else if (op === "--") res = `${this.expr(expr.operand)} = ${this.expr(expr.operand)} - 1`; else res = `${op}${this.expr(expr.operand)}`; } else if (expr instanceof UnaryExpression && expr.unaryType === UnaryType.Postfix) { if (expr.operator === "++") res = `${this.expr(expr.operand)} = ${this.expr(expr.operand)} + 1`; else if (expr.operator === "--") res = `${this.expr(expr.operand)} = ${this.expr(expr.operand)} - 1`; else res = `${this.expr(expr.operand)}${expr.operator}`; } else if (expr instanceof MapLiteral) { const repr = expr.items.map(item => `${JSON.stringify(item.key)}: ${this.expr(item.value)}`).join(",\n"); res = expr.items.length === 0 ? "{}" : `{\n${this.pad(repr)}\n}`; } else if (expr instanceof NullLiteral) { res = `None`; } else if (expr instanceof AwaitExpression) { res = `${this.expr(expr.expr)}`; } else if (expr instanceof ThisReference) { res = `self`; } else if (expr instanceof StaticThisReference) { res = `cls`; } else if (expr instanceof EnumReference) { res = `${this.enumName(expr.decl)}`; } else if (expr instanceof ClassReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof MethodParameterReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof VariableDeclarationReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof ForVariableReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof ForeachVariableReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof CatchVariableReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof GlobalFunctionReference) { res = `${this.name_(expr.decl.name)}`; } else if (expr instanceof SuperReference) { res = `super()`; } else if (expr instanceof StaticFieldReference) { res = `${this.clsName(expr.decl.parentInterface)}.${this.name_(expr.decl.name)}`; } else if (expr instanceof StaticPropertyReference) { res = `${this.clsName(expr.decl.parentClass)}.get_${this.name_(expr.decl.name)}()`; } else if (expr instanceof InstanceFieldReference) { res = `${this.expr(expr.object)}.${this.name_(expr.field.name)}`; } else if (expr instanceof InstancePropertyReference) { res = `${this.expr(expr.object)}.get_${this.name_(expr.property.name)}()`; } else if (expr instanceof EnumMemberReference) { res = `${this.enumName(expr.decl.parentEnum)}.${this.enumMemberName(expr.decl.name)}`; } else if (expr instanceof NullCoalesceExpression) { res = `${this.expr(expr.defaultExpr)} or ${this.expr(expr.exprIfNull)}`; } else debugger; return res; } stmtDefault(stmt: Statement): string { const nl = "\n"; if (stmt instanceof BreakStatement) { return "break"; } else if (stmt instanceof ReturnStatement) { return stmt.expression === null ? "return" : `return ${this.expr(stmt.expression)}`; } else if (stmt instanceof UnsetStatement) { const obj = (<InstanceMethodCallExpression>stmt.expression).object; const key = (<InstanceMethodCallExpression>stmt.expression).args[0]; // TODO: hack: transform unsets before this return `del ${this.expr(obj)}[${this.expr(key)}]`; } else if (stmt instanceof ThrowStatement) { return `raise ${this.expr(stmt.expression)}`; } else if (stmt instanceof ExpressionStatement) { return `${this.expr(stmt.expression)}`; } else if (stmt instanceof VariableDeclaration) { return stmt.initializer !== null ? `${this.name_(stmt.name)} = ${this.expr(stmt.initializer)}` : ""; } else if (stmt instanceof ForeachStatement) { return `for ${this.name_(stmt.itemVar.name)} in ${this.expr(stmt.items)}:\n${this.block(stmt.body)}`; } else if (stmt instanceof IfStatement) { const elseIf = stmt.else_ !== null && stmt.else_.statements.length === 1 && stmt.else_.statements[0] instanceof IfStatement; return `if ${this.expr(stmt.condition)}:\n${this.block(stmt.then)}` + (elseIf ? `\nel${this.stmt(stmt.else_.statements[0])}` : "") + (!elseIf && stmt.else_ !== null ? `\nelse:\n${this.block(stmt.else_)}` : ""); } else if (stmt instanceof WhileStatement) { return `while ${this.expr(stmt.condition)}:\n${this.block(stmt.body)}`; } else if (stmt instanceof ForStatement) { return (stmt.itemVar !== null ? `${this.var(stmt.itemVar, null)}\n` : "") + `\nwhile ${this.expr(stmt.condition)}:\n${this.block(stmt.body)}\n${this.pad(this.expr(stmt.incrementor))}`; } else if (stmt instanceof DoStatement) { return `while True:\n${this.block(stmt.body)}\n${this.pad(`if not (${this.expr(stmt.condition)}):${nl}${this.pad("break")}`)}`; } else if (stmt instanceof TryStatement) { return `try:\n${this.block(stmt.tryBody)}` + (stmt.catchBody !== null ? `\nexcept Exception as ${this.name_(stmt.catchVar.name)}:\n${this.block(stmt.catchBody)}` : "") + (stmt.finallyBody !== null ? `\nfinally:\n${this.block(stmt.finallyBody)}` : ""); } else if (stmt instanceof ContinueStatement) { return `continue`; } else { debugger; return "UNKNOWN-STATEMENT"; } } stmt(stmt: Statement): string { let res: string = null; if (stmt.attributes !== null && "python" in stmt.attributes) { res = stmt.attributes["python"]; } else { for (const plugin of this.plugins) { res = plugin.stmt(stmt); if (res !== null) break; } if (res === null) res = this.stmtDefault(stmt); } return this.leading(stmt) + res; } stmts(stmts: Statement[], skipPass = false): string { return this.pad(stmts.length === 0 && !skipPass ? "pass" : stmts.map(stmt => this.stmt(stmt)).join("\n")); } block(block: Block, skipPass = false): string { return this.stmts(block.statements, skipPass); } pass(str: string) { return str === "" ? "pass" : str; } cls(cls: Class) { if (cls.attributes["external"] === "true") return ""; this.currentClass = cls; const resList: string[] = []; const classAttributes: string[] = []; const staticFields = cls.fields.filter(x => x.isStatic); if (staticFields.length > 0) { this.imports.add("import onelang_core as one"); classAttributes.push("@one.static_init"); const fieldInits = staticFields.map(f => `cls.${this.vis(f.visibility)}${this.var(f, f).replace(cls.name, "cls")}`); resList.push(`@classmethod\ndef static_init(cls):\n` + this.pad(fieldInits.join("\n"))); } const constrStmts: string[] = []; for (const field of cls.fields.filter(x => !x.isStatic)) { const init = field.constructorParam !== null ? this.name_(field.constructorParam.name) : field.initializer !== null ? this.expr(field.initializer) : "None"; constrStmts.push(`self.${this.name_(field.name)} = ${init}`); } if (cls.baseClass !== null) { if (cls.constructor_ !== null && cls.constructor_.superCallArgs !== null) constrStmts.push(`super().__init__(${cls.constructor_.superCallArgs.map(x => this.expr(x)).join(", ")})`); else constrStmts.push(`super().__init__()`); } if (cls.constructor_ !== null) for (const stmt of cls.constructor_.body.statements) constrStmts.push(this.stmt(stmt)); resList.push( `def __init__(self${cls.constructor_ === null ? "" : cls.constructor_.parameters.map(p => `, ${this.var(p, null)}`).join('')}):\n` + this.pad(this.pass(constrStmts.join("\n")))); for (const prop of cls.properties) { if (prop.getter !== null) resList.push(`def get_${this.name_(prop.name)}(self):\n${this.block(prop.getter)}`); } const methods: string[] = []; for (const method of cls.methods) { if (method.body === null) continue; // declaration only methods.push( (method.isStatic ? "@classmethod\n" : "") + `def ${this.name_(method.name)}` + `(${method.isStatic ? "cls" : "self"}${method.parameters.map(p => `, ${this.var(p, null)}`).join("")}):` + "\n" + this.block(method.body)); } resList.push(methods.join("\n\n")); const resList2 = resList.filter(x => x !== ""); const clsHdr = `class ${this.clsName(cls, true)}${cls.baseClass !== null ? `(${this.clsName((<ClassType>cls.baseClass).decl)})` : ""}:\n`; return classAttributes.map(x => `${x}\n`).join("") + clsHdr + this.pad(resList2.length > 0 ? resList2.join("\n\n") : "pass"); } pad(str: string): string { return str === "" ? "" : str.split(/\n/g).map(x => ` ${x}`).join('\n'); } calcRelImport(targetPath: ExportScopeRef, fromPath: ExportScopeRef) { const targetParts = targetPath.scopeName.split(/\//g); const fromParts = fromPath.scopeName.split(/\//g); let sameLevel = 0; while (sameLevel < targetParts.length && sameLevel < fromParts.length && targetParts[sameLevel] === fromParts[sameLevel]) sameLevel++; let result = ""; for (let i = 1; i < fromParts.length - sameLevel; i++) result += "."; for (let i = sameLevel; i < targetParts.length; i++) result += "." + targetParts[i]; return result; } calcImportAlias(targetPath: ExportScopeRef): string { const parts = targetPath.scopeName.split(/\//g); const filename = parts[parts.length - 1]; return NameUtils.shortName(filename); } genFile(sourceFile: SourceFile): string { this.currentFile = sourceFile; this.imports = new Set<string>(); this.importAllScopes = new Set<string>(); this.imports.add("from onelang_core import *"); // TODO: do not add this globally, just for nativeResolver methods if (sourceFile.enums.length > 0) this.imports.add("from enum import Enum"); for (const import_ of sourceFile.imports.filter(x => !x.importAll)) { if (import_.attributes["python-ignore"] === "true") continue; if ("python-import-all" in import_.attributes) { this.imports.add(`from ${import_.attributes["python-import-all"]} import *`); this.importAllScopes.add(import_.exportScope.getId()); } else { const alias = this.calcImportAlias(import_.exportScope); this.imports.add(`import ${this.package.name}.${import_.exportScope.scopeName.replace(/\//g, ".")} as ${alias}`); } } const enums: string[] = []; for (const enum_ of sourceFile.enums) { const values: string[] = []; for (let i = 0; i < enum_.values.length; i++) values.push(`${this.enumMemberName(enum_.values[i].name)} = ${i + 1}`); enums.push(`class ${this.enumName(enum_, true)}(Enum):\n` + this.pad(values.join("\n"))); } const classes: string[] = []; for (const cls of sourceFile.classes) classes.push(this.cls(cls)); const main = sourceFile.mainBlock.statements.length > 0 ? this.block(sourceFile.mainBlock) : ""; const imports: string[] = []; for (const imp of this.imports.values()) imports.push(imp); return [imports.join("\n"), enums.join("\n\n"), classes.join("\n\n"), main].filter(x => x !== "").join("\n\n"); } generate(pkg: Package): GeneratedFile[] { this.package = pkg; const result: GeneratedFile[] = []; for (const path of Object.keys(pkg.files)) result.push(new GeneratedFile(`${pkg.name}/${path}.py`, this.genFile(pkg.files[path]))); return result; } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormSharePointDocumentLocation_Information { interface tab_general_Sections { _272EB814_0769_5EBE_3ED1_E95A0B16853E: DevKit.Controls.Section; url_option: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { general: tab_general; } interface Body { Tab: Tabs; /** Absolute URL of the SharePoint document location. */ AbsoluteURL: DevKit.Controls.String; /** Description of the SharePoint document location record. */ Description: DevKit.Controls.String; /** Location type of the SharePoint document location. */ LocationType: DevKit.Controls.OptionSet; /** Name of the SharePoint document location record. */ Name: DevKit.Controls.String; /** Unique identifier of the user or team who owns the SharePoint document location record. */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the parent site or location. */ ParentSiteOrLocation: DevKit.Controls.Lookup; /** Unique identifier of the object with which the SharePoint document location record is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** Relative URL of the SharePoint document location. */ RelativeUrl: DevKit.Controls.String; } interface Footer extends DevKit.Controls.IFooter { /** Status of the SharePoint document location record. */ StateCode: DevKit.Controls.OptionSet; } interface Navigation { navSubDocumentLocations: DevKit.Controls.NavigationItem } } class FormSharePointDocumentLocation_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form SharePointDocumentLocation_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form SharePointDocumentLocation_Information */ Body: DevKit.FormSharePointDocumentLocation_Information.Body; /** The Footer section of form SharePointDocumentLocation_Information */ Footer: DevKit.FormSharePointDocumentLocation_Information.Footer; /** The Navigation of form SharePointDocumentLocation_Information */ Navigation: DevKit.FormSharePointDocumentLocation_Information.Navigation; } class SharePointDocumentLocationApi { /** * DynamicsCrm.DevKit SharePointDocumentLocationApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Absolute URL of the SharePoint document location. */ AbsoluteURL: DevKit.WebApi.StringValue; /** Unique identifier of the user who created the SharePoint document location record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the SharePoint document location record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the SharePoint document location record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Description of the SharePoint document location record. */ Description: DevKit.WebApi.StringValue; /** Exchange rate between the currency associated with the SharePoint document location record and the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Sequence number of the import that created the SharePoint document location record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Location type of the SharePoint document location. */ LocationType: DevKit.WebApi.OptionSetValue; /** Unique identifier of the user who last modified the SharePoint document location record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the SharePoint document location record was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the SharePoint document location record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Name of the SharePoint document location record. */ Name: DevKit.WebApi.StringValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier of the business unit that owns the SharePoint document location record. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team who owns the SharePoint document location record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the SharePoint document location record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the parent site or location. */ parentsiteorlocation_sharepointdocumentlocation: DevKit.WebApi.LookupValue; /** Unique identifier of the parent site or location. */ parentsiteorlocation_sharepointsite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_account: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_contact: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_kbarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_knowledgearticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_lead: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_agreement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_agreementbookingdate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_agreementbookingsetup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_agreementinvoicedate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_agreementinvoicesetup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_bookingtimestamp: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_expense: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_incidenttypeproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_inventoryadjustment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_inventoryadjustmentproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_inventorytransfer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_playbookactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_project: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_purchaseorder: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_purchaseorderproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_purchaseorderreceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_resourceterritory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_rma: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_rmareceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_rtv: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_timegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_timegroupdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_warehouse: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_workorder: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_workorderincident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_workorderproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_workorderservice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_msdyn_workorderservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_opportunity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_product: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_quote: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the SharePoint document location record is associated. */ regardingobjectid_salesliterature: DevKit.WebApi.LookupValue; RegardingObjectIdYomiName: DevKit.WebApi.StringValue; /** Relative URL of the SharePoint document location. */ RelativeUrl: DevKit.WebApi.StringValue; /** Shows the service type of the SharePoint site. */ ServiceType: DevKit.WebApi.OptionSetValue; /** Unique identifier of the SharePoint document location record. */ SharePointDocumentLocationId: DevKit.WebApi.GuidValue; /** For internal use only. */ SiteCollectionId: DevKit.WebApi.GuidValueReadonly; /** Status of the SharePoint document location record. */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the SharePoint document location record. */ StatusCode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the SharePoint document location record. */ TransactionCurrencyId: DevKit.WebApi.LookupValueReadonly; /** Choose the user who owns the SharePoint document location. */ UserId: DevKit.WebApi.GuidValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace SharePointDocumentLocation { enum LocationType { /** 1 */ Dedicated_for_OneNote_Integration, /** 0 */ General } enum ServiceType { /** 3 */ MS_Teams, /** 1 */ OneDrive, /** 2 */ Shared_with_me, /** 0 */ SharePoint } enum StateCode { /** 0 */ Active, /** 1 */ Inactive } enum StatusCode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Component, ElementRef, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { Title } from '@angular/platform-browser'; // Third party imports import { Observable } from 'rxjs'; // App imports import { APIClient } from 'src/app/swagger'; import AppServices from '../../../shared/service/appServices'; import { ConfigFileInfo, DockerRegionalClusterParams } from 'src/app/swagger/models'; import { CliFields, CliGenerator } from '../wizard/shared/utils/cli-generator'; import { DaemonValidationStepComponent } from './daemon-validation-step/daemon-validation-step.component'; import { DockerNetworkStepComponent } from './network-step/docker-network-step.component'; import { FormDataForHTML, FormUtility } from '../wizard/shared/components/steps/form-utility'; import { ExportService } from "../../../shared/service/export.service"; import { ImportParams, ImportService } from "../../../shared/service/import.service"; import { NetworkField } from '../wizard/shared/components/steps/network-step/network-step.fieldmapping'; import { NodeSettingStepComponent } from './node-setting-step/node-setting-step.component'; import { TanzuEventType } from '../../../shared/service/Messenger'; import { WizardBaseDirective } from '../wizard/shared/wizard-base/wizard-base'; import { WizardForm } from '../wizard/shared/constants/wizard.constants'; import { DockerNodeSettingStepName } from './node-setting-step/node-setting-step.fieldmapping'; @Component({ selector: 'app-docker-wizard', templateUrl: './docker-wizard.component.html', styleUrls: ['./docker-wizard.component.scss'] }) export class DockerWizardComponent extends WizardBaseDirective implements OnInit { constructor( router: Router, el: ElementRef, private exportService: ExportService, private importService: ImportService, formBuilder: FormBuilder, titleService: Title, private apiClient: APIClient ) { super(router, el, titleService, formBuilder); } protected supplyFileImportedEvent(): TanzuEventType { return TanzuEventType.DOCKER_CONFIG_FILE_IMPORTED; } protected supplyFileImportErrorEvent(): TanzuEventType { return TanzuEventType.DOCKER_CONFIG_FILE_IMPORT_ERROR; } protected supplyWizardName(): string { return 'DockerWizard'; } protected supplyStepData(): FormDataForHTML[] { return [ this.DockerDaemonForm, this.DockerNetworkForm, this.DockerNodeSettingForm ]; } ngOnInit(): void { super.ngOnInit(); // To avoid re-open issue for the first step. this.form.markAsDirty(); this.titleService.setTitle(this.title ? this.title + ' Docker' : 'Docker'); } setFromPayload(payload: DockerRegionalClusterParams) { this.setFieldValue(WizardForm.NETWORK, NetworkField.CLUSTER_SERVICE_CIDR, payload.networking.clusterServiceCIDR); this.setFieldValue(WizardForm.NETWORK, NetworkField.CLUSTER_POD_CIDR, payload.networking.clusterPodCIDR); this.setFieldValue(WizardForm.NETWORK, NetworkField.CNI_TYPE, payload.networking.cniType); this.setFieldValue(DockerNodeSettingStepName, 'clusterName', payload.clusterName); this.storeProxyFieldsFromPayload(payload); AppServices.userDataService.updateWizardTimestamp(this.wizardName); } getPayload() { const payload: DockerRegionalClusterParams = {} payload.networking = { clusterDNSName: '', clusterNodeCIDR: '', clusterServiceCIDR: this.getFieldValue(WizardForm.NETWORK, NetworkField.CLUSTER_SERVICE_CIDR), clusterPodCIDR: this.getFieldValue(WizardForm.NETWORK, NetworkField.CLUSTER_POD_CIDR), cniType: this.getFieldValue(WizardForm.NETWORK, NetworkField.CNI_TYPE) }; payload.clusterName = this.getFieldValue(DockerNodeSettingStepName, 'clusterName'); if (this.getFieldValue(WizardForm.NETWORK, NetworkField.PROXY_SETTINGS)) { let proxySettingsMap = null; proxySettingsMap = [ ['HTTPProxyURL', WizardForm.NETWORK, NetworkField.HTTP_PROXY_URL], ['HTTPProxyUsername', WizardForm.NETWORK, NetworkField.HTTP_PROXY_USERNAME], ['HTTPProxyPassword', WizardForm.NETWORK, NetworkField.HTTP_PROXY_PASSWORD], ['noProxy', WizardForm.NETWORK, NetworkField.NO_PROXY] ]; if (this.getFieldValue(WizardForm.NETWORK, NetworkField.HTTPS_IS_SAME_AS_HTTP)) { proxySettingsMap = [ ...proxySettingsMap, ['HTTPSProxyURL', WizardForm.NETWORK, NetworkField.HTTP_PROXY_URL], ['HTTPSProxyUsername', WizardForm.NETWORK, NetworkField.HTTP_PROXY_USERNAME], ['HTTPSProxyPassword', WizardForm.NETWORK, NetworkField.HTTP_PROXY_PASSWORD] ]; } else { proxySettingsMap = [ ...proxySettingsMap, ['HTTPSProxyURL', WizardForm.NETWORK, NetworkField.HTTPS_PROXY_URL], ['HTTPSProxyUsername', WizardForm.NETWORK, NetworkField.HTTPS_PROXY_USERNAME], ['HTTPSProxyPassword', WizardForm.NETWORK, NetworkField.HTTPS_PROXY_PASSWORD] ]; } payload.networking.httpProxyConfiguration = { enabled: true }; proxySettingsMap.forEach(attr => { let val = this.getFieldValue(attr[1], attr[2]); if (attr[0] === 'noProxy') { val = val.replace(/\s/g, ''); // remove all spaces } payload.networking.httpProxyConfiguration[attr[0]] = val; }); } payload.identityManagement = { 'idm_type': 'none' } return payload; } applyTkgConfig(): Observable<ConfigFileInfo> { return this.apiClient.applyTKGConfigForDocker({ params: this.getPayload() }); } /** * Return management/standalone cluster name */ getMCName() { return this.getFieldValue(DockerNodeSettingStepName, 'clusterName'); } /** * Retrieve the config file from the backend and return as a string */ retrieveExportFile() { return this.apiClient.exportTKGConfigForDocker({ params: this.getPayload() }); } exportConfiguration() { const wizard = this; // capture 'this' outside the context of the closure below this.exportService.export( this.retrieveExportFile(), (failureMessage) => { wizard.displayError(failureMessage); } ); } getCli(configPath: string): string { const cliG = new CliGenerator(); const cliParams: CliFields = { configPath: configPath, clusterType: this.getClusterType(), clusterName: this.getMCName(), extendCliCmds: [] }; return cliG.getCli(cliParams); } createRegionalCluster(payload: any): Observable<any> { return this.apiClient.createDockerRegionalCluster(payload); } // FormDataForHTML methods // get DockerNetworkForm(): FormDataForHTML { return FormUtility.formWithOverrides(super.NetworkForm, { description: DockerNetworkStepComponent.description, clazz: DockerNetworkStepComponent }); } get DockerNodeSettingForm(): FormDataForHTML { const title = FormUtility.titleCase(this.clusterTypeDescriptor) + ' Cluster Settings'; return { name: DockerNodeSettingStepName, title: title, description: 'Optional: Specify the management cluster name', i18n: { title: 'node setting step name', description: 'node setting step description' }, clazz: NodeSettingStepComponent}; } get DockerDaemonForm(): FormDataForHTML { return { name: 'dockerDaemonForm', title: 'Docker Prerequisites', description: 'Validate the local Docker daemon, allocated CPUs and Total Memory', i18n: {title: 'docker prerequisite step name', description: 'Docker prerequisite step description'}, clazz: DaemonValidationStepComponent}; } // returns TRUE if the file contents appear to be a valid config file for Docker // returns FALSE if the file is empty or does not appear to be valid. Note that in the FALSE // case we also alert the user. importFileValidate(nameFile: string, fileContents: string): boolean { if (fileContents.includes('INFRASTRUCTURE_PROVIDER: docker')) { return true; } alert(nameFile + ' is not a valid docker configuration file!'); return false; } importFileRetrieveClusterParams(fileContents: string): Observable<DockerRegionalClusterParams> { return this.apiClient.importTKGConfigForVsphere( { params: { filecontents: fileContents } } ); } importFileProcessClusterParams(event: TanzuEventType, nameFile: string, dockerClusterParams: DockerRegionalClusterParams) { this.setFromPayload(dockerClusterParams); this.resetToFirstStep(); this.importService.publishImportSuccess(event, nameFile); } // returns TRUE if user (a) will not lose data on import, or (b) confirms it's OK onImportButtonClick() { let result = true; if (!this.isOnFirstStep()) { result = confirm('Importing will overwrite any data you have entered. Proceed with import?'); } return result; } onImportFileSelected(event) { const params: ImportParams<DockerRegionalClusterParams> = { eventSuccess: this.supplyFileImportedEvent(), eventFailure: this.supplyFileImportErrorEvent(), file: event.target.files[0], validator: this.importFileValidate, backend: this.importFileRetrieveClusterParams.bind(this), onSuccess: this.importFileProcessClusterParams.bind(this), onFailure: this.importService.publishImportFailure } this.importService.import(params); // clear file reader target so user can re-select same file if needed event.target.value = ''; } }
the_stack
import * as CodeMirror from 'codemirror' import { Addon, FlipFlop, expandRange, suggestedEditorConfig } from '../core' import { cm_t } from '../core/type' import { splitLink } from './read-link' import { HyperMDState } from '../mode/hypermd'; /********************************************************************************** */ //#region CLICK HANDLER export type TargetType = "image" | "link" | "footref" | "url" | "todo" | "hashtag" export interface ClickInfo { type: TargetType text: string url: string // for todo item, url is empty pos: CodeMirror.Position button: number clientX: number clientY: number ctrlKey: boolean altKey: boolean shiftKey: boolean } /** * User may define his click handler, which has higher priority than HyperMD's. * * param `info` is a ClickInfo object, containing target type, text etc. * * Custom handler may return `false` to prevent HyperMD's default behavior. */ export type ClickHandler = (info: ClickInfo, cm: cm_t) => (false | void) //#endregion /********************************************************************************** */ //#region defaultClickHandler export const defaultClickHandler: ClickHandler = (info, cm) => { var { text, type, url, pos } = info if (type === 'url' || type === 'link') { var footnoteRef = text.match(/\[[^\[\]]+\](?:\[\])?$/) // bare link, footref or [foot][] . assume no escaping char inside if (footnoteRef && info.altKey) { // extract footnote part (with square brackets), then jump to the footnote text = footnoteRef[0] if (text.slice(-2) === '[]') text = text.slice(0, -2) // remove [] of [foot][] type = "footref" } else if ((info.ctrlKey || info.altKey) && url) { // just open URL window.open(url, "_blank") } } if (type === 'todo') { let { from, to } = expandRange(cm, pos, "formatting-task") let text = cm.getRange(from, to) text = (text === '[ ]') ? '[x]' : '[ ]' cm.replaceRange(text, from, to) } if (type === 'footref' && (info.ctrlKey || info.altKey)) { // Jump to FootNote const footnote_name = text.slice(1, -1) const footnote = cm.hmdReadLink(footnote_name, pos.line) if (footnote) { makeBackButton(cm, footnote.line, pos) cm.setCursor({ line: footnote.line, ch: 0 }) } } } /** * Display a "go back" button. Requires "HyperMD-goback" gutter set. * * maybe not useful? * * @param line where to place the button * @param anchor when user click the back button, jumps to here */ const makeBackButton = (function () { var bookmark: { find(): CodeMirror.Position; clear() } = null function updateBookmark(cm: cm_t, pos: CodeMirror.Position) { if (bookmark) { cm.clearGutter("HyperMD-goback") bookmark.clear() } bookmark = cm.setBookmark(pos) as any } /** * Make a button, bind event handlers, but not insert the button */ function makeButton(cm: cm_t) { var hasBackButton = cm.options.gutters.indexOf("HyperMD-goback") != -1 if (!hasBackButton) return null var backButton = document.createElement("div") backButton.className = "HyperMD-goback-button" backButton.addEventListener("click", function () { cm.setCursor(bookmark.find()) cm.clearGutter("HyperMD-goback") bookmark.clear() bookmark = null }) var _tmp1 = cm.display.gutters.children _tmp1 = _tmp1[_tmp1.length - 1] _tmp1 = _tmp1.offsetLeft + _tmp1.offsetWidth backButton.style.width = _tmp1 + "px" backButton.style.marginLeft = -_tmp1 + "px" return backButton } return function (cm: cm_t, line: number, anchor: CodeMirror.Position) { var backButton = makeButton(cm) if (!backButton) return backButton.innerHTML = (anchor.line + 1) + "" updateBookmark(cm, anchor) cm.setGutterMarker(line, "HyperMD-goback", backButton) } })(); //#endregion /********************************************************************************** */ //#region Addon Options export interface Options extends Addon.AddonOptions { /** Enable Click features or not. */ enabled: boolean /** * A callback when user clicked on something. May return `false` to supress HyperMD default behavoir. * @see ClickHandler */ handler: ClickHandler } export const defaultOption: Options = { enabled: false, handler: null, } export const suggestedOption: Partial<Options> = { enabled: true, // we recommend lazy users to enable this fantastic addon! } export type OptionValueType = Partial<Options> | boolean | ClickHandler; declare global { namespace HyperMD { interface EditorConfiguration { /** * Options for Click. * * You may also provide a `false` to disable it; a `true` to enable it with default behavior; * or a callback which may return `false` to supress HyperMD default behavoir. */ hmdClick?: OptionValueType } } } suggestedEditorConfig.hmdClick = suggestedOption CodeMirror.defineOption("hmdClick", defaultOption, function (cm: cm_t, newVal: OptionValueType) { ///// convert newVal's type to `Partial<Options>`, if it is not. if (!newVal || typeof newVal === "boolean") { newVal = { enabled: !!newVal } } else if (typeof newVal === "function") { newVal = { enabled: true, handler: newVal } } ///// apply config and write new values into cm var inst = getAddon(cm) for (var k in defaultOption) { inst[k] = (k in newVal) ? newVal[k] : defaultOption[k] } }) //#endregion /********************************************************************************** */ //#region Addon Class export class Click implements Addon.Addon, Options { enabled: boolean; handler: ClickHandler; private el: HTMLElement constructor(public cm: cm_t) { this.lineDiv = cm.display.lineDiv var el = this.el = cm.getWrapperElement() new FlipFlop( /* ON */() => { this.lineDiv.addEventListener("mousedown", this._mouseDown, false) el.addEventListener("keydown", this._keyDown, false) }, /* OFF */() => { this.lineDiv.removeEventListener("mousedown", this._mouseDown, false) el.removeEventListener("keydown", this._keyDown, false) } ).bind(this, "enabled", true) } /** CodeMirror's <pre>s container */ private lineDiv: HTMLDivElement /** It's not */ private _KeyDetectorActive: boolean /** remove modifier className to editor DOM */ private _mouseMove_keyDetect = (ev: KeyboardEvent) => { var el = this.el var className = el.className, newClassName = className const altClass = "HyperMD-with-alt" const ctrlClass = "HyperMD-with-ctrl" if (!ev.altKey && className.indexOf(altClass) >= 0) { newClassName = className.replace(altClass, ""); } if (!ev.ctrlKey && className.indexOf(ctrlClass) >= 0) { newClassName = className.replace(ctrlClass, ""); } if (!ev.altKey && !ev.ctrlKey) { this._KeyDetectorActive = false; el.removeEventListener('mousemove', this._mouseMove_keyDetect, false); } if (className != newClassName) el.className = newClassName.trim() } /** add modifier className to editor DOM */ private _keyDown = (ev: KeyboardEvent) => { var kc = ev.keyCode || ev.which var className = "" if (kc == 17) className = "HyperMD-with-ctrl" if (kc == 18) className = "HyperMD-with-alt" var el = this.el if (className && el.className.indexOf(className) == -1) { el.className += " " + className; } if (!this._KeyDetectorActive) { this._KeyDetectorActive = true; this.el.addEventListener('mousemove', this._mouseMove_keyDetect, false); } } /** last click info */ private _cinfo: ClickInfo /** * Unbind _mouseUp, then call ClickHandler if mouse not bounce */ private _mouseUp = (ev: MouseEvent) => { const cinfo = this._cinfo this.lineDiv.removeEventListener("mouseup", this._mouseUp, false) if (Math.abs(ev.clientX - cinfo.clientX) > 5 || Math.abs(ev.clientY - cinfo.clientY) > 5) return if (typeof this.handler === 'function' && this.handler(cinfo, this.cm) === false) return defaultClickHandler(cinfo, this.cm) } /** * Try to construct ClickInfo and bind _mouseUp */ private _mouseDown = (ev: MouseEvent) => { var { button, clientX, clientY, ctrlKey, altKey, shiftKey, } = ev var cm = this.cm if ((ev.target as HTMLElement).tagName === "PRE") return var pos = cm.coordsChar({ left: clientX, top: clientY }, "window") var range: ReturnType<typeof expandRange> var token = cm.getTokenAt(pos) var state = token.state as HyperMDState var styles = " " + token.type + " " var mat: RegExpMatchArray var type: TargetType = null var text: string, url: string if (mat = styles.match(/\s(image|link|url)\s/)) { // Could be a image, link, bare-link, footref, footnote, plain url, plain url w/o angle brackets type = mat[1] as TargetType const isBareLink = /\shmd-barelink\s/.test(styles) if (state.linkText) { // click on content of a link text. range = expandRange(cm, pos, (token) => token.state.linkText || /(?:\s|^)link(?:\s|$)/.test(token.type)) type = "link" } else { range = expandRange(cm, pos, type) } if (/^(?:image|link)$/.test(type) && !isBareLink) { // CodeMirror breaks [text] and (url) // Let HyperMD mode handle it! let tmp_range = expandRange(cm, { line: pos.line, ch: range.to.ch + 1 }, "url") if (tmp_range) range.to = tmp_range.to } text = cm.getRange(range.from, range.to).trim() // now extract the URL. boring job let tmp: number if ( text.slice(-1) === ')' && (tmp = text.lastIndexOf('](')) !== -1 // xxxx](url) image / link without ref ) { // remove title part (if exists) url = splitLink(text.slice(tmp + 2, -1)).url } else if ( (mat = text.match(/[^\\]\]\s?\[([^\]]+)\]$/)) || // .][ref] image / link with ref (mat = text.match(/^\[(.+)\]\s?\[\]$/)) || // [ref][] (mat = text.match(/^\[(.+)\](?:\:\s*)?$/)) // [barelink] or [^ref] or [footnote]: ) { if (isBareLink && mat[1].charAt(0) === '^') type = 'footref' let t2 = cm.hmdReadLink(mat[1], pos.line) if (!t2) url = null else { // remove title part (if exists) url = splitLink(t2.content).url } } else if ( (mat = text.match(/^\<(.+)\>$/)) || // <http://laobubu.net> (mat = text.match(/^\((.+)\)$/)) || // (http://laobubu.net) (mat = [null, text]) // http://laobubu.net last possibility: plain url w/o < > ) { url = mat[1] } url = cm.hmdResolveURL(url) } else if (styles.match(/\sformatting-task\s/)) { // TO-DO checkbox type = "todo" range = expandRange(cm, pos, "formatting-task") range.to.ch = cm.getLine(pos.line).length text = cm.getRange(range.from, range.to) url = null } else if (styles.match(/\shashtag/)) { type = "hashtag" range = expandRange(cm, pos, "hashtag") text = cm.getRange(range.from, range.to) url = null } if (type !== null) { this._cinfo = { type, text, url, pos, button, clientX, clientY, ctrlKey, altKey, shiftKey, } this.lineDiv.addEventListener('mouseup', this._mouseUp, false) } } } //#endregion /** ADDON GETTER (Singleton Pattern): a editor can have only one Click instance */ export const getAddon = Addon.Getter("Click", Click, defaultOption /** if has options */) declare global { namespace HyperMD { interface HelperCollection { Click?: Click } } }
the_stack
import * as pb_1 from "google-protobuf"; export namespace blaze.worker { export class Input extends pb_1.Message { constructor(data?: any[] | { path?: string; digest?: Uint8Array; }) { super(); pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], []); if (!Array.isArray(data) && typeof data == "object") { if ("path" in data && data.path != undefined) { this.path = data.path; } if ("digest" in data && data.digest != undefined) { this.digest = data.digest; } } } get path() { return pb_1.Message.getField(this, 1) as string; } set path(value: string) { pb_1.Message.setField(this, 1, value); } get digest() { return pb_1.Message.getField(this, 2) as Uint8Array; } set digest(value: Uint8Array) { pb_1.Message.setField(this, 2, value); } toObject() { const data: { path?: string; digest?: Uint8Array; } = {}; if (this.path != null) { data.path = this.path; } if (this.digest != null) { data.digest = this.digest; } return data; } serialize(): Uint8Array; serialize(w: pb_1.BinaryWriter): void; serialize(w?: pb_1.BinaryWriter): Uint8Array | void { const writer = w || new pb_1.BinaryWriter(); if (typeof this.path === "string" && this.path.length) writer.writeString(1, this.path); if (this.digest !== undefined) writer.writeBytes(2, this.digest); if (!w) return writer.getResultBuffer(); } static deserialize(bytes: Uint8Array | pb_1.BinaryReader): Input { const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new Input(); while (reader.nextField()) { if (reader.isEndGroup()) break; switch (reader.getFieldNumber()) { case 1: message.path = reader.readString(); break; case 2: message.digest = reader.readBytes(); break; default: reader.skipField(); } } return message; } serializeBinary(): Uint8Array { return this.serialize(); } static deserializeBinary(bytes: Uint8Array): Input { return Input.deserialize(bytes); } } export class WorkRequest extends pb_1.Message { constructor(data?: any[] | { arguments?: string[]; inputs?: Input[]; request_id?: number; cancel?: boolean; verbosity?: number; }) { super(); pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1, 2], []); if (!Array.isArray(data) && typeof data == "object") { if ("arguments" in data && data.arguments != undefined) { this.arguments = data.arguments; } if ("inputs" in data && data.inputs != undefined) { this.inputs = data.inputs; } if ("request_id" in data && data.request_id != undefined) { this.request_id = data.request_id; } if ("cancel" in data && data.cancel != undefined) { this.cancel = data.cancel; } if ("verbosity" in data && data.verbosity != undefined) { this.verbosity = data.verbosity; } } } get arguments() { return pb_1.Message.getField(this, 1) as string[]; } set arguments(value: string[]) { pb_1.Message.setField(this, 1, value); } get inputs() { return pb_1.Message.getRepeatedWrapperField(this, Input, 2) as Input[]; } set inputs(value: Input[]) { pb_1.Message.setRepeatedWrapperField(this, 2, value); } get request_id() { return pb_1.Message.getField(this, 3) as number; } set request_id(value: number) { pb_1.Message.setField(this, 3, value); } get cancel() { return pb_1.Message.getField(this, 4) as boolean; } set cancel(value: boolean) { pb_1.Message.setField(this, 4, value); } get verbosity() { return pb_1.Message.getField(this, 5) as number; } set verbosity(value: number) { pb_1.Message.setField(this, 5, value); } toObject() { const data: { arguments?: string[]; inputs?: ReturnType<typeof Input.prototype.toObject>[]; request_id?: number; cancel?: boolean; verbosity?: number; } = {}; if (this.arguments != null) { data.arguments = this.arguments; } if (this.inputs != null) { data.inputs = this.inputs.map((item: Input) => item.toObject()); } if (this.request_id != null) { data.request_id = this.request_id; } if (this.cancel != null) { data.cancel = this.cancel; } if (this.verbosity != null) { data.verbosity = this.verbosity; } return data; } serialize(): Uint8Array; serialize(w: pb_1.BinaryWriter): void; serialize(w?: pb_1.BinaryWriter): Uint8Array | void { const writer = w || new pb_1.BinaryWriter(); if (this.arguments !== undefined) writer.writeRepeatedString(1, this.arguments); if (this.inputs !== undefined) writer.writeRepeatedMessage(2, this.inputs, (item: Input) => item.serialize(writer)); if (this.request_id !== undefined) writer.writeInt32(3, this.request_id); if (this.cancel !== undefined) writer.writeBool(4, this.cancel); if (this.verbosity !== undefined) writer.writeInt32(5, this.verbosity); if (!w) return writer.getResultBuffer(); } static deserialize(bytes: Uint8Array | pb_1.BinaryReader): WorkRequest { const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new WorkRequest(); while (reader.nextField()) { if (reader.isEndGroup()) break; switch (reader.getFieldNumber()) { case 1: pb_1.Message.addToRepeatedField(message, 1, reader.readString()); break; case 2: reader.readMessage(message.inputs, () => pb_1.Message.addToRepeatedWrapperField(message, 2, Input.deserialize(reader), Input)); break; case 3: message.request_id = reader.readInt32(); break; case 4: message.cancel = reader.readBool(); break; case 5: message.verbosity = reader.readInt32(); break; default: reader.skipField(); } } return message; } serializeBinary(): Uint8Array { return this.serialize(); } static deserializeBinary(bytes: Uint8Array): WorkRequest { return WorkRequest.deserialize(bytes); } } export class WorkResponse extends pb_1.Message { constructor(data?: any[] | { exit_code?: number; output?: string; request_id?: number; was_cancelled?: boolean; }) { super(); pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], []); if (!Array.isArray(data) && typeof data == "object") { if ("exit_code" in data && data.exit_code != undefined) { this.exit_code = data.exit_code; } if ("output" in data && data.output != undefined) { this.output = data.output; } if ("request_id" in data && data.request_id != undefined) { this.request_id = data.request_id; } if ("was_cancelled" in data && data.was_cancelled != undefined) { this.was_cancelled = data.was_cancelled; } } } get exit_code() { return pb_1.Message.getField(this, 1) as number; } set exit_code(value: number) { pb_1.Message.setField(this, 1, value); } get output() { return pb_1.Message.getField(this, 2) as string; } set output(value: string) { pb_1.Message.setField(this, 2, value); } get request_id() { return pb_1.Message.getField(this, 3) as number; } set request_id(value: number) { pb_1.Message.setField(this, 3, value); } get was_cancelled() { return pb_1.Message.getField(this, 4) as boolean; } set was_cancelled(value: boolean) { pb_1.Message.setField(this, 4, value); } toObject() { const data: { exit_code?: number; output?: string; request_id?: number; was_cancelled?: boolean; } = {}; if (this.exit_code != null) { data.exit_code = this.exit_code; } if (this.output != null) { data.output = this.output; } if (this.request_id != null) { data.request_id = this.request_id; } if (this.was_cancelled != null) { data.was_cancelled = this.was_cancelled; } return data; } serialize(): Uint8Array; serialize(w: pb_1.BinaryWriter): void; serialize(w?: pb_1.BinaryWriter): Uint8Array | void { const writer = w || new pb_1.BinaryWriter(); if (this.exit_code !== undefined) writer.writeInt32(1, this.exit_code); if (typeof this.output === "string" && this.output.length) writer.writeString(2, this.output); if (this.request_id !== undefined) writer.writeInt32(3, this.request_id); if (this.was_cancelled !== undefined) writer.writeBool(4, this.was_cancelled); if (!w) return writer.getResultBuffer(); } static deserialize(bytes: Uint8Array | pb_1.BinaryReader): WorkResponse { const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new WorkResponse(); while (reader.nextField()) { if (reader.isEndGroup()) break; switch (reader.getFieldNumber()) { case 1: message.exit_code = reader.readInt32(); break; case 2: message.output = reader.readString(); break; case 3: message.request_id = reader.readInt32(); break; case 4: message.was_cancelled = reader.readBool(); break; default: reader.skipField(); } } return message; } serializeBinary(): Uint8Array { return this.serialize(); } static deserializeBinary(bytes: Uint8Array): WorkResponse { return WorkResponse.deserialize(bytes); } } }
the_stack
////interface I { //// methodOfInterface(): number; ////} ////interface I2 { //// methodOfInterface2(): number; ////} ////interface I3 { //// getValue(): string; //// method(): string; ////} ////interface I4 { //// staticMethod(): void; //// method(): string; ////} ////class B0 { //// private privateMethod() { } //// protected protectedMethod() { } //// static staticMethod() { } //// getValue(): string | boolean { return "hello"; } //// private privateMethod1() { } //// protected protectedMethod1() { } //// static staticMethod1() { } //// getValue1(): string | boolean { return "hello"; } ////} ////interface I5 extends B0 { //// methodOfInterface5(): number; ////} ////interface I6 extends B0 { //// methodOfInterface6(): number; //// staticMethod(): void; ////} ////interface I7 extends I { //// methodOfInterface7(): number; ////} ////class B { //// private privateMethod() { } //// protected protectedMethod() { } //// static staticMethod() { } //// getValue(): string | boolean { return "hello"; } ////} ////class C0 implements I, I2 { //// /*implementsIAndI2*/ ////} ////class C00 implements I, I2 { //// static /*implementsIAndI2AndWritingStatic*/ ////} ////class C001 implements I, I2 { //// methodOfInterface/*implementsIAndI2AndWritingMethodNameOfI*/ ////} ////class C extends B implements I, I2 { //// /*extendsBAndImplementsIAndI2*/ ////} ////class C1 extends B implements I, I2 { //// static /*extendsBAndImplementsIAndI2AndWritingStatic*/ ////} ////class D extends B implements I, I2 { //// /*extendsBAndImplementsIAndI2WithMethodFromB*/ //// protected protectedMethod() { //// return "protected"; //// } ////} ////class E extends B implements I, I2 { //// /*extendsBAndImplementsIAndI2WithMethodFromI*/ //// methodOfInterface() { //// return 1; //// } ////} ////class F extends B implements I, I2 { //// /*extendsBAndImplementsIAndI2WithMethodFromBAndI*/ //// protected protectedMethod() { //// return "protected" //// } //// methodOfInterface() { //// return 1; //// } ////} ////class F2 extends B implements I, I2 { //// protected protectedMethod() { //// return "protected" //// } //// methodOfInterface() { //// return 1; //// } //// static /*extendsBAndImplementsIAndI2WithMethodFromBAndIAndTypesStatic*/ ////} ////class G extends B implements I3 { //// /*extendsBAndImplementsI3WithSameNameMembers*/ ////} ////class H extends B implements I3 { //// /*extendsBAndImplementsI3WithSameNameMembersAndHasImplementedTheMember*/ //// getValue() { //// return "hello"; //// } ////} ////class J extends B0 implements I4 { //// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethod*/ ////} ////class L extends B0 implements I4 { //// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethod*/ //// staticMethod2() { //// return "hello"; //// } ////} ////class K extends B0 implements I4 { //// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethod*/ //// staticMethod() { //// return "hello"; //// } ////} ////class M extends B0 implements I4 { //// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStatic*/ //// static staticMethod() { //// return "hello"; //// } ////} ////class N extends B0 implements I4 { //// /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBoth*/ //// staticMethod() { //// return "hello"; //// } //// static staticMethod() { //// return "hello"; //// } ////} ////class J1 extends B0 implements I4 { //// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodWritingStatic*/ ////} ////class L1 extends B0 implements I4 { //// staticMethod2() { //// return "hello"; //// } //// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethodWritingStatic*/ ////} ////class K1 extends B0 implements I4 { //// staticMethod() { //// return "hello"; //// } //// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodWritingStatic*/ ////} ////class M1 extends B0 implements I4 { //// static staticMethod() { //// return "hello"; //// } //// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStaticWritingStatic*/ ////} ////class N1 extends B0 implements I4 { //// staticMethod() { //// return "hello"; //// } //// static staticMethod() { //// return "hello"; //// } //// static /*extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBothWritingStatic*/ ////} ////class O implements I7 { //// /*implementsI7whichExtendsI*/ ////} ////class P implements I7, I { //// /*implementsI7whichExtendsIAndAlsoImplementsI*/ ////} ////class Q implements I, I7 { //// /*implementsIAndAlsoImplementsI7whichExtendsI*/ ////} ////class R implements I5 { //// /*implementsI5ThatExtendsB0*/ ////} ////class S implements I6 { //// /*implementsI6ThatExtendsB0AndHasStaticMethodOfB0*/ ////} ////class T extends B0 implements I5 { //// /*extendsB0AndImplementsI5ThatExtendsB0*/ ////} ////class U extends B0 implements I6 { //// /*extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0*/ ////} ////class R1 implements I5 { //// static /*implementsI5ThatExtendsB0TypesStatic*/ ////} ////class S1 implements I6 { //// static /*implementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic*/ ////} ////class T1 extends B0 implements I5 { //// static /*extendsB0AndImplementsI5ThatExtendsB0TypesStatic*/ ////} ////class U1 extends B0 implements I6 { //// static /*extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic*/ ////} const validInstanceMembersOfBaseClassB: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "protectedMethod", text: "(method) B.protectedMethod(): void", kindModifiers: "protected" }, { name: "getValue", text: "(method) B.getValue(): string | boolean" }, ]; const validStaticMembersOfBaseClassB: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "staticMethod", text: "(method) B.staticMethod(): void", kindModifiers: "static" }, ]; const privateMembersOfBaseClassB: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "privateMethod", text: "(method) B.privateMethod(): void" }, ]; const protectedPropertiesOfBaseClassB0: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "protectedMethod", text: "(method) B0.protectedMethod(): void", kindModifiers: "protected" }, { name: "protectedMethod1", text: "(method) B0.protectedMethod1(): void", kindModifiers: "protected" }, ]; const publicPropertiesOfBaseClassB0: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "getValue", text: "(method) B0.getValue(): string | boolean" }, { name: "getValue1", text: "(method) B0.getValue1(): string | boolean" }, ]; const validInstanceMembersOfBaseClassB0: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = protectedPropertiesOfBaseClassB0.concat(publicPropertiesOfBaseClassB0); const validInstanceMembersOfBaseClassB0_2 : ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ protectedPropertiesOfBaseClassB0[0], publicPropertiesOfBaseClassB0[0], protectedPropertiesOfBaseClassB0[1], publicPropertiesOfBaseClassB0[1], ]; const validStaticMembersOfBaseClassB0: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "staticMethod", text: "(method) B0.staticMethod(): void", kindModifiers: "static" }, { name: "staticMethod1", text: "(method) B0.staticMethod1(): void", kindModifiers: "static" }, ]; const privateMembersOfBaseClassB0: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "privateMethod", text: "(method) B0.privateMethod(): void", kindModifiers: "private" }, { name: "privateMethod1", text: "(method) B0.privateMethod1(): void", kindModifiers: "private" }, ]; const membersOfI: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "methodOfInterface", text: "(method) I.methodOfInterface(): number" }, ]; const membersOfI2: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "methodOfInterface2", text: "(method) I2.methodOfInterface2(): number" }, ]; const membersOfI3: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "getValue", text: "(method) I3.getValue(): string" }, { name: "method", text: "(method) I3.method(): string" }, ]; const membersOfI4: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "staticMethod", text: "(method) I4.staticMethod(): void" }, { name: "method", text: "(method) I4.method(): string" }, ]; const membersOfI5: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = publicPropertiesOfBaseClassB0.concat([ { name: "methodOfInterface5", text: "(method) I5.methodOfInterface5(): number" }, ]); const membersOfJustI5: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "methodOfInterface5", text: "(method) I5.methodOfInterface5(): number" }, ]; const membersOfI6: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = publicPropertiesOfBaseClassB0.concat([ { name: "staticMethod", text: "(method) I6.staticMethod(): void" }, { name: "methodOfInterface6", text: "(method) I6.methodOfInterface6(): number" }, ]); const membersOfI7: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ { name: "methodOfInterface7", text: "(method) I7.methodOfInterface7(): number" }, ...membersOfI, ]; const membersOfI7_2: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = [ ...membersOfI, { name: "methodOfInterface7", text: "(method) I7.methodOfInterface7(): number" }, ]; const noMembers: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> = []; const membersOfIAndI2 = [...membersOfI, ...membersOfI2]; const invalidMembersOfBAtInstanceLocation = privateMembersOfBaseClassB.concat(validStaticMembersOfBaseClassB); const allInstanceBAndIAndI2 = [...validInstanceMembersOfBaseClassB, ...membersOfIAndI2]; const invalidMembersOfB0AtInstanceSide = [...privateMembersOfBaseClassB0, ...validStaticMembersOfBaseClassB0]; const invalidMembersOfB0AtStaticSide = [...privateMembersOfBaseClassB0, validInstanceMembersOfBaseClassB0]; const invalidMembersOfB0AtInstanceSideFromInterfaceExtendingB0 = invalidMembersOfB0AtInstanceSide; const tests: ReadonlyArray<{ readonly marker: string | ReadonlyArray<string>, readonly members: ReadonlyArray<FourSlashInterface.ExpectedCompletionEntryObject> }> = [ // members of I and I2 { marker: ["implementsIAndI2", "implementsIAndI2AndWritingMethodNameOfI"], members: membersOfIAndI2 }, // Static location so no members of I and I2 { marker: "implementsIAndI2AndWritingStatic", members: [] }, // members of instance B, I and I2 { marker: "extendsBAndImplementsIAndI2", members: allInstanceBAndIAndI2 }, // static location so only static members of B and no members of instance B, I and I2 { marker: [ "extendsBAndImplementsIAndI2AndWritingStatic", "extendsBAndImplementsIAndI2WithMethodFromBAndIAndTypesStatic" ], members: validStaticMembersOfBaseClassB, }, // instance members of B without protectedMethod, I and I2 { marker: "extendsBAndImplementsIAndI2WithMethodFromB",members: [validInstanceMembersOfBaseClassB[1], ...membersOfIAndI2] }, //TODO:NEATER // instance members of B, members of T without methodOfInterface and I2 { marker: "extendsBAndImplementsIAndI2WithMethodFromI", members: [...validInstanceMembersOfBaseClassB, ...membersOfI2] }, // instance members of B without protectedMethod, members of T without methodOfInterface and I2 { marker: "extendsBAndImplementsIAndI2WithMethodFromBAndI", members: [validInstanceMembersOfBaseClassB[1], ...membersOfI2] }, // members of B and members of I3 that are not same as name of method in B { marker: "extendsBAndImplementsI3WithSameNameMembers", members: [...validInstanceMembersOfBaseClassB, membersOfI3[1]] }, //TODO:NEATER // members of B (without getValue since its implemented) and members of I3 that are not same as name of method in B { marker: "extendsBAndImplementsI3WithSameNameMembersAndHasImplementedTheMember", members: [validInstanceMembersOfBaseClassB[0], membersOfI3[1]] }, //TODO:NEATER // members of B0 and members of I4 { marker: [ "extendsB0ThatExtendsAndImplementsI4WithStaticMethod", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethod", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStatic", ], members: [...validInstanceMembersOfBaseClassB0_2, ...membersOfI4], }, // members of B0 and members of I4 that are not staticMethod { marker: [ "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethod", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBoth", ], members: [...validInstanceMembersOfBaseClassB0_2, membersOfI4[1]], //TODO:NEATER }, // static members of B0 { marker: [ "extendsB0ThatExtendsAndImplementsI4WithStaticMethodWritingStatic", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedAnotherMethodWritingStatic", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodWritingStatic", ], members: validStaticMembersOfBaseClassB0, }, // static members of B0 without staticMethod { marker: [ "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsStaticWritingStatic", "extendsB0ThatExtendsAndImplementsI4WithStaticMethodAndImplementedThatMethodAsBothWritingStatic", ], members: [validStaticMembersOfBaseClassB0[1]] // TODO:NEATER }, // members of I7 extends I { marker: [ "implementsI7whichExtendsI", "implementsI7whichExtendsIAndAlsoImplementsI", ], members: membersOfI7, }, { marker: "implementsIAndAlsoImplementsI7whichExtendsI", members: membersOfI7_2, }, // members of I5 extends B0 { marker: "implementsI5ThatExtendsB0", members: [...membersOfJustI5, protectedPropertiesOfBaseClassB0[0], publicPropertiesOfBaseClassB0[0], protectedPropertiesOfBaseClassB0[1], publicPropertiesOfBaseClassB0[1]], //TODO:NEATER }, // members of I6 extends B0 { marker: "implementsI6ThatExtendsB0AndHasStaticMethodOfB0", //TODO:NEATER members:[ membersOfI6[3], membersOfI6[2], protectedPropertiesOfBaseClassB0[0], membersOfI6[0], protectedPropertiesOfBaseClassB0[1], membersOfI6[1], ], }, // members of B0 and I5 that extends B0 { marker: "extendsB0AndImplementsI5ThatExtendsB0", members: [ protectedPropertiesOfBaseClassB0[0], membersOfI5[0], protectedPropertiesOfBaseClassB0[1], membersOfI5[1], membersOfI5[2], ], }, // members of B0 and I6 that extends B0 { marker: "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0", members: [ protectedPropertiesOfBaseClassB0[0], membersOfI6[0], protectedPropertiesOfBaseClassB0[1], membersOfI6[1], membersOfI6[3], membersOfI6[2], ], }, // nothing on static side as these do not extend any other class { marker: [ "implementsI5ThatExtendsB0TypesStatic", "implementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic", ], members: [], }, { marker: [ "extendsB0AndImplementsI5ThatExtendsB0TypesStatic", "extendsB0AndImplementsI6ThatExtendsB0AndHasStaticMethodOfB0TypesStatic", ], // statics of base B but nothing from instance side members: validStaticMembersOfBaseClassB0, }, ]; verify.completions(...tests.map(({ marker, members }): FourSlashInterface.CompletionsOptions => ({ marker, unsorted: [...members.map(m => ({ ...m, kind: "method" })), ...completion.classElementKeywords], isNewIdentifierLocation: true, })));
the_stack
import {TestBed, waitForAsync} from '@angular/core/testing'; import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core'; import {Locale} from 'date-fns'; import {ja, enUS, da, de} from 'date-fns/locale'; import {DateFnsModule} from './index'; const JAN = 0, FEB = 1, MAR = 2, DEC = 11; describe('DateFnsAdapter', () => { let adapter: DateAdapter<Date, Locale>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [DateFnsModule], }).compileComponents(); adapter = TestBed.inject(DateAdapter); adapter.setLocale(enUS); })); it('should get year', () => { expect(adapter.getYear(new Date(2017, JAN, 1))).toBe(2017); }); it('should get month', () => { expect(adapter.getMonth(new Date(2017, JAN, 1))).toBe(0); }); it('should get date', () => { expect(adapter.getDate(new Date(2017, JAN, 1))).toBe(1); }); it('should get day of week', () => { expect(adapter.getDayOfWeek(new Date(2017, JAN, 1))).toBe(0); }); it('should get long month names', () => { expect(adapter.getMonthNames('long')).toEqual([ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]); }); it('should get short month names', () => { expect(adapter.getMonthNames('short')).toEqual([ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]); }); it('should get narrow month names', () => { expect(adapter.getMonthNames('narrow')).toEqual([ 'J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D', ]); }); it('should get month names in a different locale', () => { adapter.setLocale(da); expect(adapter.getMonthNames('long')).toEqual([ 'januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december', ]); }); it('should get date names', () => { expect(adapter.getDateNames()).toEqual([ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', ]); }); it('should get date names in a different locale', () => { adapter.setLocale(ja); if (typeof Intl !== 'undefined') { expect(adapter.getDateNames()).toEqual([ '1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日', ]); } else { expect(adapter.getDateNames()).toEqual([ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', ]); } }); it('should get long day of week names', () => { expect(adapter.getDayOfWeekNames('long')).toEqual([ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]); }); it('should get short day of week names', () => { expect(adapter.getDayOfWeekNames('short')).toEqual([ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', ]); }); it('should get narrow day of week names', () => { expect(adapter.getDayOfWeekNames('narrow')).toEqual(['S', 'M', 'T', 'W', 'T', 'F', 'S']); }); it('should get day of week names in a different locale', () => { adapter.setLocale(ja); expect(adapter.getDayOfWeekNames('long')).toEqual([ '日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日', ]); }); it('should get year name', () => { expect(adapter.getYearName(new Date(2017, JAN, 1))).toBe('2017'); }); it('should get year name in a different locale', () => { adapter.setLocale(ja); expect(adapter.getYearName(new Date(2017, JAN, 1))).toBe('2017'); }); it('should get first day of week', () => { expect(adapter.getFirstDayOfWeek()).toBe(0); }); it('should not create Date with month over/under-flow', () => { expect(() => adapter.createDate(2017, 12, 1)).toThrow(); expect(() => adapter.createDate(2017, -1, 1)).toThrow(); }); it('should not create Date with date over/under-flow', () => { expect(() => adapter.createDate(2017, JAN, 32)).toThrow(); expect(() => adapter.createDate(2017, JAN, 0)).toThrow(); }); it("should get today's date", () => { expect(adapter.sameDate(adapter.today(), new Date())) .withContext("should be equal to today's date") .toBe(true); }); it('should parse string according to given format', () => { expect(adapter.parse('1/2/2017', 'M/d/yyyy')).toEqual(new Date(2017, JAN, 2)); expect(adapter.parse('1/2/2017', 'd/M/yyyy')).toEqual(new Date(2017, FEB, 1)); }); it('should parse string according to first matching format', () => { expect(adapter.parse('1/2/2017', ['M/d/yyyy', 'yyyy/d/M'])).toEqual(new Date(2017, JAN, 2)); expect(adapter.parse('1/2/2017', ['yyyy/d/M', 'M/d/yyyy'])).toEqual(new Date(2017, JAN, 2)); }); it('should throw if parse formats are an empty array', () => { expect(() => adapter.parse('1/2/2017', [])).toThrowError('Formats array must not be empty.'); }); it('should parse number', () => { const timestamp = new Date().getTime(); expect(adapter.parse(timestamp, 'MM/dd/yyyy')!.getTime()).toEqual(timestamp); }); it('should parse Date', () => { let date = new Date(2017, JAN, 1); expect(adapter.parse(date, 'MM/dd/yyyy')).toEqual(date); }); it('should parse empty string as null', () => { expect(adapter.parse('', 'MM/dd/yyyy')).toBeNull(); }); it('should parse based on the specified locale', () => { adapter.setLocale(de); expect(adapter.parse('02.01.2017', 'P')).toEqual(new Date(2017, JAN, 2)); }); it('should parse invalid value as invalid', () => { let d = adapter.parse('hello', 'MM/dd/yyyy'); expect(d).not.toBeNull(); expect(adapter.isDateInstance(d)).toBe(true); expect(adapter.isValid(d as Date)) .withContext('Expected to parse as "invalid date" object') .toBe(false); }); it('should format date according to given format', () => { expect(adapter.format(new Date(2017, JAN, 2), 'MM/dd/yyyy')).toEqual('01/02/2017'); }); it('should format with a different locale', () => { let date = adapter.format(new Date(2017, JAN, 2), 'PP'); expect(stripDirectionalityCharacters(date)).toEqual('Jan 2, 2017'); adapter.setLocale(da); date = adapter.format(new Date(2017, JAN, 2), 'PP'); expect(stripDirectionalityCharacters(date)).toEqual('2. jan. 2017'); }); it('should throw when attempting to format invalid date', () => { expect(() => adapter.format(new Date(NaN), 'MM/dd/yyyy')).toThrowError( /DateFnsAdapter: Cannot format invalid date\./, ); }); it('should add years', () => { expect(adapter.addCalendarYears(new Date(2017, JAN, 1), 1)).toEqual(new Date(2018, JAN, 1)); expect(adapter.addCalendarYears(new Date(2017, JAN, 1), -1)).toEqual(new Date(2016, JAN, 1)); }); it('should respect leap years when adding years', () => { expect(adapter.addCalendarYears(new Date(2016, FEB, 29), 1)).toEqual(new Date(2017, FEB, 28)); expect(adapter.addCalendarYears(new Date(2016, FEB, 29), -1)).toEqual(new Date(2015, FEB, 28)); }); it('should add months', () => { expect(adapter.addCalendarMonths(new Date(2017, JAN, 1), 1)).toEqual(new Date(2017, FEB, 1)); expect(adapter.addCalendarMonths(new Date(2017, JAN, 1), -1)).toEqual(new Date(2016, DEC, 1)); }); it('should respect month length differences when adding months', () => { expect(adapter.addCalendarMonths(new Date(2017, JAN, 31), 1)).toEqual(new Date(2017, FEB, 28)); expect(adapter.addCalendarMonths(new Date(2017, MAR, 31), -1)).toEqual(new Date(2017, FEB, 28)); }); it('should add days', () => { expect(adapter.addCalendarDays(new Date(2017, JAN, 1), 1)).toEqual(new Date(2017, JAN, 2)); expect(adapter.addCalendarDays(new Date(2017, JAN, 1), -1)).toEqual(new Date(2016, DEC, 31)); }); it('should clone', () => { let date = new Date(2017, JAN, 1); let clone = adapter.clone(date); expect(clone).not.toBe(date); expect(clone.getTime()).toEqual(date.getTime()); }); it('should compare dates', () => { expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, JAN, 2))).toBeLessThan(0); expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, FEB, 1))).toBeLessThan(0); expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2018, JAN, 1))).toBeLessThan(0); expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, JAN, 1))).toBe(0); expect(adapter.compareDate(new Date(2018, JAN, 1), new Date(2017, JAN, 1))).toBeGreaterThan(0); expect(adapter.compareDate(new Date(2017, FEB, 1), new Date(2017, JAN, 1))).toBeGreaterThan(0); expect(adapter.compareDate(new Date(2017, JAN, 2), new Date(2017, JAN, 1))).toBeGreaterThan(0); }); it('should clamp date at lower bound', () => { expect( adapter.clampDate(new Date(2017, JAN, 1), new Date(2018, JAN, 1), new Date(2019, JAN, 1)), ).toEqual(new Date(2018, JAN, 1)); }); it('should clamp date at upper bound', () => { expect( adapter.clampDate(new Date(2020, JAN, 1), new Date(2018, JAN, 1), new Date(2019, JAN, 1)), ).toEqual(new Date(2019, JAN, 1)); }); it('should clamp date already within bounds', () => { expect( adapter.clampDate(new Date(2018, FEB, 1), new Date(2018, JAN, 1), new Date(2019, JAN, 1)), ).toEqual(new Date(2018, FEB, 1)); }); it('should count today as a valid date instance', () => { let d = new Date(); expect(adapter.isValid(d)).toBe(true); expect(adapter.isDateInstance(d)).toBe(true); }); it('should count an invalid date as an invalid date instance', () => { let d = new Date(NaN); expect(adapter.isValid(d)).toBe(false); expect(adapter.isDateInstance(d)).toBe(true); }); it('should count a string as not a date instance', () => { let d = '1/1/2017'; expect(adapter.isDateInstance(d)).toBe(false); }); it('should create valid dates from valid ISO strings', () => { assertValidDate(adapter, adapter.deserialize('1985-04-12T23:20:50.52Z'), true); assertValidDate(adapter, adapter.deserialize('1996-12-19T16:39:57-08:00'), true); assertValidDate(adapter, adapter.deserialize('1937-01-01T12:00:27.87+00:20'), true); assertValidDate(adapter, adapter.deserialize('1990-13-31T23:59:00Z'), false); assertValidDate(adapter, adapter.deserialize('1/1/2017'), false); expect(adapter.deserialize('')).toBeNull(); expect(adapter.deserialize(null)).toBeNull(); assertValidDate(adapter, adapter.deserialize(new Date()), true); assertValidDate(adapter, adapter.deserialize(new Date(NaN)), false); assertValidDate(adapter, adapter.deserialize(new Date()), true); assertValidDate(adapter, adapter.deserialize(new Date('Not valid')), false); }); it('should create invalid date', () => { assertValidDate(adapter, adapter.invalid(), false); }); }); describe('DateFnsAdapter with MAT_DATE_LOCALE override', () => { let adapter: DateAdapter<Date, Locale>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [DateFnsModule], providers: [{provide: MAT_DATE_LOCALE, useValue: da}], }).compileComponents(); adapter = TestBed.inject(DateAdapter); })); it('should take the default locale id from the MAT_DATE_LOCALE injection token', () => { const date = adapter.format(new Date(2017, JAN, 2), 'PP'); expect(stripDirectionalityCharacters(date)).toEqual('2. jan. 2017'); }); }); function stripDirectionalityCharacters(str: string) { return str.replace(/[\u200e\u200f]/g, ''); } function assertValidDate(adapter: DateAdapter<Date, Locale>, d: Date | null, valid: boolean) { expect(adapter.isDateInstance(d)) .not.withContext(`Expected ${d} to be a date instance`) .toBeNull(); expect(adapter.isValid(d!)) .withContext( `Expected ${d} to be ${valid ? 'valid' : 'invalid'},` + ` but was ${valid ? 'invalid' : 'valid'}`, ) .toBe(valid); }
the_stack
import { UnigraphUpsert } from "../types/unigraph" import _, { has, uniqueId } from "lodash"; import { typeMap } from '../types/consts' import { getRandomInt } from "../api/unigraph"; function buildDgraphFunctionFromRefQuery(query: {key: string, value: string}[]) { let string = ""; let string1 = ""; let typeSelector = ""; let typeSelectorName = ""; const innerRefs: string[] = []; query.forEach(({key, value}: any) => { const refTarget = key.replace(/["%@\\]/g, ""); const refQuery = value.replace(/["%@\\]/g, ""); if (refTarget === "unigraph.id") { string += `AND eq(${refTarget}, "${refQuery}")`; string1 = `eq(${refTarget}, "${refQuery}")`; } else if (refTarget === "type/unigraph.id") { //innerRefs.push(`type @filter(eq(<unigraph.id>, "${refQuery}"))`); typeSelectorName = "typeSelector" + getRandomInt().toString(); typeSelector = `var(func: eq(<unigraph.id>, "${refQuery}")) { <~type> { `+ typeSelectorName +" as uid } }" } else { // Referencing a field (not unigraph.id), do manual padding! // TODO: Support deep nested references innerRefs.push(`_value { ${refTarget} @filter(eq(<${typeMap[typeof refQuery]}>, "${refQuery}")) }`) } }) if (innerRefs.length) { if (typeSelectorName.length) { string1 = `uid(${typeSelectorName})` string = `AND type(Entity)` } else { string1 = `type(Entity)` string = `AND type(Entity)` } } let fn = `var(func: ${string1}) @filter(${string.slice(4)})`; if (innerRefs.length) { fn += " @cascade {\n"; innerRefs.forEach(str => fn += str + "\n"); fn += "}"; } if (typeSelector) fn = [fn, typeSelector] as any; return fn; } /** * Wraps a given updater in upsert format by adding UIDs to body. * * @param object * @param string The first couple of characters passed in as uids */ export function wrapUpsertFromUpdater(orig: any, queryHead: string, hasUid: string | false = false, blankUidsToRef: any): any { const queries: string[] = [] function buildQuery(parUid: string, key: string, hasUid: string | false = false) { const currentQuery = `${parUid}_${queries.length.toString()}` const getUidQuery = hasUid ? hasUid : parUid const query = `var(func: uid(${getUidQuery})) { <${key}> { ${currentQuery} as uid }}` queries.push(query); return currentQuery; } function buildQueryCount(parUid: string, n: number, hasUid: string | false = false) { const currentQuery = `${parUid}_${queries.length.toString()}` const getUidQuery = hasUid ? hasUid : parUid const query = `var(func: uid(${getUidQuery})) { ${currentQuery}_scoped as count(<_value[>) }` const subqueries = []; for (let i=0; i<n; ++i) {subqueries.push(`${currentQuery}_${i} as math(${currentQuery}+${i})`)} const query2 = `var() {${currentQuery} as sum(val(${currentQuery}_scoped)) ${subqueries.join(' ')} }` queries.push(query, query2); return currentQuery; } function recurse(origNow: any, thisUid: string, hasUid: string | false = false): any { //console.log("recursing --- " + JSON.stringify(origNow, null, 2) + thisUid) if (['undefined', 'null', 'number', 'bigint', 'string', 'boolean', 'symbol'].includes(typeof origNow)) { // This means the updater is creating new things inside or changing primitive values: we don't need uid queries.pop(); return origNow; } else if (typeof origNow === 'object' && Array.isArray(origNow)) { // TODO: document expected behavior: when upserting an array, elements are always appended. if (typeof origNow[0] === 'object') { const currPos = buildQueryCount(thisUid, origNow.length, hasUid); const newOrig = origNow.map((el, index) => { return {...el, _index: {"_value.#i": `val(${currPos}_${index})`}} }); return newOrig; // Appends it } else if (origNow.length > 0) { // No UID available for list of primitives queries.pop(); // Just a bunch of simple objects - we're not doing index management return origNow; } else return origNow; } else if (typeof origNow == 'object' && !Array.isArray(origNow)) { const res = Object.fromEntries([ ...Object.entries(origNow).map(([key, value]) => { if (key !== '_value[' && key !== '$ref' && key !== 'type') { // FIXME: This currently ignores subsequent UIDs if one is specified. Fix ASAP! return [key, recurse(origNow[key], buildQuery(thisUid, key, hasUid))] } else if (key !== '$ref' && key !== 'type') { return [key, recurse(origNow[key], thisUid)] } else { // Don't process `$ref` because we need it later or `type` because it's overwritten if (key === '$ref') {queries.pop()} // Have ref, will be overwritten, so no use keeping a duplicate variable return [key, value] } // TODO: These matches are of lowest priority - so we should allow the upsert even if these objects are not used }), ["uid", hasUid ? hasUid : `uid(${thisUid})`] // Must have UID to do anything with it ]); if (origNow.uid?.startsWith?.('_:')) blankUidsToRef[origNow.uid] = res.uid; return res; } } const upsertObject = recurse(orig, queryHead, hasUid); return [upsertObject, queries]; } function* nextUid() { let index = 0; while (true) { yield `_:${index}` index++; } } /** * Converts a list of objects or schemas to a dgraph upsert operation. * This function will ensure that the field `unigraph.id` is unique and all references to be resolved. * @param inserts An array of objects or schemas to insert, containing the `$ref` field */ export function insertsToUpsert(inserts: any[]): UnigraphUpsert { const refUids: string[] = []; const genUid = nextUid(); const blankUids: any[] = []; const blankUidsToRef: Record<string, string> = {} function insertsToUpsertRecursive(inserts: any[], appends: any[], queries: string[], currentObject: any, currentOrigin: any[]) { let isBlankUid = false; // If this is a reference object if (currentObject) { if (currentObject.uid?.startsWith('_:')) isBlankUid = true; if (currentObject.uid && currentObject.uid.startsWith('0x')) { // uid takes precedence over $ref: when specifying explicit; otherwise doesnt care delete currentObject['$ref']; const refUid = "unigraphquery" + (queries.length + 1); const [upsertObject, upsertQueries] = wrapUpsertFromUpdater({"_value": currentObject['_value']}, refUid, currentObject.uid, blankUidsToRef); queries.push(...upsertQueries); currentObject = Object.assign(currentObject, upsertObject); } else if (currentObject["$ref"] && currentObject["$ref"].query) { let refUid = "unigraphquery" + (queries.length + 1) if (currentObject.uid && currentObject.uid.startsWith('_:')) { // definitely switch to same UID import refUid = "unigraphref" + currentObject.uid.slice(2) } currentOrigin?.map(el => {if (el?.uid === currentObject.uid) el.uid = `uid(${refUid})`;}) const query = currentObject['$ref'].query; delete currentObject['$ref']; // FIXME: Some objects (e.g. with standoff properties or type aliases) doesn't use `_value` const [upsertObject, upsertQueries] = wrapUpsertFromUpdater({"_value": currentObject['_value']}, refUid, false, blankUidsToRef); if (!refUids.includes(refUid)) { refUids.push(refUid) let dgraphFunction = buildDgraphFunctionFromRefQuery(query); if (Array.isArray(dgraphFunction)) { queries.push(dgraphFunction[1]); dgraphFunction = dgraphFunction[0]; } queries.push(refUid + " as " + dgraphFunction + "\n"); //currentObject["uid"] = refUid; //currentObject = {"uid": `uid(${refUid})`} queries.push(...upsertQueries) } currentObject = Object.assign(currentObject, {"uid": `uid(${refUid})`, ...upsertObject}) const append: any = {uid: `uid(${refUid})`} query.forEach(({key, value}: any) => {if (key === "unigraph.id") append[key] = value}); appends.push(append) } if (isBlankUid) blankUids.push(currentObject) } //console.log('++++++++++++++++++++++++++++++++++') //console.log(JSON.stringify(currentObject, null, 4)) if (currentObject['dgraph.type']?.includes('Entity')) { currentOrigin = currentOrigin ? JSON.parse(JSON.stringify(currentOrigin)) : undefined; if (!currentObject.uid) currentObject.uid = genUid.next().value; if (!currentObject['unigraph.origin']) currentObject['unigraph.origin'] = {uid: currentObject.uid}; if (currentObject['unigraph.origin'] && !Array.isArray(currentObject['unigraph.origin'])) currentObject['unigraph.origin'] = [currentObject['unigraph.origin']]; if (!currentOrigin) currentOrigin = []; currentOrigin.push(...currentObject['unigraph.origin']); } const objectValues = Object.values(currentObject); for(let i=0; i<objectValues.length; ++i) { if (typeof objectValues[i] === "object" && !Array.isArray(objectValues[i])) { insertsToUpsertRecursive(inserts, appends, queries, objectValues[i], currentOrigin); } else if (typeof objectValues[i] === "object" && Array.isArray(objectValues[i])) { for(let j=0; j<(objectValues[i] as any[]).length; ++j) { if (!Object.keys(currentObject).includes('unigraph.origin')) insertsToUpsertRecursive(inserts, appends, queries, (objectValues[i] as any[])[j], currentOrigin); } } } blankUids.forEach(el => { if (el.uid?.startsWith('_:') && Object.keys(blankUidsToRef).includes(el.uid)) { el.uid = blankUidsToRef[el.uid] } }) if (typeof currentObject === 'object' && !Array.isArray(currentObject) && currentOrigin) currentObject['unigraph.origin'] = currentOrigin; //console.log("-----------------------2", currentObject) } const insertsCopy = JSON.parse(JSON.stringify(inserts)) const queries: any[] = [] const appends: any[] = [] for(let i=0; i<insertsCopy.length; ++i) { const curr = insertsCopy[i]; if (!curr.uid) curr.uid = genUid.next().value; let origin = curr['unigraph.origin']; if (!origin && (!curr['dgraph.type'] || curr['dgraph.type'].includes['Entity'])) origin = {uid: curr.uid}; if (origin && !Array.isArray(origin)) origin = [origin]; insertsToUpsertRecursive(insertsCopy, appends, queries, curr, origin); } //console.log("Upsert processed!") //const util = require('util') //console.log(util.inspect({queries: queries, mutations: insertsCopy, appends: appends}, false, null, true /* enable colors */)) return {queries: queries, mutations: insertsCopy, appends: appends} } // TODO: add the functionality to delete duplicate queries in upsert export function anchorBatchUpsert(upsert: UnigraphUpsert): UnigraphUpsert { const queries = upsert.queries; const appends = upsert.appends; // 1. Use regex to make queries into a deduplicated array const re = /unigraphquery[0-9_]*/g; const extracted_queries = queries.map(query => {return { orig: query, pattern: query.replace(re, "unigraphquery"), elements: query.match(re) }}); // 2. Establish duplicacy const aliases: any = {}; // somehow const unique_extracted = _.uniqBy(extracted_queries, 'pattern'); const appendsMap: any = {}; appends.forEach(it => {appendsMap[it.uid] = it}); const ids = _.flatten(unique_extracted.map(it => it.elements)); const unique_appends = ids.map(el => appendsMap[`uid(${el})`]); return { queries: unique_extracted.map(it => it.orig), mutations: [], appends: unique_appends }; }
the_stack
import { setAutoFreeze, produce, enablePatches as enablePatchesWithImmer, } from 'immer'; import { combineReducers, ReducersMapObject, createStore as createStoreWithRedux, PreloadedState, applyMiddleware, Reducer, AnyAction, } from 'redux'; import type { Container, ServiceIdentifiersMap, ModuleOptions, } from 'reactant-di'; import { ReactantAction, PluginHooks, DevOptions, Subscriptions, ThisService, ReactantStore, Loader, Service as IService, ModulesMap, } from '../interfaces'; import { storeKey, subscriptionsKey, stateKey, actionIdentifier, loaderKey, enablePatchesKey, containerKey, identifierKey, modulesKey, nameKey, } from '../constants'; import { getStageName, perform, getComposeEnhancers } from '../utils'; import { handlePlugin } from './handlePlugin'; import { getStagedState } from '../decorators'; // TODO: refactor export function createStore<T = any>( modules: ModuleOptions[], container: Container, ServiceIdentifiers: ServiceIdentifiersMap, loadedModules: Set<any>, load: (...args: Parameters<Loader>) => void, pluginHooks: PluginHooks, // optional preloadedState?: PreloadedState<T>, devOptions: DevOptions = {}, originalStore?: ReactantStore, beforeReplaceReducer?: () => void, modulesMap: ModulesMap = {} ): ReactantStore { let isExistReducer = false; let store: ReactantStore | undefined = originalStore; let reducers: ReducersMapObject = {}; const subscriptions: Subscriptions = []; const enableAutoFreeze = devOptions.autoFreeze ?? __DEV__; const enableReduxDevTools = devOptions.reduxDevTools ?? __DEV__; const enablePatches = devOptions.enablePatches ?? false; if (typeof store === 'undefined') { setAutoFreeze(enableAutoFreeze); if (enablePatches) { enablePatchesWithImmer(); } } // add Non-dependent `modules` to ServiceIdentifiers config. for (const module of modules) { const moduleIdentifier = typeof module === 'function' ? module : module.provide; if (!ServiceIdentifiers.has(moduleIdentifier)) { ServiceIdentifiers.set(moduleIdentifier, []); } } for (const [Service] of ServiceIdentifiers) { // `Service` should be bound before `createStore`. if (container.isBound(Service) && !loadedModules.has(Service)) { const services: IService[] = container.getAll(Service); loadedModules.add(Service); services.forEach((service, index) => { if (typeof service !== 'object' || service === null) { return; } handlePlugin(service, pluginHooks); const isPlainObject = toString.call(service[stateKey]) === '[object Object]'; const className = (Service as Function).name; let identifier: string | undefined = service[nameKey]; // The `options.name` property of the decorator `@injectable(options)` parameter must be specified as a string, otherwise a staged string will be generated. // this solution replaces the `combineReducers` need `Object.keys` get keys without `symbol` keys. identifier ??= getStageName(className); if (typeof identifier !== 'string') { if (__DEV__) { console.error(` Since '${className}' module has set the module state, '${className}' module must set a unique and valid class property 'nameKey' to be used as the module index. Example: @injectable({ name: 'fooBar' }) // <- add identifier for modules. class FooBar {} `); } else { throw new Error( `'${className}' module 'options.name' property in '@injectable(options)' should be defined as a valid 'string'.` ); } } if (services.length > 1) { // injection about multi-instances identifier += `:${index}`; } if (modulesMap[identifier]) { throw new Error( `'${className}' module name '${identifier}' property and other module conflicts.` ); } Object.assign(modulesMap, { [identifier]: service, }); if (isPlainObject) { const isEmptyObject = Object.keys(service[stateKey]!).length === 0; if (!isEmptyObject) { const descriptors: Record<string, PropertyDescriptor> = {}; for (const key in service[stateKey]) { const descriptor = Object.getOwnPropertyDescriptor(service, key); // eslint-disable-next-line no-continue if (typeof descriptor === 'undefined') continue; Object.assign(service[stateKey], { [key]: descriptor.value, }); descriptors[key] = { enumerable: true, configurable: false, get(this: ThisService) { return this[stateKey]![key]; }, set(this: ThisService, value: unknown) { this[stateKey]![key] = value; }, }; } const initState = enableAutoFreeze ? produce({ ...service[stateKey] }, () => {}) // freeze init state : service[stateKey]!; const serviceReducers = Object.keys(initState).reduce( (serviceReducersMapObject: ReducersMapObject, key) => { const value = initState[key]; // support pure reducer if (typeof value === 'function') { const pureReducer: Reducer = value; const _initState = pureReducer(undefined, {} as AnyAction); const reducer = ( state = _initState, action: ReactantAction ) => { return action._reactant === actionIdentifier && action.state[identifier!] ? action.state[identifier!][key] : pureReducer(state, action); }; return Object.assign(serviceReducersMapObject, { [key]: reducer, }); } const reducer = (state = value, action: ReactantAction) => { return action._reactant === actionIdentifier && action.state[identifier!] ? action.state[identifier!][key] : state; }; return Object.assign(serviceReducersMapObject, { [key]: reducer, }); }, {} ); isExistReducer = true; const reducer = combineReducers(serviceReducers); Object.assign(reducers, { [identifier]: reducer, }); Object.defineProperties(service, descriptors); // redefine get service state from store state. Object.defineProperties(service, { [stateKey]: { enumerable: false, configurable: false, get() { const stagedState = getStagedState(); if (stagedState) return stagedState[identifier!]; const currentState = store!.getState()[identifier!]; if (enableAutoFreeze && !Object.isFrozen(currentState)) { return Object.freeze(currentState); } return currentState; }, }, }); } else { throw new Error(` '${className}' class property 'state' must have at least one state key. `); } } if (Array.isArray(service[subscriptionsKey])) { subscriptions.push(...service[subscriptionsKey]!); } Object.defineProperties(service, { [modulesKey]: { enumerable: false, configurable: false, writable: false, value: modulesMap, }, [identifierKey]: { enumerable: false, configurable: false, writable: false, value: identifier, }, // in order to support multiple instances for stores. [storeKey]: { enumerable: false, configurable: false, get() { return store; }, }, [containerKey]: { enumerable: false, configurable: false, get() { return container; }, }, // loader for dynamic modules. [loaderKey]: { enumerable: false, configurable: false, value(...args: Parameters<Loader>) { load(...args); }, }, // enablePatches options for immer [enablePatchesKey]: { enumerable: false, configurable: false, value: enablePatches, }, }); }); } } if (typeof store === 'undefined') { // load reducers and create store for Redux const reducer = isExistReducer ? combineReducers( (reducers = perform(pluginHooks.beforeCombineRootReducers, reducers)) ) : () => null; const composeEnhancers = getComposeEnhancers( enableReduxDevTools, devOptions.reduxDevToolsOptions ); store = createStoreWithRedux( perform(pluginHooks.afterCombineRootReducers, reducer), perform( pluginHooks.preloadedStateHandler, preloadedState ? Object.entries(preloadedState).reduce<Record<string, any>>( (state, [key, value]) => modulesMap[key] ? Object.assign(state, { [key]: value, }) : state, {} ) : preloadedState ), composeEnhancers( applyMiddleware(...pluginHooks.middleware), ...pluginHooks.enhancer ) ); if (isExistReducer) { Object.assign(store, { reducers, }); } perform(pluginHooks.afterCreateStore, store); } else if (isExistReducer) { // just load reducers store.reducers = { ...store.reducers, ...perform(pluginHooks.beforeCombineRootReducers, reducers), }; const reducer = combineReducers(store.reducers!); const rootReducer = perform(pluginHooks.afterCombineRootReducers, reducer); if (typeof beforeReplaceReducer === 'function') { beforeReplaceReducer(); } store.replaceReducer(rootReducer); } else if (typeof beforeReplaceReducer === 'function') { // TODO: refactor hook beforeReplaceReducer(); } perform(subscriptions); return store; }
the_stack
import { MarketType, MAX_TRADE_GAS_PERCENTAGE_DIVISOR, } from '@augurproject/sdk-lite'; import { BigNumber } from 'bignumber.js'; import * as _ from 'lodash'; import { Augur } from '../Augur'; import { QUINTILLION } from '../utils'; export interface Order { price: string; amount: string; } export interface OutcomeOrderBook { bids: Order[]; asks: Order[]; } export interface OrderBook { [outcome: number]: OutcomeOrderBook; } interface BidsAsksLiquidity { bids: BigNumber; asks: BigNumber; } interface HorizontalLiquidity { total: BigNumber; [outcome: number]: BidsAsksLiquidity; } interface LeftRightLiquidity { left: BigNumber; right: BigNumber; } interface VerticalLiquidity extends LeftRightLiquidity { [outcome: number]: LeftRightLiquidity; } export interface GetLiquidityParams { orderBook: OrderBook; numTicks: BigNumber; marketType: MarketType; reportingFeeDivisor: BigNumber; feePerCashInAttoCash: BigNumber; numOutcomes: number; spread?: number; estimatedTradeGasCostInAttoDai: BigNumber; } // Helpers const sortBids = collection => { return collection .sort((a, b) => { return ( new BigNumber(a.price).minus(new BigNumber(b.price)).toNumber() || new BigNumber(a.amount).minus(new BigNumber(b.amount)).toNumber() ); }) .reverse(); }; const sortAsks = collection => { return collection.sort((a, b) => { return ( new BigNumber(a.price).minus(new BigNumber(b.price)).toNumber() || new BigNumber(b.amount).minus(new BigNumber(a.amount)).toNumber() ); }); }; export class Liquidity { private readonly augur: Augur; constructor(augur: Augur) { this.augur = augur; } async getLiquidityForSpread(params: GetLiquidityParams): Promise<BigNumber> { const marketFee = new BigNumber(params.feePerCashInAttoCash).dividedBy( QUINTILLION ); const gasPrice = (await this.augur.getGasPrice()).div(10**9); // if gasPrice greater than 15gwei use 5% value, less than 15gwei use 3% value const gasCostMultiplier = gasPrice.gte(15) ? 5 : 3; const feeMultiplier = new BigNumber(1) .minus(new BigNumber(1).div(params.reportingFeeDivisor)) .minus(marketFee); // filter out orders based on current gas trade cost Object.keys(params.orderBook).map(outcomeId => { Object.keys(params.orderBook[outcomeId]).forEach(orderType => { // Cut out orders where gas costs > max gasCost multiplier of the trade params.orderBook[outcomeId][orderType] = _.filter(params.orderBook[outcomeId][orderType], (order) => { const gasCost = new BigNumber(order.amount).multipliedBy(params.numTicks).div(MAX_TRADE_GAS_PERCENTAGE_DIVISOR); const maxGasCost = gasCost.multipliedBy(gasCostMultiplier); return maxGasCost.gte(params.estimatedTradeGasCostInAttoDai); } ); }); }); const horizontalLiquidity = this.getHorizontalLiquidity( params.orderBook, params.numTicks, feeMultiplier, params.numOutcomes, params.spread ); const verticalLiquidity = this.getVerticalLiquidity( params.orderBook, params.numTicks, params.marketType, feeMultiplier, params.numOutcomes, params.spread ); let left_overlap = new BigNumber(0); let right_overlap = new BigNumber(0); for (let outcome = 1; outcome < params.numOutcomes; outcome++) { const left = verticalLiquidity[outcome] === undefined ? new BigNumber(0) : verticalLiquidity[outcome].left; const right = verticalLiquidity[outcome] === undefined ? new BigNumber(0) : verticalLiquidity[outcome].right; left_overlap = left_overlap.plus( BigNumber.min(left, horizontalLiquidity[outcome].bids) ); right_overlap = right_overlap.plus( BigNumber.min(right, horizontalLiquidity[outcome].asks) ); } return verticalLiquidity.left .plus(horizontalLiquidity.total) .plus(verticalLiquidity.right) .minus(left_overlap) .minus(right_overlap); } getHorizontalLiquidity( orderBook: OrderBook, numTicks: BigNumber, feeMultiplier: BigNumber, numOutcomes: number, spread: number ): HorizontalLiquidity { const horizontalLiquidity: HorizontalLiquidity = { total: new BigNumber(0), }; for (let outcome = 1; outcome < numOutcomes; outcome++) { horizontalLiquidity[outcome] = { bids: new BigNumber(0), asks: new BigNumber(0), }; if ( !orderBook[outcome] || orderBook[outcome].bids.length < 1 || orderBook[outcome].asks.length < 1 ) continue; let best_bid = new BigNumber(orderBook[outcome].bids[0].price); let best_ask = new BigNumber(orderBook[outcome].asks[0].price); best_bid = best_bid.multipliedBy(feeMultiplier); best_ask = best_ask.dividedBy(feeMultiplier); const midpoint_price = best_bid.plus(best_ask).div(2); const ask_price = midpoint_price.plus( numTicks .div(2) .multipliedBy(spread) .div(100) ); const bid_price = midpoint_price.minus( numTicks .div(2) .multipliedBy(spread) .div(100) ); let bid_quantities = new BigNumber(0); let ask_quantities = new BigNumber(0); const bidOrders = _.takeWhile(orderBook[outcome].bids, order => bid_price.lte(order.price) ); const askOrders = _.takeWhile(orderBook[outcome].asks, order => ask_price.gte(order.price) ); // Sort bids by Price, Amount and group by orderCreator const sortedBidOrders = _.groupBy(sortBids(bidOrders), 'orderCreator'); // Sort asks by Price, Amount and group by orderCreator const sortedAskOrders = _.groupBy(sortAsks(askOrders), 'orderCreator'); let bidOrdersTopThree = []; let askOrdersTopThree = []; // Only count for the liquidity sorts/filters up to 3 orders per side of the book per outcome per user per market Object.keys(sortedBidOrders).forEach(ordersByUser => { bidOrdersTopThree = bidOrdersTopThree.concat( sortedBidOrders[ordersByUser].slice(0, 3) ); }); Object.keys(sortedAskOrders).forEach(ordersByUser => { askOrdersTopThree = askOrdersTopThree.concat( sortedAskOrders[ordersByUser].slice(0, 3) ); }); // for bids we get orders from the midpoint down to and inclusive of the bid price. For asks we get the orders from the midpoint *up to* inclusive of the ask price. for (const order of bidOrdersTopThree) bid_quantities = bid_quantities.plus(order.amount); for (const order of askOrdersTopThree) ask_quantities = ask_quantities.plus(order.amount); const num_shares = BigNumber.max(bid_quantities, ask_quantities); let raw_bid_value = new BigNumber(0); let raw_ask_value = new BigNumber(0); // the getters return a dictionary of orders w/ quantity and price let bid_quantity_gotten = new BigNumber(0); let ask_quantity_gotten = new BigNumber(0); if (num_shares.gt(0)) { for (const order of bidOrdersTopThree) { let quantityToTake = new BigNumber(order.amount); if (bid_quantity_gotten.plus(quantityToTake).gt(num_shares)) quantityToTake = num_shares.minus(bid_quantity_gotten); if (bid_quantity_gotten.gte(num_shares)) break; raw_bid_value = raw_bid_value.plus( quantityToTake.multipliedBy(order.price) ); bid_quantity_gotten = bid_quantity_gotten.plus(quantityToTake); } for (const order of askOrdersTopThree) { let quantityToTake = new BigNumber(order.amount); if (ask_quantity_gotten.plus(quantityToTake).gt(num_shares)) quantityToTake = num_shares.minus(ask_quantity_gotten); if (ask_quantity_gotten.gte(num_shares)) break; raw_ask_value = raw_ask_value.plus( quantityToTake.multipliedBy(numTicks.minus(order.price)) ); ask_quantity_gotten = ask_quantity_gotten.plus(quantityToTake); } horizontalLiquidity[outcome].bids = raw_bid_value; horizontalLiquidity[outcome].asks = raw_ask_value; horizontalLiquidity.total = horizontalLiquidity.total .plus(raw_bid_value) .plus(raw_ask_value); } } return horizontalLiquidity; } getVerticalLiquidity( orderBook: OrderBook, numTicks: BigNumber, marketType: MarketType, feeMultiplier: BigNumber, numOutcomes: number, spread: number ): VerticalLiquidity { const vertical_liquidity = { left: new BigNumber(0), right: new BigNumber(0), }; const bid_quantities = {}; const ask_quantities = {}; const bid_prices = {}; const ask_prices = {}; let bid_sum = new BigNumber(0); let ask_sum = new BigNumber(0); if ([MarketType.YesNo, MarketType.Categorical].includes(marketType)) { for (let outcome = 1; outcome < numOutcomes; outcome++) { vertical_liquidity[outcome] = { left: new BigNumber(0), right: new BigNumber(0), }; } const orderBookByCreator = {}; const orderBookSliced: OrderBook = {}; // Sort bids/asks by Price, Amount and group by orderCreator Object.keys(orderBook).forEach(outcome => { orderBookByCreator[outcome] = { bids: _.groupBy(sortBids(orderBook[outcome].bids), 'orderCreator'), asks: _.groupBy(sortAsks(orderBook[outcome].asks), 'orderCreator'), }; }); // Only count for the liquidity sorts/filters up to 3 orders per side of the book per outcome per user per market Object.keys(orderBookByCreator).forEach(outcome => { orderBookSliced[outcome] = { bids: [], asks: [] }; const bids = orderBookByCreator[outcome].bids; const bidsByUser = Object.keys(bids); bidsByUser.forEach(bid => { const slicedBids = bids[bid].slice(0, 3); orderBookSliced[outcome].bids = orderBookSliced[outcome].bids.concat( slicedBids ); }); const asks = orderBookByCreator[outcome].asks; const asksByUser = Object.keys(asks); asksByUser.forEach(ask => { const slicedAsks = asks[ask].slice(0, 3); orderBookSliced[outcome].asks = orderBookSliced[outcome].asks.concat( slicedAsks ); }); }); // BIDS (`outcome` starts at 1 because the Invalid outcome is 0 and is not included in liquidity calculations) for (let outcome = 1; outcome < numOutcomes; outcome++) { if ( !orderBookSliced[outcome] || orderBookSliced[outcome].bids.length < 1 ) { bid_sum = new BigNumber(0); break; } const best_bid = orderBookSliced[outcome].bids[0]; bid_prices[outcome] = feeMultiplier.multipliedBy(best_bid.price); bid_sum = bid_sum.plus(bid_prices[outcome]); } let excess_spread = bid_sum.minus( numTicks.multipliedBy(100 - spread).div(100) ); // if liquidity > the spread % even at best bids or there is no best bid we dont calulate anything if (excess_spread.gt(0) && !bid_sum.isZero()) { for (let outcome = 1; outcome < numOutcomes; outcome++) { bid_prices[outcome] = bid_prices[outcome].minus( excess_spread.div(numOutcomes - 1) ); const bidOrders = _.takeWhile(orderBookSliced[outcome].bids, order => bid_prices[outcome].lte(order.price) ); if (bid_quantities[outcome] === undefined) bid_quantities[outcome] = new BigNumber(0); for (const order of bidOrders) bid_quantities[outcome] = bid_quantities[outcome].plus( order.amount ); } const num_shares = BigNumber.min.apply(null, _.values(bid_quantities)); for (let outcome = 1; outcome < numOutcomes; outcome++) { let raw_bid_value = new BigNumber(0); let bid_quantity_gotten = new BigNumber(0); const bidOrders = _.takeWhile(orderBookSliced[outcome].bids, order => bid_prices[outcome].lte(order.price) ); for (const order of bidOrders) { let quantityToTake = new BigNumber(order.amount); if (bid_quantity_gotten.plus(quantityToTake).gt(num_shares)) quantityToTake = num_shares.minus(bid_quantity_gotten); if (bid_quantity_gotten.gte(num_shares)) break; raw_bid_value = raw_bid_value.plus( quantityToTake.multipliedBy(order.price) ); bid_quantity_gotten = bid_quantity_gotten.plus(quantityToTake); } vertical_liquidity[outcome].left = raw_bid_value; vertical_liquidity.left = vertical_liquidity.left.plus(raw_bid_value); } } // ASKS (`outcome` starts at 1 because the Invalid outcome is 0 and is not included in liquidity calculations) for (let outcome = 1; outcome < numOutcomes; outcome++) { if ( !orderBookSliced[outcome] || orderBookSliced[outcome].asks.length < 1 ) { ask_sum = new BigNumber(0); break; } const best_ask = orderBookSliced[outcome].asks[0]; ask_prices[outcome] = new BigNumber(best_ask.price).div(feeMultiplier); ask_sum = ask_sum.plus(ask_prices[outcome]); } excess_spread = ask_sum.minus( numTicks.multipliedBy(100 - spread).div(100) ); // if liquidity > the spread % even at best asks or there is no best ask we dont calulate anything if (excess_spread.gt(0) && !ask_sum.isZero()) { for (let outcome = 1; outcome < numOutcomes; outcome++) { ask_prices[outcome] = ask_prices[outcome].plus( excess_spread.div(numOutcomes - 1) ); const askOrders = _.takeWhile(orderBookSliced[outcome].asks, order => ask_prices[outcome].gte(order.price) ); if (ask_quantities[outcome] === undefined) ask_quantities[outcome] = new BigNumber(0); for (const order of askOrders) ask_quantities[outcome] = ask_quantities[outcome].plus( order.amount ); } const num_shares = BigNumber.min.apply(null, _.values(ask_quantities)); for (let outcome = 1; outcome < numOutcomes; outcome++) { let raw_ask_value = new BigNumber(0); let ask_quantity_gotten = new BigNumber(0); const askOrders = _.takeWhile(orderBookSliced[outcome].asks, order => ask_prices[outcome].gte(order.price) ); for (const order of askOrders) { let quantityToTake = new BigNumber(order.amount); if (ask_quantity_gotten.plus(quantityToTake).gt(num_shares)) quantityToTake = num_shares.minus(ask_quantity_gotten); if (ask_quantity_gotten.gte(num_shares)) break; raw_ask_value = raw_ask_value.plus( quantityToTake.multipliedBy(numTicks.minus(order.price)) ); ask_quantity_gotten = ask_quantity_gotten.plus(quantityToTake); } vertical_liquidity[outcome].right = raw_ask_value; vertical_liquidity.right = vertical_liquidity.right.plus( raw_ask_value ); } } } return vertical_liquidity; } }
the_stack
import { createFacet, Facet } from '@react-facet/core' import React, { ReactElement, useEffect, useState } from 'react' import { Fiber } from 'react-reconciler' import { createFiberRoot } from './createFiberRoot' import { createReconciler } from './createReconciler' import { setupHostConfig } from './setupHostConfig' import { InputType, ElementContainer, ElementProps, Props } from './types' document.body.innerHTML = `<div id="root"></div>` const reconcilerInstance = createReconciler() const root = document.getElementById('root') as HTMLElement const fiberRoot = createFiberRoot(reconcilerInstance)(root) /** * Render function local to testing that shared the same instance of the reconciler. * * This is needed otherwise React complains that we are sharing a context across different renderers. */ const render = function render(ui: ReactElement) { reconcilerInstance.updateContainer(ui, fiberRoot, null, () => {}) } afterEach(() => { reconcilerInstance.updateContainer(null, fiberRoot, null, () => {}) }) jest.useFakeTimers() describe('mount', () => { describe('without facet', () => { it('renders text', () => { render(<div>Hello World</div>) expect(root).toContainHTML('<div id="root"><div>Hello World</div></div>') }) it('sets the className', () => { render(<div className="testing">Hello World</div>) expect(root).toContainHTML('<div id="root"><div class="testing">Hello World</div></div>') }) it('sets the id', () => { render(<div id="testing">Hello World</div>) expect(root).toContainHTML('<div id="root"><div id="testing">Hello World</div></div>') }) it('sets the style', () => { render(<div style={{ background: 'red' }}>Hello World</div>) expect(root).toContainHTML('<div id="root"><div style="background: red;">Hello World</div></div>') }) it('sets the src', () => { render(<img className="image" src="bananafrita.png" />) const img = document.getElementsByClassName('image')[0] as HTMLImageElement | undefined // jsdom is adding the http://localhost expect(img && img.src).toEqual('http://localhost/bananafrita.png') }) it('sets the value', () => { render(<input value="foo" />) expect(root?.innerHTML ?? '').toBe('<input value="foo">') }) it('sets the type', () => { render( <> <input type="text" /> <input type="password" /> <input type="button" /> </>, ) expect(root?.innerHTML ?? '').toBe('<input type="text"><input type="password"><input type="button">') }) it('sets disabled', () => { render(<input disabled />) expect(root?.innerHTML ?? '').toBe('<input disabled="">') }) it('sets maxlength', () => { render(<input type="text" maxLength={10} />) expect(root?.innerHTML ?? '').toBe('<input maxlength="10" type="text">') }) it('sets the data-droppable', () => { render(<div data-droppable />) expect(root?.innerHTML ?? '').toBe('<div data-droppable=""></div>') }) it('sets the href and target', () => { render(<a href="url" target="__blank"></a>) expect(root?.innerHTML ?? '').toBe('<a href="url" target="__blank"></a>') }) it('sets dangerouslySetInnerHTML', () => { render(<div dangerouslySetInnerHTML={{ __html: '<span/>' }} />) expect(root?.innerHTML ?? '').toBe('<div><span></span></div>') }) }) describe('with facets', () => { it('renders text', () => { const textFacet = createFacet({ initialValue: 'Hello World' }) render(<fast-text text={textFacet} />) expect(root).toContainHTML('<div id="root">Hello World</div>') textFacet.set('Updated World') expect(root).toContainHTML('<div id="root">Updated World</div>') }) it('sets the className', () => { const classNameFacet = createFacet({ initialValue: 'testing' }) render(<fast-div className={classNameFacet}>Hello World</fast-div>) expect(root).toContainHTML('<div id="root"><div class="testing">Hello World</div></div>') classNameFacet.set('updated testing') expect(root).toContainHTML('<div id="root"><div class="updated testing">Hello World</div></div>') }) it('sets the id', () => { const idFacet = createFacet({ initialValue: 'testing' }) render(<fast-div id={idFacet}>Hello World</fast-div>) expect(root).toContainHTML('<div id="root"><div id="testing">Hello World</div></div>') idFacet.set('updated testing') expect(root).toContainHTML('<div id="root"><div id="updated testing">Hello World</div></div>') }) it('sets the style', () => { const backgroundFacet = createFacet({ initialValue: 'red' }) render(<fast-div style={{ background: backgroundFacet }}>Hello World</fast-div>) expect(root).toContainHTML('<div id="root"><div style="background: red;">Hello World</div></div>') backgroundFacet.set('yellow') expect(root).toContainHTML('<div id="root"><div style="background: yellow;">Hello World</div></div>') }) it('sets the src', () => { const srcFacet = createFacet({ initialValue: 'bananafrita.png' }) render(<fast-img className="image" src={srcFacet} />) const img = document.getElementsByClassName('image')[0] as HTMLImageElement | undefined // jsdom is adding the http://localhost expect(img && img.src).toEqual('http://localhost/bananafrita.png') srcFacet.set('updated.png') expect(img && img.src).toEqual('http://localhost/updated.png') }) it('sets the value', () => { const valueFacet = createFacet({ initialValue: 'foo' }) render(<fast-input value={valueFacet} />) expect(root?.innerHTML ?? '').toBe('<input value="foo">') valueFacet.set('updated') expect(root?.innerHTML ?? '').toBe('<input value="updated">') }) it('sets the type', () => { const textFacet = createFacet<InputType>({ initialValue: 'text' }) const passwordFacet = createFacet<InputType>({ initialValue: 'password' }) const buttonFacet = createFacet<InputType>({ initialValue: 'button' }) const radioFacet = createFacet<InputType>({ initialValue: 'radio' }) const checkboxFacet = createFacet<InputType>({ initialValue: 'checkbox' }) render( <> <fast-input type={textFacet} /> <fast-input type={passwordFacet} /> <fast-input type={buttonFacet} /> <fast-input type={radioFacet} /> <fast-input type={checkboxFacet} /> </>, ) expect(root?.innerHTML ?? '').toBe( '<input type="text"><input type="password"><input type="button"><input type="radio"><input type="checkbox">', ) textFacet.set('checkbox') expect(root?.innerHTML ?? '').toBe( '<input type="checkbox"><input type="password"><input type="button"><input type="radio"><input type="checkbox">', ) }) it('sets disabled', () => { const disabledFacet = createFacet({ initialValue: true }) render(<fast-input disabled={disabledFacet} />) expect(root?.innerHTML ?? '').toBe('<input disabled="">') disabledFacet.set(false) expect(root?.innerHTML ?? '').toBe('<input>') }) it('sets maxlength', () => { const maxLengthFacet = createFacet({ initialValue: 10 }) render(<fast-input type="text" maxLength={maxLengthFacet} />) expect(root?.innerHTML ?? '').toBe('<input maxlength="10" type="text">') maxLengthFacet.set(20) expect(root?.innerHTML ?? '').toBe('<input maxlength="20" type="text">') }) it('sets rows', () => { const rowsFacet = createFacet({ initialValue: 10 }) render(<fast-textarea type="text" rows={rowsFacet} />) expect(root?.innerHTML ?? '').toBe('<textarea rows="10" type="text"></textarea>') rowsFacet.set(20) expect(root?.innerHTML ?? '').toBe('<textarea rows="20" type="text"></textarea>') }) it('sets the data-droppable', () => { const dataDroppableFacet = createFacet({ initialValue: true }) render(<fast-div data-droppable={dataDroppableFacet} />) expect(root?.innerHTML ?? '').toBe('<div data-droppable=""></div>') dataDroppableFacet.set(false) expect(root?.innerHTML ?? '').toBe('<div></div>') }) it('sets the data-testid', () => { const dataFacet = createFacet({ initialValue: 'test-id' }) render(<fast-div data-testid={dataFacet} />) expect(root?.innerHTML ?? '').toBe('<div data-testid="test-id"></div>') dataFacet.set('updated-test-id') expect(root?.innerHTML ?? '').toBe('<div data-testid="updated-test-id"></div>') }) it('sets the data-x-ray', () => { const dataFacet = createFacet({ initialValue: true }) render(<fast-div data-x-ray={dataFacet} />) expect(root?.innerHTML ?? '').toBe('<div data-x-ray=""></div>') dataFacet.set(false) expect(root?.innerHTML ?? '').toBe('<div></div>') }) it('sets the href and target', () => { const hrefFacet = createFacet({ initialValue: 'url' }) const targetFacet = createFacet({ initialValue: '_blank' }) render(<fast-a href={hrefFacet} target={targetFacet}></fast-a>) expect(root?.innerHTML ?? '').toBe('<a href="url" target="_blank"></a>') hrefFacet.set('updated') targetFacet.set('_top') expect(root?.innerHTML ?? '').toBe('<a href="updated" target="_top"></a>') }) it('sets the autoPlay', () => { const dataFacet = createFacet({ initialValue: true }) render(<fast-div autoPlay={dataFacet} />) expect(root?.innerHTML ?? '').toBe('<div autoplay=""></div>') dataFacet.set(false) expect(root?.innerHTML ?? '').toBe('<div></div>') }) it('sets the loop', () => { const dataFacet = createFacet({ initialValue: true }) render(<fast-div loop={dataFacet} />) expect(root?.innerHTML ?? '').toBe('<div loop=""></div>') dataFacet.set(false) expect(root?.innerHTML ?? '').toBe('<div></div>') }) }) describe('setting listeners', () => { let onClick: jest.Mock let onFocus: jest.Mock let onBlur: jest.Mock let onMouseDown: jest.Mock let onMouseUp: jest.Mock let onTouchStart: jest.Mock let onTouchMove: jest.Mock let onTouchEnd: jest.Mock let onMouseEnter: jest.Mock let onMouseLeave: jest.Mock let onKeyPress: jest.Mock let onKeyDown: jest.Mock let onKeyUp: jest.Mock let div: Element beforeEach(() => { onClick = jest.fn() onFocus = jest.fn() onBlur = jest.fn() onMouseDown = jest.fn() onMouseUp = jest.fn() onTouchStart = jest.fn() onTouchMove = jest.fn() onTouchEnd = jest.fn() onMouseEnter = jest.fn() onMouseLeave = jest.fn() onKeyPress = jest.fn() onKeyDown = jest.fn() onKeyUp = jest.fn() render( <div className="testing" onClick={onClick} onFocus={onFocus} onBlur={onBlur} onMouseDown={onMouseDown} onMouseUp={onMouseUp} onTouchStart={onTouchStart} onTouchMove={onTouchMove} onTouchEnd={onTouchEnd} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} onKeyPress={onKeyPress} onKeyDown={onKeyDown} onKeyUp={onKeyUp} > Hello World </div>, ) div = document.getElementsByClassName('testing')[0] if (div == null) throw new Error('Root element not found') }) it('supports onClick', () => { div.dispatchEvent(new Event('click')) expect(onClick).toHaveBeenCalled() }) it('supports onFocus', () => { div.dispatchEvent(new Event('focus')) expect(onFocus).toHaveBeenCalled() }) it('supports onBlur', () => { div.dispatchEvent(new Event('blur')) expect(onBlur).toHaveBeenCalled() }) it('supports onMouseDown', () => { div.dispatchEvent(new Event('mousedown')) expect(onMouseDown).toHaveBeenCalled() }) it('supports onMouseUp', () => { div.dispatchEvent(new Event('mouseup')) expect(onMouseUp).toHaveBeenCalled() }) it('supports onTouchStart', () => { div.dispatchEvent(new Event('touchstart')) expect(onTouchStart).toHaveBeenCalled() }) it('supports onTouchMove', () => { div.dispatchEvent(new Event('touchmove')) expect(onTouchMove).toHaveBeenCalled() }) it('supports onTouchEnd', () => { div.dispatchEvent(new Event('touchend')) expect(onTouchEnd).toHaveBeenCalled() }) it('supports onMouseEnter', () => { div.dispatchEvent(new Event('mouseenter')) expect(onMouseEnter).toHaveBeenCalled() }) it('supports onMouseLeave', () => { div.dispatchEvent(new Event('mouseleave')) expect(onMouseLeave).toHaveBeenCalled() }) it('supports onKeyPress', () => { div.dispatchEvent(new Event('keypress')) expect(onKeyPress).toHaveBeenCalled() }) it('supports onKeyDown', () => { div.dispatchEvent(new Event('keydown')) expect(onKeyDown).toHaveBeenCalled() }) it('supports onKeyUp', () => { div.dispatchEvent(new Event('keyup')) expect(onKeyUp).toHaveBeenCalled() }) }) }) describe('update', () => { it('updates text', () => { function TestComponent() { const [hello, setHello] = useState(false) useEffect(() => { setTimeout(() => { setHello(true) }, 1000) }, []) return <div>{hello ? 'Hello' : 'Goodbye'} World</div> } render(<TestComponent />) expect(root).toContainHTML('<div id="root"><div>Goodbye World</div></div>') jest.runAllTimers() expect(root).toContainHTML('<div id="root"><div>Hello World</div></div>') }) it('updates className', () => { function TestComponent() { const [hello, setHello] = useState(false) useEffect(() => { setTimeout(() => { setHello(true) }, 1000) }, []) return <div className={hello ? 'hello' : 'goodbye'}>Hello World</div> } render(<TestComponent />) expect(root).toContainHTML('<div id="root"><div class="goodbye">Hello World</div></div>') jest.runAllTimers() expect(root).toContainHTML('<div id="root"><div class="hello">Hello World</div></div>') }) it('updates id', () => { function TestComponent() { const [hello, setHello] = useState(false) useEffect(() => { setTimeout(() => { setHello(true) }, 1000) }, []) return <div id={hello ? 'hello' : 'goodbye'}>Hello World</div> } render(<TestComponent />) expect(root).toContainHTML('<div id="root"><div id="goodbye">Hello World</div></div>') jest.runAllTimers() expect(root).toContainHTML('<div id="root"><div id="hello">Hello World</div></div>') }) it('updates style', () => { function TestComponent() { const [hello, setHello] = useState(false) useEffect(() => { setTimeout(() => { setHello(true) }, 1000) }, []) return <div style={hello ? { background: 'red' } : { background: 'yellow' }}>Hello World</div> } render(<TestComponent />) expect(root).toContainHTML('<div id="root"><div style="background: yellow;">Hello World</div></div>') jest.runAllTimers() expect(root).toContainHTML('<div id="root"><div style="background: red;">Hello World</div></div>') }) it('updates src', () => { function TestComponent() { const [src, setSrc] = useState(false) useEffect(() => { setTimeout(() => { setSrc(true) }, 1000) }, []) return <img className="image" src={src ? 'banana.png' : 'frita.png'} /> } render(<TestComponent />) let img = document.getElementsByClassName('image')[0] as HTMLImageElement | undefined // jsdom is adding the http://localhost expect(img && img.src).toEqual('http://localhost/frita.png') jest.runAllTimers() img = document.getElementsByClassName('image')[0] as HTMLImageElement | undefined // jsdom is adding the http://localhost expect(img && img.src).toEqual('http://localhost/banana.png') }) it('updates href', () => { function TestComponent() { const [href, setHref] = useState(false) useEffect(() => { setTimeout(() => { setHref(true) }, 1000) }, []) return <a href={href ? 'new' : 'old'} /> } render(<TestComponent />) expect(root?.innerHTML ?? '').toBe('<a href="old"></a>') jest.runAllTimers() expect(root?.innerHTML ?? '').toBe('<a href="new"></a>') }) it('updates target', () => { function TestComponent() { const [target, setTarget] = useState(false) useEffect(() => { setTimeout(() => { setTarget(true) }, 1000) }, []) return <a target={target ? 'new' : 'old'} /> } render(<TestComponent />) expect(root?.innerHTML ?? '').toBe('<a target="old"></a>') jest.runAllTimers() expect(root?.innerHTML ?? '').toBe('<a target="new"></a>') }) it('updates the value', () => { const MockComponent = () => { const [data, setData] = useState<string | undefined>('foo') useEffect(() => { setTimeout(() => setData('bar'), 1) setTimeout(() => setData(undefined), 2) }, []) return <input value={data} /> } render(<MockComponent />) expect(root?.innerHTML ?? '').toBe('<input value="foo">') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<input value="bar">') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<input>') }) it('updates the type', () => { const MockComponent = () => { const [types, setTypes] = useState<(InputType | undefined)[]>(['text', 'password', 'button']) useEffect(() => { setTimeout(() => setTypes(['button', 'text', 'password']), 1) setTimeout(() => setTypes([undefined, undefined, undefined]), 2) }, []) return ( <> <input type={types[0]} /> <input type={types[1]} /> <input type={types[2]} /> </> ) } render(<MockComponent />) expect(root?.innerHTML ?? '').toBe('<input type="text"><input type="password"><input type="button">') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<input type="button"><input type="text"><input type="password">') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<input><input><input>') }) it('updates disabled', () => { const MockComponent = () => { const [disabled, setDisabled] = useState<boolean | undefined>(true) useEffect(() => { setTimeout(() => setDisabled(false), 1) setTimeout(() => setDisabled(true), 2) setTimeout(() => setDisabled(undefined), 3) }, []) return <input disabled={disabled} /> } render(<MockComponent />) expect(root?.innerHTML ?? '').toBe('<input disabled="">') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<input>') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<input disabled="">') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<input>') }) it('updates maxLength', () => { const MockComponent = () => { const [maxLength, setMaxLength] = useState<number | undefined>(1) useEffect(() => { setTimeout(() => setMaxLength(undefined), 1) setTimeout(() => setMaxLength(2), 2) setTimeout(() => setMaxLength(undefined), 3) }, []) return <input maxLength={maxLength} /> } render(<MockComponent />) expect(root?.innerHTML ?? '').toBe('<input maxlength="1">') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<input>') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<input maxlength="2">') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<input>') }) it('updates data-droppable', () => { const MockComponent = () => { const [droppable, setDroppable] = useState<true | undefined>(true) useEffect(() => { setTimeout(() => setDroppable(undefined), 1) setTimeout(() => setDroppable(true), 2) setTimeout(() => setDroppable(undefined), 3) }, []) return <div data-droppable={droppable} /> } render(<MockComponent />) expect(root?.innerHTML ?? '').toBe('<div data-droppable=""></div>') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<div></div>') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<div data-droppable=""></div>') jest.advanceTimersByTime(1) expect(root?.innerHTML ?? '').toBe('<div></div>') }) describe('setting listeners', () => { let firstOnClick: jest.Mock let firstOnFocus: jest.Mock let firstOnBlur: jest.Mock let firstOnMouseDown: jest.Mock let firstOnMouseUp: jest.Mock let firstOnTouchStart: jest.Mock let firstOnTouchMove: jest.Mock let firstOnTouchEnd: jest.Mock let firstOnMouseEnter: jest.Mock let firstOnMouseLeave: jest.Mock let firstOnKeyPress: jest.Mock let firstOnKeyDown: jest.Mock let firstOnKeyUp: jest.Mock let secondOnClick: jest.Mock let secondOnFocus: jest.Mock let secondOnBlur: jest.Mock let secondOnMouseDown: jest.Mock let secondOnMouseUp: jest.Mock let secondOnTouchStart: jest.Mock let secondOnTouchMove: jest.Mock let secondOnTouchEnd: jest.Mock let secondOnMouseEnter: jest.Mock let secondOnMouseLeave: jest.Mock let secondOnKeyPress: jest.Mock let secondOnKeyDown: jest.Mock let secondOnKeyUp: jest.Mock let div: Element function TestComponent() { const [second, setSecond] = useState(false) useEffect(() => { setTimeout(() => { setSecond(true) }, 1000) }, []) return ( <div className="testing" onClick={second ? secondOnClick : firstOnClick} onFocus={second ? secondOnFocus : firstOnFocus} onBlur={second ? secondOnBlur : firstOnBlur} onMouseDown={second ? secondOnMouseDown : firstOnMouseDown} onMouseUp={second ? secondOnMouseUp : firstOnMouseUp} onTouchStart={second ? secondOnTouchStart : firstOnTouchStart} onTouchMove={second ? secondOnTouchMove : firstOnTouchMove} onTouchEnd={second ? secondOnTouchEnd : firstOnTouchEnd} onMouseEnter={second ? secondOnMouseEnter : firstOnMouseEnter} onMouseLeave={second ? secondOnMouseLeave : firstOnMouseLeave} onKeyPress={second ? secondOnKeyPress : firstOnKeyPress} onKeyDown={second ? secondOnKeyDown : firstOnKeyDown} onKeyUp={second ? secondOnKeyUp : firstOnKeyUp} > Hello World </div> ) } beforeEach(() => { firstOnClick = jest.fn() firstOnFocus = jest.fn() firstOnBlur = jest.fn() firstOnMouseDown = jest.fn() firstOnMouseUp = jest.fn() firstOnTouchStart = jest.fn() firstOnTouchMove = jest.fn() firstOnTouchEnd = jest.fn() firstOnMouseEnter = jest.fn() firstOnMouseLeave = jest.fn() firstOnKeyPress = jest.fn() firstOnKeyDown = jest.fn() firstOnKeyUp = jest.fn() secondOnClick = jest.fn() secondOnFocus = jest.fn() secondOnBlur = jest.fn() secondOnMouseDown = jest.fn() secondOnMouseUp = jest.fn() secondOnTouchStart = jest.fn() secondOnTouchMove = jest.fn() secondOnTouchEnd = jest.fn() secondOnMouseEnter = jest.fn() secondOnMouseLeave = jest.fn() secondOnKeyPress = jest.fn() secondOnKeyDown = jest.fn() secondOnKeyUp = jest.fn() render(<TestComponent />) div = document.getElementsByClassName('testing')[0] if (div == null) throw new Error('Root element not found') }) it('supports onClick', () => { div.dispatchEvent(new Event('click')) expect(firstOnClick).toHaveBeenCalled() expect(secondOnClick).not.toHaveBeenCalled() firstOnClick.mockClear() secondOnClick.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('click')) expect(firstOnClick).not.toHaveBeenCalled() expect(secondOnClick).toHaveBeenCalled() }) it('supports onFocus', () => { div.dispatchEvent(new Event('focus')) expect(firstOnFocus).toHaveBeenCalled() expect(secondOnFocus).not.toHaveBeenCalled() firstOnFocus.mockClear() secondOnFocus.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('focus')) expect(firstOnFocus).not.toHaveBeenCalled() expect(secondOnFocus).toHaveBeenCalled() }) it('supports onBlur', () => { div.dispatchEvent(new Event('blur')) expect(firstOnBlur).toHaveBeenCalled() expect(secondOnBlur).not.toHaveBeenCalled() firstOnBlur.mockClear() secondOnBlur.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('blur')) expect(firstOnBlur).not.toHaveBeenCalled() expect(secondOnBlur).toHaveBeenCalled() }) it('supports onMouseDown', () => { div.dispatchEvent(new Event('mousedown')) expect(firstOnMouseDown).toHaveBeenCalled() expect(secondOnMouseDown).not.toHaveBeenCalled() firstOnMouseDown.mockClear() secondOnMouseDown.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('mousedown')) expect(firstOnMouseDown).not.toHaveBeenCalled() expect(secondOnMouseDown).toHaveBeenCalled() }) it('supports onMouseUp', () => { div.dispatchEvent(new Event('mouseup')) expect(firstOnMouseUp).toHaveBeenCalled() expect(secondOnMouseUp).not.toHaveBeenCalled() firstOnMouseUp.mockClear() secondOnMouseUp.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('mouseup')) expect(firstOnMouseUp).not.toHaveBeenCalled() expect(secondOnMouseUp).toHaveBeenCalled() }) it('supports onTouchStart', () => { div.dispatchEvent(new Event('touchstart')) expect(firstOnTouchStart).toHaveBeenCalled() expect(secondOnTouchStart).not.toHaveBeenCalled() firstOnTouchStart.mockClear() secondOnTouchStart.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('touchstart')) expect(firstOnTouchStart).not.toHaveBeenCalled() expect(secondOnTouchStart).toHaveBeenCalled() }) it('supports onTouchMove', () => { div.dispatchEvent(new Event('touchmove')) expect(firstOnTouchMove).toHaveBeenCalled() expect(secondOnTouchMove).not.toHaveBeenCalled() firstOnTouchMove.mockClear() secondOnTouchMove.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('touchmove')) expect(firstOnTouchMove).not.toHaveBeenCalled() expect(secondOnTouchMove).toHaveBeenCalled() }) it('supports onTouchEnd', () => { div.dispatchEvent(new Event('touchend')) expect(firstOnTouchEnd).toHaveBeenCalled() expect(secondOnTouchEnd).not.toHaveBeenCalled() firstOnTouchEnd.mockClear() secondOnTouchEnd.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('touchend')) expect(firstOnTouchEnd).not.toHaveBeenCalled() expect(secondOnTouchEnd).toHaveBeenCalled() }) it('supports onMouseEnter', () => { div.dispatchEvent(new Event('mouseenter')) expect(firstOnMouseEnter).toHaveBeenCalled() expect(secondOnMouseEnter).not.toHaveBeenCalled() firstOnMouseEnter.mockClear() secondOnMouseEnter.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('mouseenter')) expect(firstOnMouseEnter).not.toHaveBeenCalled() expect(secondOnMouseEnter).toHaveBeenCalled() }) it('supports onMouseLeave', () => { div.dispatchEvent(new Event('mouseleave')) expect(firstOnMouseLeave).toHaveBeenCalled() expect(secondOnMouseLeave).not.toHaveBeenCalled() firstOnMouseLeave.mockClear() secondOnMouseLeave.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('mouseleave')) expect(firstOnMouseLeave).not.toHaveBeenCalled() expect(secondOnMouseLeave).toHaveBeenCalled() }) it('supports onKeyPress', () => { div.dispatchEvent(new Event('keypress')) expect(firstOnKeyPress).toHaveBeenCalled() expect(secondOnKeyPress).not.toHaveBeenCalled() firstOnKeyPress.mockClear() secondOnKeyPress.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('keypress')) expect(firstOnKeyPress).not.toHaveBeenCalled() expect(secondOnKeyPress).toHaveBeenCalled() }) it('supports onKeyDown', () => { div.dispatchEvent(new Event('keydown')) expect(firstOnKeyDown).toHaveBeenCalled() expect(secondOnKeyDown).not.toHaveBeenCalled() firstOnKeyDown.mockClear() secondOnKeyDown.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('keydown')) expect(firstOnKeyDown).not.toHaveBeenCalled() expect(secondOnKeyDown).toHaveBeenCalled() }) it('supports onKeyUp', () => { div.dispatchEvent(new Event('keyup')) expect(firstOnKeyUp).toHaveBeenCalled() expect(secondOnKeyUp).not.toHaveBeenCalled() firstOnKeyUp.mockClear() secondOnKeyUp.mockClear() jest.runAllTimers() div.dispatchEvent(new Event('keyup')) expect(firstOnKeyUp).not.toHaveBeenCalled() expect(secondOnKeyUp).toHaveBeenCalled() }) }) }) describe('umnount', () => { it('unsubscribes from all facets when a element component is unmounted', () => { const unsubscribe = jest.fn() // eslint-disable-next-line @typescript-eslint/no-explicit-any const facet: Facet<any> = { get: () => 'text', observe: jest.fn().mockReturnValue(unsubscribe), } render( <fast-div style={{ background: facet, color: facet }} className={facet} data-droppable={facet} data-testid={facet} data-x-ray={facet} src={facet} href={facet} target={facet} autoPlay={facet} loop={facet} disabled={facet} maxLength={facet} rows={facet} value={facet} type={facet} />, ) // on mount, we verify that we have added 16 subscriptions (one for each prop and style above) expect(facet.observe).toHaveBeenCalledTimes(16) // on unmount, we check that unsubscribe was called once for each subscription render(<></>) expect(unsubscribe).toHaveBeenCalledTimes(16) }) it('unsubscribes from the text facet when a fast-text component is unmounted', () => { const unsubscribe = jest.fn() const facet: Facet<string> = { get: () => 'text', observe: jest.fn().mockReturnValue(unsubscribe), } render(<fast-text text={facet} />) expect(facet.observe).toHaveBeenCalledTimes(1) render(<></>) expect(unsubscribe).toHaveBeenCalledTimes(1) }) it('unsubscribe from facets when the parent of a component is unmounted', () => { const unsubscribe = jest.fn() const facet: Facet<string> = { get: () => 'text', observe: jest.fn().mockReturnValue(unsubscribe), } render( <div> <fast-text text={facet} /> </div>, ) expect(facet.observe).toHaveBeenCalledTimes(1) expect(unsubscribe).toHaveBeenCalledTimes(0) render(<></>) expect(unsubscribe).toHaveBeenCalledTimes(1) }) it('keeps the subscription of facets when moving in a keyed list', () => { const unsubscribeA = jest.fn() const facetA: Facet<string> = { get: () => 'text', observe: jest.fn().mockReturnValue(unsubscribeA), } const unsubscribeB = jest.fn() const facetB: Facet<string> = { get: () => 'text', observe: jest.fn().mockReturnValue(unsubscribeB), } render(<div>{[<fast-div key={'A'} className={facetA} />, <fast-div key={'B'} className={facetB} />]}</div>) expect(facetA.observe).toHaveBeenCalledTimes(1) expect(facetB.observe).toHaveBeenCalledTimes(1) render(<div>{[<fast-div key={'B'} className={facetB} />, <fast-div key={'A'} className={facetA} />]}</div>) expect(facetA.observe).toHaveBeenCalledTimes(1) expect(facetB.observe).toHaveBeenCalledTimes(1) expect(unsubscribeA).not.toHaveBeenCalled() expect(unsubscribeB).not.toHaveBeenCalled() }) }) describe('commitUpdate style prop', () => { it('subscribes when updating from null', () => { const hostConfig = setupHostConfig() const instance: ElementContainer = { children: new Set(), element: document.createElement('div'), styleUnsubscribers: new Map(), } const oldProps: ElementProps<HTMLDivElement> = { style: { color: undefined, }, } const newColorFacet: Facet<string> = { get: () => 'blue', observe: jest.fn(), } const newProps: ElementProps<HTMLDivElement> = { style: { color: newColorFacet, }, } hostConfig.commitUpdate?.( instance, true, 'fast-div', oldProps as Props<HTMLDivElement>, newProps as Props<HTMLDivElement>, null as unknown as Fiber, ) // Adds a new subscription to the new Facet expect(newColorFacet.observe).toHaveBeenCalledTimes(1) }) it('unsubscribes when updating to null', () => { const colorUnsubscriber = jest.fn() const hostConfig = setupHostConfig() const instance: ElementContainer = { children: new Set(), element: document.createElement('div'), styleUnsubscribers: new Map([['color', colorUnsubscriber]]), } const oldColorFacet: Facet<string> = { get: () => 'blue', observe: jest.fn(), } const oldProps: ElementProps<HTMLDivElement> = { style: { color: oldColorFacet, }, } const newProps: ElementProps<HTMLDivElement> = { style: { color: undefined, }, } hostConfig.commitUpdate?.( instance, true, 'fast-div', oldProps as Props<HTMLDivElement>, newProps as Props<HTMLDivElement>, null as unknown as Fiber, ) expect(colorUnsubscriber).toHaveBeenCalledTimes(1) }) it('unsubscribes from previous facet when changing to a primitive value', () => { const colorUnsubscriber = jest.fn() const hostConfig = setupHostConfig() const instance: ElementContainer = { children: new Set(), element: document.createElement('div'), styleUnsubscribers: new Map([['color', colorUnsubscriber]]), } const oldProps: ElementProps<HTMLDivElement> = { style: { color: createFacet({ initialValue: 'blue' }), }, } const newProps: ElementProps<HTMLDivElement> = { style: { color: 'yellow', }, } hostConfig.commitUpdate?.( instance, true, 'fast-div', oldProps as Props<HTMLDivElement>, newProps as Props<HTMLDivElement>, null as unknown as Fiber, ) expect(colorUnsubscriber).toHaveBeenCalledTimes(1) }) it('unsubscribes from previous facet when changing to a new facet', () => { const colorUnsubscriber = jest.fn() const hostConfig = setupHostConfig() const instance: ElementContainer = { children: new Set(), element: document.createElement('div'), styleUnsubscribers: new Map([['color', colorUnsubscriber]]), } const oldColorFacet: Facet<string> = { get: () => 'blue', observe: jest.fn(), } const oldProps: ElementProps<HTMLDivElement> = { style: { color: oldColorFacet, }, } const newColorFacet: Facet<string> = { get: () => 'blue', observe: jest.fn(), } const newProps: ElementProps<HTMLDivElement> = { style: { color: newColorFacet, }, } hostConfig.commitUpdate?.( instance, true, 'fast-div', oldProps as Props<HTMLDivElement>, newProps as Props<HTMLDivElement>, null as unknown as Fiber, ) // Unsubscribes from the old subscription, since it is a new Facet expect(colorUnsubscriber).toHaveBeenCalledTimes(1) // Adds a new subscription to the new Facet expect(newColorFacet.observe).toHaveBeenCalledTimes(1) }) it('keeps the same subscription when updating with the same facet', () => { const colorUnsubscriber = jest.fn() const hostConfig = setupHostConfig() const instance: ElementContainer = { children: new Set(), element: document.createElement('div'), styleUnsubscribers: new Map([['color', colorUnsubscriber]]), } const colorFacet: Facet<string> = { get: () => 'blue', observe: jest.fn(), } const oldProps: ElementProps<HTMLDivElement> = { style: { color: colorFacet, }, } const newProps: ElementProps<HTMLDivElement> = { style: { color: colorFacet, }, } hostConfig.commitUpdate?.( instance, true, 'fast-div', oldProps as Props<HTMLDivElement>, newProps as Props<HTMLDivElement>, null as unknown as Fiber, ) // I shouldn't unsubscribe, since it is the same Facet expect(colorUnsubscriber).not.toHaveBeenCalled() // So I must not also observe again, since I should stick with the previous subscription expect(colorFacet.observe).toHaveBeenCalledTimes(0) }) })
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "./utilities"; /** * Provides a DigitalOcean database connection pool resource. * * ## Example Usage * ### Create a new PostgreSQL database connection pool * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as digitalocean from "@pulumi/digitalocean"; * * const postgres_example = new digitalocean.DatabaseCluster("postgres-example", { * engine: "pg", * version: "11", * size: "db-s-1vcpu-1gb", * region: "nyc1", * nodeCount: 1, * }); * const pool_01 = new digitalocean.DatabaseConnectionPool("pool-01", { * clusterId: postgres_example.id, * mode: "transaction", * size: 20, * dbName: "defaultdb", * user: "doadmin", * }); * ``` * * ## Import * * Database connection pools can be imported using the `id` of the source database cluster and the `name` of the connection pool joined with a comma. For example * * ```sh * $ pulumi import digitalocean:index/databaseConnectionPool:DatabaseConnectionPool pool-01 245bcfd0-7f31-4ce6-a2bc-475a116cca97,pool-01 * ``` */ export class DatabaseConnectionPool extends pulumi.CustomResource { /** * Get an existing DatabaseConnectionPool resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: DatabaseConnectionPoolState, opts?: pulumi.CustomResourceOptions): DatabaseConnectionPool { return new DatabaseConnectionPool(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'digitalocean:index/databaseConnectionPool:DatabaseConnectionPool'; /** * Returns true if the given object is an instance of DatabaseConnectionPool. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is DatabaseConnectionPool { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === DatabaseConnectionPool.__pulumiType; } /** * The ID of the source database cluster. Note: This must be a PostgreSQL cluster. */ public readonly clusterId!: pulumi.Output<string>; /** * The database for use with the connection pool. */ public readonly dbName!: pulumi.Output<string>; /** * The hostname used to connect to the database connection pool. */ public /*out*/ readonly host!: pulumi.Output<string>; /** * The PGBouncer transaction mode for the connection pool. The allowed values are session, transaction, and statement. */ public readonly mode!: pulumi.Output<string>; /** * The name for the database connection pool. */ public readonly name!: pulumi.Output<string>; /** * Password for the connection pool's user. */ public /*out*/ readonly password!: pulumi.Output<string>; /** * Network port that the database connection pool is listening on. */ public /*out*/ readonly port!: pulumi.Output<number>; /** * Same as `host`, but only accessible from resources within the account and in the same region. */ public /*out*/ readonly privateHost!: pulumi.Output<string>; /** * Same as `uri`, but only accessible from resources within the account and in the same region. */ public /*out*/ readonly privateUri!: pulumi.Output<string>; /** * The desired size of the PGBouncer connection pool. */ public readonly size!: pulumi.Output<number>; /** * The full URI for connecting to the database connection pool. */ public /*out*/ readonly uri!: pulumi.Output<string>; /** * The name of the database user for use with the connection pool. */ public readonly user!: pulumi.Output<string>; /** * Create a DatabaseConnectionPool resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: DatabaseConnectionPoolArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: DatabaseConnectionPoolArgs | DatabaseConnectionPoolState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as DatabaseConnectionPoolState | undefined; inputs["clusterId"] = state ? state.clusterId : undefined; inputs["dbName"] = state ? state.dbName : undefined; inputs["host"] = state ? state.host : undefined; inputs["mode"] = state ? state.mode : undefined; inputs["name"] = state ? state.name : undefined; inputs["password"] = state ? state.password : undefined; inputs["port"] = state ? state.port : undefined; inputs["privateHost"] = state ? state.privateHost : undefined; inputs["privateUri"] = state ? state.privateUri : undefined; inputs["size"] = state ? state.size : undefined; inputs["uri"] = state ? state.uri : undefined; inputs["user"] = state ? state.user : undefined; } else { const args = argsOrState as DatabaseConnectionPoolArgs | undefined; if ((!args || args.clusterId === undefined) && !opts.urn) { throw new Error("Missing required property 'clusterId'"); } if ((!args || args.dbName === undefined) && !opts.urn) { throw new Error("Missing required property 'dbName'"); } if ((!args || args.mode === undefined) && !opts.urn) { throw new Error("Missing required property 'mode'"); } if ((!args || args.size === undefined) && !opts.urn) { throw new Error("Missing required property 'size'"); } if ((!args || args.user === undefined) && !opts.urn) { throw new Error("Missing required property 'user'"); } inputs["clusterId"] = args ? args.clusterId : undefined; inputs["dbName"] = args ? args.dbName : undefined; inputs["mode"] = args ? args.mode : undefined; inputs["name"] = args ? args.name : undefined; inputs["size"] = args ? args.size : undefined; inputs["user"] = args ? args.user : undefined; inputs["host"] = undefined /*out*/; inputs["password"] = undefined /*out*/; inputs["port"] = undefined /*out*/; inputs["privateHost"] = undefined /*out*/; inputs["privateUri"] = undefined /*out*/; inputs["uri"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(DatabaseConnectionPool.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering DatabaseConnectionPool resources. */ export interface DatabaseConnectionPoolState { /** * The ID of the source database cluster. Note: This must be a PostgreSQL cluster. */ clusterId?: pulumi.Input<string>; /** * The database for use with the connection pool. */ dbName?: pulumi.Input<string>; /** * The hostname used to connect to the database connection pool. */ host?: pulumi.Input<string>; /** * The PGBouncer transaction mode for the connection pool. The allowed values are session, transaction, and statement. */ mode?: pulumi.Input<string>; /** * The name for the database connection pool. */ name?: pulumi.Input<string>; /** * Password for the connection pool's user. */ password?: pulumi.Input<string>; /** * Network port that the database connection pool is listening on. */ port?: pulumi.Input<number>; /** * Same as `host`, but only accessible from resources within the account and in the same region. */ privateHost?: pulumi.Input<string>; /** * Same as `uri`, but only accessible from resources within the account and in the same region. */ privateUri?: pulumi.Input<string>; /** * The desired size of the PGBouncer connection pool. */ size?: pulumi.Input<number>; /** * The full URI for connecting to the database connection pool. */ uri?: pulumi.Input<string>; /** * The name of the database user for use with the connection pool. */ user?: pulumi.Input<string>; } /** * The set of arguments for constructing a DatabaseConnectionPool resource. */ export interface DatabaseConnectionPoolArgs { /** * The ID of the source database cluster. Note: This must be a PostgreSQL cluster. */ clusterId: pulumi.Input<string>; /** * The database for use with the connection pool. */ dbName: pulumi.Input<string>; /** * The PGBouncer transaction mode for the connection pool. The allowed values are session, transaction, and statement. */ mode: pulumi.Input<string>; /** * The name for the database connection pool. */ name?: pulumi.Input<string>; /** * The desired size of the PGBouncer connection pool. */ size: pulumi.Input<number>; /** * The name of the database user for use with the connection pool. */ user: pulumi.Input<string>; }
the_stack
import { expect } from 'chai'; import { Signal } from '@phosphor/signaling'; class TestObject { readonly one = new Signal<this, void>(this); readonly two = new Signal<this, number>(this); readonly three = new Signal<this, string[]>(this); } class ExtendedObject extends TestObject { notifyCount = 0; onNotify(): void { this.notifyCount++; } } class TestHandler { name = ''; oneCount = 0; twoValue = 0; twoSender: TestObject | null = null; onOne(): void { this.oneCount++; } onTwo(sender: TestObject, args: number): void { this.twoSender = sender; this.twoValue = args; } onThree(sender: TestObject, args: string[]): void { args.push(this.name); } onThrow(): void { throw new Error(); } } describe('@phosphor/signaling', () => { describe('Signal', () => { describe('#sender', () => { it('should be the sender of the signal', () => { let obj = new TestObject(); expect(obj.one.sender).to.equal(obj); expect(obj.two.sender).to.equal(obj); expect(obj.three.sender).to.equal(obj); }); }); describe('#connect()', () => { it('should return true on success', () => { let obj = new TestObject(); let handler = new TestHandler(); let c1 = obj.one.connect(handler.onOne, handler); expect(c1).to.equal(true); }); it('should return false on failure', () => { let obj = new TestObject(); let handler = new TestHandler(); let c1 = obj.one.connect(handler.onOne, handler); let c2 = obj.one.connect(handler.onOne, handler); expect(c1).to.equal(true); expect(c2).to.equal(false); }); it('should connect plain functions', () => { let obj = new TestObject(); let handler = new TestHandler(); let c1 = obj.one.connect(handler.onThrow); expect(c1).to.equal(true); }); it('should ignore duplicate connections', () => { let obj = new TestObject(); let handler = new TestHandler(); let c1 = obj.one.connect(handler.onOne, handler); let c2 = obj.one.connect(handler.onOne, handler); let c3 = obj.two.connect(handler.onTwo, handler); let c4 = obj.two.connect(handler.onTwo, handler); obj.one.emit(undefined); obj.two.emit(42); expect(c1).to.equal(true); expect(c2).to.equal(false); expect(c3).to.equal(true); expect(c4).to.equal(false); expect(handler.oneCount).to.equal(1); expect(handler.twoValue).to.equal(42); }); }); describe('#disconnect()', () => { it('should return true on success', () => { let obj = new TestObject(); let handler = new TestHandler(); obj.one.connect(handler.onOne, handler); let d1 = obj.one.disconnect(handler.onOne, handler); expect(d1).to.equal(true); }); it('should return false on failure', () => { let obj = new TestObject(); let handler = new TestHandler(); let d1 = obj.one.disconnect(handler.onOne, handler); expect(d1).to.equal(false); }); it('should disconnect plain functions', () => { let obj = new TestObject(); let handler = new TestHandler(); obj.one.connect(handler.onThrow); expect(obj.one.disconnect(handler.onThrow)).to.equal(true); expect(() => obj.one.emit(undefined)).to.not.throw(Error); }); it('should disconnect a specific signal', () => { let obj1 = new TestObject(); let obj2 = new TestObject(); let obj3 = new TestObject(); let handler1 = new TestHandler(); let handler2 = new TestHandler(); let handler3 = new TestHandler(); obj1.one.connect(handler1.onOne, handler1); obj2.one.connect(handler2.onOne, handler2); obj1.one.connect(handler3.onOne, handler3); obj2.one.connect(handler3.onOne, handler3); obj3.one.connect(handler3.onOne, handler3); let d1 = obj1.one.disconnect(handler1.onOne, handler1); let d2 = obj1.one.disconnect(handler1.onOne, handler1); let d3 = obj2.one.disconnect(handler3.onOne, handler3); obj1.one.emit(undefined); obj2.one.emit(undefined); obj3.one.emit(undefined); expect(d1).to.equal(true); expect(d2).to.equal(false); expect(d3).to.equal(true); expect(handler1.oneCount).to.equal(0); expect(handler2.oneCount).to.equal(1); expect(handler3.oneCount).to.equal(2); }); }); describe('#emit()', () => { it('should be a no-op if there are no connection', () => { let obj = new TestObject(); expect(() => { obj.one.emit(undefined); }).to.not.throw(Error); }); it('should pass the sender and args to the handlers', () => { let obj = new TestObject(); let handler1 = new TestHandler(); let handler2 = new TestHandler(); obj.two.connect(handler1.onTwo, handler1); obj.two.connect(handler2.onTwo, handler2); obj.two.emit(15); expect(handler1.twoSender).to.equal(obj); expect(handler2.twoSender).to.equal(obj); expect(handler1.twoValue).to.equal(15); expect(handler2.twoValue).to.equal(15); }); it('should invoke handlers in connection order', () => { let obj = new TestObject(); let handler1 = new TestHandler(); let handler2 = new TestHandler(); let handler3 = new TestHandler(); handler1.name = 'foo'; handler2.name = 'bar'; handler3.name = 'baz'; obj.three.connect(handler1.onThree, handler1); obj.one.connect(handler1.onOne, handler1); obj.three.connect(handler2.onThree, handler2); obj.three.connect(handler3.onThree, handler3); let names: string[] = []; obj.three.emit(names); obj.one.emit(undefined); expect(names).to.deep.equal(['foo', 'bar', 'baz']); expect(handler1.oneCount).to.equal(1); expect(handler2.oneCount).to.equal(0); }); it('should catch any exceptions in handlers', () => { let obj = new TestObject(); let handler1 = new TestHandler(); let handler2 = new TestHandler(); let handler3 = new TestHandler(); handler1.name = 'foo'; handler2.name = 'bar'; handler3.name = 'baz'; obj.three.connect(handler1.onThree, handler1); obj.three.connect(handler2.onThrow, handler2); obj.three.connect(handler3.onThree, handler3); let threw = false; let names1: string[] = []; try { obj.three.emit(names1); } catch (e) { threw = true; } expect(threw).to.equal(false); expect(names1).to.deep.equal(['foo', 'baz']); }); it('should not invoke signals added during emission', () => { let obj = new TestObject(); let handler1 = new TestHandler(); let handler2 = new TestHandler(); let handler3 = new TestHandler(); handler1.name = 'foo'; handler2.name = 'bar'; handler3.name = 'baz'; let adder = { add: () => { obj.three.connect(handler3.onThree, handler3); }, }; obj.three.connect(handler1.onThree, handler1); obj.three.connect(handler2.onThree, handler2); obj.three.connect(adder.add, adder); let names1: string[] = []; obj.three.emit(names1); obj.three.disconnect(adder.add, adder); let names2: string[] = []; obj.three.emit(names2); expect(names1).to.deep.equal(['foo', 'bar']); expect(names2).to.deep.equal(['foo', 'bar', 'baz']); }); it('should not invoke signals removed during emission', () => { let obj = new TestObject(); let handler1 = new TestHandler(); let handler2 = new TestHandler(); let handler3 = new TestHandler(); handler1.name = 'foo'; handler2.name = 'bar'; handler3.name = 'baz'; let remover = { remove: () => { obj.three.disconnect(handler3.onThree, handler3); }, }; obj.three.connect(handler1.onThree, handler1); obj.three.connect(handler2.onThree, handler2); obj.three.connect(remover.remove, remover); obj.three.connect(handler3.onThree, handler3); let names: string[] = []; obj.three.emit(names); expect(names).to.deep.equal(['foo', 'bar']); }); }); describe('.disconnectBetween()', () => { it('should clear all connections between a sender and receiver', () => { let obj = new TestObject(); let handler1 = new TestHandler(); let handler2 = new TestHandler(); obj.one.connect(handler1.onOne, handler1); obj.one.connect(handler2.onOne, handler2); obj.two.connect(handler1.onTwo, handler1); obj.two.connect(handler2.onTwo, handler2); obj.one.emit(undefined); expect(handler1.oneCount).to.equal(1); expect(handler2.oneCount).to.equal(1); obj.two.emit(42); expect(handler1.twoValue).to.equal(42); expect(handler2.twoValue).to.equal(42); Signal.disconnectBetween(obj, handler1); obj.one.emit(undefined); expect(handler1.oneCount).to.equal(1); expect(handler2.oneCount).to.equal(2); obj.two.emit(7); expect(handler1.twoValue).to.equal(42); expect(handler2.twoValue).to.equal(7); }); it('should be a no-op if the sender or receiver is not connected', () => { expect(() => Signal.disconnectBetween({}, {})).to.not.throw(Error); }); }); describe('.disconnectSender()', () => { it('should disconnect all signals from a specific sender', () => { let obj1 = new TestObject(); let obj2 = new TestObject(); let handler1 = new TestHandler(); let handler2 = new TestHandler(); obj1.one.connect(handler1.onOne, handler1); obj1.one.connect(handler2.onOne, handler2); obj2.one.connect(handler1.onOne, handler1); obj2.one.connect(handler2.onOne, handler2); Signal.disconnectSender(obj1); obj1.one.emit(undefined); obj2.one.emit(undefined); expect(handler1.oneCount).to.equal(1); expect(handler2.oneCount).to.equal(1); }); it('should be a no-op if the sender is not connected', () => { expect(() => Signal.disconnectSender({})).to.not.throw(Error); }); }); describe('.disconnectReceiver()', () => { it('should disconnect all signals from a specific receiver', () => { let obj1 = new TestObject(); let obj2 = new TestObject(); let handler1 = new TestHandler(); let handler2 = new TestHandler(); obj1.one.connect(handler1.onOne, handler1); obj1.one.connect(handler2.onOne, handler2); obj2.one.connect(handler1.onOne, handler1); obj2.one.connect(handler2.onOne, handler2); obj2.two.connect(handler1.onTwo, handler1); obj2.two.connect(handler2.onTwo, handler2); Signal.disconnectReceiver(handler1); obj1.one.emit(undefined); obj2.one.emit(undefined); obj2.two.emit(42); expect(handler1.oneCount).to.equal(0); expect(handler2.oneCount).to.equal(2); expect(handler1.twoValue).to.equal(0); expect(handler2.twoValue).to.equal(42); }); it('should be a no-op if the receiver is not connected', () => { expect(() => Signal.disconnectReceiver({})).to.not.throw(Error); }); }); describe('.disconnectAll()', () => { it('should clear all connections for an object', () => { let counter = 0; let onCount = () => { counter++ }; let ext1 = new ExtendedObject(); let ext2 = new ExtendedObject(); ext1.one.connect(ext1.onNotify, ext1); ext1.one.connect(ext2.onNotify, ext2); ext1.one.connect(onCount); ext2.one.connect(ext1.onNotify, ext1); ext2.one.connect(ext2.onNotify, ext2); ext2.one.connect(onCount); Signal.disconnectAll(ext1); ext1.one.emit(undefined); ext2.one.emit(undefined); expect(ext1.notifyCount).to.equal(0); expect(ext2.notifyCount).to.equal(1); expect(counter).to.equal(1); }); }); describe('.clearData()', () => { it('should clear all signal data associated with an object', () => { let counter = 0; let onCount = () => { counter++ }; let ext1 = new ExtendedObject(); let ext2 = new ExtendedObject(); ext1.one.connect(ext1.onNotify, ext1); ext1.one.connect(ext2.onNotify, ext2); ext1.one.connect(onCount); ext2.one.connect(ext1.onNotify, ext1); ext2.one.connect(ext2.onNotify, ext2); ext2.one.connect(onCount); Signal.clearData(ext1); ext1.one.emit(undefined); ext2.one.emit(undefined); expect(ext1.notifyCount).to.equal(0); expect(ext2.notifyCount).to.equal(1); expect(counter).to.equal(1); }); }); describe('.getExceptionHandler()', () => { it('should default to an exception handler', () => { expect(Signal.getExceptionHandler()).to.be.a('function'); }); }); describe('.setExceptionHandler()', () => { afterEach(() => { Signal.setExceptionHandler(console.error); }); it('should set the exception handler', () => { let handler = (err: Error) => { console.error(err); }; Signal.setExceptionHandler(handler); expect(Signal.getExceptionHandler()).to.equal(handler); }); it('should return the old exception handler', () => { let handler = (err: Error) => { console.error(err); }; let old1 = Signal.setExceptionHandler(handler); let old2 = Signal.setExceptionHandler(old1); expect(old1).to.equal(console.error); expect(old2).to.equal(handler); }); it('should invoke the exception handler on a slot exception', () => { let called = false; let obj = new TestObject(); let handler = new TestHandler(); obj.one.connect(handler.onThrow, handler); Signal.setExceptionHandler(() => { called = true; }); expect(called).to.equal(false); obj.one.emit(undefined); expect(called).to.equal(true); }); }); }); context('https://github.com/phosphorjs/phosphor-signaling/issues/5', () => { it('should handle connect after disconnect and emit', () => { let obj = new TestObject(); let handler = new TestHandler(); let c1 = obj.one.connect(handler.onOne, handler); expect(c1).to.equal(true); obj.one.disconnect(handler.onOne, handler); obj.one.emit(undefined); let c2 = obj.one.connect(handler.onOne, handler); expect(c2).to.equal(true); }); }); context('https://github.com/phosphorjs/phosphor-signaling/issues/8', () => { it('should handle disconnecting sender after receiver', () => { let obj = new TestObject(); let handler = new TestHandler(); obj.one.connect(handler.onOne, handler); Signal.disconnectReceiver(handler); Signal.disconnectSender(obj); obj.one.emit(undefined); expect(handler.oneCount).to.equal(0); }); it('should handle disconnecting receiver after sender', () => { let obj = new TestObject(); let handler = new TestHandler(); obj.one.connect(handler.onOne, handler); Signal.disconnectSender(obj); Signal.disconnectReceiver(handler); obj.one.emit(undefined); expect(handler.oneCount).to.equal(0); }); }); });
the_stack
import * as coreClient from "@azure/core-client"; export const KeyListResult: coreClient.CompositeMapper = { type: { name: "Composite", className: "KeyListResult", modelProperties: { items: { serializedName: "items", type: { name: "Sequence", element: { type: { name: "Composite", className: "Key" } } } }, nextLink: { serializedName: "@nextLink", type: { name: "String" } } } } }; export const Key: coreClient.CompositeMapper = { type: { name: "Composite", className: "Key", modelProperties: { name: { serializedName: "name", readOnly: true, type: { name: "String" } } } } }; export const ErrorModel: coreClient.CompositeMapper = { type: { name: "Composite", className: "ErrorModel", modelProperties: { type: { serializedName: "type", type: { name: "String" } }, title: { serializedName: "title", type: { name: "String" } }, name: { serializedName: "name", type: { name: "String" } }, detail: { serializedName: "detail", type: { name: "String" } }, status: { serializedName: "status", type: { name: "Number" } } } } }; export const KeyValueListResult: coreClient.CompositeMapper = { type: { name: "Composite", className: "KeyValueListResult", modelProperties: { items: { serializedName: "items", type: { name: "Sequence", element: { type: { name: "Composite", className: "KeyValue" } } } }, nextLink: { serializedName: "@nextLink", type: { name: "String" } } } } }; export const KeyValue: coreClient.CompositeMapper = { type: { name: "Composite", className: "KeyValue", modelProperties: { key: { serializedName: "key", type: { name: "String" } }, label: { serializedName: "label", type: { name: "String" } }, contentType: { serializedName: "content_type", type: { name: "String" } }, value: { serializedName: "value", type: { name: "String" } }, lastModified: { serializedName: "last_modified", type: { name: "DateTime" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, locked: { serializedName: "locked", type: { name: "Boolean" } }, etag: { serializedName: "etag", type: { name: "String" } } } } }; export const LabelListResult: coreClient.CompositeMapper = { type: { name: "Composite", className: "LabelListResult", modelProperties: { items: { serializedName: "items", type: { name: "Sequence", element: { type: { name: "Composite", className: "Label" } } } }, nextLink: { serializedName: "@nextLink", type: { name: "String" } } } } }; export const Label: coreClient.CompositeMapper = { type: { name: "Composite", className: "Label", modelProperties: { name: { serializedName: "name", readOnly: true, type: { name: "String" } } } } }; export const AppConfigurationClientGetKeysHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientGetKeysHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const AppConfigurationClientCheckKeysHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientCheckKeysHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const AppConfigurationClientGetKeyValuesHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientGetKeyValuesHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const AppConfigurationClientCheckKeyValuesHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientCheckKeyValuesHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const AppConfigurationClientGetKeyValueHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientGetKeyValueHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "String" } } } } }; export const AppConfigurationClientPutKeyValueHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientPutKeyValueHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } } } } }; export const AppConfigurationClientDeleteKeyValueHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientDeleteKeyValueHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } } } } }; export const AppConfigurationClientCheckKeyValueHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientCheckKeyValueHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "String" } } } } }; export const AppConfigurationClientGetLabelsHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientGetLabelsHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const AppConfigurationClientCheckLabelsHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientCheckLabelsHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const AppConfigurationClientPutLockHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientPutLockHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } } } } }; export const AppConfigurationClientDeleteLockHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientDeleteLockHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } }, eTag: { serializedName: "etag", type: { name: "String" } } } } }; export const AppConfigurationClientGetRevisionsHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientGetRevisionsHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const AppConfigurationClientCheckRevisionsHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientCheckRevisionsHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const AppConfigurationClientGetKeysNextHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientGetKeysNextHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const AppConfigurationClientGetKeyValuesNextHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientGetKeyValuesNextHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const AppConfigurationClientGetLabelsNextHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientGetLabelsNextHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } }; export const AppConfigurationClientGetRevisionsNextHeaders: coreClient.CompositeMapper = { type: { name: "Composite", className: "AppConfigurationClientGetRevisionsNextHeaders", modelProperties: { syncToken: { serializedName: "sync-token", type: { name: "String" } } } } };
the_stack
import { BadRequestException, ConflictException, HttpException, HttpStatus, Injectable, Logger, NotFoundException, OnModuleInit, UnauthorizedException, } from '@nestjs/common'; import { ConfigService } from '../../config'; import { ClusterService } from '../cluster/cluster.service'; import { KubeContext } from '../interfaces/kube-context'; import * as Api from 'kubernetes-client'; const Request = require('kubernetes-client/backends/request'); const Client = Api.Client1_13; const config = Request.config; @Injectable() export class KubernetesService implements OnModuleInit { private readonly logger = new Logger(KubernetesService.name); private clusters: Map<string, Api.ApiRoot>; constructor(private readonly appConfig: ConfigService, private readonly clusterService: ClusterService) {} async onModuleInit() { await this.refreshClusters(); // @ts-ignore // for (const [key, client] of this.clusters.entries()) { // try { // await client.loadSpec(); // } catch (err) { // console.error(`Unable to connect to ${key}`, err); // } // } } /** * for admin */ async refreshClusters() { this.logger.log('Refreshing Kubernetes Clusters...'); const { total: size, items: clusters } = await this.clusterService.findAll(); this.logger.log(`Refreshed ${size} Kubernetes Clusters`); this.clusters = new Map( clusters.map<[string, Api.ApiRoot]>((cluster) => [ cluster.name, new Client({ backend: new Request({ url: cluster.baseUrl, auth: { bearer: cluster.token, }, insecureSkipTlsVerify: true, version: 'v1', promises: true, }), version: cluster.version || '1.13', }), ]) ); } async listNamespaces(cluster: string) { try { const namespaces = await this.clusters.get(cluster).api.v1.namespaces.get(); return namespaces.body.items; } catch (error) { this.handleError(error); } } /** * for any */ async hasNamespace({ cluster, namespace }: KubeContext) { try { const foundNamespace = await this.clusters.get(cluster).api.v1.namespaces(namespace).get(); return !!foundNamespace; } catch (error) { if (error.code === 404) { return false; } this.handleError(error); } } async getNamespace({ cluster, namespace }: KubeContext) { try { const response = await this.clusters.get(cluster).api.v1.namespaces(namespace).get(); return response.body; } catch (error) { this.handleError(error); } } async createNamespace({ cluster, namespace, labels: { name = namespace } }: KubeContext) { const request = { body: { apiVersion: 'v1', kind: 'Namespace', metadata: { name, labels: { namespace, }, }, }, }; try { return await this.clusters.get(cluster).api.v1.namespaces.post(request); } catch (error) { this.handleError(error); } } async deleteNamespace({ cluster, namespace }: KubeContext) { try { return await this.clusters.get(cluster).api.v1.namespaces(namespace).delete(); } catch (error) { this.handleError(error); } } async createServiceAccount({ cluster, namespace }: KubeContext, serviceAccountName: string) { const request = { body: { apiVersion: 'v1', kind: 'ServiceAccount', metadata: { name: serviceAccountName, }, }, }; try { return await this.clusters.get(cluster).api.v1.namespaces(namespace).serviceaccounts.post(request); } catch (error) { this.handleError(error); } } async deleteServiceAccount({ cluster, namespace }: KubeContext, serviceAccountName: string) { try { return await this.clusters.get(cluster).api.v1.namespaces(namespace).serviceaccounts(serviceAccountName).delete(); } catch (error) { this.handleError(error); } } async createNetworkPolicy({ cluster, namespace }: KubeContext) { const request = { body: { apiVersion: 'networking.k8s.io/v1', kind: 'NetworkPolicy', metadata: { name: 'default-deny' }, spec: { policyTypes: ['Egress', 'Ingress'], ingress: [ { from: [ { namespaceSelector: { matchLabels: { namespace, }, }, }, ], }, ], egress: [ { to: [ { namespaceSelector: { matchLabels: { namespace, }, }, }, ], }, { ports: [ { port: 53, protocol: 'TCP', }, { port: 53, protocol: 'UDP', }, ], }, ], }, }, }; try { return await this.clusters .get(cluster) .apis['networking.k8s.io'].v1.namespaces(namespace) .networkpolicies.post(request); } catch (error) { this.handleError(error); } } async createClusterRoleBindingForServiceAccount( { cluster, namespace, labels: { name = namespace } }: KubeContext, serviceAccountName: string, role: string ) { const request = { body: { apiVersion: 'rbac.authorization.k8s.io/v1', kind: 'RoleBinding', metadata: { name: `rb-${name}-${serviceAccountName}-${role}-sa`, labels: { created: 'kubeadmin', }, }, roleRef: { kind: 'ClusterRole', name: role, apiGroup: 'rbac.authorization.k8s.io', }, subjects: [ { kind: 'ServiceAccount', name: serviceAccountName, namespace, }, ], }, }; try { return await this.clusters .get(cluster) .apis['rbac.authorization.k8s.io'].v1.namespaces(namespace) .rolebindings.post(request); } catch (error) { this.handleError(error); } } async createClusterRoleBindingForDashboardUsers( { cluster, namespace, labels: { name = namespace } }: KubeContext, username: string ) { const request = { body: { apiVersion: 'rbac.authorization.k8s.io/v1', kind: 'RoleBinding', metadata: { name: `rb-${name}-${username}`, labels: { created: 'kubeadmin', }, }, roleRef: { kind: 'ClusterRole', name: 'admin', apiGroup: 'rbac.authorization.k8s.io', }, subjects: [ { kind: 'User', name: username, apiGroup: 'rbac.authorization.k8s.io', namespace, }, ], }, }; try { return await this.clusters .get(cluster) .apis['rbac.authorization.k8s.io'].v1.namespaces(namespace) .rolebindings.post(request); } catch (error) { this.handleError(error); } } async createResourceQuotaForNamespace({ cluster, namespace, labels: { name = namespace } }: KubeContext) { const request = { body: { apiVersion: 'v1', kind: 'ResourceQuota', metadata: { name: `rq-${name.toLowerCase()}`, }, spec: { hard: { cpu: '156', memory: '720Gi', 'requests.cpu': '156', 'requests.memory': '720Gi', 'limits.cpu': '156', 'limits.memory': '720Gi', }, }, }, }; try { return await this.clusters.get(cluster).api.v1.namespaces(namespace).resourcequotas.post(request); } catch (error) { this.handleError(error); } } async createResourceLimitRangeForNamespace({ cluster, namespace, labels: { name = namespace } }: KubeContext) { const request = { body: { apiVersion: 'v1', kind: 'LimitRange', metadata: { name: `rq-${name.toLowerCase()}`, }, spec: { limits: [ { max: { cpu: '32', memory: '128Gi', }, min: { cpu: '300m', memory: '6Mi', }, type: 'Pod', }, { default: { cpu: '500m', memory: '500Mi', }, defaultRequest: { cpu: '300m', memory: '300Mi', }, type: 'Container', }, ], }, }, }; try { return await this.clusters.get(cluster).api.v1.namespaces(namespace).limitranges.post(request); } catch (error) { this.handleError(error); } } async listDeployments({ cluster, namespace }: KubeContext) { try { const deployments = await this.clusters.get(cluster).apis.apps.v1.namespaces(namespace).deployments.get(); return deployments.body.items; } catch (error) { this.handleError(error); } } /** * for me */ async myNamespaces(context: KubeContext) { const { cluster, namespace } = context; try { // this.clusters.get(cluster).setToken(token) const namespaces = await this.clusters.get(cluster).api.v1.namespaces.get(); return namespaces.items; } catch (error) { this.handleError(error); } } async myServiceAccounts(context: KubeContext) { const { cluster, namespace } = context; try { const namespaces = await this.clusters.get(cluster).api.v1.namespaces(namespace).serviceaccounts.get(); return namespaces.body.items; } catch (error) { this.handleError(error); } } async scrape(context: KubeContext) { const { cluster, namespace } = context; const data: any = {}; try { const services = await this.clusters.get(cluster).api.v1.namespaces(namespace).services.get(); const endpoints = await this.clusters.get(cluster).api.v1.namespaces(namespace).endpoints.get(); const ingresses = await this.clusters.get(cluster).apis.extensions.v1beta1.namespaces(namespace).ingresses.get(); const pods = await this.clusters.get(cluster).api.v1.namespaces(namespace).pods.get(); const deployments = await this.clusters.get(cluster).apis.apps.v1.namespaces(namespace).deployments.get(); const replicasets = await this.clusters.get(cluster).apis.apps.v1.namespaces(namespace).replicasets.get(); const daemonsets = await this.clusters.get(cluster).apis.apps.v1.namespaces(namespace).daemonsets.get(); const statefulsets = await this.clusters.get(cluster).apis.apps.v1.namespaces(namespace).statefulsets.get(); const persistentvolumeclaims = await this.clusters .get(cluster) .api.v1.namespaces(namespace) .persistentvolumeclaims.get(); const persistentvolumes = await this.clusters.get(cluster).api.v1.persistentvolumes.get(); // Build response data and send data.services = services.body.items; data.endpoints = endpoints.body.items; data.ingresses = ingresses.body.items; data.pods = pods.body.items; data.deployments = deployments.body.items; data.replicasets = replicasets.body.items; data.daemonsets = daemonsets.body.items; data.statefulsets = statefulsets.body.items; data.persistentvolumeclaims = persistentvolumeclaims.body.items; data.persistentvolumes = persistentvolumes.body.items; return data; } catch (err) { console.error(err); throw err; } } private handleError(error: Error & { code?: number; statusCode?: number }) { const message = error.message || 'unknown error'; const statusCode = error.statusCode || error.code || HttpStatus.I_AM_A_TEAPOT; console.log(message, statusCode); switch (statusCode) { case HttpStatus.CONFLICT: throw new ConflictException(error.message); case HttpStatus.UNAUTHORIZED: throw new UnauthorizedException(error.message); case HttpStatus.NOT_FOUND: throw new NotFoundException(error.message); case HttpStatus.BAD_REQUEST: throw new BadRequestException(error.message); default: throw new HttpException(message, statusCode); } } }
the_stack
import { indexOf } from "./utils"; /** * @class Autolinker.HtmlTag * @extends Object * * Represents an HTML tag, which can be used to easily build/modify HTML tags programmatically. * * Autolinker uses this abstraction to create HTML tags, and then write them out as strings. You may also use * this class in your code, especially within a {@link Autolinker#replaceFn replaceFn}. * * ## Examples * * Example instantiation: * * var tag = new Autolinker.HtmlTag( { * tagName : 'a', * attrs : { 'href': 'http://google.com', 'class': 'external-link' }, * innerHtml : 'Google' * } ); * * tag.toAnchorString(); // <a href="http://google.com" class="external-link">Google</a> * * // Individual accessor methods * tag.getTagName(); // 'a' * tag.getAttr( 'href' ); // 'http://google.com' * tag.hasClass( 'external-link' ); // true * * * Using mutator methods (which may be used in combination with instantiation config properties): * * var tag = new Autolinker.HtmlTag(); * tag.setTagName( 'a' ); * tag.setAttr( 'href', 'http://google.com' ); * tag.addClass( 'external-link' ); * tag.setInnerHtml( 'Google' ); * * tag.getTagName(); // 'a' * tag.getAttr( 'href' ); // 'http://google.com' * tag.hasClass( 'external-link' ); // true * * tag.toAnchorString(); // <a href="http://google.com" class="external-link">Google</a> * * * ## Example use within a {@link Autolinker#replaceFn replaceFn} * * var html = Autolinker.link( "Test google.com", { * replaceFn : function( match ) { * var tag = match.buildTag(); // returns an {@link Autolinker.HtmlTag} instance, configured with the Match's href and anchor text * tag.setAttr( 'rel', 'nofollow' ); * * return tag; * } * } ); * * // generated html: * // Test <a href="http://google.com" target="_blank" rel="nofollow">google.com</a> * * * ## Example use with a new tag for the replacement * * var html = Autolinker.link( "Test google.com", { * replaceFn : function( match ) { * var tag = new Autolinker.HtmlTag( { * tagName : 'button', * attrs : { 'title': 'Load URL: ' + match.getAnchorHref() }, * innerHtml : 'Load URL: ' + match.getAnchorText() * } ); * * return tag; * } * } ); * * // generated html: * // Test <button title="Load URL: http://google.com">Load URL: google.com</button> */ export class HtmlTag { /** * @cfg {String} tagName * * The tag name. Ex: 'a', 'button', etc. * * Not required at instantiation time, but should be set using {@link #setTagName} before {@link #toAnchorString} * is executed. */ private tagName: string = ''; // default value just to get the above doc comment in the ES5 output and documentation generator /** * @cfg {Object.<String, String>} attrs * * An key/value Object (map) of attributes to create the tag with. The keys are the attribute names, and the * values are the attribute values. */ private attrs: { [key: string]: string } = {}; // default value just to get the above doc comment in the ES5 output and documentation generator /** * @cfg {String} innerHTML * * The inner HTML for the tag. */ private innerHTML: string = ''; // default value just to get the above doc comment in the ES5 output and documentation generator /** * @protected * @property {RegExp} whitespaceRegex * * Regular expression used to match whitespace in a string of CSS classes. */ protected whitespaceRegex = /\s+/; // default value just to get the above doc comment in the ES5 output and documentation generator /** * @method constructor * @param {Object} [cfg] The configuration properties for this class, in an Object (map) */ constructor( cfg: HtmlTagCfg = {} ) { this.tagName = cfg.tagName || ''; this.attrs = cfg.attrs || {}; this.innerHTML = cfg.innerHtml || cfg.innerHTML || ''; // accept either the camelCased form or the fully capitalized acronym as in the DOM } /** * Sets the tag name that will be used to generate the tag with. * * @param {String} tagName * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained. */ setTagName( tagName: string ) { this.tagName = tagName; return this; } /** * Retrieves the tag name. * * @return {String} */ getTagName() { return this.tagName || ''; } /** * Sets an attribute on the HtmlTag. * * @param {String} attrName The attribute name to set. * @param {String} attrValue The attribute value to set. * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained. */ setAttr( attrName: string, attrValue: string ) { let tagAttrs = this.getAttrs(); tagAttrs[ attrName ] = attrValue; return this; } /** * Retrieves an attribute from the HtmlTag. If the attribute does not exist, returns `undefined`. * * @param {String} attrName The attribute name to retrieve. * @return {String} The attribute's value, or `undefined` if it does not exist on the HtmlTag. */ getAttr( attrName: string ) { return this.getAttrs()[ attrName ]; } /** * Sets one or more attributes on the HtmlTag. * * @param {Object.<String, String>} attrs A key/value Object (map) of the attributes to set. * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained. */ setAttrs( attrs: {[attr: string]: string} ) { Object.assign( this.getAttrs(), attrs ); return this; } /** * Retrieves the attributes Object (map) for the HtmlTag. * * @return {Object.<String, String>} A key/value object of the attributes for the HtmlTag. */ getAttrs() { return this.attrs || ( this.attrs = {} ); } /** * Sets the provided `cssClass`, overwriting any current CSS classes on the HtmlTag. * * @param {String} cssClass One or more space-separated CSS classes to set (overwrite). * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained. */ setClass( cssClass: string ) { return this.setAttr( 'class', cssClass ); } /** * Convenience method to add one or more CSS classes to the HtmlTag. Will not add duplicate CSS classes. * * @param {String} cssClass One or more space-separated CSS classes to add. * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained. */ addClass( cssClass: string ) { let classAttr = this.getClass(), whitespaceRegex = this.whitespaceRegex, classes = ( !classAttr ) ? [] : classAttr.split( whitespaceRegex ), newClasses = cssClass.split( whitespaceRegex ), newClass: string | undefined; while( newClass = newClasses.shift() ) { if( indexOf( classes, newClass ) === -1 ) { classes.push( newClass ); } } this.getAttrs()[ 'class' ] = classes.join( " " ); return this; } /** * Convenience method to remove one or more CSS classes from the HtmlTag. * * @param {String} cssClass One or more space-separated CSS classes to remove. * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained. */ removeClass( cssClass: string ) { let classAttr = this.getClass(), whitespaceRegex = this.whitespaceRegex, classes = ( !classAttr ) ? [] : classAttr.split( whitespaceRegex ), removeClasses = cssClass.split( whitespaceRegex ), removeClass: string | undefined; while( classes.length && ( removeClass = removeClasses.shift() ) ) { let idx = indexOf( classes, removeClass ); if( idx !== -1 ) { classes.splice( idx, 1 ); } } this.getAttrs()[ 'class' ] = classes.join( " " ); return this; } /** * Convenience method to retrieve the CSS class(es) for the HtmlTag, which will each be separated by spaces when * there are multiple. * * @return {String} */ getClass() { return this.getAttrs()[ 'class' ] || ""; } /** * Convenience method to check if the tag has a CSS class or not. * * @param {String} cssClass The CSS class to check for. * @return {Boolean} `true` if the HtmlTag has the CSS class, `false` otherwise. */ hasClass( cssClass: string ) { return ( ' ' + this.getClass() + ' ' ).indexOf( ' ' + cssClass + ' ' ) !== -1; } /** * Sets the inner HTML for the tag. * * @param {String} html The inner HTML to set. * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained. */ setInnerHTML( html: string ) { this.innerHTML = html; return this; } /** * Backwards compatibility method name. * * @param {String} html The inner HTML to set. * @return {Autolinker.HtmlTag} This HtmlTag instance, so that method calls may be chained. */ setInnerHtml( html: string ) { return this.setInnerHTML( html ); } /** * Retrieves the inner HTML for the tag. * * @return {String} */ getInnerHTML() { return this.innerHTML || ""; } /** * Backward compatibility method name. * * @return {String} */ getInnerHtml() { return this.getInnerHTML(); } /** * Override of superclass method used to generate the HTML string for the tag. * * @return {String} */ toAnchorString() { let tagName = this.getTagName(), attrsStr = this.buildAttrsStr(); attrsStr = ( attrsStr ) ? ' ' + attrsStr : ''; // prepend a space if there are actually attributes return [ '<', tagName, attrsStr, '>', this.getInnerHtml(), '</', tagName, '>' ].join( "" ); } /** * Support method for {@link #toAnchorString}, returns the string space-separated key="value" pairs, used to populate * the stringified HtmlTag. * * @protected * @return {String} Example return: `attr1="value1" attr2="value2"` */ protected buildAttrsStr() { if( !this.attrs ) return ""; // no `attrs` Object (map) has been set, return empty string let attrs = this.getAttrs(), attrsArr: string[] = []; for( let prop in attrs ) { if( attrs.hasOwnProperty( prop ) ) { attrsArr.push( prop + '="' + attrs[ prop ] + '"' ); } } return attrsArr.join( " " ); } } export interface HtmlTagCfg { tagName?: string; attrs?: { [key: string]: string }; innerHtml?: string; innerHTML?: string; }
the_stack
import * as React from 'react'; import { Dropdown, TextField, Toggle, Link, IconButton, DocumentCard, DocumentCardPreview, IDocumentCardPreviewProps, ImageFit, PrimaryButton, IDropdownOption, ActionButton, Spinner, SpinnerSize } from 'office-ui-fabric-react'; import styles from './SiteDesignEditor.module.scss'; import { escape, assign } from '@microsoft/sp-lodash-subset'; import * as strings from 'SiteDesignsStudioWebPartStrings'; import GenericObjectEditor from '../genericObjectEditor/GenericObjectEditor'; import { ISiteScriptAction, ISiteScript } from '../../models/ISiteScript'; import ScriptActionAdder from '../scriptActionAdder/ScriptActionAdder'; import { IServiceConsumerComponentProps } from '../ISiteDesignsStudioProps'; import { ISiteScriptSchemaService, SiteScriptSchemaServiceKey } from '../../services/siteScriptSchema/SiteScriptSchemaService'; import { ISiteDesignsService, SiteDesignsServiceKey } from '../../services/siteDesigns/SiteDesignsService'; import { ISiteDesign, WebTemplate } from '../../models/ISiteDesign'; export interface ISiteDesignEditorState { isEditingPreview: boolean; availableSiteScripts: ISiteScript[]; scriptToAdd: string; isLoading: boolean; } export interface ISiteDesignEditorProps extends IServiceConsumerComponentProps { siteDesign: ISiteDesign; onSiteDesignChanged?: (siteDesign: ISiteDesign) => void; } export default class SiteDesignEditor extends React.Component<ISiteDesignEditorProps, ISiteDesignEditorState> { private siteDesignsService: ISiteDesignsService; constructor(props: ISiteDesignEditorProps) { super(props); this.props.serviceScope.whenFinished(() => { this.siteDesignsService = this.props.serviceScope.consume(SiteDesignsServiceKey); }); this.state = { isEditingPreview: false, availableSiteScripts: [], scriptToAdd: '', isLoading: true }; } // public componentWillReceiveProps(nextProps: IScriptActionEditorProps) { // this._setAllSubactionsExpanded(nextProps.isExpanded); // } public componentWillMount() { this._loadAvailableSiteScripts(); } private _loadAvailableSiteScripts() { this.siteDesignsService.getSiteScripts().then((scripts) => { this.setState({ availableSiteScripts: scripts, isLoading: false }); }); } private _translateLabel(value: string): string { const key = 'LABEL_' + value; return strings[key] || value; } public render(): React.ReactElement<ISiteDesignEditorProps> { let { siteDesign } = this.props; let { isEditingPreview, isLoading } = this.state; let previewProps: IDocumentCardPreviewProps = { previewImages: [ { name: siteDesign.PreviewImageAltText, url: siteDesign.PreviewImageUrl, previewImageSrc: siteDesign.PreviewImageUrl, imageFit: ImageFit.cover, width: 280, height: 173 } ] }; if (isLoading) { return ( <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm6 ms-smOffset3"> <Spinner size={SpinnerSize.large} label="Loading..." /> </div> </div> ); } return ( <div className={styles.siteDesignEditor}> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12 ms-lg6"> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> {isEditingPreview ? ( <div className={styles.imagePreview}> <h3>Preview Image</h3> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <TextField label="Url" value={siteDesign.PreviewImageUrl} onChanged={(v) => this._onPropertyChanged('PreviewImageUrl', v)} /> </div> </div>{' '} <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <TextField label="Alternative Text" value={siteDesign.PreviewImageAltText} onChanged={(v) => this._onPropertyChanged('PreviewImageAltText', v)} /> </div> </div> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-smPush6 ms-sm4"> <div className={styles.imagePreviewButton}> <PrimaryButton text="Ok" onClick={() => this._toggleImagePreviewEdition()} /> </div> </div> </div> </div> ) : ( <div onClick={() => this._toggleImagePreviewEdition()}> {siteDesign.PreviewImageUrl ? ( <DocumentCard> <DocumentCardPreview {...previewProps} /> </DocumentCard> ) : ( <div className={styles.imagePreview + " " + styles.imagePreviewUpdateLink}>Click here to modify preview</div> )} </div> )} </div> </div> {siteDesign.Id && ( <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <TextField readOnly={true} disabled={true} label="Id" value={siteDesign.Id} /> </div> </div> )} <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <TextField label="Title" value={siteDesign.Title} onChanged={(v) => this._onPropertyChanged('Title', v)} /> </div> </div> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <TextField label="Description" value={siteDesign.Description} multiline={true} rows={6} onChanged={(v) => this._onPropertyChanged('Description', v)} /> </div> </div> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <TextField label="Version" value={siteDesign.Version.toString()} onChanged={(v) => this._onPropertyChanged('Version', v)} /> </div> </div> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12"> <Dropdown label="Site Template" options={[ { key: WebTemplate.TeamSite.toString(), text: 'Team Site' }, { key: WebTemplate.CommunicationSite.toString(), text: 'Communication Site' } ]} selectedKey={siteDesign.WebTemplate} onChanged={(v) => this._onPropertyChanged('WebTemplate', v.key)} /> </div> </div> </div> <div className="ms-Grid-col ms-sm12 ms-lg6"> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm12">{this._renderSiteScripts()}</div> </div> </div> </div> </div> ); } private _renderSiteScripts() { let { siteDesign } = this.props; let { availableSiteScripts, scriptToAdd } = this.state; if (!availableSiteScripts || availableSiteScripts.length == 0) { return <div>No available Site Scripts...</div>; } let availableScriptsToAdd = this._hasAvailableScriptsToAdd(); return ( <div> <div className="ms-Grid-row"> <div className="ms-Grid-col ms-sm10"> <Dropdown options={this._getAvailableScriptsToAddDropdownOptions()} onChanged={(v) => this._setScriptToAdd(v.key.toString())} selectedKey={scriptToAdd || null} disabled={!availableScriptsToAdd} label="Available scripts" /> </div> <div className="ms-Grid-col ms-sm2"> <div className={styles.addScriptButton}> <ActionButton iconProps={{ iconName: 'Add' }} text="Add" disabled={!availableScriptsToAdd} onClick={() => this._addSiteScript(scriptToAdd)} /> </div> </div> </div> <div className={styles.siteScripts}> {siteDesign.SiteScriptIds.map((scriptId) => this._getSiteScript(scriptId)).map( (script: ISiteScript, index: number) => script ? ( <div className={styles.siteScript}> <h3>{script.Title}</h3> <h4>{script.Description}</h4> <IconButton iconProps={{ iconName: 'Up' }} onClick={() => this._moveSiteScriptUp(index)} disabled={!this._canMoveSiteScriptUp(index)} /> <IconButton iconProps={{ iconName: 'Down' }} onClick={() => this._moveSiteScriptDOwn(index)} disabled={!this._canMoveSiteScriptDown(index)} /> <IconButton iconProps={{ iconName: 'Delete' }} onClick={() => this._removeSiteScript(script.Id)} /> </div> ) : null )} </div> </div> ); } private _getSiteScript(siteScriptId: string): ISiteScript { let { availableSiteScripts } = this.state; if (!availableSiteScripts || availableSiteScripts.length == 0) { console.log('Site Script is not found'); return null; } let foundItems = availableSiteScripts.filter((s) => s.Id == siteScriptId); let result = foundItems.length == 1 ? foundItems[0] : null; console.log('Site Script =', result); return result; } private _getAvailableScriptsToAddDropdownOptions(): IDropdownOption[] { let { availableSiteScripts } = this.state; let { siteDesign } = this.props; return availableSiteScripts .map((s) => ({ key: s.Id, text: s.Title })) .filter((s) => siteDesign.SiteScriptIds.indexOf(s.key) < 0); } private _hasAvailableScriptsToAdd(): boolean { let { availableSiteScripts } = this.state; let { siteDesign } = this.props; return availableSiteScripts.filter((s) => siteDesign.SiteScriptIds.indexOf(s.Id) < 0).length > 0; } private _setScriptToAdd(scriptId: string) { this.setState({ scriptToAdd: scriptId }); } private _addSiteScript(scriptId: string) { let currentScripts = this.props.siteDesign.SiteScriptIds; if (currentScripts.indexOf(scriptId) >= 0) { return; } let newScripts = [].concat(currentScripts, scriptId); this.setState({ scriptToAdd: '' }); this._onPropertyChanged('SiteScriptIds', newScripts); } private _removeSiteScript(scriptId: string) { let currentScripts = this.props.siteDesign.SiteScriptIds; let newScripts = currentScripts.filter((s) => s != scriptId); this._onPropertyChanged('SiteScriptIds', newScripts); } private _swapSiteScript(oldIndex: number, newIndex: number) { let { siteDesign } = this.props; if (newIndex < 0 || newIndex > siteDesign.SiteScriptIds.length - 1) { return; } let newSiteScriptIds = [].concat(siteDesign.SiteScriptIds); let old = newSiteScriptIds[oldIndex]; newSiteScriptIds[oldIndex] = newSiteScriptIds[newIndex]; newSiteScriptIds[newIndex] = old; this._onPropertyChanged('SiteScriptIds', newSiteScriptIds); } private _moveSiteScriptUp(index: number) { this._swapSiteScript(index, index - 1); } private _canMoveSiteScriptUp(index: number): boolean { return index > 0; } private _moveSiteScriptDOwn(index: number) { this._swapSiteScript(index, index + 1); } private _canMoveSiteScriptDown(index: number): boolean { return index < this.props.siteDesign.SiteScriptIds.length - 1; } private _toggleImagePreviewEdition() { let { isEditingPreview } = this.state; this.setState({ isEditingPreview: !isEditingPreview }); } private _onPropertyChanged(propertyName: string, value: any) { let { siteDesign, onSiteDesignChanged } = this.props; if (!onSiteDesignChanged) { return; } let changed = assign({}, siteDesign); // Transform value if needed if (propertyName == 'Version') { try { value = parseFloat(value); } catch (error) {} } changed[propertyName] = value; onSiteDesignChanged(changed); } }
the_stack
import type { ILinksShadow } from "../Options/Interfaces/Particles/Links/ILinksShadow"; import type { IShadow } from "../Options/Interfaces/Particles/IShadow"; import type { Container } from "../Core/Container"; import { getDistance, getDistances } from "./NumberUtils"; import { colorMix, colorToRgb, getStyleFromHsl, getStyleFromRgb } from "./ColorUtils"; import type { IContainerPlugin, ICoordinates, IDelta, IDimension, IHsl, IParticle, IParticleGradientAnimation, IRgb, } from "../Core/Interfaces"; import type { Particle } from "../Core/Particle"; import { AlterType, GradientType, RollMode } from "../Enums"; function drawLine(context: CanvasRenderingContext2D, begin: ICoordinates, end: ICoordinates): void { context.beginPath(); context.moveTo(begin.x, begin.y); context.lineTo(end.x, end.y); context.closePath(); } function drawTriangle(context: CanvasRenderingContext2D, p1: ICoordinates, p2: ICoordinates, p3: ICoordinates): void { context.beginPath(); context.moveTo(p1.x, p1.y); context.lineTo(p2.x, p2.y); context.lineTo(p3.x, p3.y); context.closePath(); } export function paintBase(context: CanvasRenderingContext2D, dimension: IDimension, baseColor?: string): void { context.save(); context.fillStyle = baseColor ?? "rgba(0,0,0,0)"; context.fillRect(0, 0, dimension.width, dimension.height); context.restore(); } export function clear(context: CanvasRenderingContext2D, dimension: IDimension): void { context.clearRect(0, 0, dimension.width, dimension.height); } export function drawLinkLine( context: CanvasRenderingContext2D, width: number, begin: ICoordinates, end: ICoordinates, maxDistance: number, canvasSize: IDimension, warp: boolean, backgroundMask: boolean, composite: string, colorLine: IRgb, opacity: number, shadow: ILinksShadow ): void { // this.ctx.lineCap = "round"; /* performance issue */ /* path */ let drawn = false; if (getDistance(begin, end) <= maxDistance) { drawLine(context, begin, end); drawn = true; } else if (warp) { let pi1: ICoordinates | undefined; let pi2: ICoordinates | undefined; const endNE = { x: end.x - canvasSize.width, y: end.y, }; const d1 = getDistances(begin, endNE); if (d1.distance <= maxDistance) { const yi = begin.y - (d1.dy / d1.dx) * begin.x; pi1 = { x: 0, y: yi }; pi2 = { x: canvasSize.width, y: yi }; } else { const endSW = { x: end.x, y: end.y - canvasSize.height, }; const d2 = getDistances(begin, endSW); if (d2.distance <= maxDistance) { const yi = begin.y - (d2.dy / d2.dx) * begin.x; const xi = -yi / (d2.dy / d2.dx); pi1 = { x: xi, y: 0 }; pi2 = { x: xi, y: canvasSize.height }; } else { const endSE = { x: end.x - canvasSize.width, y: end.y - canvasSize.height, }; const d3 = getDistances(begin, endSE); if (d3.distance <= maxDistance) { const yi = begin.y - (d3.dy / d3.dx) * begin.x; const xi = -yi / (d3.dy / d3.dx); pi1 = { x: xi, y: yi }; pi2 = { x: pi1.x + canvasSize.width, y: pi1.y + canvasSize.height }; } } } if (pi1 && pi2) { drawLine(context, begin, pi1); drawLine(context, end, pi2); drawn = true; } } if (!drawn) { return; } context.lineWidth = width; if (backgroundMask) { context.globalCompositeOperation = composite; } context.strokeStyle = getStyleFromRgb(colorLine, opacity); if (shadow.enable) { const shadowColor = colorToRgb(shadow.color); if (shadowColor) { context.shadowBlur = shadow.blur; context.shadowColor = getStyleFromRgb(shadowColor); } } context.stroke(); } export function drawLinkTriangle( context: CanvasRenderingContext2D, pos1: ICoordinates, pos2: ICoordinates, pos3: ICoordinates, backgroundMask: boolean, composite: string, colorTriangle: IRgb, opacityTriangle: number ): void { // this.ctx.lineCap = "round"; /* performance issue */ /* path */ drawTriangle(context, pos1, pos2, pos3); if (backgroundMask) { context.globalCompositeOperation = composite; } context.fillStyle = getStyleFromRgb(colorTriangle, opacityTriangle); context.fill(); } export function drawConnectLine( context: CanvasRenderingContext2D, width: number, lineStyle: CanvasGradient, begin: ICoordinates, end: ICoordinates ): void { context.save(); drawLine(context, begin, end); context.lineWidth = width; context.strokeStyle = lineStyle; context.stroke(); context.restore(); } export function gradient( context: CanvasRenderingContext2D, p1: IParticle, p2: IParticle, opacity: number ): CanvasGradient | undefined { const gradStop = Math.floor(p2.getRadius() / p1.getRadius()); const color1 = p1.getFillColor(); const color2 = p2.getFillColor(); if (!color1 || !color2) { return; } const sourcePos = p1.getPosition(); const destPos = p2.getPosition(); const midRgb = colorMix(color1, color2, p1.getRadius(), p2.getRadius()); const grad = context.createLinearGradient(sourcePos.x, sourcePos.y, destPos.x, destPos.y); grad.addColorStop(0, getStyleFromHsl(color1, opacity)); grad.addColorStop(gradStop > 1 ? 1 : gradStop, getStyleFromRgb(midRgb, opacity)); grad.addColorStop(1, getStyleFromHsl(color2, opacity)); return grad; } export function drawGrabLine( context: CanvasRenderingContext2D, width: number, begin: ICoordinates, end: ICoordinates, colorLine: IRgb, opacity: number ): void { context.save(); drawLine(context, begin, end); context.strokeStyle = getStyleFromRgb(colorLine, opacity); context.lineWidth = width; context.stroke(); context.restore(); } export function drawParticle( container: Container, context: CanvasRenderingContext2D, particle: IParticle, delta: IDelta, fillColorValue: string | undefined, strokeColorValue: string | undefined, backgroundMask: boolean, composite: string, radius: number, opacity: number, shadow: IShadow, gradient?: IParticleGradientAnimation ): void { const pos = particle.getPosition(); const tiltOptions = particle.options.tilt; const rollOptions = particle.options.roll; context.save(); if (tiltOptions.enable || rollOptions.enable) { const roll = rollOptions.enable && particle.roll; const tilt = tiltOptions.enable && particle.tilt; const rollHorizontal = roll && (rollOptions.mode === RollMode.horizontal || rollOptions.mode === RollMode.both); const rollVertical = roll && (rollOptions.mode === RollMode.vertical || rollOptions.mode === RollMode.both); context.setTransform( rollHorizontal ? Math.cos(particle.roll.angle) : 1, tilt ? Math.cos(particle.tilt.value) * particle.tilt.cosDirection : 0, tilt ? Math.sin(particle.tilt.value) * particle.tilt.sinDirection : 0, rollVertical ? Math.sin(particle.roll.angle) : 1, pos.x, pos.y ); } else { context.translate(pos.x, pos.y); } context.beginPath(); const angle = (particle.rotate?.value ?? 0) + (particle.options.rotate.path ? particle.velocity.angle : 0); if (angle !== 0) { context.rotate(angle); } if (backgroundMask) { context.globalCompositeOperation = composite; } const shadowColor = particle.shadowColor; if (shadow.enable && shadowColor) { context.shadowBlur = shadow.blur; context.shadowColor = getStyleFromRgb(shadowColor); context.shadowOffsetX = shadow.offset.x; context.shadowOffsetY = shadow.offset.y; } if (gradient) { const gradientAngle = gradient.angle.value; const fillGradient = gradient.type === GradientType.radial ? context.createRadialGradient(0, 0, 0, 0, 0, radius) : context.createLinearGradient( Math.cos(gradientAngle) * -radius, Math.sin(gradientAngle) * -radius, Math.cos(gradientAngle) * radius, Math.sin(gradientAngle) * radius ); for (const color of gradient.colors) { fillGradient.addColorStop( color.stop, getStyleFromHsl( { h: color.value.h.value, s: color.value.s.value, l: color.value.l.value, }, color.opacity?.value ?? opacity ) ); } context.fillStyle = fillGradient; } else { if (fillColorValue) { context.fillStyle = fillColorValue; } } const stroke = particle.stroke; context.lineWidth = particle.strokeWidth ?? 0; if (strokeColorValue) { context.strokeStyle = strokeColorValue; } drawShape(container, context, particle, radius, opacity, delta); if ((stroke?.width ?? 0) > 0) { context.stroke(); } if (particle.close) { context.closePath(); } if (particle.fill) { context.fill(); } context.restore(); context.save(); if (tiltOptions.enable && particle.tilt) { context.setTransform( 1, Math.cos(particle.tilt.value) * particle.tilt.cosDirection, Math.sin(particle.tilt.value) * particle.tilt.sinDirection, 1, pos.x, pos.y ); } else { context.translate(pos.x, pos.y); } if (angle !== 0) { context.rotate(angle); } if (backgroundMask) { context.globalCompositeOperation = composite; } drawShapeAfterEffect(container, context, particle, radius, opacity, delta); context.restore(); } export function drawShape( container: Container, context: CanvasRenderingContext2D, particle: IParticle, radius: number, opacity: number, delta: IDelta ): void { if (!particle.shape) { return; } const drawer = container.drawers.get(particle.shape); if (!drawer) { return; } drawer.draw(context, particle, radius, opacity, delta, container.retina.pixelRatio); } export function drawShapeAfterEffect( container: Container, context: CanvasRenderingContext2D, particle: IParticle, radius: number, opacity: number, delta: IDelta ): void { if (!particle.shape) { return; } const drawer = container.drawers.get(particle.shape); if (!drawer?.afterEffect) { return; } drawer.afterEffect(context, particle, radius, opacity, delta, container.retina.pixelRatio); } export function drawPlugin(context: CanvasRenderingContext2D, plugin: IContainerPlugin, delta: IDelta): void { if (!plugin.draw) { return; } context.save(); plugin.draw(context, delta); context.restore(); } export function drawParticlePlugin( context: CanvasRenderingContext2D, plugin: IContainerPlugin, particle: Particle, delta: IDelta ): void { if (plugin.drawParticle !== undefined) { context.save(); plugin.drawParticle(context, particle, delta); context.restore(); } } export function drawEllipse( context: CanvasRenderingContext2D, particle: IParticle, fillColorValue: IHsl | undefined, radius: number, opacity: number, width: number, rotation: number, start: number, end: number ): void { const pos = particle.getPosition(); if (fillColorValue) { context.strokeStyle = getStyleFromHsl(fillColorValue, opacity); } if (width === 0) { return; } context.lineWidth = width; const rotationRadian = (rotation * Math.PI) / 180; context.beginPath(); context.ellipse(pos.x, pos.y, radius / 2, radius * 2, rotationRadian, start, end); context.stroke(); } export function alterHsl(color: IHsl, type: AlterType, value: number): IHsl { return { h: color.h, s: color.s, l: color.l + (type === AlterType.darken ? -1 : 1) * value, }; }
the_stack
import {select} from "d3-selection"; // // Create the symbols // export function defineSymbols(baseSvg: SVGElement) { const defs = select(baseSvg).append("defs"); // Build the arrow defs.append("svg:marker") .attr("id", "arrow") .attr("viewBox", "0 -5 10 10") .attr("refX", 18) .attr("refY", 0) .attr("markerWidth", 5) .attr("markerHeight", 5) .attr("orient", "auto-start-reverse") .append("svg:path") .attr("d", "M0,-5L10,0L0,5"); // Build the default symbol. Use this symbol if there is not a better fit defs.append("circle") .attr("id", "default-symbol") .attr("class", "qg-symbol-fill-fg") .attr("r", 5); // Build the run query symbol const runQueryGroup = defs.append("g").attr("id", "run-query-symbol"); runQueryGroup .append("circle") .attr("class", "qg-symbol-fill-fg") .attr("r", 6); runQueryGroup .append("path") .attr("class", "qg-run-query") .attr("d", "M-2.5,-3.5L4,0L-2.5,3.5 z"); // Build the Join symbols. They are just 2 overlapped circles for the most part. const radius = 6.0; const leftOffset = -3.0; const rightOffset = 3.0; const leftJoinGroup = defs.append("g").attr("id", "left-join-symbol"); leftJoinGroup .append("circle") .attr("class", "qg-empty-join") .attr("r", radius) .attr("cx", rightOffset); leftJoinGroup .append("circle") .attr("class", "qg-fill-join") .attr("r", radius) .attr("cx", leftOffset); leftJoinGroup .append("circle") .attr("class", "qg-only-stroke-join") .attr("r", radius) .attr("cx", rightOffset); const rightJoinGroup = defs.append("g").attr("id", "right-join-symbol"); rightJoinGroup .append("circle") .attr("class", "qg-empty-join") .attr("r", radius) .attr("cx", leftOffset); rightJoinGroup .append("circle") .attr("class", "qg-fill-join") .attr("r", radius) .attr("cx", rightOffset); rightJoinGroup .append("circle") .attr("class", "qg-only-stroke-join") .attr("r", radius) .attr("cx", leftOffset); const fullJoinGroup = defs.append("g").attr("id", "full-join-symbol"); fullJoinGroup .append("circle") .attr("class", "qg-fill-join qg-symbol-no-stroke") .attr("r", radius) .attr("cx", rightOffset); fullJoinGroup .append("circle") .attr("class", "qg-fill-join") .attr("r", radius) .attr("cx", leftOffset); fullJoinGroup .append("circle") .attr("class", "qg-only-stroke-join") .attr("r", radius) .attr("cx", rightOffset); // Drawing inner joins is more complex. We'll clip a circle (with another circle) to get the intersection shape defs.append("clipPath") .attr("id", "join-clip") .append("circle") .attr("class", "qg-empty-join") .attr("r", radius) .attr("cx", leftOffset); const innerJoinGroup = defs.append("g").attr("id", "inner-join-symbol"); innerJoinGroup .append("circle") .attr("class", "qg-empty-join") .attr("r", radius) .attr("cx", leftOffset); innerJoinGroup .append("circle") .attr("class", "qg-empty-join") .attr("r", radius) .attr("cx", rightOffset); innerJoinGroup .append("circle") .attr("class", "qg-fill-join qg-symbol-no-stroke") .attr("clip-path", "url(#join-clip)") .attr("r", radius) .attr("cx", rightOffset); innerJoinGroup .append("circle") .attr("class", "qg-only-stroke-join") .attr("r", radius) .attr("cx", leftOffset); innerJoinGroup .append("circle") .attr("class", "qg-only-stroke-join") .attr("r", radius) .attr("cx", rightOffset); // Build the table symbol. Made out of several rectangles. const tableRowWidth = 5.2; const tableRowHeight = 2.8; const tableWidth = tableRowWidth * 3; const tableHeight = tableRowHeight * 4; const tableStartLeft = -tableWidth / 2; const tableStartTop = -tableHeight / 2; const tableGroup = defs.append("g").attr("id", "table-symbol"); tableGroup .append("rect") .attr("class", "qg-table-background") .attr("x", tableStartLeft) .attr("width", tableWidth) .attr("y", tableStartTop) .attr("height", tableHeight); tableGroup .append("rect") .attr("class", "qg-table-header") .attr("x", tableStartLeft) .attr("width", tableWidth) .attr("y", tableStartTop) .attr("height", tableRowHeight); tableGroup .append("rect") .attr("class", "qg-table-border") .attr("x", tableStartLeft) .attr("width", tableWidth) .attr("y", 0) .attr("height", tableRowHeight); tableGroup .append("rect") .attr("class", "qg-table-border") .attr("x", -tableRowWidth / 2) .attr("width", tableRowWidth) .attr("y", tableStartTop + tableRowHeight) .attr("height", tableHeight - tableRowHeight); // The filter symbol defs.append("path") .attr("id", "filter-symbol") .attr("class", "qg-symbol-fill-fg") .attr("d", "M-6,-6 L6,-6 L0.8,0 L0.8,5 L-0.8,7 L-0.8,0 Z"); // The sort symbol const sortGroup = defs.append("g").attr("id", "sort-symbol"); sortGroup .append("rect") .attr("class", "qg-symbol-fill-bg qg-symbol-no-stroke") .attr("x", "-8") .attr("y", "-8") .attr("width", "16") .attr("height", "16"); sortGroup .append("path") .attr("class", "qg-symbol-fill-fg") .attr("d", "M6,3 L6,6 L-7,6 L-7,3 Z"); sortGroup .append("path") .attr("class", "qg-symbol-fill-fg") .attr("d", "M0,-2 L0,1 L-7,1 L-7,-2 Z"); sortGroup .append("path") .attr("class", "qg-symbol-fill-fg") .attr("d", "M-3,-7 L-3,-4 L-7,-4 L-7,-7 Z"); sortGroup .append("path") .attr("class", "qg-symbol-fill-fg") .attr("d", "M6,-7 L6,-2 L8,-2 L5.7,0.77 L5.3,0.77 L3,-2 L5,-2 L5,-7 Z"); // Build the additional table symbol, very similar to the regular table symbol function createLabeledTableSymbol(id: string, label: string) { const labeledTableGroup = defs.append("g").attr("id", id); labeledTableGroup .append("rect") .attr("class", "qg-table-background") .attr("x", tableStartLeft) .attr("width", tableWidth) .attr("y", tableStartTop) .attr("height", tableHeight); labeledTableGroup .append("rect") .attr("class", "qg-table-header") .attr("x", tableStartLeft) .attr("width", tableWidth) .attr("y", tableStartTop) .attr("height", tableRowHeight); labeledTableGroup .append("text") .attr("class", "qg-table-text") .attr("y", tableRowHeight + 0.8 /* stroke-width */ / 2) .text(label); } createLabeledTableSymbol("temp-table-symbol", "tmp"); createLabeledTableSymbol("virtual-table-symbol", "dmv"); createLabeledTableSymbol("const-table-symbol", "cnst"); // -- TOOLBAR SYMBOLS -- // Zoom In Symbol const zoomInGroup = defs.append("g").attr("id", "zoom-in-symbol"); zoomInGroup .append("circle") .attr("class", "qg-symbol-fill-bg") .attr("r", 5) .attr("cx", 2) .attr("cy", -2); zoomInGroup .append("path") .attr("class", "qg-magnifier-handle") .attr("d", "M-5,5 -2,2"); zoomInGroup .append("path") .attr("class", "") .attr("d", "m 2,-4.5 v 5 m -2.5,-2.5 h 5"); // Zoom Out Symbol const zoomOutGroup = defs.append("g").attr("id", "zoom-out-symbol"); zoomOutGroup .append("circle") .attr("class", "qg-symbol-fill-bg") .attr("r", 5) .attr("cx", 2) .attr("cy", -2); zoomOutGroup .append("path") .attr("class", "qg-magnifier-handle") .attr("d", "M-5,5 -2,2"); zoomOutGroup .append("path") .attr("class", "") .attr("d", "m -0.5,-2 h 5"); // Rotate 90 degrees left const rotateLeftGroup = defs.append("g").attr("id", "rotate-left-symbol"); rotateLeftGroup .append("path") .attr("class", "qg-symbol-stroke-only") .attr("d", "m -3.53 3.53 a 5 5 0 1 1 7.08 0"); rotateLeftGroup .append("path") .attr("class", "qg-symbol-stroke-only") .attr("d", "m -3.25 0.80 v 2.6 h -2.6"); // Rotate 90 degrees right const rotateRightGroup = defs.append("g").attr("id", "rotate-right-symbol"); rotateRightGroup .append("path") .attr("class", "qg-symbol-stroke-only") .attr("d", "m -3.53 3.53 a 5 5 0 1 1 7.08 0"); rotateRightGroup .append("path") .attr("class", "qg-symbol-stroke-only") .attr("d", "m 3.25 0.80 v 2.6 h 2.6"); // Recenter symbol const recenterGroup = defs.append("g").attr("id", "recenter-symbol"); recenterGroup .append("circle") .attr("class", "qg-symbol-fill-fg") .attr("r", 2); recenterGroup .append("circle") .attr("class", "qg-symbol-stroke-only") .attr("r", 4); recenterGroup .append("path") .attr("class", "qg-symbol-stroke-only") .attr("d", "m -4 0 h -3"); recenterGroup .append("path") .attr("class", "qg-symbol-stroke-only") .attr("d", "m 4 0 h 3"); recenterGroup .append("path") .attr("class", "qg-symbol-stroke-only") .attr("d", "m 0 -4 v -3"); recenterGroup .append("path") .attr("class", "qg-symbol-stroke-only") .attr("d", "m 0 4 v 3"); // Fit to screen symbol const fitScreenGroup = defs.append("g").attr("id", "fit-screen-symbol"); fitScreenGroup .append("path") .attr("class", "qg-symbol-stroke-only") .attr( "d", "m -5 -2 v -3 h 3 m 4 0 h 3 v 3 m 0 4 v 3 h -3 m -4 0 h -3 v -3 M -5 -5 l 3 3 M -5 5 l 3 -3 M 5 -5 l -3 3 M 5 5 l -3 -3", ); }
the_stack
* @file * Support for Render (https://github.com/saalfeldlab/render) servers. */ import {makeDataBoundsBoundingBoxAnnotationSet} from 'neuroglancer/annotation'; import {ChunkManager, WithParameters} from 'neuroglancer/chunk_manager/frontend'; import {makeCoordinateSpace, makeIdentityTransform, makeIdentityTransformedBoundingBox} from 'neuroglancer/coordinate_transform'; import {CompleteUrlOptions, CompletionResult, DataSource, DataSourceProvider, GetDataSourceOptions} from 'neuroglancer/datasource'; import {TileChunkSourceParameters} from 'neuroglancer/datasource/render/base'; import {SliceViewSingleResolutionSource} from 'neuroglancer/sliceview/frontend'; import {DataType, makeVolumeChunkSpecification, VolumeSourceOptions, VolumeType} from 'neuroglancer/sliceview/volume/base'; import {MultiscaleVolumeChunkSource, VolumeChunkSource} from 'neuroglancer/sliceview/volume/frontend'; import {transposeNestedArrays} from 'neuroglancer/util/array'; import {applyCompletionOffset, getPrefixMatchesWithDescriptions} from 'neuroglancer/util/completion'; import {mat4, vec3} from 'neuroglancer/util/geom'; import {fetchOk} from 'neuroglancer/util/http_request'; import {parseArray, parseQueryStringParameters, verifyFloat, verifyObject, verifyObjectProperty, verifyOptionalBoolean, verifyOptionalInt, verifyOptionalString, verifyString} from 'neuroglancer/util/json'; const VALID_ENCODINGS = new Set<string>(['jpg', 'raw16']); const TileChunkSourceBase = WithParameters(VolumeChunkSource, TileChunkSourceParameters); class TileChunkSource extends TileChunkSourceBase {} const VALID_STACK_STATES = new Set<string>(['COMPLETE', 'READ_ONLY']); const PARTIAL_STACK_STATES = new Set<string>(['LOADING']); interface OwnerInfo { owner: string; projects: Map<string, ProjectInfo>; } interface ProjectInfo { stacks: Map<string, StackInfo>; } interface StackInfo { lowerVoxelBound: vec3; upperVoxelBound: vec3; voxelResolution: vec3; /* in nm */ project: string; channels: string[]; } function parseOwnerInfo(obj: any): OwnerInfo { let stackObjs = parseArray(obj, verifyObject); if (stackObjs.length < 1) { throw new Error(`No stacks found for owner object.`); } let projects = new Map<string, ProjectInfo>(); // Get the owner from the first stack let owner = verifyObjectProperty(stackObjs[0], 'stackId', parseStackOwner); for (let stackObj of stackObjs) { let stackName = verifyObjectProperty(stackObj, 'stackId', parseStackName); let stackInfo = parseStackInfo(stackObj); if (stackInfo !== undefined) { let projectName = stackInfo.project; let projectInfo = projects.get(projectName); if (projectInfo === undefined) { let stacks = new Map<string, StackInfo>(); projects.set(projectName, {stacks}); projectInfo = projects.get(projectName); } projectInfo!.stacks.set(stackName, stackInfo); } } return {owner, projects}; } function parseStackName(stackIdObj: any): string { verifyObject(stackIdObj); return verifyObjectProperty(stackIdObj, 'stack', verifyString); } function parseStackOwner(stackIdObj: any): string { verifyObject(stackIdObj); return verifyObjectProperty(stackIdObj, 'owner', verifyString); } function parseStackInfo(obj: any): StackInfo|undefined { verifyObject(obj); let state = verifyObjectProperty(obj, 'state', verifyString); let channels: string[] = []; let lowerVoxelBound: vec3 = vec3.create(); let upperVoxelBound: vec3 = vec3.create(); if (VALID_STACK_STATES.has(state)) { let stackStatsObj = verifyObjectProperty(obj, 'stats', verifyObject); lowerVoxelBound = parseLowerVoxelBounds(stackStatsObj); upperVoxelBound = parseUpperVoxelBounds(stackStatsObj); if (stackStatsObj.hasOwnProperty('channelNames')) { channels = parseChannelNames(stackStatsObj); } } else if (PARTIAL_STACK_STATES.has(state)) { // Stacks in LOADING state will not have a 'stats' object. // Values will be populated from command arguments in MultiscaleVolumeChunkSource() } else { return undefined; } let voxelResolution: vec3 = verifyObjectProperty(obj, 'currentVersion', parseStackVersionInfo); let project: string = verifyObjectProperty(obj, 'stackId', parseStackProject); return {lowerVoxelBound, upperVoxelBound, voxelResolution, project, channels}; } function parseUpperVoxelBounds(stackStatsObj: any): vec3 { verifyObject(stackStatsObj); let stackBounds = verifyObjectProperty(stackStatsObj, 'stackBounds', verifyObject); let upperVoxelBound: vec3 = vec3.create(); upperVoxelBound[0] = verifyObjectProperty(stackBounds, 'maxX', verifyFloat) + 1; upperVoxelBound[1] = verifyObjectProperty(stackBounds, 'maxY', verifyFloat) + 1; upperVoxelBound[2] = verifyObjectProperty(stackBounds, 'maxZ', verifyFloat) + 1; return upperVoxelBound; } function parseLowerVoxelBounds(stackStatsObj: any): vec3 { verifyObject(stackStatsObj); let stackBounds = verifyObjectProperty(stackStatsObj, 'stackBounds', verifyObject); let lowerVoxelBound: vec3 = vec3.create(); lowerVoxelBound[0] = verifyObjectProperty(stackBounds, 'minX', verifyFloat); lowerVoxelBound[1] = verifyObjectProperty(stackBounds, 'minY', verifyFloat); lowerVoxelBound[2] = verifyObjectProperty(stackBounds, 'minZ', verifyFloat); return lowerVoxelBound; } function parseChannelNames(stackStatsObj: any): string[] { verifyObject(stackStatsObj); return verifyObjectProperty(stackStatsObj, 'channelNames', channelNamesObj => { return parseArray(channelNamesObj, verifyString); }); } function parseStackVersionInfo(stackVersionObj: any): vec3 { verifyObject(stackVersionObj); let voxelResolution: vec3 = vec3.create(); try { voxelResolution[0] = verifyObjectProperty(stackVersionObj, 'stackResolutionX', verifyFloat); voxelResolution[1] = verifyObjectProperty(stackVersionObj, 'stackResolutionY', verifyFloat); voxelResolution[2] = verifyObjectProperty(stackVersionObj, 'stackResolutionZ', verifyFloat); } catch (ignoredError) { // default is 1, 1, 1 voxelResolution[0] = 1; voxelResolution[1] = 1; voxelResolution[2] = 1; } return voxelResolution; } function parseStackProject(stackIdObj: any): string { verifyObject(stackIdObj); return verifyObjectProperty(stackIdObj, 'project', verifyString); } class RenderMultiscaleVolumeChunkSource extends MultiscaleVolumeChunkSource { get dataType() { if (this.parameters.encoding === 'raw16') { return DataType.UINT16; } else { // JPEG return DataType.UINT8; } } get volumeType() { return VolumeType.IMAGE; } channel: string|undefined; stack: string; stackInfo: StackInfo; dims: vec3; encoding: string; numLevels: number|undefined; // Render Parameters minIntensity: number|undefined; maxIntensity: number|undefined; // Bounding box override parameters minX: number|undefined; minY: number|undefined; minZ: number|undefined; maxX: number|undefined; maxY: number|undefined; maxZ: number|undefined; // Force limited number of tile specs to render for downsampled views of large projects maxTileSpecsToRender: number|undefined; filter: boolean|undefined; get rank() { return 3; } constructor( chunkManager: ChunkManager, public baseUrl: string, public ownerInfo: OwnerInfo, stack: string|undefined, public project: string, channel: string|undefined, public parameters: {[index: string]: any}) { super(chunkManager); let projectInfo = ownerInfo.projects.get(project); if (projectInfo === undefined) { throw new Error( `Specified project ${JSON.stringify(project)} does not exist for ` + `specified owner ${JSON.stringify(ownerInfo.owner)}`); } if (stack === undefined) { const stackNames = Array.from(projectInfo.stacks.keys()); if (stackNames.length !== 1) { throw new Error(`Dataset contains multiple stacks: ${JSON.stringify(stackNames)}`); } stack = stackNames[0]; } const stackInfo = projectInfo.stacks.get(stack); if (stackInfo === undefined) { throw new Error( `Specified stack ${JSON.stringify(stack)} is not one of the supported stacks: ` + JSON.stringify(Array.from(projectInfo.stacks.keys()))); } this.stack = stack; this.stackInfo = stackInfo; if (channel !== undefined && channel.length > 0) { this.channel = channel; } this.minIntensity = verifyOptionalInt(parameters['minIntensity']); this.maxIntensity = verifyOptionalInt(parameters['maxIntensity']); this.maxTileSpecsToRender = verifyOptionalInt(parameters['maxTileSpecsToRender']); this.filter = verifyOptionalBoolean(parameters['filter']); this.minX = verifyOptionalInt(parameters['minX']); this.minY = verifyOptionalInt(parameters['minY']); this.minZ = verifyOptionalInt(parameters['minZ']); this.maxX = verifyOptionalInt(parameters['maxX']); this.maxY = verifyOptionalInt(parameters['maxY']); this.maxZ = verifyOptionalInt(parameters['maxZ']); if (this.minX !== undefined) { stackInfo.lowerVoxelBound[0] = this.minX; } if (this.minY !== undefined) { stackInfo.lowerVoxelBound[1] = this.minY; } if (this.minZ !== undefined) { stackInfo.lowerVoxelBound[2] = this.minZ; } if (this.maxX !== undefined) { stackInfo.upperVoxelBound[0] = this.maxX; } if (this.maxY !== undefined) { stackInfo.upperVoxelBound[1] = this.maxY; } if (this.maxZ !== undefined) { stackInfo.upperVoxelBound[2] = this.maxZ; } let encoding = verifyOptionalString(parameters['encoding']); if (encoding === undefined) { encoding = 'jpg'; } else { if (!VALID_ENCODINGS.has(encoding)) { throw new Error(`Invalid encoding: ${JSON.stringify(encoding)}.`); } } this.encoding = encoding; this.numLevels = verifyOptionalInt(parameters['numlevels']); this.dims = vec3.create(); let tileSize = verifyOptionalInt(parameters['tilesize']); if (tileSize === undefined) { tileSize = 1024; // Default tile size is 1024 x 1024 } this.dims[0] = tileSize; this.dims[1] = tileSize; this.dims[2] = 1; } getSources(volumeSourceOptions: VolumeSourceOptions) { volumeSourceOptions; const sources: SliceViewSingleResolutionSource<VolumeChunkSource>[][] = []; let numLevels = this.numLevels; if (numLevels === undefined) { numLevels = computeStackHierarchy(this.stackInfo, this.dims[0]); } const {lowerVoxelBound: baseLowerVoxelBound, upperVoxelBound: baseUpperVoxelBound} = this.stackInfo; for (let level = 0; level < numLevels; level++) { const chunkToMultiscaleTransform = mat4.create(); const chunkDataSize = Uint32Array.of(1, 1, 1); // tiles are NxMx1 for (let i = 0; i < 2; ++i) { chunkToMultiscaleTransform[5 * i] = Math.pow(2, level); chunkDataSize[i] = this.dims[i]; } const lowerVoxelBound = vec3.create(), upperVoxelBound = vec3.create(); const lowerClipBound = vec3.create(), upperClipBound = vec3.create(); for (let i = 0; i < 3; i++) { const downsampleFactor = chunkToMultiscaleTransform[5 * i]; const lower = lowerClipBound[i] = baseLowerVoxelBound[i] / downsampleFactor; const upper = upperClipBound[i] = baseUpperVoxelBound[i] / downsampleFactor; lowerVoxelBound[i] = Math.floor(lower); upperVoxelBound[i] = Math.ceil(upper); } const spec = makeVolumeChunkSpecification({ rank: 3, chunkDataSize, dataType: this.dataType, lowerVoxelBound, upperVoxelBound, }); const source = this.chunkManager.getChunkSource(TileChunkSource, { spec, parameters: { 'baseUrl': this.baseUrl, 'owner': this.ownerInfo.owner, 'project': this.stackInfo.project, 'stack': this.stack, 'channel': this.channel, 'minIntensity': this.minIntensity, 'maxIntensity': this.maxIntensity, 'maxTileSpecsToRender': this.maxTileSpecsToRender, 'filter': this.filter, 'dims': `${this.dims[0]}_${this.dims[1]}`, 'level': level, 'encoding': this.encoding, } }); sources.push([{ chunkSource: source, chunkToMultiscaleTransform, lowerClipBound, upperClipBound, }]); } return transposeNestedArrays(sources); } } export function computeStackHierarchy(stackInfo: StackInfo, tileSize: number) { let maxBound = 0; for (let i = 0; i < 2; i++) { maxBound = Math.max(maxBound, stackInfo.upperVoxelBound[i]); } if (tileSize >= maxBound) { return 1; } let counter = 0; while (maxBound > tileSize) { maxBound = maxBound / 2; counter++; } return counter; } export function getOwnerInfo( chunkManager: ChunkManager, hostname: string, owner: string): Promise<OwnerInfo> { return chunkManager.memoize.getUncounted( {'type': 'render:getOwnerInfo', hostname, owner}, () => fetchOk(`${hostname}/render-ws/v1/owner/${owner}/stacks`) .then(response => response.json()) .then(parseOwnerInfo)); } const pathPattern = /^([^\/?]+)(?:\/([^\/?]+))?(?:\/([^\/?]+))(?:\/([^\/?]*))?(?:\?(.*))?$/; const urlPattern = /^((?:(?:(?:http|https):\/\/[^,\/]+)[^\/?]))\/(.*)$/; function getVolume(chunkManager: ChunkManager, datasourcePath: string) { let hostname: string, path: string; { let match = datasourcePath.match(urlPattern); if (match === null) { throw new Error(`Invalid render volume path: ${JSON.stringify(datasourcePath)}`); } hostname = match[1]; path = match[2]; } const match = path.match(pathPattern); if (match === null) { throw new Error(`Invalid volume path ${JSON.stringify(path)}`); } const owner = match[1]; const project = match[2]; const stack = match[3]; const channel = match[4]; const parameters = parseQueryStringParameters(match[5] || ''); return chunkManager.memoize.getUncounted( {type: 'render:MultiscaleVolumeChunkSource', hostname, path}, async () => { const ownerInfo = await getOwnerInfo(chunkManager, hostname, owner); const volume = new RenderMultiscaleVolumeChunkSource( chunkManager, hostname, ownerInfo, stack, project, channel, parameters); const modelSpace = makeCoordinateSpace({ rank: 3, names: ['x', 'y', 'z'], units: ['m', 'm', 'm'], scales: Float64Array.from(volume.stackInfo.voxelResolution, x => x / 1e9), boundingBoxes: [makeIdentityTransformedBoundingBox({ lowerBounds: new Float64Array(volume.stackInfo.lowerVoxelBound), upperBounds: new Float64Array(volume.stackInfo.upperVoxelBound) })], }); const dataSource: DataSource = { modelTransform: makeIdentityTransform(modelSpace), subsources: [ { id: 'default', default: true, subsource: {volume}, }, { id: 'bounds', default: true, subsource: {staticAnnotations: makeDataBoundsBoundingBoxAnnotationSet(modelSpace.bounds)}, } ], }; return dataSource; }); } export async function stackAndProjectCompleter( chunkManager: ChunkManager, hostname: string, path: string): Promise<CompletionResult> { const stackMatch = path.match(/^(?:([^\/]+)(?:\/([^\/]*))?(?:\/([^\/]*))?(\/.*?)?)?$/); if (stackMatch === null) { // URL has incorrect format, don't return any results. throw null; } if (stackMatch[2] === undefined) { // Don't autocomplete the owner throw null; } if (stackMatch[3] === undefined) { let projectPrefix = stackMatch[2] || ''; const ownerInfo = await getOwnerInfo(chunkManager, hostname, stackMatch[1]); let completions = getPrefixMatchesWithDescriptions( projectPrefix, ownerInfo.projects, x => x[0] + '/', () => undefined); return {offset: stackMatch[1].length + 1, completions}; } if (stackMatch[4] === undefined) { let stackPrefix = stackMatch[3] || ''; const ownerInfo = await getOwnerInfo(chunkManager, hostname, stackMatch[1]); let projectInfo = ownerInfo.projects.get(stackMatch[2]); if (projectInfo === undefined) { throw null; } let completions = getPrefixMatchesWithDescriptions(stackPrefix, projectInfo.stacks, x => x[0] + '/', x => { return x[1].project; }); return {offset: stackMatch[1].length + stackMatch[2].length + 2, completions}; } let channelPrefix = stackMatch[4].substr(1) || ''; const ownerInfo = await getOwnerInfo(chunkManager, hostname, stackMatch[1]); let projectInfo = ownerInfo.projects.get(stackMatch[2]); if (projectInfo === undefined) { throw null; } let stackInfo = projectInfo.stacks.get(stackMatch[3]); if (stackInfo === undefined) { throw null; } let channels = stackInfo.channels; if (channels.length === 0) { throw null; } // Try and complete the channel let completions = getPrefixMatchesWithDescriptions(channelPrefix, channels, x => x, () => undefined); return { offset: stackMatch[1].length + stackMatch[2].length + stackMatch[3].length + 3, completions }; } export async function volumeCompleter( url: string, chunkManager: ChunkManager): Promise<CompletionResult> { let match = url.match(urlPattern); if (match === null) { // We don't yet have a full hostname. throw null; } let hostname = match[1]; let path = match[2]; const completions = await stackAndProjectCompleter(chunkManager, hostname, path); return applyCompletionOffset(match![1].length + 1, completions); } export class RenderDataSource extends DataSourceProvider { get description() { return 'Render'; } get(options: GetDataSourceOptions): Promise<DataSource> { return getVolume(options.chunkManager, options.providerUrl); } completeUrl(options: CompleteUrlOptions) { return volumeCompleter(options.providerUrl, options.chunkManager); } }
the_stack
import { createInvalidStateError } from "./dom-exception" import { Event, getEventInternalData } from "./event" import { EventWrapper } from "./event-wrapper" import { Global } from "./global" import { invokeCallback, isCapture, isOnce, isPassive, isRemoved, Listener, } from "./listener" import { addListener, findIndexOfListener, removeListener, removeListenerAt, } from "./listener-list" import { createListenerListMap, ensureListenerList, ListenerListMap, } from "./listener-list-map" import { assertType, format } from "./misc" import { EventListenerWasDuplicated, InvalidEventListener, OptionWasIgnored, } from "./warnings" /** * An implementation of the `EventTarget` interface. * @see https://dom.spec.whatwg.org/#eventtarget */ export class EventTarget< TEventMap extends Record<string, Event> = Record<string, Event>, TMode extends "standard" | "strict" = "standard" > { /** * Initialize this instance. */ constructor() { internalDataMap.set(this, createListenerListMap()) } /** * Add an event listener. * @param type The event type. * @param callback The event listener. * @param options Options. */ addEventListener<T extends string & keyof TEventMap>( type: T, callback?: EventTarget.EventListener<this, TEventMap[T]> | null, options?: EventTarget.AddOptions, ): void /** * Add an event listener. * @param type The event type. * @param callback The event listener. * @param options Options. */ addEventListener( type: string, callback?: EventTarget.FallbackEventListener<this, TMode>, options?: EventTarget.AddOptions, ): void /** * Add an event listener. * @param type The event type. * @param callback The event listener. * @param capture The capture flag. * @deprecated Use `{capture: boolean}` object instead of a boolean value. */ addEventListener<T extends string & keyof TEventMap>( type: T, callback: | EventTarget.EventListener<this, TEventMap[T]> | null | undefined, capture: boolean, ): void /** * Add an event listener. * @param type The event type. * @param callback The event listener. * @param capture The capture flag. * @deprecated Use `{capture: boolean}` object instead of a boolean value. */ addEventListener( type: string, callback: EventTarget.FallbackEventListener<this, TMode>, capture: boolean, ): void // Implementation addEventListener<T extends string & keyof TEventMap>( type0: T, callback0?: EventTarget.EventListener<this, TEventMap[T]> | null, options0?: boolean | EventTarget.AddOptions, ): void { const listenerMap = $(this) const { callback, capture, once, passive, signal, type, } = normalizeAddOptions(type0, callback0, options0) if (callback == null || signal?.aborted) { return } const list = ensureListenerList(listenerMap, type) // Find existing listener. const i = findIndexOfListener(list, callback, capture) if (i !== -1) { warnDuplicate(list.listeners[i], passive, once, signal) return } // Add the new listener. addListener(list, callback, capture, passive, once, signal) } /** * Remove an added event listener. * @param type The event type. * @param callback The event listener. * @param options Options. */ removeEventListener<T extends string & keyof TEventMap>( type: T, callback?: EventTarget.EventListener<this, TEventMap[T]> | null, options?: EventTarget.Options, ): void /** * Remove an added event listener. * @param type The event type. * @param callback The event listener. * @param options Options. */ removeEventListener( type: string, callback?: EventTarget.FallbackEventListener<this, TMode>, options?: EventTarget.Options, ): void /** * Remove an added event listener. * @param type The event type. * @param callback The event listener. * @param capture The capture flag. * @deprecated Use `{capture: boolean}` object instead of a boolean value. */ removeEventListener<T extends string & keyof TEventMap>( type: T, callback: | EventTarget.EventListener<this, TEventMap[T]> | null | undefined, capture: boolean, ): void /** * Remove an added event listener. * @param type The event type. * @param callback The event listener. * @param capture The capture flag. * @deprecated Use `{capture: boolean}` object instead of a boolean value. */ removeEventListener( type: string, callback: EventTarget.FallbackEventListener<this, TMode>, capture: boolean, ): void // Implementation removeEventListener<T extends string & keyof TEventMap>( type0: T, callback0?: EventTarget.EventListener<this, TEventMap[T]> | null, options0?: boolean | EventTarget.Options, ): void { const listenerMap = $(this) const { callback, capture, type } = normalizeOptions( type0, callback0, options0, ) const list = listenerMap[type] if (callback != null && list) { removeListener(list, callback, capture) } } /** * Dispatch an event. * @param event The `Event` object to dispatch. */ dispatchEvent<T extends string & keyof TEventMap>( event: EventTarget.EventData<TEventMap, TMode, T>, ): boolean /** * Dispatch an event. * @param event The `Event` object to dispatch. */ dispatchEvent(event: EventTarget.FallbackEvent<TMode>): boolean // Implementation dispatchEvent( e: | EventTarget.EventData<TEventMap, TMode, string> | EventTarget.FallbackEvent<TMode>, ): boolean { const list = $(this)[String(e.type)] if (list == null) { return true } const event = e instanceof Event ? e : EventWrapper.wrap(e) const eventData = getEventInternalData(event, "event") if (eventData.dispatchFlag) { throw createInvalidStateError("This event has been in dispatching.") } eventData.dispatchFlag = true eventData.target = eventData.currentTarget = this if (!eventData.stopPropagationFlag) { const { cow, listeners } = list // Set copy-on-write flag. list.cow = true // Call listeners. for (let i = 0; i < listeners.length; ++i) { const listener = listeners[i] // Skip if removed. if (isRemoved(listener)) { continue } // Remove this listener if has the `once` flag. if (isOnce(listener) && removeListenerAt(list, i, !cow)) { // Because this listener was removed, the next index is the // same as the current value. i -= 1 } // Call this listener with the `passive` flag. eventData.inPassiveListenerFlag = isPassive(listener) invokeCallback(listener, this, event) eventData.inPassiveListenerFlag = false // Stop if the `event.stopImmediatePropagation()` method was called. if (eventData.stopImmediatePropagationFlag) { break } } // Restore copy-on-write flag. if (!cow) { list.cow = false } } eventData.target = null eventData.currentTarget = null eventData.stopImmediatePropagationFlag = false eventData.stopPropagationFlag = false eventData.dispatchFlag = false return !eventData.canceledFlag } } export namespace EventTarget { /** * The event listener. */ export type EventListener< TEventTarget extends EventTarget<any, any>, TEvent extends Event > = CallbackFunction<TEventTarget, TEvent> | CallbackObject<TEvent> /** * The event listener function. */ export interface CallbackFunction< TEventTarget extends EventTarget<any, any>, TEvent extends Event > { (this: TEventTarget, event: TEvent): void } /** * The event listener object. * @see https://dom.spec.whatwg.org/#callbackdef-eventlistener */ export interface CallbackObject<TEvent extends Event> { handleEvent(event: TEvent): void } /** * The common options for both `addEventListener` and `removeEventListener` methods. * @see https://dom.spec.whatwg.org/#dictdef-eventlisteneroptions */ export interface Options { capture?: boolean } /** * The options for the `addEventListener` methods. * @see https://dom.spec.whatwg.org/#dictdef-addeventlisteneroptions */ export interface AddOptions extends Options { passive?: boolean once?: boolean signal?: AbortSignal | null | undefined } /** * The abort signal. * @see https://dom.spec.whatwg.org/#abortsignal */ export interface AbortSignal extends EventTarget<{ abort: Event }> { readonly aborted: boolean onabort: CallbackFunction<this, Event> | null } /** * The event data to dispatch in strict mode. */ export type EventData< TEventMap extends Record<string, Event>, TMode extends "standard" | "strict", TEventType extends string > = TMode extends "strict" ? IsValidEventMap<TEventMap> extends true ? ExplicitType<TEventType> & Omit<TEventMap[TEventType], keyof Event> & Partial<Omit<Event, "type">> : never : never /** * Define explicit `type` property if `T` is a string literal. * Otherwise, never. */ export type ExplicitType<T extends string> = string extends T ? never : { readonly type: T } /** * The event listener type in standard mode. * Otherwise, never. */ export type FallbackEventListener< TEventTarget extends EventTarget<any, any>, TMode extends "standard" | "strict" > = TMode extends "standard" ? EventListener<TEventTarget, Event> | null | undefined : never /** * The event type in standard mode. * Otherwise, never. */ export type FallbackEvent< TMode extends "standard" | "strict" > = TMode extends "standard" ? Event : never /** * Check if given event map is valid. * It's valid if the keys of the event map are narrower than `string`. */ export type IsValidEventMap<T> = string extends keyof T ? false : true } export { $ as getEventTargetInternalData } //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Internal data for EventTarget */ type EventTargetInternalData = ListenerListMap /** * Internal data. */ const internalDataMap = new WeakMap<any, EventTargetInternalData>() /** * Get private data. * @param target The event target object to get private data. * @param name The variable name to report. * @returns The private data of the event. */ function $(target: any, name = "this"): EventTargetInternalData { const retv = internalDataMap.get(target) assertType( retv != null, "'%s' must be an object that EventTarget constructor created, but got another one: %o", name, target, ) return retv } /** * Normalize options. * @param options The options to normalize. */ function normalizeAddOptions( type: string, callback: EventTarget.EventListener<any, any> | null | undefined, options: boolean | EventTarget.AddOptions | undefined, ): { type: string callback: EventTarget.EventListener<any, any> | undefined capture: boolean passive: boolean once: boolean signal: EventTarget.AbortSignal | undefined } { assertCallback(callback) if (typeof options === "object" && options !== null) { return { type: String(type), callback: callback ?? undefined, capture: Boolean(options.capture), passive: Boolean(options.passive), once: Boolean(options.once), signal: options.signal ?? undefined, } } return { type: String(type), callback: callback ?? undefined, capture: Boolean(options), passive: false, once: false, signal: undefined, } } /** * Normalize options. * @param options The options to normalize. */ function normalizeOptions( type: string, callback: EventTarget.EventListener<any, any> | null | undefined, options: boolean | EventTarget.Options | undefined, ): { type: string callback: EventTarget.EventListener<any, any> | undefined capture: boolean } { assertCallback(callback) if (typeof options === "object" && options !== null) { return { type: String(type), callback: callback ?? undefined, capture: Boolean(options.capture), } } return { type: String(type), callback: callback ?? undefined, capture: Boolean(options), } } /** * Assert the type of 'callback' argument. * @param callback The callback to check. */ function assertCallback(callback: any): void { if ( typeof callback === "function" || (typeof callback === "object" && callback !== null && typeof callback.handleEvent === "function") ) { return } if (callback == null || typeof callback === "object") { InvalidEventListener.warn(callback) return } throw new TypeError(format(InvalidEventListener.message, [callback])) } /** * Print warning for duplicated. * @param listener The current listener that is duplicated. * @param passive The passive flag of the new duplicated listener. * @param once The once flag of the new duplicated listener. * @param signal The signal object of the new duplicated listener. */ function warnDuplicate( listener: Listener, passive: boolean, once: boolean, signal: EventTarget.AbortSignal | undefined, ): void { EventListenerWasDuplicated.warn( isCapture(listener) ? "capture" : "bubble", listener.callback, ) if (isPassive(listener) !== passive) { OptionWasIgnored.warn("passive") } if (isOnce(listener) !== once) { OptionWasIgnored.warn("once") } if (listener.signal !== signal) { OptionWasIgnored.warn("signal") } } // Set enumerable const keys = Object.getOwnPropertyNames(EventTarget.prototype) for (let i = 0; i < keys.length; ++i) { if (keys[i] === "constructor") { continue } Object.defineProperty(EventTarget.prototype, keys[i], { enumerable: true }) } // Ensure `eventTarget instanceof window.EventTarget` is `true`. if ( typeof Global !== "undefined" && typeof Global.EventTarget !== "undefined" ) { Object.setPrototypeOf(EventTarget.prototype, Global.EventTarget.prototype) }
the_stack
import * as vscode from 'vscode'; import * as path from 'path'; import { readFile } from 'fs-extra' import { getRawTasks, getTknTasksSnippets } from './tkn-tasks-provider'; import { schemeStorage } from './tkn-scheme-storage' import { pipelineYaml } from './tkn-yaml'; import { Snippet } from './snippet'; import { getTknConditionsSnippets } from './tkn-conditions-provider'; import { yamlLocator } from './yaml-locator'; import { TknDocument } from '../model/document'; import { Pipeline } from '../model/pipeline/pipeline-model'; import { TknElementType } from '../model/element-type'; import { TknTask } from '../tekton'; const pipelineVariables: Snippet<string>[] = [ { label: '"$(context.pipelineRun.name)"', body: '"$(context.pipelineRun.name)"', description: 'The name of the PipelineRun that this Pipeline is running in.' }, { label: '"$(context.pipelineRun.namespace)"', body: '"$(context.pipelineRun.namespace)"', description: 'The namespace of the PipelineRun that this Pipeline is running in.' }, { label: '"$(context.pipelineRun.uid)"', body: '"$(context.pipelineRun.uid)"', description: 'The uid of the PipelineRun that this Pipeline is running in.' }, { label: '"$(context.pipeline.name)"', body: '"$(context.pipeline.name)"', description: 'The name of this Pipeline.' } ]; export function generateScheme(vsDocument: vscode.TextDocument, schemaPath: string): Promise<string> { return schemeStorage.getScheme(vsDocument, doc => generate(doc, schemaPath)); } // eslint-disable-next-line @typescript-eslint/no-explicit-any function injectTaskSnippets(templateObj: any, snippets: Snippet<{}>[]): {} { snippets.push({ label: 'inline task', description: 'Snippet for inline task', body: { name: '$1', taskSpec: { steps: [ { name: '$2\n', } ] } }, }) templateObj.definitions.PipelineSpec.properties.tasks.defaultSnippets = snippets; return templateObj; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function injectTasksName(templateObj: any, tasks: string[], tasksRef: string[]): {} { templateObj.definitions.PipelineTask.properties.runAfter.items.enum = tasks; //inject names of all tasks deployed in cluster + namespace if (tasksRef && tasksRef.length > 0) { templateObj.definitions.TaskRef.properties.name.enum = tasksRef; } return templateObj; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function injectResourceName(templateObj: any, resNames: string[]): {} { if (resNames && resNames.length > 0) { templateObj.definitions.PipelineTaskInputResource.properties.resource.enum = resNames; templateObj.definitions.PipelineTaskOutputResource.properties.resource.enum = resNames; } return templateObj; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function injectConditionRefs(templateObj: any, conditions: string[]): {} { if (conditions && conditions.length > 0) { templateObj.definitions.PipelineTaskCondition.properties.conditionRef.enum = conditions; } return templateObj; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function injectMarkdownDescription(templateObj: any): {} { templateObj.definitions.Pipeline.properties.apiVersion.markdownDescription = 'Specifies the API version, for example `tekton.dev/v1beta1`. [more](https://kubernetes.io/docs/concepts/overview/working-with-objects/kubernetes-objects/#required-fields)'; templateObj.definitions.Pipeline.properties.kind.markdownDescription = 'Identifies this resource object as a `Pipeline` object. [more](https://kubernetes.io/docs/concepts/overview/working-with-objects/kubernetes-objects/#required-fields)'; templateObj.definitions.Pipeline.properties.metadata.markdownDescription = 'Specifies metadata that uniquely identifies the `Pipeline` object. For example, a `name`. [more](https://kubernetes.io/docs/concepts/overview/working-with-objects/kubernetes-objects/#required-fields)'; templateObj.definitions.Pipeline.properties.spec.markdownDescription = `Specifies the configuration information for this \`Pipeline\` object. This must include: - [\`tasks\`](https://tekton.dev/docs/pipelines/pipelines/#adding-tasks-to-the-pipeline) - Specifies the \`Tasks\` that comprise the \`Pipeline\`; and the details of their execution.`; templateObj.definitions.PipelineSpec.properties.resources.markdownDescription = 'Specifies [`PipelineResources`](https://tekton.dev/docs/pipelines/resources) needed or created by the `Tasks` comprising the `Pipeline`.' templateObj.definitions.PipelineSpec.properties.params.markdownDescription = 'You can specify global parameters, such as compilation flags or artifact names, that you want to supply to the `Pipeline` at execution time. `Parameters` are passed to the `Pipeline` from its corresponding `PipelineRun` and can replace template values specified within each `Task` in the `Pipeline`. [more](https://tekton.dev/docs/pipelines/pipelines/#specifying-parameters)'; templateObj.definitions.PipelineSpec.properties.description.markdownDescription = 'The `description` field is an optional field and can be used to provide description of the `Pipeline`.'; templateObj.definitions.PipelineSpec.properties.tasks.markdownDescription = 'Specifies the `Tasks` that comprise the `Pipeline`. [more](https://tekton.dev/docs/pipelines/pipelines/#adding-tasks-to-the-pipeline)'; templateObj.definitions.PipelineSpec.properties.workspaces.markdownDescription = '`Workspaces` allow you to specify one or more volumes that each `Task` in the `Pipeline` requires during execution. You specify one or more `Workspaces` in the `workspaces` field. [more](https://tekton.dev/docs/pipelines/pipelines/#specifying-workspaces)'; templateObj.definitions.PipelineTask.properties.name.markdownDescription = '`name` is the name of this task within the context of a Pipeline. Name is used as a coordinate with the `from` and `runAfter` fields to establish the execution order of tasks relative to one another.'; templateObj.definitions.PipelineTask.properties.taskRef.markdownDescription = '`taskRef` is a reference to a task definition.'; templateObj.definitions.PipelineTask.properties.taskSpec.markdownDescription = '`taskSpec` is a specification of a task'; templateObj.definitions.PipelineTask.properties.conditions.markdownDescription = 'Specifies `conditions` that only allow a `Task` to execute if they successfully evaluate. [more](https://tekton.dev/docs/pipelines/pipelines/#guard-task-execution-using-conditions)'; templateObj.definitions.PipelineTask.properties.retries.markdownDescription = 'Specifies the number of times to retry the execution of a `Task` after a failure. Does not apply to execution cancellations. [more](https://tekton.dev/docs/pipelines/pipelines/#guard-task-execution-using-conditions)'; templateObj.definitions.PipelineTask.properties.runAfter.markdownDescription = 'Indicates that a `Task` should execute after one or more other `Tasks` without output linking. [more](https://tekton.dev/docs/pipelines/pipelines/#using-the-runafter-parameter)'; templateObj.definitions.PipelineTask.properties.resources.markdownDescription = 'Resources declares the resources given to this task as inputs and outputs.'; templateObj.definitions.PipelineTask.properties.params.markdownDescription = 'Parameters declares parameters passed to this task.'; templateObj.definitions.PipelineTask.properties.workspaces.markdownDescription = 'Workspaces maps workspaces from the pipeline spec to the workspaces declared in the Task.'; templateObj.definitions.PipelineTask.properties.timeout.markdownDescription = 'Time after which the TaskRun times out. Defaults to 1 hour. Specified TaskRun timeout should be less than 24h.' return templateObj; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function injectVariables(templateObj: any, docs: TknDocument[], tasks: TknTask[]): unknown { const snippets: Snippet<string>[] = []; const taskMap = new Map<string, TknTask>(); for (const task of tasks) { taskMap.set(task.metadata.name, task); } for (const doc of docs) { if (doc.getChildren()?.type === TknElementType.PIPELINE) { const pipeline: Pipeline = doc.getChildren(); const params = pipeline.spec.params?.getChildren() ?? []; for (const param of params) { snippets.push({ label: `"$(params.${param.name?.value})"`, body: `"$(params.${param.name?.value})"`, description: 'The value of the parameter at runtime.' }); } const workspaces = pipeline.spec.workspaces?.getChildren() ?? []; for (const ws of workspaces) { snippets.push({ label: `"$(workspaces.${ws.name?.value}.bound)"`, body: `"$(workspaces.${ws.name?.value}.bound)"`, description: 'Whether a Workspace has been bound or not. "false" if the Workspace declaration has optional: true and the Workspace binding was omitted by the PipelineRun.' }); } for (const task of pipeline.spec.tasks.getChildren()){ if (taskMap.has(task.taskRef?.name?.value)){ const rawTask = taskMap.get(task.taskRef.name.value); if (rawTask.spec.results) { for (const res of rawTask.spec.results) { snippets.push({ label: `"$(tasks.${task.name.value}.results.${res.name})"`, body: `"$(tasks.${task.name.value}.results.${res.name})"`, description: res.description }); } } } } } } templateObj.definitions.Param.properties.value.defaultSnippets = [ ...pipelineVariables, ...snippets ]; templateObj.definitions.PipelineResult.properties.value.defaultSnippets = [ ...pipelineVariables, ...snippets ]; templateObj.definitions.PipelineTask.properties.when.items.properties.input.defaultSnippets = [ ...pipelineVariables, ...snippets ]; return templateObj; } async function generate(doc: vscode.TextDocument, schemaPath: string): Promise<string> { const template = await readFile(schemaPath, 'UTF8'); if (schemaPath.endsWith(path.join('tekton.dev', 'v1beta1_Pipeline.json'))) { const snippets = await getTknTasksSnippets(); const conditions = await getTknConditionsSnippets(); const definedTasks = pipelineYaml.getPipelineTasksName(doc); const declaredResources = pipelineYaml.getDeclaredResources(doc); const yamlDocs = yamlLocator.getTknDocuments(doc); const clusterTasks = await getRawTasks(); const resNames = declaredResources.map(item => item.name); const templateObj = JSON.parse(template); let templateWithSnippets = injectTaskSnippets(templateObj, [...snippets]); const tasksRef = snippets.map(value => value.body.taskRef.name); const customTasks = pipelineYaml.getCustomTasks(doc); if (customTasks.length > 0){ tasksRef.push(...customTasks); } templateWithSnippets = injectTasksName(templateWithSnippets, definedTasks, tasksRef); templateWithSnippets = injectResourceName(templateWithSnippets, resNames); templateWithSnippets = injectConditionRefs(templateWithSnippets, conditions); templateWithSnippets = injectMarkdownDescription(templateWithSnippets); templateWithSnippets = injectVariables(templateWithSnippets, yamlDocs, clusterTasks); return JSON.stringify(templateWithSnippets); } return template; }
the_stack
import global from '../../../src/shim/global'; import String, * as stringUtil from '../../../src/shim/string'; const { registerSuite } = intern.getInterface('object'); const { assert } = intern.getPlugin('chai'); function testCodePointAt(text: string, codePoint?: number, expected?: number) { assert.strictEqual(stringUtil.codePointAt(text, codePoint as any), expected); if (typeof codePoint !== 'undefined') { assert.strictEqual(text.codePointAt(codePoint), expected); } } function getPositionAndExpected( position: number | boolean | undefined, expected?: boolean ): { positionArg: number | undefined; expectedValue: boolean } { let positionArg: number | undefined = position as any; let expectedValue = expected; if (arguments.length === 1) { expectedValue = position as any; positionArg = undefined; } return { positionArg, expectedValue: Boolean(expectedValue) }; } function testEndsWith(text: string, endsWith: string, position: number | boolean | undefined, expected?: boolean) { const { expectedValue, positionArg } = getPositionAndExpected(position, expected); assert.strictEqual(stringUtil.endsWith(text, endsWith, positionArg), expectedValue); assert.strictEqual(text.endsWith(endsWith, positionArg), expectedValue); } function testFromCodePoint(codePoints: number[], expected: string) { assert.equal(stringUtil.fromCodePoint(...codePoints), expected); assert.equal(String.fromCodePoint(...codePoints), expected); } function testInclude(text: string, includes: string, position: number | boolean | undefined, expected?: boolean) { const { positionArg, expectedValue } = getPositionAndExpected(position, expected); assert.strictEqual(stringUtil.includes(text, includes, positionArg), expectedValue); assert.strictEqual(text.includes(includes, positionArg), expectedValue); } function testStartsWith(text: string, startsWith: string, position: number | boolean | undefined, expected?: boolean) { const { positionArg, expectedValue } = getPositionAndExpected(position, expected); assert.strictEqual(stringUtil.startsWith(text, startsWith, positionArg), expectedValue); assert.strictEqual(text.startsWith(startsWith, positionArg), expectedValue); } function testPadEnd(text: string, maxLength: number, fillString?: string, expected?: string) { if (expected === undefined) { expected = fillString; fillString = undefined; } assert.strictEqual(stringUtil.padEnd(text, maxLength, fillString), expected); assert.strictEqual(text.padEnd(maxLength, fillString), expected); } function testPadStart(text: string, maxLength: number, fillString?: string, expected?: string) { if (expected === undefined) { expected = fillString; fillString = undefined; } assert.strictEqual(stringUtil.padStart(text, maxLength, fillString), expected); assert.strictEqual(text.padStart(maxLength, fillString), expected); } registerSuite('shim - string functions', { polyfill() { assert.equal(String, global.String); }, '.codePointAt()': { 'throws on undefined or null string'() { assert.throws(function() { stringUtil.codePointAt(<any>undefined, <any>undefined); }, TypeError); assert.throws(function() { stringUtil.codePointAt(<any>null, <any>undefined); }, TypeError); }, 'string starting with a BMP symbol'() { const text = 'abc\uD834\uDF06def'; // Cases expected to return the first code point (i.e. position 0) testCodePointAt(text, undefined, 0x61); testCodePointAt(text, 0, 0x61); testCodePointAt(text, NaN, 0x61); testCodePointAt(text, <any>null, 0x61); testCodePointAt(text, <any>undefined, 0x61); // Cases expected to return undefined (i.e. position out of range) testCodePointAt(text, -Infinity, <any>undefined); testCodePointAt(text, Infinity, <any>undefined); testCodePointAt(text, -1, <any>undefined); testCodePointAt(text, 42, <any>undefined); // Test various code points in the string testCodePointAt(text, 3, 0x1d306); testCodePointAt(text, 4, 0xdf06); testCodePointAt(text, 5, 0x64); }, 'string starting with an astral symbol'() { const text = '\uD834\uDF06def'; testCodePointAt(text, 0, 0x1d306); testCodePointAt(text, 1, 0xdf06); }, 'lone high/low surrogates'() { testCodePointAt('\uD834abc', 0, 0xd834); testCodePointAt('\uDF06abc', 0, 0xdf06); } }, '.endsWith()': { 'throws on undefined or null string'() { assert.throws(function() { stringUtil.endsWith(<any>undefined, 'abc'); }); assert.throws(function() { stringUtil.endsWith(<any>null, 'abc'); }); }, 'null or undefined search value'() { testEndsWith('undefined', <any>undefined, true); testEndsWith('undefined', <any>null, false); testEndsWith('null', <any>null, true); testEndsWith('null', <any>undefined, false); }, 'position is Infinity, not included, or NaN'() { testEndsWith('abc', '', Infinity, true); testEndsWith('abc', '\0', Infinity, false); testEndsWith('abc', 'c', Infinity, true); testEndsWith('abc', 'b', Infinity, false); testEndsWith('abc', 'bc', Infinity, true); testEndsWith('abc', 'abc', Infinity, true); testEndsWith('abc', 'abcd', Infinity, false); testEndsWith('abc', '', undefined, true); testEndsWith('abc', '\0', undefined, false); testEndsWith('abc', 'c', undefined, true); testEndsWith('abc', 'b', undefined, false); testEndsWith('abc', 'bc', undefined, true); testEndsWith('abc', 'abc', undefined, true); testEndsWith('abc', 'abcd', undefined, false); testEndsWith('abc', '', null as any, true); testEndsWith('abc', '\0', null as any, false); testEndsWith('abc', 'c', null as any, false); testEndsWith('abc', 'b', null as any, false); testEndsWith('abc', 'bc', null as any, false); testEndsWith('abc', 'abc', null as any, false); testEndsWith('abc', 'abcd', null as any, false); testEndsWith('abc', '', NaN, true); testEndsWith('abc', '\0', NaN, false); testEndsWith('abc', 'c', NaN, false); testEndsWith('abc', 'b', NaN, false); testEndsWith('abc', 'bc', NaN, false); testEndsWith('abc', 'abc', NaN, false); testEndsWith('abc', 'abcd', NaN, false); }, 'position is 0 or negative'() { let counts = [0, -1]; for (let count of counts) { testEndsWith('abc', '', count, true); testEndsWith('abc', '\0', count, false); testEndsWith('abc', 'a', count, false); testEndsWith('abc', 'b', count, false); testEndsWith('abc', 'ab', count, false); testEndsWith('abc', 'abc', count, false); testEndsWith('abc', 'abcd', count, false); } }, 'position is 1'() { testEndsWith('abc', '', 1, true); testEndsWith('abc', '\0', 1, false); testEndsWith('abc', 'a', 1, true); testEndsWith('abc', 'b', 1, false); testEndsWith('abc', 'bc', 1, false); testEndsWith('abc', 'abc', 1, false); testEndsWith('abc', 'abcd', 1, false); }, 'unicode support'() { testEndsWith('\xA2fa\xA3', 'fa\xA3', true); testEndsWith('\xA2fa', '\xA2', 1, true); testEndsWith('\xA2fa\uDA04', '\xA2fa\uDA04', true); testEndsWith('\xA2fa\uDA04', 'fa', 3, true); testEndsWith('\xA2fa\uDA04', '\uDA04', true); } }, '.fromCodePoint()': { 'error cases'() { let codePoints = [-1, 0x10ffff + 1, 3.14, 3e-2, Infinity, -Infinity, NaN, <any>undefined]; let codePoint: any; for (codePoint of codePoints) { assert.throws(function() { stringUtil.fromCodePoint(codePoint); }, RangeError); } }, 'basic cases'() { testFromCodePoint([<any>null], '\0'); testFromCodePoint([0], '\0'); testFromCodePoint([], ''); testFromCodePoint([0x1d306], '\uD834\uDF06'); testFromCodePoint([0x1d306, 0x61, 0x1d307], '\uD834\uDF06a\uD834\uDF07'); testFromCodePoint([0x61, 0x62, 0x1d307], 'ab\uD834\uDF07'); }, 'test that valid cases do not throw'() { let counter = (Math.pow(2, 15) * 3) / 2; let oneUnitArgs: number[] = []; let twoUnitArgs: number[] = []; while (--counter >= 0) { oneUnitArgs.push(0); // one code unit per symbol twoUnitArgs.push(0xffff + 1); // two code units per symbol } assert.doesNotThrow(function() { stringUtil.fromCodePoint.apply(null, oneUnitArgs); stringUtil.fromCodePoint.apply(null, twoUnitArgs); String.fromCodePoint.apply(null, oneUnitArgs); String.fromCodePoint.apply(null, twoUnitArgs); }); } }, '.includes()': { 'throws on undefined or null string'() { assert.throws(function() { stringUtil.includes(<any>undefined, 'abc'); }); assert.throws(function() { stringUtil.includes(<any>null, 'abc'); }); }, 'null or undefined search value'() { testInclude('undefined', <any>undefined, true); testInclude('undefined', <any>null, false); testInclude('null', <any>null, true); testInclude('null', <any>undefined, false); }, 'position is 0 (whether explicitly, by default, or due to NaN or negative)'() { let counts = [0, -1, NaN, <any>undefined, null]; for (let count of counts) { testInclude('abc', '', count, true); testInclude('abc', '\0', count, false); testInclude('abc', 'a', count, true); testInclude('abc', 'b', count, true); testInclude('abc', 'ab', count, true); testInclude('abc', 'abc', count, true); testInclude('abc', 'abcd', count, false); } }, 'position is Infinity'() { testInclude('abc', '', Infinity, true); testInclude('abc', '\0', Infinity, false); testInclude('abc', 'a', Infinity, false); testInclude('abc', 'b', Infinity, false); testInclude('abc', 'ab', Infinity, false); testInclude('abc', 'abc', Infinity, false); testInclude('abc', 'abcd', Infinity, false); }, 'position is 1'() { testInclude('abc', '', 1, true); testInclude('abc', '\0', 1, false); testInclude('abc', 'a', 1, false); testInclude('abc', 'b', 1, true); testInclude('abc', 'bc', 1, true); testInclude('abc', 'abc', 1, false); testInclude('abc', 'abcd', 1, false); }, 'unicode support'() { testInclude('\xA2fa', '\xA2', true); testInclude('\xA2fa', 'fa', 1, true); testInclude('\xA2fa\uDA04', '\xA2fa\uDA04', true); testInclude('\xA2fa\uDA04', 'fa\uDA04', 1, true); testInclude('\xA2fa\uDA04', '\uDA04', 3, true); } }, '.raw()': { 'error cases'() { assert.throws(function() { stringUtil.raw(<any>null); }, TypeError); }, 'basic tests'() { let answer = 42; assert.strictEqual( stringUtil.raw`The answer is:\n${answer}`, 'The answer is:\\n42', 'stringUtil.raw applied to template string should result in expected value' ); assert.strictEqual( String.raw`The answer is:\n${answer}`, 'The answer is:\\n42', 'stringUtil.raw applied to template string should result in expected value' ); function getCallSite(callSite: TemplateStringsArray, ...substitutions: any[]): TemplateStringsArray { const result = [...callSite]; (result as any).raw = callSite.raw; return result as any; } let callSite = getCallSite`The answer is:\n${answer}`; assert.strictEqual( stringUtil.raw(callSite), 'The answer is:\\n', 'stringUtil.raw applied with insufficient arguments should result in no substitution' ); assert.strictEqual( String.raw(callSite), 'The answer is:\\n', 'stringUtil.raw applied with insufficient arguments should result in no substitution' ); (callSite as any).raw = ['The answer is:\\n']; assert.strictEqual( stringUtil.raw(callSite, 42), 'The answer is:\\n', 'stringUtil.raw applied with insufficient raw fragments should result in truncation before substitution' ); assert.strictEqual( String.raw(callSite, 42), 'The answer is:\\n', 'stringUtil.raw applied with insufficient raw fragments should result in truncation before substitution' ); } }, '.repeat()': { 'throws on undefined or null string'() { assert.throws(function() { stringUtil.repeat(<any>undefined, <any>undefined); }, TypeError); assert.throws(function() { stringUtil.repeat(<any>null, <any>null); }, TypeError); }, 'throws on negative or infinite count'() { let counts = [-Infinity, -1, Infinity]; let count: number; for (count of counts) { assert.throws(function() { stringUtil.repeat('abc', count); }, RangeError); assert.throws(function() { 'abc'.repeat(count); }, RangeError); } }, 'returns empty string when passed 0, NaN, or no count'() { assert.strictEqual((stringUtil.repeat as any)('abc'), ''); let counts = [<any>undefined, null, 0, NaN]; for (let count of counts) { assert.strictEqual(stringUtil.repeat('abc', count), ''); assert.strictEqual('abc'.repeat(count), ''); } }, 'returns expected string for positive numbers'() { assert.strictEqual(stringUtil.repeat('abc', 1), 'abc'); assert.strictEqual(stringUtil.repeat('abc', 2), 'abcabc'); assert.strictEqual(stringUtil.repeat('abc', 3), 'abcabcabc'); assert.strictEqual(stringUtil.repeat('abc', 4), 'abcabcabcabc'); assert.strictEqual('abc'.repeat(1), 'abc'); assert.strictEqual('abc'.repeat(2), 'abcabc'); assert.strictEqual('abc'.repeat(3), 'abcabcabc'); assert.strictEqual('abc'.repeat(4), 'abcabcabcabc'); } }, '.startsWith()': { 'throws on undefined or null string'() { assert.throws(function() { stringUtil.startsWith(<any>undefined, 'abc'); }); assert.throws(function() { stringUtil.startsWith(<any>null, 'abc'); }); }, 'null or undefined search value'() { testStartsWith('undefined', <any>undefined, true); testStartsWith('undefined', <any>null, false); testStartsWith('null', <any>null, true); testStartsWith('null', <any>undefined, false); }, 'position is 0 (whether explicitly, by default, or due to NaN or negative)'() { let counts = [0, -1, NaN, <any>undefined, null]; for (let count of counts) { testStartsWith('abc', '', count, true); testStartsWith('abc', '\0', count, false); testStartsWith('abc', 'a', count, true); testStartsWith('abc', 'b', count, false); testStartsWith('abc', 'ab', count, true); testStartsWith('abc', 'abc', count, true); testStartsWith('abc', 'abcd', count, false); } }, 'position is Infinity'() { testStartsWith('abc', '', Infinity, true); testStartsWith('abc', '\0', Infinity, false); testStartsWith('abc', 'a', Infinity, false); testStartsWith('abc', 'b', Infinity, false); testStartsWith('abc', 'ab', Infinity, false); testStartsWith('abc', 'abc', Infinity, false); testStartsWith('abc', 'abcd', Infinity, false); }, 'position is 1'() { testStartsWith('abc', '', 1, true); testStartsWith('abc', '\0', 1, false); testStartsWith('abc', 'a', 1, false); testStartsWith('abc', 'b', 1, true); testStartsWith('abc', 'bc', 1, true); testStartsWith('abc', 'abc', 1, false); testStartsWith('abc', 'abcd', 1, false); }, 'unicode support'() { testStartsWith('\xA2fa', '\xA2', true); testStartsWith('\xA2fa', 'fa', 1, true); testStartsWith('\xA2fa\uDA04', '\xA2fa\uDA04', true); testStartsWith('\xA2fa\uDA04', 'fa\uDA04', 1, true); testStartsWith('\xA2fa\uDA04', '\uDA04', 3, true); } }, '.padEnd()': { 'null/undefined string'() { assert.throws(() => { stringUtil.padEnd(<any>null, 12); }); assert.throws(() => { stringUtil.padEnd(<any>undefined, 12); }); }, 'null/undefined/invalid length'() { testPadEnd('test', <any>null, 'test'); testPadEnd('test', <any>undefined, 'test'); testPadEnd('test', -1, 'test'); assert.throws(() => { stringUtil.padEnd('', Infinity); }); assert.throws(() => { ''.padEnd(Infinity); }); }, 'padEnd()'() { testPadEnd('', 10, ' '); testPadEnd('test', 5, 'test '); testPadEnd('test', 10, 'test', 'testtestte'); testPadEnd('test', 3, 'padding', 'test'); } }, '.padStart()': { 'null/undefined string'() { assert.throws(() => { stringUtil.padStart(<any>null, 12); }); assert.throws(() => { stringUtil.padStart(<any>undefined, 12); }); }, 'null/undefined/invalid length'() { testPadStart('test', <any>null, 'test'); testPadStart('test', <any>undefined, 'test'); testPadStart('test', -1, 'test'); assert.throws(() => { stringUtil.padStart('', Infinity); }); assert.throws(() => { ''.padStart(Infinity); }); }, 'padStart()'() { testPadStart('', 10, ' '); testPadStart('test', 5, ' test'); testPadStart('test', 10, 'test', 'testtetest'); testPadStart('test', 3, 'padding', 'test'); } } });
the_stack
import { ArrayHelper, Convert, StringHelper } from "../ExtensionMethods"; import { DateTime } from '../DateTime'; import { Dictionary } from '../AltDictionary'; import { EwsLogging } from '../Core/EwsLogging'; import { EwsServiceJsonReader } from '../Core/EwsServiceJsonReader'; import { EwsServiceXmlWriter } from "../Core/EwsServiceXmlWriter"; import { EwsUtilities } from '../Core/EwsUtilities'; import { ExchangeService } from "../Core/ExchangeService"; import { ExchangeServiceBase } from "../Core/ExchangeServiceBase"; import { IOutParam } from '../Interfaces/IOutParam'; import { IRefParam } from '../Interfaces/IRefParam'; import { ServiceLocalException } from '../Exceptions/ServiceLocalException'; import { Strings } from '../Strings'; import { UserConfigurationDictionaryObjectType } from "../Enumerations/UserConfigurationDictionaryObjectType"; import { XmlAttributeNames } from "../Core/XmlAttributeNames"; import { XmlElementNames } from "../Core/XmlElementNames"; import { XmlNamespace } from "../Enumerations/XmlNamespace"; import { ComplexProperty } from "./ComplexProperty"; /** * Represents a user configuration's Dictionary property. * * @sealed */ export class UserConfigurationDictionary extends ComplexProperty {//IEnumerable, IJsonCollectionDeserializer /** * required before initializing new UserConfigurationDictionary */ public static _dictionaryKeyPicker: (key) => string = (key) => { return key ? key.toString() : '' } private dictionary: Dictionary<any, any> = null; private isDirty: boolean = false; /** * Gets the number of elements in the user configuration dictionary. */ get Count(): number { return this.dictionary.Count; } /** * @internal Gets or sets the isDirty flag. */ get IsDirty(): boolean { return this.isDirty; } set IsDirty(value: boolean) { this.isDirty = value; } /** * @internal Initializes a new instance of **UserConfigurationDictionary** class. */ constructor() { super(); this.dictionary = new Dictionary<any, any>(UserConfigurationDictionary._dictionaryKeyPicker); } /** * Gets or sets the element with the specified key. * * @param {string | DateTime | boolean | number} key The key of the element to get or set. * @return {DateTime | string | number | boolean | string[] | number[]} The element with the specified key. */ _getItem(key: string | DateTime | boolean | number): DateTime | string | number | boolean | string[] | number[] { return this.dictionary.get(key); } /** * Gets or sets the element with the specified key. * * @param {string | DateTime | boolean | number} key The key of the element to get or set. * @param {DateTime | string | number | boolean | string[] | number[]} value The element value to update at specified key. */ _setItem(key: string | DateTime | boolean | number, value: DateTime | string | number | boolean | string[] | number[]): void { this.ValidateEntry(key, value); this.dictionary.set(key, value); this.Changed(); } /** * Adds an element with the provided key and value to the user configuration dictionary. * * @param {string | DateTime | boolean | number} key The object to use as the key of the element to add. **Restrict usage of byteArray or complex type for key, consider using string and number only**. * @param {DateTime | string | number | boolean | string[] | number[]} value The object to use as the value of the element to add. */ Add(key: string | DateTime | boolean | number, value: DateTime | string | number | boolean | string[] | number[]): void { this.ValidateEntry(key, value); this.dictionary.Add(key, value); this.Changed(); } /** * @internal Instance was changed. */ Changed(): void { super.Changed(); this.isDirty = true; } /** * Removes all items from the user configuration dictionary. */ Clear(): void { if (this.dictionary.Count != 0) { this.dictionary.clear(); this.Changed(); } } /** * Constructs a dictionary object (key or entry value) from the specified type and string list. * * @param {UserConfigurationDictionaryObjectType} type Object type to construct. * @param {string[]} value Value of the dictionary object as a string list * @param {ExchangeService} service The service. * @return {any} Dictionary object. */ private ConstructObject(type: UserConfigurationDictionaryObjectType, value: string[] /*System.Collections.Generic.List<string>*/, service: ExchangeService): any { EwsLogging.Assert( value != null, "UserConfigurationDictionary.ConstructObject", "value is null"); EwsLogging.Assert( (value.length == 1 || type == UserConfigurationDictionaryObjectType.StringArray), "UserConfigurationDictionary.ConstructObject", "value is array but type is not StringArray"); let dictionaryObject: any = null; switch (type) { case UserConfigurationDictionaryObjectType.Boolean: dictionaryObject = Convert.toBool(value[0]); break; case UserConfigurationDictionaryObjectType.Byte: dictionaryObject = Convert.toNumber(value[0]); //info: byte is number, no Byte type in js break; case UserConfigurationDictionaryObjectType.ByteArray: dictionaryObject = value[0]; //Convert.FromBase64String(value[0]); //info: ByteArray is base64 string here, avoiding binary value here break; case UserConfigurationDictionaryObjectType.DateTime: let dateTime: DateTime = service.ConvertUniversalDateTimeStringToLocalDateTime(value[0]); if (dateTime) { dictionaryObject = dateTime; } else { EwsLogging.Assert( false, "UserConfigurationDictionary.ConstructObject", "DateTime is null"); } break; case UserConfigurationDictionaryObjectType.Integer32: dictionaryObject = Convert.toNumber(value[0]); break; case UserConfigurationDictionaryObjectType.Integer64: dictionaryObject = Convert.toNumber(value[0]); break; case UserConfigurationDictionaryObjectType.String: dictionaryObject = value[0]; break; case UserConfigurationDictionaryObjectType.StringArray: dictionaryObject = value; break; case UserConfigurationDictionaryObjectType.UnsignedInteger32: dictionaryObject = Convert.toNumber(value[0]); break; case UserConfigurationDictionaryObjectType.UnsignedInteger64: dictionaryObject = Convert.toNumber(value[0]); break; default: EwsLogging.Assert( false, "UserConfigurationDictionary.ConstructObject", "Type not recognized: " + UserConfigurationDictionaryObjectType[<any>type]); break; } return dictionaryObject; } /** * Determines whether the user configuration dictionary contains an element with the specified key. * * @param {any} key The key to locate in the user configuration dictionary. * @return {boolean} true if the user configuration dictionary contains an element with the key; otherwise false. */ ContainsKey(key: any): boolean { return this.dictionary.containsKey(key); } /** * @internal Loads from XMLJsObject collection to create a new collection item. * * @interface IJsonCollectionDeserializer * * @param {any} jsObjectCollection The json collection. * @param {ExchangeService} service The service. */ CreateFromXMLJsObjectCollection(jsObjectCollection: any, service: ExchangeService): void { let collection: any[] = EwsServiceJsonReader.ReadAsArray(jsObjectCollection, XmlElementNames.DictionaryEntry); for (let jsonEntry of collection) { let parsedKey: any = this.GetDictionaryObject(jsonEntry[XmlElementNames.DictionaryKey], service); let parsedValue: any = this.GetDictionaryObject(jsonEntry[XmlElementNames.DictionaryValue], service); this.dictionary.addUpdate(parsedKey, parsedValue); } } /** * Gets the dictionary object. * * @param {any} jsonObject The json object. * @param {ExchangeService} service The service. * @return {any} the dictionary object */ private GetDictionaryObject(jsonObject: any, service: ExchangeService): any { if (jsonObject == null) { return null; } let type: UserConfigurationDictionaryObjectType = UserConfigurationDictionary.GetObjectType(jsonObject[XmlElementNames.Type]); let values: string[] = this.GetObjectValue(EwsServiceJsonReader.ReadAsArray(jsonObject, XmlElementNames.Value)); return this.ConstructObject(type, values, service); } GetEnumerator(): Dictionary<any, any> { return this.dictionary; } /** * Gets the type of the object. * * @param {string} type The type. * @return {UserConfigurationDictionaryObjectType} UserConfigurationDictionaryObjectType for the string value */ private static GetObjectType(type: string): UserConfigurationDictionaryObjectType { return UserConfigurationDictionaryObjectType[type]; } /** * Gets the object value. * * @param {any[]} valueArray The value array. * @return {string[]} string array from object Array */ private GetObjectValue(valueArray: any[]): string[] /*System.Collections.Generic.List<string>*/ { let stringArray: string[] = []; for (let value of valueArray) { stringArray.push(value as string); } return stringArray; } /** * Gets the type code. * * @param {ExchangeServiceBase} service The service. * @param {any} dictionaryObject The dictionary object. * @param {IRefParam<UserConfigurationDictionaryObjectType>} dictionaryObjectType Type of the dictionary object. * @param {IRefParam<string>} valueAsString The value as string. */ private static GetTypeCode(service: ExchangeServiceBase, dictionaryObject: any, dictionaryObjectType: IRefParam<UserConfigurationDictionaryObjectType>, valueAsString: IRefParam<string>): void { // Handle all other types by TypeCode let typeofDictionaryObject: string = typeof dictionaryObject; if (typeofDictionaryObject === 'string') { dictionaryObjectType.setValue(UserConfigurationDictionaryObjectType.String); valueAsString.setValue(dictionaryObject); } else if (typeofDictionaryObject === 'boolean') { dictionaryObjectType.setValue(UserConfigurationDictionaryObjectType.Boolean); valueAsString.setValue(EwsUtilities.BoolToXSBool(dictionaryObject)); } else if (typeofDictionaryObject === 'number') { let num: number = Convert.toNumber(dictionaryObject); dictionaryObjectType.setValue(UserConfigurationDictionaryObjectType.Integer32); if (num >= 0 && num <= 255) { dictionaryObjectType.setValue(UserConfigurationDictionaryObjectType.Byte); } else if (num < 0 && num < -2147483648) { dictionaryObjectType.setValue(UserConfigurationDictionaryObjectType.Integer64); } else if (num >= 0 && num > 2147483647) { dictionaryObjectType.setValue(UserConfigurationDictionaryObjectType.UnsignedInteger64); } else if (num >= 0 && num <= 2147483647) { dictionaryObjectType.setValue(UserConfigurationDictionaryObjectType.UnsignedInteger32); } valueAsString.setValue(num.toString()); } else if (dictionaryObject instanceof DateTime) { dictionaryObjectType.setValue(UserConfigurationDictionaryObjectType.DateTime); valueAsString.setValue(service.ConvertDateTimeToUniversalDateTimeString(dictionaryObject)); } else { EwsLogging.Assert( false, "UserConfigurationDictionary.WriteObjectValueToXml", "Unsupported type: " + typeof dictionaryObject); } } /** * @internal Loads service object from XML. * * @param {any} jsObject Json Object converted from XML. * @param {ExchangeService} service The service. */ LoadFromXmlJsObject(jsObject: any, service: ExchangeService): void { this.CreateFromXMLJsObjectCollection(jsObject, service); } /** * Removes the element with the specified key from the user configuration dictionary. * * @param {key} key The key of the element to remove. * @return {boolean} true if the element is successfully removed; otherwise false. */ Remove(key: any): boolean { let isRemoved: boolean = this.dictionary.remove(key); if (isRemoved) { this.Changed(); } return isRemoved; } /** * Gets the value associated with the specified key. * * @param {any} key The key whose value to get. * @param {any} value When this method returns, the value associated with the specified key, if the key is found; otherwise, null. * @return {boolean} true if the user configuration dictionary contains the key; otherwise false. */ TryGetValue(key: any, value: IOutParam<any>): boolean { return this.dictionary.tryGetValue(key, value); } /** * @internal Loads from XMLJsObject collection to update collection Items. * * @interface IJsonCollectionDeserializer * * @param {any} jsObjectCollection The XMLJsObject collection. * @param {ExchangeService} service The service. */ UpdateFromXMLJsObjectCollection(jsObjectCollection: any, service: ExchangeService): void { throw new Error("UserConfigurationDictionary.ts - UpdateFromJsonCollection : Not implemented."); } /** * Validate the array object. * * @param {Array<any>} dictionaryObjectAsArray Object to validate */ private ValidateArrayObject(dictionaryObjectAsArray: Array<any> /*System.Array*/): void { // // This logic is based on Microsoft.Exchange.Data.Storage.ConfigurationDictionary.CheckElementSupportedType(). // if (dictionaryObjectAsArray as string[]) { // if (dictionaryObjectAsArray.Length > 0) { // for (let arrayElement of dictionaryObjectAsArray) { // if (arrayElement == null) { // throw new ServiceLocalException(Strings.NullStringArrayElementInvalid); // } // } // } // else { // throw new ServiceLocalException(Strings.ZeroLengthArrayInvalid); // } // } // else if (dictionaryObjectAsArray as byte[]) { // if (dictionaryObjectAsArray.Length <= 0) { // throw new ServiceLocalException(Strings.ZeroLengthArrayInvalid); // } // } // else { // throw new ServiceLocalException(string.Format(Strings.ObjectTypeNotSupported, dictionaryObjectAsArray.GetType())); // } // This logic is based on Microsoft.Exchange.Data.Storage.ConfigurationDictionary.CheckElementSupportedType(). if (dictionaryObjectAsArray.length > 0) { let firstNonEmptyElement = ArrayHelper.Find(dictionaryObjectAsArray, (item) => { return item != null && typeof item !== 'undefined' }); if (!firstNonEmptyElement) { throw new ServiceLocalException(Strings.NullStringArrayElementInvalid); } let arrayType: string = typeof firstNonEmptyElement; if (arrayType !== 'string' && arrayType !== 'number') { throw new ServiceLocalException(StringHelper.Format(Strings.ObjectTypeNotSupported, arrayType)); } for (let arrayElement of dictionaryObjectAsArray) { let elementType: string = typeof arrayElement; if (arrayElement && elementType != arrayType) { throw new ServiceLocalException(StringHelper.Format(Strings.ObjectTypeNotSupported, "<" + elementType + "," + arrayType + ">")); } if (arrayType === 'string' && arrayElement == null) { throw new ServiceLocalException(Strings.NullStringArrayElementInvalid); } } } else { throw new ServiceLocalException(Strings.ZeroLengthArrayInvalid); } } /** * Validates the specified key and value. * * @param {any} key The dictionary entry key. * @param {any} value The dictionary entry value. */ private ValidateEntry(key: any, value: any): void { this.ValidateObject(key); this.ValidateObject(value); } /** * Validates the dictionary object (key or entry value). * * @param {any} dictionaryObject Object to validate. */ private ValidateObject(dictionaryObject: any): void { // Keys may not be null but we rely on the internal dictionary to throw if the key is null. if (dictionaryObject != null) { let dictionaryObjectAsArray: Array<any> = dictionaryObject as Array<any>; if (ArrayHelper.isArray(dictionaryObjectAsArray)) //info: c# "as" keyword does not work here { this.ValidateArrayObject(dictionaryObjectAsArray); } else { this.ValidateObjectType(dictionaryObject); } } } /** * Validates the dictionary object type. * * @param {any} type Type to validate. */ private ValidateObjectType(dictionaryObject: any/*System.Type*/): void { let typeofDictionaryObject: string = typeof dictionaryObject; let type: UserConfigurationDictionaryObjectType = null; if (typeofDictionaryObject === 'string') { type = UserConfigurationDictionaryObjectType.String; } else if (typeofDictionaryObject === 'boolean') { type = UserConfigurationDictionaryObjectType.Boolean; } else if (typeofDictionaryObject === 'number') { let num: number = Convert.toNumber(dictionaryObject); type = UserConfigurationDictionaryObjectType.Integer32; if (num >= 0 && num <= 255) { type = UserConfigurationDictionaryObjectType.Byte; } else if (num < 0 && num < -2147483648) { type = UserConfigurationDictionaryObjectType.Integer64; } else if (num >= 0 && num > 2147483647) { type = UserConfigurationDictionaryObjectType.UnsignedInteger64; } else if (num >= 0 && num <= 2147483647) { type = UserConfigurationDictionaryObjectType.UnsignedInteger32; } } else if (dictionaryObject instanceof DateTime) { type = UserConfigurationDictionaryObjectType.DateTime; } let isValidType: boolean = false; switch (type) { case UserConfigurationDictionaryObjectType.Boolean: case UserConfigurationDictionaryObjectType.Byte: case UserConfigurationDictionaryObjectType.DateTime: case UserConfigurationDictionaryObjectType.Integer32: case UserConfigurationDictionaryObjectType.Integer64: case UserConfigurationDictionaryObjectType.String: case UserConfigurationDictionaryObjectType.UnsignedInteger32: case UserConfigurationDictionaryObjectType.UnsignedInteger64: isValidType = true; break; } if (!isValidType) { throw new ServiceLocalException(StringHelper.Format(Strings.ObjectTypeNotSupported, type)); } } /** * @internal Writes elements to XML. * * @param {EwsServiceXmlWriter} writer The writer. */ WriteElementsToXml(writer: EwsServiceXmlWriter): void { EwsLogging.Assert( writer != null, "UserConfigurationDictionary.WriteElementsToXml", "writer is null"); for (let dictionaryEntry of this.dictionary.Items) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.DictionaryEntry); this.WriteObjectToXml( writer, XmlElementNames.DictionaryKey, dictionaryEntry.key); this.WriteObjectToXml( writer, XmlElementNames.DictionaryValue, dictionaryEntry.value); writer.WriteEndElement(); } } /** * Writes a dictionary entry type to Xml. * * @param {EwsServiceXmlWriter} writer The writer. * @param {UserConfigurationDictionaryObjectType} dictionaryObjectType Type to write. */ private WriteEntryTypeToXml(writer: EwsServiceXmlWriter, dictionaryObjectType: UserConfigurationDictionaryObjectType): void { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Type); writer.WriteValue(UserConfigurationDictionaryObjectType[dictionaryObjectType], XmlElementNames.Type); writer.WriteEndElement(); } /** * Writes a dictionary entry value to Xml. * * @param {EwsServiceXmlWriter} writer The writer. * @param {string} value Value to write. */ private WriteEntryValueToXml(writer: EwsServiceXmlWriter, value: string): void { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Value); // While an entry value can't be null, if the entry is an array, an element of the array can be null. if (value != null) { writer.WriteValue(value, XmlElementNames.Value); } writer.WriteEndElement(); } /** * Writes a dictionary object (key or value) to Xml. * * @param {EwsServiceXmlWriter} writer The writer. * @param {string} xmlElementName The Xml element name. * @param {any} dictionaryObject The object to write. */ private WriteObjectToXml(writer: EwsServiceXmlWriter, xmlElementName: string, dictionaryObject: any): void { EwsLogging.Assert( writer != null, "UserConfigurationDictionary.WriteObjectToXml", "writer is null"); EwsLogging.Assert( xmlElementName != null, "UserConfigurationDictionary.WriteObjectToXml", "xmlElementName is null"); writer.WriteStartElement(XmlNamespace.Types, xmlElementName); if (dictionaryObject == null) { EwsLogging.Assert( xmlElementName != XmlElementNames.DictionaryKey, "UserConfigurationDictionary.WriteObjectToXml", "Key is null"); writer.WriteAttributeValue( EwsUtilities.EwsXmlSchemaInstanceNamespacePrefix, XmlAttributeNames.Nil, EwsUtilities.XSTrue); } else { this.WriteObjectValueToXml(writer, dictionaryObject); } writer.WriteEndElement(); } /** * Writes a dictionary Object's value to Xml. * * @param {EwsServiceXmlWriter} writer The writer. * @param {any} dictionaryObject The dictionary object to write. */ private WriteObjectValueToXml(writer: EwsServiceXmlWriter, dictionaryObject: any): void { EwsLogging.Assert( writer != null, "UserConfigurationDictionary.WriteObjectValueToXml", "writer is null"); EwsLogging.Assert( dictionaryObject != null, "UserConfigurationDictionary.WriteObjectValueToXml", "dictionaryObject is null"); // This logic is based on Microsoft.Exchange.Services.Core.GetUserConfiguration.ConstructDictionaryObject(). // // Object values are either: // . an array of strings // . a single value // // Single values can be: // . base64 string (from a byte array) // . datetime, boolean, byte, short, int, long, string, ushort, unint, ulong // //Assume string value for default let dictionaryObjectType: UserConfigurationDictionaryObjectType = UserConfigurationDictionaryObjectType.String; let valueAsString: string = null; //First check for Array if (ArrayHelper.isArray<any>(dictionaryObject)) { // First check for a string array let dictionaryObjectAsStringArray: string[] = ArrayHelper.OfType<string, string>(dictionaryObject, (item) => { return typeof item === 'string' }); if (dictionaryObjectAsStringArray.length > 0) { //array with string if (dictionaryObjectAsStringArray.length === dictionaryObject.length) { //all array elements are string this.WriteEntryTypeToXml(writer, UserConfigurationDictionaryObjectType.StringArray); for (let arrayElement of dictionaryObjectAsStringArray) { this.WriteEntryValueToXml(writer, arrayElement); } } else { throw new ServiceLocalException(Strings.NullStringArrayElementInvalid); } } else { //check for byte[] for base64 conversion to single element //todo: byte[] conversion to base64 using Buffer let dictionaryObjectAsByteArray: number[] = ArrayHelper.OfType<number, number>(dictionaryObject, (item) => { return typeof item === 'number' }); if (dictionaryObjectAsByteArray.length > 0 && dictionaryObjectAsByteArray.length === dictionaryObject.length) { // Convert byte array to base64 string dictionaryObjectType = UserConfigurationDictionaryObjectType.ByteArray; valueAsString = Convert.ToBase64String(dictionaryObjectAsByteArray); this.WriteEntryTypeToXml(writer, dictionaryObjectType); this.WriteEntryValueToXml(writer, valueAsString); } else { throw new ServiceLocalException(Strings.NullStringArrayElementInvalid); } } } else { // if not a string array, all other object values are returned as a single element let refDictionaryObjectType: IRefParam<UserConfigurationDictionaryObjectType> = { getValue: () => { return dictionaryObjectType; }, setValue: (value) => { dictionaryObjectType = value; } }; let refValueAsString: IRefParam<string> = { getValue: () => { return valueAsString; }, setValue: (value) => { valueAsString = value } }; UserConfigurationDictionary.GetTypeCode(writer.Service, dictionaryObject, refDictionaryObjectType, refValueAsString); this.WriteEntryTypeToXml(writer, refDictionaryObjectType.getValue()); this.WriteEntryValueToXml(writer, refValueAsString.getValue()); } } }
the_stack
import { PoolInfo, PoolStats, RewardStats } from '../mempool.interfaces'; import BlocksRepository from '../repositories/BlocksRepository'; import PoolsRepository from '../repositories/PoolsRepository'; import HashratesRepository from '../repositories/HashratesRepository'; import bitcoinClient from './bitcoin/bitcoin-client'; import logger from '../logger'; import { Common } from './common'; import loadingIndicators from './loading-indicators'; import { escape } from 'mysql2'; class Mining { constructor() { } /** * Get historical block total fee */ public async $getHistoricalBlockFees(interval: string | null = null): Promise<any> { return await BlocksRepository.$getHistoricalBlockFees( this.getTimeRange(interval), Common.getSqlInterval(interval) ); } /** * Get historical block rewards */ public async $getHistoricalBlockRewards(interval: string | null = null): Promise<any> { return await BlocksRepository.$getHistoricalBlockRewards( this.getTimeRange(interval), Common.getSqlInterval(interval) ); } /** * Get historical block fee rates percentiles */ public async $getHistoricalBlockFeeRates(interval: string | null = null): Promise<any> { return await BlocksRepository.$getHistoricalBlockFeeRates( this.getTimeRange(interval), Common.getSqlInterval(interval) ); } /** * Get historical block sizes */ public async $getHistoricalBlockSizes(interval: string | null = null): Promise<any> { return await BlocksRepository.$getHistoricalBlockSizes( this.getTimeRange(interval), Common.getSqlInterval(interval) ); } /** * Get historical block weights */ public async $getHistoricalBlockWeights(interval: string | null = null): Promise<any> { return await BlocksRepository.$getHistoricalBlockWeights( this.getTimeRange(interval), Common.getSqlInterval(interval) ); } /** * Generate high level overview of the pool ranks and general stats */ public async $getPoolsStats(interval: string | null): Promise<object> { const poolsStatistics = {}; const poolsInfo: PoolInfo[] = await PoolsRepository.$getPoolsInfo(interval); const emptyBlocks: any[] = await BlocksRepository.$countEmptyBlocks(null, interval); const poolsStats: PoolStats[] = []; let rank = 1; poolsInfo.forEach((poolInfo: PoolInfo) => { const emptyBlocksCount = emptyBlocks.filter((emptyCount) => emptyCount.poolId === poolInfo.poolId); const poolStat: PoolStats = { poolId: poolInfo.poolId, // mysql row id name: poolInfo.name, link: poolInfo.link, blockCount: poolInfo.blockCount, rank: rank++, emptyBlocks: emptyBlocksCount.length > 0 ? emptyBlocksCount[0]['count'] : 0, slug: poolInfo.slug, }; poolsStats.push(poolStat); }); poolsStatistics['pools'] = poolsStats; const blockCount: number = await BlocksRepository.$blockCount(null, interval); poolsStatistics['blockCount'] = blockCount; const totalBlock24h: number = await BlocksRepository.$blockCount(null, '24h'); try { poolsStatistics['lastEstimatedHashrate'] = await bitcoinClient.getNetworkHashPs(totalBlock24h); } catch (e) { poolsStatistics['lastEstimatedHashrate'] = 0; logger.debug('Bitcoin Core is not available, using zeroed value for current hashrate'); } return poolsStatistics; } /** * Get all mining pool stats for a pool */ public async $getPoolStat(slug: string): Promise<object> { const pool = await PoolsRepository.$getPool(slug); if (!pool) { throw new Error('This mining pool does not exist ' + escape(slug)); } const blockCount: number = await BlocksRepository.$blockCount(pool.id); const totalBlock: number = await BlocksRepository.$blockCount(null, null); const blockCount24h: number = await BlocksRepository.$blockCount(pool.id, '24h'); const totalBlock24h: number = await BlocksRepository.$blockCount(null, '24h'); const blockCount1w: number = await BlocksRepository.$blockCount(pool.id, '1w'); const totalBlock1w: number = await BlocksRepository.$blockCount(null, '1w'); let currentEstimatedHashrate = 0; try { currentEstimatedHashrate = await bitcoinClient.getNetworkHashPs(totalBlock24h); } catch (e) { logger.debug('Bitcoin Core is not available, using zeroed value for current hashrate'); } return { pool: pool, blockCount: { 'all': blockCount, '24h': blockCount24h, '1w': blockCount1w, }, blockShare: { 'all': blockCount / totalBlock, '24h': blockCount24h / totalBlock24h, '1w': blockCount1w / totalBlock1w, }, estimatedHashrate: currentEstimatedHashrate * (blockCount24h / totalBlock24h), reportedHashrate: null, }; } /** * Get miner reward stats */ public async $getRewardStats(blockCount: number): Promise<RewardStats> { return await BlocksRepository.$getBlockStats(blockCount); } /** * [INDEXING] Generate weekly mining pool hashrate history */ public async $generatePoolHashrateHistory(): Promise<void> { const now = new Date(); try { const lastestRunDate = await HashratesRepository.$getLatestRun('last_weekly_hashrates_indexing'); // Run only if: // * lastestRunDate is set to 0 (node backend restart, reorg) // * we started a new week (around Monday midnight) const runIndexing = lastestRunDate === 0 || now.getUTCDay() === 1 && lastestRunDate !== now.getUTCDate(); if (!runIndexing) { return; } } catch (e) { throw e; } try { const indexedTimestamp = await HashratesRepository.$getWeeklyHashrateTimestamps(); const hashrates: any[] = []; const genesisTimestamp = 1231006505000; // bitcoin-cli getblock 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f const lastMonday = new Date(now.setDate(now.getDate() - (now.getDay() + 6) % 7)); const lastMondayMidnight = this.getDateMidnight(lastMonday); let toTimestamp = lastMondayMidnight.getTime(); const totalWeekIndexed = (await BlocksRepository.$blockCount(null, null)) / 1008; let indexedThisRun = 0; let totalIndexed = 0; let newlyIndexed = 0; const startedAt = new Date().getTime() / 1000; let timer = new Date().getTime() / 1000; logger.debug(`Indexing weekly mining pool hashrate`); loadingIndicators.setProgress('weekly-hashrate-indexing', 0); while (toTimestamp > genesisTimestamp) { const fromTimestamp = toTimestamp - 604800000; // Skip already indexed weeks if (indexedTimestamp.includes(toTimestamp / 1000)) { toTimestamp -= 604800000; ++totalIndexed; continue; } // Check if we have blocks for the previous week (which mean that the week // we are currently indexing has complete data) const blockStatsPreviousWeek: any = await BlocksRepository.$blockCountBetweenTimestamp( null, (fromTimestamp - 604800000) / 1000, (toTimestamp - 604800000) / 1000); if (blockStatsPreviousWeek.blockCount === 0) { // We are done indexing break; } const blockStats: any = await BlocksRepository.$blockCountBetweenTimestamp( null, fromTimestamp / 1000, toTimestamp / 1000); const lastBlockHashrate = await bitcoinClient.getNetworkHashPs(blockStats.blockCount, blockStats.lastBlockHeight); let pools = await PoolsRepository.$getPoolsInfoBetween(fromTimestamp / 1000, toTimestamp / 1000); const totalBlocks = pools.reduce((acc, pool) => acc + pool.blockCount, 0); pools = pools.map((pool: any) => { pool.hashrate = (pool.blockCount / totalBlocks) * lastBlockHashrate; pool.share = (pool.blockCount / totalBlocks); return pool; }); for (const pool of pools) { hashrates.push({ hashrateTimestamp: toTimestamp / 1000, avgHashrate: pool['hashrate'], poolId: pool.poolId, share: pool['share'], type: 'weekly', }); } newlyIndexed += hashrates.length; await HashratesRepository.$saveHashrates(hashrates); hashrates.length = 0; const elapsedSeconds = Math.max(1, Math.round((new Date().getTime() / 1000) - timer)); if (elapsedSeconds > 1) { const runningFor = Math.max(1, Math.round((new Date().getTime() / 1000) - startedAt)); const weeksPerSeconds = Math.max(1, Math.round(indexedThisRun / elapsedSeconds)); const progress = Math.round(totalIndexed / totalWeekIndexed * 10000) / 100; const timeLeft = Math.round((totalWeekIndexed - totalIndexed) / weeksPerSeconds); const formattedDate = new Date(fromTimestamp).toUTCString(); logger.debug(`Getting weekly pool hashrate for ${formattedDate} | ~${weeksPerSeconds.toFixed(2)} weeks/sec | total: ~${totalIndexed}/${Math.round(totalWeekIndexed)} (${progress}%) | elapsed: ${runningFor} seconds | left: ~${timeLeft} seconds`); timer = new Date().getTime() / 1000; indexedThisRun = 0; loadingIndicators.setProgress('weekly-hashrate-indexing', progress, false); } toTimestamp -= 604800000; ++indexedThisRun; ++totalIndexed; } await HashratesRepository.$setLatestRun('last_weekly_hashrates_indexing', new Date().getUTCDate()); if (newlyIndexed > 0) { logger.notice(`Weekly mining pools hashrates indexing completed: indexed ${newlyIndexed}`); } loadingIndicators.setProgress('weekly-hashrate-indexing', 100); } catch (e) { loadingIndicators.setProgress('weekly-hashrate-indexing', 100); throw e; } } /** * [INDEXING] Generate daily hashrate data */ public async $generateNetworkHashrateHistory(): Promise<void> { try { // We only run this once a day around midnight const latestRunDate = await HashratesRepository.$getLatestRun('last_hashrates_indexing'); const now = new Date().getUTCDate(); if (now === latestRunDate) { return; } } catch (e) { throw e; } try { const indexedTimestamp = (await HashratesRepository.$getNetworkDailyHashrate(null)).map(hashrate => hashrate.timestamp); const genesisTimestamp = 1231006505000; // bitcoin-cli getblock 000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f const lastMidnight = this.getDateMidnight(new Date()); let toTimestamp = Math.round(lastMidnight.getTime()); const hashrates: any[] = []; const totalDayIndexed = (await BlocksRepository.$blockCount(null, null)) / 144; let indexedThisRun = 0; let totalIndexed = 0; let newlyIndexed = 0; const startedAt = new Date().getTime() / 1000; let timer = new Date().getTime() / 1000; logger.debug(`Indexing daily network hashrate`); loadingIndicators.setProgress('daily-hashrate-indexing', 0); while (toTimestamp > genesisTimestamp) { const fromTimestamp = toTimestamp - 86400000; // Skip already indexed weeks if (indexedTimestamp.includes(toTimestamp / 1000)) { toTimestamp -= 86400000; ++totalIndexed; continue; } // Check if we have blocks for the previous day (which mean that the day // we are currently indexing has complete data) const blockStatsPreviousDay: any = await BlocksRepository.$blockCountBetweenTimestamp( null, (fromTimestamp - 86400000) / 1000, (toTimestamp - 86400000) / 1000); if (blockStatsPreviousDay.blockCount === 0) { // We are done indexing break; } const blockStats: any = await BlocksRepository.$blockCountBetweenTimestamp( null, fromTimestamp / 1000, toTimestamp / 1000); const lastBlockHashrate = await bitcoinClient.getNetworkHashPs(blockStats.blockCount, blockStats.lastBlockHeight); hashrates.push({ hashrateTimestamp: toTimestamp / 1000, avgHashrate: lastBlockHashrate, poolId: 0, share: 1, type: 'daily', }); if (hashrates.length > 10) { newlyIndexed += hashrates.length; await HashratesRepository.$saveHashrates(hashrates); hashrates.length = 0; } const elapsedSeconds = Math.max(1, Math.round((new Date().getTime() / 1000) - timer)); if (elapsedSeconds > 1) { const runningFor = Math.max(1, Math.round((new Date().getTime() / 1000) - startedAt)); const daysPerSeconds = Math.max(1, Math.round(indexedThisRun / elapsedSeconds)); const progress = Math.round(totalIndexed / totalDayIndexed * 10000) / 100; const timeLeft = Math.round((totalDayIndexed - totalIndexed) / daysPerSeconds); const formattedDate = new Date(fromTimestamp).toUTCString(); logger.debug(`Getting network daily hashrate for ${formattedDate} | ~${daysPerSeconds.toFixed(2)} days/sec | total: ~${totalIndexed}/${Math.round(totalDayIndexed)} (${progress}%) | elapsed: ${runningFor} seconds | left: ~${timeLeft} seconds`); timer = new Date().getTime() / 1000; indexedThisRun = 0; loadingIndicators.setProgress('daily-hashrate-indexing', progress); } toTimestamp -= 86400000; ++indexedThisRun; ++totalIndexed; } // Add genesis block manually if (toTimestamp <= genesisTimestamp && !indexedTimestamp.includes(genesisTimestamp)) { hashrates.push({ hashrateTimestamp: genesisTimestamp, avgHashrate: await bitcoinClient.getNetworkHashPs(1, 1), poolId: null, type: 'daily', }); } newlyIndexed += hashrates.length; await HashratesRepository.$saveHashrates(hashrates); await HashratesRepository.$setLatestRun('last_hashrates_indexing', new Date().getUTCDate()); if (newlyIndexed > 0) { logger.notice(`Daily network hashrate indexing completed: indexed ${newlyIndexed} days`); } loadingIndicators.setProgress('daily-hashrate-indexing', 100); } catch (e) { loadingIndicators.setProgress('daily-hashrate-indexing', 100); throw e; } } private getDateMidnight(date: Date): Date { date.setUTCHours(0); date.setUTCMinutes(0); date.setUTCSeconds(0); date.setUTCMilliseconds(0); return date; } private getTimeRange(interval: string | null): number { switch (interval) { case '3y': return 43200; // 12h case '2y': return 28800; // 8h case '1y': return 28800; // 8h case '6m': return 10800; // 3h case '3m': return 7200; // 2h case '1m': return 1800; // 30min case '1w': return 300; // 5min case '3d': return 1; case '24h': return 1; default: return 86400; // 24h } } } export default new Mining();
the_stack
import '@aws-cdk/assert-internal/jest'; import * as ecs from '@aws-cdk/aws-ecs'; import * as sns from '@aws-cdk/aws-sns'; import * as sqs from '@aws-cdk/aws-sqs'; import * as cdk from '@aws-cdk/core'; import { Container, Environment, QueueExtension, Service, ServiceDescription, TopicSubscription } from '../lib'; describe('queue', () => { test('should only create a default queue when no input props are provided', () => { // GIVEN const stack = new cdk.Stack(); const environment = new Environment(stack, 'production'); const serviceDescription = new ServiceDescription(); serviceDescription.add(new Container({ cpu: 256, memoryMiB: 512, trafficPort: 80, image: ecs.ContainerImage.fromRegistry('nathanpeck/name'), environment: { PORT: '80', }, })); // WHEN serviceDescription.add(new QueueExtension()); new Service(stack, 'my-service', { environment, serviceDescription, }); // THEN // Ensure creation of default queue and queue policy allowing SNS Topics to send message to the queue expect(stack).toHaveResource('AWS::SQS::Queue', { MessageRetentionPeriod: 1209600, }); expect(stack).toHaveResource('AWS::SQS::Queue', { RedrivePolicy: { deadLetterTargetArn: { 'Fn::GetAtt': [ 'EventsDeadLetterQueue404572C7', 'Arn', ], }, maxReceiveCount: 3, }, }); // Ensure the task role is given permissions to consume messages from the queue expect(stack).toHaveResource('AWS::IAM::Policy', { PolicyDocument: { Statement: [ { Action: [ 'sqs:ReceiveMessage', 'sqs:ChangeMessageVisibility', 'sqs:GetQueueUrl', 'sqs:DeleteMessage', 'sqs:GetQueueAttributes', ], Effect: 'Allow', Resource: { 'Fn::GetAtt': [ 'EventsQueueB96EB0D2', 'Arn', ], }, }, ], Version: '2012-10-17', }, }); // Ensure there are no SNS Subscriptions created expect(stack).toCountResources('AWS::SNS::Subscription', 0); // Ensure that the queue URL has been correctly appended to the environment variables expect(stack).toHaveResource('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Cpu: 256, Environment: [ { Name: 'PORT', Value: '80', }, { Name: 'MY-SERVICE_QUEUE_URI', Value: { Ref: 'EventsQueueB96EB0D2', }, }, ], Image: 'nathanpeck/name', Essential: true, Memory: 512, Name: 'app', PortMappings: [ { ContainerPort: 80, Protocol: 'tcp', }, ], Ulimits: [ { HardLimit: 1024000, Name: 'nofile', SoftLimit: 1024000, }, ], }, ], }); }); test('should be able to subscribe default events queue created by the extension to given topics', () => { // GIVEN const stack = new cdk.Stack(); const environment = new Environment(stack, 'production'); const serviceDescription = new ServiceDescription(); serviceDescription.add(new Container({ cpu: 256, memoryMiB: 512, trafficPort: 80, image: ecs.ContainerImage.fromRegistry('nathanpeck/name'), environment: { PORT: '80', }, })); // WHEN const topicSubscription1 = new TopicSubscription({ topic: new sns.Topic(stack, 'topic1'), }); const topicSubscription2 = new TopicSubscription({ topic: new sns.Topic(stack, 'topic2'), }); serviceDescription.add(new QueueExtension({ subscriptions: [topicSubscription1, topicSubscription2], })); new Service(stack, 'my-service', { environment, serviceDescription, }); // THEN // Ensure creation of default queue and queue policy allowing SNS Topics to send message to the queue expect(stack).toHaveResource('AWS::SQS::Queue', { MessageRetentionPeriod: 1209600, }); expect(stack).toHaveResource('AWS::SQS::Queue', { RedrivePolicy: { deadLetterTargetArn: { 'Fn::GetAtt': [ 'EventsDeadLetterQueue404572C7', 'Arn', ], }, maxReceiveCount: 3, }, }); expect(stack).toHaveResource('AWS::SQS::QueuePolicy', { PolicyDocument: { Statement: [ { Action: 'sqs:SendMessage', Condition: { ArnEquals: { 'aws:SourceArn': { Ref: 'topic152D84A37', }, }, }, Effect: 'Allow', Principal: { Service: 'sns.amazonaws.com', }, Resource: { 'Fn::GetAtt': [ 'EventsQueueB96EB0D2', 'Arn', ], }, }, { Action: 'sqs:SendMessage', Condition: { ArnEquals: { 'aws:SourceArn': { Ref: 'topic2A4FB547F', }, }, }, Effect: 'Allow', Principal: { Service: 'sns.amazonaws.com', }, Resource: { 'Fn::GetAtt': [ 'EventsQueueB96EB0D2', 'Arn', ], }, }, ], Version: '2012-10-17', }, }); // Ensure the task role is given permissions to consume messages from the queue expect(stack).toHaveResource('AWS::IAM::Policy', { PolicyDocument: { Statement: [ { Action: [ 'sqs:ReceiveMessage', 'sqs:ChangeMessageVisibility', 'sqs:GetQueueUrl', 'sqs:DeleteMessage', 'sqs:GetQueueAttributes', ], Effect: 'Allow', Resource: { 'Fn::GetAtt': [ 'EventsQueueB96EB0D2', 'Arn', ], }, }, ], Version: '2012-10-17', }, }); // Ensure SNS Subscriptions for given topics expect(stack).toHaveResource('AWS::SNS::Subscription', { Protocol: 'sqs', TopicArn: { Ref: 'topic152D84A37', }, Endpoint: { 'Fn::GetAtt': [ 'EventsQueueB96EB0D2', 'Arn', ], }, }); expect(stack).toHaveResource('AWS::SNS::Subscription', { Protocol: 'sqs', TopicArn: { Ref: 'topic2A4FB547F', }, Endpoint: { 'Fn::GetAtt': [ 'EventsQueueB96EB0D2', 'Arn', ], }, }); // Ensure that the queue URL has been correctly appended to the environment variables expect(stack).toHaveResource('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Cpu: 256, Environment: [ { Name: 'PORT', Value: '80', }, { Name: 'MY-SERVICE_QUEUE_URI', Value: { Ref: 'EventsQueueB96EB0D2', }, }, ], Image: 'nathanpeck/name', Essential: true, Memory: 512, Name: 'app', PortMappings: [ { ContainerPort: 80, Protocol: 'tcp', }, ], Ulimits: [ { HardLimit: 1024000, Name: 'nofile', SoftLimit: 1024000, }, ], }, ], }); }); test('should be able to subscribe user-provided queue to given topics', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const environment = new Environment(stack, 'production'); const serviceDescription = new ServiceDescription(); serviceDescription.add(new Container({ cpu: 256, memoryMiB: 512, trafficPort: 80, image: ecs.ContainerImage.fromRegistry('nathanpeck/name'), })); const topicSubscription1 = new TopicSubscription({ topic: new sns.Topic(stack, 'topic1'), topicSubscriptionQueue: { queue: new sqs.Queue(stack, 'myQueue'), }, }); const topicSubscription2 = new TopicSubscription({ topic: new sns.Topic(stack, 'topic2'), }); serviceDescription.add(new QueueExtension({ subscriptions: [topicSubscription1, topicSubscription2], eventsQueue: new sqs.Queue(stack, 'defQueue'), })); new Service(stack, 'my-service', { environment, serviceDescription, }); // THEN // Ensure queue policy allows SNS Topics to send message to the queue expect(stack).toHaveResource('AWS::SQS::QueuePolicy', { PolicyDocument: { Statement: [ { Action: 'sqs:SendMessage', Condition: { ArnEquals: { 'aws:SourceArn': { Ref: 'topic152D84A37', }, }, }, Effect: 'Allow', Principal: { Service: 'sns.amazonaws.com', }, Resource: { 'Fn::GetAtt': [ 'myQueue4FDFF71C', 'Arn', ], }, }, ], Version: '2012-10-17', }, }); expect(stack).toHaveResource('AWS::SQS::QueuePolicy', { PolicyDocument: { Statement: [ { Action: 'sqs:SendMessage', Condition: { ArnEquals: { 'aws:SourceArn': { Ref: 'topic2A4FB547F', }, }, }, Effect: 'Allow', Principal: { Service: 'sns.amazonaws.com', }, Resource: { 'Fn::GetAtt': [ 'defQueue1F91A65B', 'Arn', ], }, }, ], Version: '2012-10-17', }, }); // Ensure the task role is given permissions to consume messages from the queue expect(stack).toHaveResource('AWS::IAM::Policy', { PolicyDocument: { Statement: [ { Action: [ 'sqs:ReceiveMessage', 'sqs:ChangeMessageVisibility', 'sqs:GetQueueUrl', 'sqs:DeleteMessage', 'sqs:GetQueueAttributes', ], Effect: 'Allow', Resource: { 'Fn::GetAtt': [ 'defQueue1F91A65B', 'Arn', ], }, }, { Action: [ 'sqs:ReceiveMessage', 'sqs:ChangeMessageVisibility', 'sqs:GetQueueUrl', 'sqs:DeleteMessage', 'sqs:GetQueueAttributes', ], Effect: 'Allow', Resource: { 'Fn::GetAtt': [ 'myQueue4FDFF71C', 'Arn', ], }, }, ], Version: '2012-10-17', }, }); // Ensure SNS Subscriptions for given topics expect(stack).toHaveResource('AWS::SNS::Subscription', { Protocol: 'sqs', TopicArn: { Ref: 'topic152D84A37', }, Endpoint: { 'Fn::GetAtt': [ 'myQueue4FDFF71C', 'Arn', ], }, }); expect(stack).toHaveResource('AWS::SNS::Subscription', { Protocol: 'sqs', TopicArn: { Ref: 'topic2A4FB547F', }, Endpoint: { 'Fn::GetAtt': [ 'defQueue1F91A65B', 'Arn', ], }, }); // Ensure that the queue URL has been correctly added to the environment variables expect(stack).toHaveResource('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Cpu: 256, Environment: [ { Name: 'MY-SERVICE_QUEUE_URI', Value: { Ref: 'defQueue1F91A65B', }, }, ], Image: 'nathanpeck/name', Essential: true, Memory: 512, Name: 'app', PortMappings: [ { ContainerPort: 80, Protocol: 'tcp', }, ], Ulimits: [ { HardLimit: 1024000, Name: 'nofile', SoftLimit: 1024000, }, ], }, ], }); }); test('should error when providing both the subscriptionQueue and queue (deprecated) props for a topic subscription', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const serviceDescription = new ServiceDescription(); serviceDescription.add(new Container({ cpu: 256, memoryMiB: 512, trafficPort: 80, image: ecs.ContainerImage.fromRegistry('nathanpeck/name'), })); // THEN expect(() => { new TopicSubscription({ topic: new sns.Topic(stack, 'topic1'), queue: new sqs.Queue(stack, 'delete-queue'), topicSubscriptionQueue: { queue: new sqs.Queue(stack, 'sign-up-queue'), }, }); }).toThrow('Either provide the `subscriptionQueue` or the `queue` (deprecated) for the topic subscription, but not both.'); }); test('should be able to add target tracking scaling policy for the Events Queue with no subscriptions', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const environment = new Environment(stack, 'production'); const serviceDescription = new ServiceDescription(); serviceDescription.add(new Container({ cpu: 256, memoryMiB: 512, trafficPort: 80, image: ecs.ContainerImage.fromRegistry('nathanpeck/name'), })); serviceDescription.add(new QueueExtension({ scaleOnLatency: { acceptableLatency: cdk.Duration.minutes(5), messageProcessingTime: cdk.Duration.seconds(20), }, })); new Service(stack, 'my-service', { environment, serviceDescription, autoScaleTaskCount: { maxTaskCount: 10, }, }); // THEN expect(stack).toHaveResourceLike('AWS::ApplicationAutoScaling::ScalableTarget', { MaxCapacity: 10, MinCapacity: 1, }); expect(stack).toHaveResourceLike('AWS::ApplicationAutoScaling::ScalingPolicy', { PolicyType: 'TargetTrackingScaling', TargetTrackingScalingPolicyConfiguration: { CustomizedMetricSpecification: { Dimensions: [ { Name: 'QueueName', Value: { 'Fn::GetAtt': [ 'EventsQueueB96EB0D2', 'QueueName', ], }, }, ], MetricName: 'BacklogPerTask', Namespace: 'production-my-service', Statistic: 'Average', Unit: 'Count', }, TargetValue: 15, }, }); }); test('should be able to add target tracking scaling policy for the SQS Queues', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const environment = new Environment(stack, 'production'); const serviceDescription = new ServiceDescription(); serviceDescription.add(new Container({ cpu: 256, memoryMiB: 512, trafficPort: 80, image: ecs.ContainerImage.fromRegistry('nathanpeck/name'), })); const topicSubscription1 = new TopicSubscription({ topic: new sns.Topic(stack, 'topic1'), topicSubscriptionQueue: { queue: new sqs.Queue(stack, 'myQueue'), scaleOnLatency: { acceptableLatency: cdk.Duration.minutes(10), messageProcessingTime: cdk.Duration.seconds(20), }, }, }); const topicSubscription2 = new TopicSubscription({ topic: new sns.Topic(stack, 'topic2'), queue: new sqs.Queue(stack, 'tempQueue'), }); serviceDescription.add(new QueueExtension({ subscriptions: [topicSubscription1, topicSubscription2], eventsQueue: new sqs.Queue(stack, 'defQueue'), scaleOnLatency: { acceptableLatency: cdk.Duration.minutes(5), messageProcessingTime: cdk.Duration.seconds(20), }, })); new Service(stack, 'my-service', { environment, serviceDescription, autoScaleTaskCount: { maxTaskCount: 10, }, }); // THEN expect(stack).toHaveResourceLike('AWS::ApplicationAutoScaling::ScalableTarget', { MaxCapacity: 10, MinCapacity: 1, }); expect(stack).toHaveResourceLike('AWS::ApplicationAutoScaling::ScalingPolicy', { PolicyType: 'TargetTrackingScaling', TargetTrackingScalingPolicyConfiguration: { CustomizedMetricSpecification: { Dimensions: [ { Name: 'QueueName', Value: { 'Fn::GetAtt': [ 'defQueue1F91A65B', 'QueueName', ], }, }, ], MetricName: 'BacklogPerTask', Namespace: 'production-my-service', Statistic: 'Average', Unit: 'Count', }, TargetValue: 15, }, }); expect(stack).toHaveResourceLike('AWS::ApplicationAutoScaling::ScalingPolicy', { PolicyType: 'TargetTrackingScaling', TargetTrackingScalingPolicyConfiguration: { CustomizedMetricSpecification: { Dimensions: [ { Name: 'QueueName', Value: { 'Fn::GetAtt': [ 'myQueue4FDFF71C', 'QueueName', ], }, }, ], MetricName: 'BacklogPerTask', Namespace: 'production-my-service', Statistic: 'Average', Unit: 'Count', }, TargetValue: 30, }, }); expect(stack).toHaveResourceLike('AWS::ApplicationAutoScaling::ScalingPolicy', { PolicyType: 'TargetTrackingScaling', TargetTrackingScalingPolicyConfiguration: { CustomizedMetricSpecification: { Dimensions: [ { Name: 'QueueName', Value: { 'Fn::GetAtt': [ 'tempQueueEF946882', 'QueueName', ], }, }, ], MetricName: 'BacklogPerTask', Namespace: 'production-my-service', Statistic: 'Average', Unit: 'Count', }, TargetValue: 15, }, }); }); test('should error when adding scaling policy if scaling target has not been configured', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const environment = new Environment(stack, 'production'); const serviceDescription = new ServiceDescription(); serviceDescription.add(new Container({ cpu: 256, memoryMiB: 512, trafficPort: 80, image: ecs.ContainerImage.fromRegistry('nathanpeck/name'), })); const topicSubscription1 = new TopicSubscription({ topic: new sns.Topic(stack, 'topic1'), }); serviceDescription.add(new QueueExtension({ subscriptions: [topicSubscription1], scaleOnLatency: { acceptableLatency: cdk.Duration.minutes(10), messageProcessingTime: cdk.Duration.seconds(20), }, })); // THEN expect(() => { new Service(stack, 'my-service', { environment, serviceDescription, }); }).toThrow(/Auto scaling target for the service 'my-service' hasn't been configured. Please use Service construct to configure 'minTaskCount' and 'maxTaskCount'./); }); test('should error when message processing time for the queue is greater than acceptable latency', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const environment = new Environment(stack, 'production'); const serviceDescription = new ServiceDescription(); serviceDescription.add(new Container({ cpu: 256, memoryMiB: 512, trafficPort: 80, image: ecs.ContainerImage.fromRegistry('nathanpeck/name'), })); const topicSubscription1 = new TopicSubscription({ topic: new sns.Topic(stack, 'topic1'), topicSubscriptionQueue: { queue: new sqs.Queue(stack, 'sign-up-queue'), }, }); serviceDescription.add(new QueueExtension({ subscriptions: [topicSubscription1], scaleOnLatency: { acceptableLatency: cdk.Duration.seconds(10), messageProcessingTime: cdk.Duration.seconds(20), }, })); // THEN expect(() => { new Service(stack, 'my-service', { environment, serviceDescription, autoScaleTaskCount: { maxTaskCount: 10, }, }); }).toThrow('Message processing time (20s) for the queue cannot be greater acceptable queue latency (10s).'); }); test('should error when configuring auto scaling only for topic-specific queue', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const environment = new Environment(stack, 'production'); const serviceDescription = new ServiceDescription(); serviceDescription.add(new Container({ cpu: 256, memoryMiB: 512, trafficPort: 80, image: ecs.ContainerImage.fromRegistry('nathanpeck/name'), })); const topicSubscription1 = new TopicSubscription({ topic: new sns.Topic(stack, 'topic1'), topicSubscriptionQueue: { queue: new sqs.Queue(stack, 'sign-up-queue'), scaleOnLatency: { acceptableLatency: cdk.Duration.minutes(10), messageProcessingTime: cdk.Duration.seconds(20), }, }, }); serviceDescription.add(new QueueExtension({ subscriptions: [topicSubscription1], })); // THEN expect(() => { new Service(stack, 'my-service', { environment, serviceDescription, autoScaleTaskCount: { maxTaskCount: 10, }, }); }).toThrow(/Autoscaling for a topic-specific queue cannot be configured as autoscaling based on SQS Queues hasn’t been set up for the service 'my-service'. If you want to enable autoscaling for this service, please also specify 'scaleOnLatency' in the 'QueueExtension'/); }); });
the_stack
import { expect } from "chai"; import * as React from "react"; import { ButtonGroupEditorParams, DialogItem, DialogItemValue, DialogPropertySyncItem, PropertyDescription, PropertyEditorParamTypes, SuppressLabelEditorParams, } from "@itwin/appui-abstract"; import { render } from "@testing-library/react"; import { ConfigurableUiManager, CoreTools, DefaultToolSettingsProvider, Frontstage, FrontstageManager, FrontstageProps, FrontstageProvider, SyncToolSettingsPropertiesEventArgs, ToolSettingsManager, Widget, Zone, } from "../../../appui-react"; import TestUtils from "../../TestUtils"; describe("DefaultToolUiSettingsProvider", () => { const firstToolId = "DefaultToolUiSettingsProvider-FirstTestTool"; const testToolId = "DefaultToolUiSettingsProvider-TestTool"; const useLengthDescription: PropertyDescription = { name: "use-length", displayLabel: "TEST-USELENGTH", typename: "boolean", editor: { params: [{ type: PropertyEditorParamTypes.SuppressEditorLabel } as SuppressLabelEditorParams], }, }; const lengthDescription: PropertyDescription = { name: "length", displayLabel: "TEST-LENGTH", typename: "string", }; const enumDescription: PropertyDescription = { displayLabel: "TEST-ENUM-PICKER", name: "test-enum", typename: "enum", enum: { choices: [ { label: "Yellow", value: 0 }, { label: "Red", value: 1 }, { label: "Green", value: 2 }, { label: "Blue", value: 3 }, ], isStrict: false, }, }; const testEnumDescription1: PropertyDescription = { name: "buttongroup1", displayLabel: "", typename: "enum", editor: { name: "enum-buttongroup", params: [ { type: PropertyEditorParamTypes.ButtonGroupData, buttons: [ { iconSpec: "testIconOne" }, { iconSpec: "testIconTwo" }, ], } as ButtonGroupEditorParams, { type: PropertyEditorParamTypes.SuppressEditorLabel, suppressLabelPlaceholder: true, } as SuppressLabelEditorParams, ], }, enum: { choices: [ { label: "Choice 1", value: 10 }, { label: "Choice 2", value: 20 }, ], }, }; const testEnumDescription2: PropertyDescription = { name: "buttongroup2", displayLabel: "", typename: "enum", editor: { name: "enum-buttongroup", params: [ { type: PropertyEditorParamTypes.ButtonGroupData, buttons: [ { iconSpec: "plusOne" }, { iconSpec: "plusTwo" }, { iconSpec: "plusThree" }, ], } as ButtonGroupEditorParams, { type: PropertyEditorParamTypes.SuppressEditorLabel, suppressLabelPlaceholder: true, } as SuppressLabelEditorParams, ], }, enum: { choices: [ { label: "Plus 1", value: 100 }, { label: "Plus 2", value: 200 }, { label: "Plus 3", value: 300 }, ], }, }; const methodsDescription: PropertyDescription = { name: "methods", displayLabel: "", typename: "enum", editor: { name: "enum-buttongroup", params: [ { type: PropertyEditorParamTypes.ButtonGroupData, buttons: [ { iconSpec: "icon-select-single" }, { iconSpec: "icon-select-line" }, { iconSpec: "icon-select-box" }, ], } as ButtonGroupEditorParams, { type: PropertyEditorParamTypes.SuppressEditorLabel, suppressLabelPlaceholder: true, } as SuppressLabelEditorParams, ], }, enum: { choices: [ { label: "Pick", value: 0 }, { label: "Line", value: 1 }, { label: "Box", value: 2 }, ], }, }; before(async () => { await TestUtils.initializeUiFramework(); class Frontstage1 extends FrontstageProvider { public static stageId = "ToolUiProvider-TestFrontstage"; public get id(): string { return Frontstage1.stageId; } public get frontstage(): React.ReactElement<FrontstageProps> { return ( <Frontstage id={this.id} defaultTool={CoreTools.selectElementCommand} contentGroup={TestUtils.TestContentGroup1} topCenter={ <Zone widgets={[ <Widget isToolSettings={true} />, // eslint-disable-line react/jsx-key ]} /> } /> ); } } const frontstageProvider = new Frontstage1(); ConfigurableUiManager.addFrontstageProvider(frontstageProvider); ToolSettingsManager.useDefaultToolSettingsProvider = false; }); after(() => { TestUtils.terminateUiFramework(); }); it("starting a tool with undefined tool settings", async () => { const frontstageDef = await FrontstageManager.getFrontstageDef("ToolUiProvider-TestFrontstage"); expect(frontstageDef).to.not.be.undefined; if (frontstageDef) { await FrontstageManager.setActiveFrontstageDef(frontstageDef); FrontstageManager.ensureToolInformationIsSet(firstToolId); // If a tool does not define toolSettingsProperties then useDefaultToolSettingsProvider should be false, but make sure we can gracefully handle // case where useDefaultToolSettingsProvider is true but toolSettingsProperties are not defined. ToolSettingsManager.useDefaultToolSettingsProvider = true; FrontstageManager.setActiveToolId(firstToolId); expect(FrontstageManager.activeToolId).to.eq(firstToolId); const toolInformation = FrontstageManager.activeToolInformation; expect(toolInformation).to.not.be.undefined; if (toolInformation) { const toolUiProvider = toolInformation.toolUiProvider; expect(toolUiProvider).to.be.undefined; } } }); it("starting a tool with tool settings", async () => { const frontstageDef = await FrontstageManager.getFrontstageDef("ToolUiProvider-TestFrontstage"); expect(frontstageDef).to.not.be.undefined; if (frontstageDef) { await FrontstageManager.setActiveFrontstageDef(frontstageDef); const toolSettingsProperties: DialogItem[] = []; const useLengthValue: DialogItemValue = { value: false }; const lengthValue: DialogItemValue = { value: 1.2345, displayValue: "1.2345" }; const enumValue: DialogItemValue = { value: "1" }; const methodsValue: DialogItemValue = { value: 0 }; const groupOneValue: DialogItemValue = { value: 10 }; const groupTwoValue: DialogItemValue = { value: 100 }; toolSettingsProperties.push({ value: useLengthValue, property: useLengthDescription, editorPosition: { rowPriority: 0, columnIndex: 1 } }); toolSettingsProperties.push({ value: lengthValue, property: lengthDescription, editorPosition: { rowPriority: 0, columnIndex: 3 } }); toolSettingsProperties.push({ value: enumValue, property: enumDescription, editorPosition: { rowPriority: 1, columnIndex: 3 } }); toolSettingsProperties.push({ value: methodsValue, property: methodsDescription, editorPosition: { rowPriority: 2, columnIndex: 1 } }); toolSettingsProperties.push({ value: groupOneValue, property: testEnumDescription1, editorPosition: { rowPriority: 3, columnIndex: 1 } }); toolSettingsProperties.push({ value: groupTwoValue, property: testEnumDescription2, editorPosition: { rowPriority: 3, columnIndex: 2 }, isDisabled: true }); ToolSettingsManager.initializeToolSettingsData(toolSettingsProperties, testToolId, "testToolLabel", "testToolDescription"); // override the property getter to return the properties needed for the test const propertyDescriptorToRestore = Object.getOwnPropertyDescriptor(ToolSettingsManager, "toolSettingsProperties")!; Object.defineProperty(ToolSettingsManager, "toolSettingsProperties", { get: () => toolSettingsProperties, }); expect(ToolSettingsManager.useDefaultToolSettingsProvider).to.be.true; expect(ToolSettingsManager.toolSettingsProperties.length).to.equal(toolSettingsProperties.length); FrontstageManager.ensureToolInformationIsSet(testToolId); FrontstageManager.setActiveToolId(testToolId); expect(FrontstageManager.activeToolId).to.eq(testToolId); const toolInformation = FrontstageManager.activeToolInformation; expect(toolInformation).to.not.be.undefined; if (toolInformation) { const toolSettingsProvider = toolInformation.toolUiProvider as DefaultToolSettingsProvider; expect(toolSettingsProvider).to.not.be.undefined; if (toolSettingsProvider) { const tsNode = toolSettingsProvider.toolSettingsNode; expect(tsNode).to.not.be.undefined; } } const toolSettingsNode = FrontstageManager.activeToolSettingsProvider?.toolSettingsNode; expect(toolSettingsNode).to.not.be.undefined; const renderedComponent = render(toolSettingsNode as React.ReactElement<any>); expect(renderedComponent).not.to.be.undefined; expect(renderedComponent.queryByText("TEST-USELENGTH:")).to.be.null; const toggleEditor = renderedComponent.getByTestId("components-checkbox-editor"); expect(toggleEditor).not.to.be.undefined; const textLabel = renderedComponent.getByText("TEST-LENGTH:"); expect(textLabel).not.to.be.undefined; const textEditor = renderedComponent.getByTestId("components-text-editor"); expect(textEditor).not.to.be.undefined; const enumLabel = renderedComponent.getByText("TEST-ENUM-PICKER:"); expect(enumLabel).not.to.be.undefined; const enumEditor = renderedComponent.getByTestId("components-select-editor"); expect(enumEditor).not.to.be.undefined; const buttonGroupEnumButton = renderedComponent.getByTestId("Pick"); expect(buttonGroupEnumButton).not.to.be.undefined; const buttonGroup1EnumButton = renderedComponent.getByTestId("Choice 1"); expect(buttonGroup1EnumButton).not.to.be.undefined; const buttonGroup2EnumButton = renderedComponent.getByTestId("Plus 1"); expect(buttonGroup2EnumButton).not.to.be.undefined; // simulate sync from tool const newUseLengthValue: DialogItemValue = { value: false }; const syncItem: DialogPropertySyncItem = { value: newUseLengthValue, propertyName: useLengthDescription.name, isDisabled: false }; const syncArgs = { toolId: testToolId, syncProperties: [syncItem] } as SyncToolSettingsPropertiesEventArgs; // ToolSettingsManager.onSyncToolSettingsProperties.emit(syncArgs); FrontstageManager.activeToolSettingsProvider?.syncToolSettingsProperties(syncArgs); FrontstageManager.activeToolSettingsProvider?.reloadPropertiesFromTool(); FrontstageManager.onToolSettingsReloadEvent.emit(); // restore the overriden property getter Object.defineProperty(ToolSettingsManager, "toolSettingsProperties", propertyDescriptorToRestore); } }); it("starting a tool with nested lock toggle in tool settings", async () => { const frontstageDef = await FrontstageManager.getFrontstageDef("ToolUiProvider-TestFrontstage"); expect(frontstageDef).to.not.be.undefined; if (frontstageDef) { await FrontstageManager.setActiveFrontstageDef(frontstageDef); const toolSettingsProperties: DialogItem[] = []; const useLengthValue: DialogItemValue = { value: false }; const lengthValue: DialogItemValue = { value: 1.2345, displayValue: "1.2345" }; const lockToggle: DialogItem = { value: useLengthValue, property: useLengthDescription, editorPosition: { rowPriority: 0, columnIndex: 1 } }; toolSettingsProperties.push({ value: lengthValue, property: lengthDescription, editorPosition: { rowPriority: 0, columnIndex: 3 }, isDisabled: false, lockProperty: lockToggle }); ToolSettingsManager.initializeToolSettingsData(toolSettingsProperties, testToolId, "testToolLabel", "testToolDescription"); // override the property getter to return the properties needed for the test const propertyDescriptorToRestore = Object.getOwnPropertyDescriptor(ToolSettingsManager, "toolSettingsProperties")!; Object.defineProperty(ToolSettingsManager, "toolSettingsProperties", { get: () => toolSettingsProperties, }); expect(ToolSettingsManager.useDefaultToolSettingsProvider).to.be.true; expect(ToolSettingsManager.toolSettingsProperties.length).to.equal(toolSettingsProperties.length); FrontstageManager.ensureToolInformationIsSet(testToolId); FrontstageManager.setActiveToolId(testToolId); expect(FrontstageManager.activeToolId).to.eq(testToolId); const toolInformation = FrontstageManager.activeToolInformation; expect(toolInformation).to.not.be.undefined; if (toolInformation) { const toolUiProvider = toolInformation.toolUiProvider; expect(toolUiProvider).to.not.be.undefined; if (toolUiProvider) { expect(toolUiProvider.toolSettingsNode).to.not.be.undefined; // simulate property update const newlengthValue: DialogItemValue = { value: 7.5 }; const lengthSyncItem: DialogPropertySyncItem = { value: newlengthValue, propertyName: lengthDescription.name }; const newUselengthValue: DialogItemValue = { value: false }; const useLengthSyncItem: DialogPropertySyncItem = { value: newUselengthValue, propertyName: useLengthDescription.name }; const defaultProvider = toolUiProvider as DefaultToolSettingsProvider; if (defaultProvider) { defaultProvider.uiDataProvider.applyUiPropertyChange(lengthSyncItem); defaultProvider.uiDataProvider.applyUiPropertyChange(useLengthSyncItem); } } } const toolSettingsNode = FrontstageManager.activeToolSettingsProvider?.toolSettingsNode; expect(toolSettingsNode).to.not.be.undefined; const renderedComponent = render(toolSettingsNode as React.ReactElement<any>); expect(renderedComponent).not.to.be.undefined; expect(renderedComponent.queryByText("TEST-USELENGTH:")).to.be.null; const toggleEditor = renderedComponent.getByTestId("components-checkbox-editor"); expect(toggleEditor).not.to.be.undefined; const textLabel = renderedComponent.getByText("TEST-LENGTH:"); expect(textLabel).not.to.be.undefined; const textEditor = renderedComponent.getByTestId("components-text-editor"); expect(textEditor).not.to.be.undefined; // simulate sync from tool const newUseLengthValue: DialogItemValue = { value: false }; const syncItem: DialogPropertySyncItem = { value: newUseLengthValue, propertyName: useLengthDescription.name, isDisabled: false }; const syncArgs = { toolId: testToolId, syncProperties: [syncItem] } as SyncToolSettingsPropertiesEventArgs; FrontstageManager.activeToolSettingsProvider?.syncToolSettingsProperties(syncArgs); FrontstageManager.activeToolSettingsProvider?.reloadPropertiesFromTool(); FrontstageManager.onToolSettingsReloadEvent.emit(); // restore the overriden property getter Object.defineProperty(ToolSettingsManager, "toolSettingsProperties", propertyDescriptorToRestore); } }); });
the_stack
import { fileNameFromPath, Headers, HttpDownloadRequestOptions, HttpError, HttpRequestOptions, isImageUrl, SaveImageStorageKey, TNSHttpSettings } from './http-request-common'; import { NetworkAgent } from '@nativescript/core/debugger'; import { File, Folder, knownFolders, path, Utils, Application, ApplicationSettings } from '@nativescript/core'; import { FileManager } from '../file/file'; import { isString, isObject, isNullOrUndefined } from '@nativescript/core/utils/types'; export type CancellablePromise = Promise<any> & { cancel: () => void }; declare var com; export enum HttpResponseEncoding { UTF8, GBK } const statuses = { 100: 'Continue', 101: 'Switching Protocols', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non - Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 307: 'Temporary Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request - URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported' }; function parseJSON(source: string): any { const src = source.trim(); if (src.lastIndexOf(')') === src.length - 1) { return JSON.parse( src.substring(src.indexOf('(') + 1, src.lastIndexOf(')')) ); } return JSON.parse(src); } const textTypes: string[] = [ 'text/plain', 'application/xml', 'application/rss+xml', 'text/html', 'text/xml' ]; const isTextContentType = (contentType: string): boolean => { let result = false; for (let i = 0; i < textTypes.length; i++) { if (contentType.toLowerCase().indexOf(textTypes[i]) >= 0) { result = true; break; } } return result; }; const requestCallbacks = new Map(); let requestIdCounter = 0; export class Http { constructor() { } private static buildJavaOptions(options: HttpRequestOptions) { if (!isString(options.url)) { throw new Error('Http request must provide a valid url.'); } let javaOptions = new com.github.triniwiz.async.Async2.Http.RequestOptions(); javaOptions.url = options.url; let method; if (isString(typeof options.method)) { javaOptions.method = options.method; method = options.method.toLowerCase(); } if ((method && method === 'post') || method === 'put') { if ( isString(options.content) ) { javaOptions.content = new java.lang.String(options.content); } else if (isObject(options.content)) { javaOptions.content = serialize(options.content); } } if (typeof options.timeout === 'number') { javaOptions.timeout = options.timeout; } if (options.headers) { const arrayList = new java.util.ArrayList<any>(); const pair = com.github.triniwiz.async.Async2.Http.KeyValuePair; if (options.headers instanceof Map) { options.headers.forEach((value, key) => { arrayList.add(new pair(key, value + '')); }); } else { for (let key in options.headers) { arrayList.add(new pair(key, options.headers[key] + '')); } } javaOptions.headers = arrayList; } return javaOptions; } private static buildJavaDownloadOptions(options: HttpDownloadRequestOptions) { if (!isString(options.url)) { throw new Error('Http request must provide a valid url.'); } const javaOptions = new com.github.triniwiz.async.Async2.Http.DownloadRequestOptions(); javaOptions.url = options.url; if (typeof options.timeout === 'number') { javaOptions.timeout = options.timeout; } if (typeof options.filePath === 'string') { javaOptions.filePath = options.filePath; } else { // creates directory Folder.fromPath(path.join(knownFolders.temp().path, 'async_http')); javaOptions.filePath = path.join(knownFolders.temp().path, 'async_http', java.util.UUID.randomUUID().toString()); } if (options.headers) { const arrayList = new java.util.ArrayList<any>(); const pair = com.github.triniwiz.async.Async2.Http.KeyValuePair; if (options.headers instanceof Map) { options.headers.forEach((value, key) => { arrayList.add(new pair(key, value + '')); }); } else { for (let key in options.headers) { arrayList.add(new pair(key, options.headers[key] + '')); } } javaOptions.headers = arrayList; } return javaOptions; } request(options: HttpRequestOptions): CancellablePromise { const headers: Headers = {}; let statusCode = 0; let id; const counter = requestIdCounter; const request = <CancellablePromise>new Promise<any>((resolve, reject) => { try { // initialize the options const javaOptions = Http.buildJavaOptions(options); if (TNSHttpSettings.debug) { // @ts-ignore if (global.__inspector && global.__inspector.isConnected) { NetworkAgent.requestWillBeSent(requestIdCounter, options); } } const makeRemoteRequest = () => { const callback = new com.github.triniwiz.async.Async2.Http.Callback({ onCancel(param: any): void { reject({ type: HttpError.Cancelled, result: param }); requestCallbacks.delete(id); }, onComplete(result: any): void { let content; let responseText; let _isString = false; if (result.content instanceof org.json.JSONObject || result.content instanceof org.json.JSONArray) { content = deserialize(result.content); responseText = result.contentText; _isString = true; } else { content = result.content; responseText = result.contentText; } if (result && result.headers) { const length = result.headers.size(); let pair; for (let i = 0; i < length; i++) { pair = result.headers.get(i); addHeader(headers, pair.key, pair.value); } } // send response data (for requestId) to network debugger let contentType = headers['Content-Type']; if (isNullOrUndefined(contentType)) { contentType = headers['content-type']; } let acceptHeader; if (isNullOrUndefined(contentType)) { acceptHeader = headers['Accept']; if (isNullOrUndefined(acceptHeader)) { acceptHeader = headers['accept']; } } else { acceptHeader = contentType; } let returnType = 'text/plain'; if (!isNullOrUndefined(acceptHeader) && isString(acceptHeader)) { let acceptValues = acceptHeader.split(','); let quality = []; let defaultQuality = []; let customQuality = []; for (let value of acceptValues) { if (value.indexOf(';q=') > -1) { customQuality.push(value); } else { defaultQuality.push(value); } } customQuality = customQuality.sort((a, b) => { const a_quality = parseFloat(a.substring(a.indexOf(';q=')).replace(';q=', '')); const b_quality = parseFloat(b.substring(b.indexOf(';q=')).replace(';q=', '')); return (b_quality - a_quality); }); quality.push(...defaultQuality); quality.push(...customQuality); returnType = quality[0]; } result['statusCode'] = statusCode; if (TNSHttpSettings.debug) { // send response data (for requestId) to network debugger // @ts-ignore if (global.__inspector && global.__inspector.isConnected) { NetworkAgent.responseReceived(counter, { url: result.url, statusCode, headers, responseAsString: isString ? (result.contentText ? result.contentText : result.content.toString()) : null, responseAsImage: null // TODO needs base64 Image } as any, headers); } } if (isTextContentType(returnType) && isNullOrUndefined(responseText)) { responseText = result.contentText; } if (TNSHttpSettings.saveImage && TNSHttpSettings.currentlySavedImages && TNSHttpSettings.currentlySavedImages[this._url]) { // ensure saved to disk if (TNSHttpSettings.currentlySavedImages[this._url].localPath) { FileManager.writeFile(content, TNSHttpSettings.currentlySavedImages[this._url].localPath, function (error, result) { if (TNSHttpSettings.debug) { console.log('http image save:', error ? error : result); } }); } } resolve({ url: result.url, content, responseText, statusCode: statusCode, headers: headers }); requestCallbacks.delete(id); }, onError(param0: string, param1: java.lang.Exception): void { reject({ type: HttpError.Error, message: param0 }); requestCallbacks.delete(id); }, onHeaders(jHeaders: any, status: number): void { statusCode = status; const length = jHeaders.size(); let pair; for (let i = 0; i < length; i++) { pair = jHeaders.get(i); addHeader(headers, pair.key, pair.value); } if (options.onHeaders) { options.onHeaders(headers, statusCode); } requestCallbacks.delete(id); }, onLoading(): void { options.onLoading(); requestCallbacks.delete(id); }, onProgress(lengthComputable: boolean, loaded: number, total: number): void { if (options.onProgress) { options.onProgress({ lengthComputable, loaded, total }); } requestCallbacks.delete(id); }, onTimeout(): void { reject({ type: HttpError.Timeout }); requestCallbacks.delete(id); } }); id = com.github.triniwiz.async.Async2.Http.makeRequest(javaOptions, callback); requestCallbacks.set(id, callback); }; if (TNSHttpSettings.saveImage && isImageUrl(options.url)) { // handle saved images to disk if (!TNSHttpSettings.currentlySavedImages) { const stored = ApplicationSettings.getString(SaveImageStorageKey); if (stored) { try { TNSHttpSettings.currentlySavedImages = JSON.parse(stored); } catch (err) { TNSHttpSettings.currentlySavedImages = {}; } } else { TNSHttpSettings.currentlySavedImages = {}; } } const imageSetting = TNSHttpSettings.currentlySavedImages[options.url]; const requests = imageSetting ? imageSetting.requests : 0; let localPath: string; if (imageSetting && imageSetting.localPath && File.exists(imageSetting.localPath)) { // previously saved to disk FileManager.readFile(imageSetting.localPath, null, (error, file) => { if (error) { if (TNSHttpSettings.debug) { console.log('http image load error:', error); } } resolve({ url: options.url, responseText: '', statusCode: 200, content: file, headers: { 'Content-Type': 'arraybuffer' } }); }); } else if (requests >= TNSHttpSettings.saveImage.numberOfRequests) { // setup to write to disk when response finishes let filename = fileNameFromPath(options.url); if (filename.indexOf('?')) { // strip any params if were any filename = filename.split('?')[0]; } localPath = path.join(knownFolders.documents().path, filename); makeRemoteRequest(); } // save settings TNSHttpSettings.currentlySavedImages[options.url] = { ...(imageSetting || {}), date: Date.now(), requests: requests + 1, localPath }; ApplicationSettings.setString(SaveImageStorageKey, JSON.stringify(TNSHttpSettings.currentlySavedImages)); } else { makeRemoteRequest(); } requestIdCounter++; } catch (ex) { reject({ type: HttpError.Error, message: ex.message }); } }); request['cancel'] = function () { com.github.triniwiz.async.Async2.Http.cancelRequest(id); }; return request; } public static getFile(options: HttpDownloadRequestOptions): CancellablePromise { const headers: Headers = {}; let statusCode = 0; let id; const counter = requestIdCounter; const request = <CancellablePromise>new Promise<any>((resolve, reject) => { try { // initialize the options const javaOptions = Http.buildJavaDownloadOptions(options); if (TNSHttpSettings.debug) { // @ts-ignore if (global.__inspector && global.__inspector.isConnected) { NetworkAgent.requestWillBeSent(requestIdCounter, options); } } const makeRemoteRequest = () => { const callback = new com.github.triniwiz.async.Async2.Http.Callback({ onCancel(param: any): void { reject({ type: HttpError.Cancelled, result: param }); requestCallbacks.delete(id); }, onComplete(result: any): void { if (result && result.headers) { const length = result.headers.size(); let pair; for (let i = 0; i < length; i++) { pair = result.headers.get(i); addHeader(headers, pair.key, pair.value); } } // send response data (for requestId) to network debugger let contentType = headers['Content-Type']; if (isNullOrUndefined(contentType)) { contentType = headers['content-type']; } let acceptHeader; if (isNullOrUndefined(contentType)) { acceptHeader = headers['Accept']; if (isNullOrUndefined(acceptHeader)) { acceptHeader = headers['accept']; } } else { acceptHeader = contentType; } let returnType = 'text/plain'; if (!isNullOrUndefined(acceptHeader) && isString(acceptHeader)) { let acceptValues = acceptHeader.split(','); let quality = []; let defaultQuality = []; let customQuality = []; for (let value of acceptValues) { if (value.indexOf(';q=') > -1) { customQuality.push(value); } else { defaultQuality.push(value); } } customQuality = customQuality.sort((a, b) => { const a_quality = parseFloat(a.substring(a.indexOf(';q=')).replace(';q=', '')); const b_quality = parseFloat(b.substring(b.indexOf(';q=')).replace(';q=', '')); return (b_quality - a_quality); }); quality.push(...defaultQuality); quality.push(...customQuality); returnType = quality[0]; } result['statusCode'] = statusCode; if (TNSHttpSettings.debug) { // send response data (for requestId) to network debugger // @ts-ignore if (global.__inspector && global.__inspector.isConnected) { NetworkAgent.responseReceived(counter, { url: result.url, statusCode, headers, responseAsString: isString ? (result.contentText ? result.contentText : result.content.toString()) : null, responseAsImage: null // TODO needs base64 Image } as any, headers); } } resolve(result.filePath); requestCallbacks.delete(id); }, onError(param0: string, param1: java.lang.Exception): void { reject({ type: HttpError.Error, message: param0 }); requestCallbacks.delete(id); }, onHeaders(jHeaders: any, status: number): void { statusCode = status; const length = jHeaders.size(); let pair; for (let i = 0; i < length; i++) { pair = jHeaders.get(i); addHeader(headers, pair.key, pair.value); } if (options.onHeaders) { options.onHeaders(headers, statusCode); } requestCallbacks.delete(id); }, onLoading(): void { options.onLoading(); requestCallbacks.delete(id); }, onProgress(lengthComputable: boolean, loaded: number, total: number): void { if (options.onProgress) { options.onProgress({ lengthComputable, loaded, total }); } requestCallbacks.delete(id); }, onTimeout(): void { reject({ type: HttpError.Timeout }); requestCallbacks.delete(id); } }); id = com.github.triniwiz.async.Async2.Http.getFileRequest(javaOptions, callback); requestCallbacks.set(id, callback); }; makeRemoteRequest(); requestIdCounter++; } catch (ex) { reject({ type: HttpError.Error, message: ex.message }); } }); request['cancel'] = function () { com.github.triniwiz.async.Async2.Http.cancelRequest(id); }; return request; } } function serialize(data: any): any { let store; switch (typeof data) { case 'string': case 'boolean': case 'number': { return data; } case 'object': { if (!data) { return null; } if (data instanceof Date) { return data.toJSON(); } if (Array.isArray(data)) { store = new org.json.JSONArray(); data.forEach((item) => store.put(serialize(item))); return store; } store = new org.json.JSONObject(); Object.keys(data).forEach((key) => store.put(key, serialize(data[key]))); return store; } default: return null; } } function deserialize(data): any { if (isNullOrUndefined(data)) { return null; } if (typeof data !== 'object') { return data; } if (typeof data.getClass === 'function') { let store; switch (data.getClass().getName()) { case 'java.lang.String': { return String(data); } case 'java.lang.Boolean': { return String(data) === 'true'; } case 'java.lang.Integer': case 'java.lang.Long': case 'java.lang.Double': case 'java.lang.Short': { return Number(data); } case 'org.json.JSONArray': { store = []; for (let j = 0; j < data.length(); j++) { store[j] = deserialize(data.get(j)); } break; } case 'org.json.JSONObject': { store = {}; let i = data.keys(); while (i.hasNext()) { let key = i.next(); store[key] = deserialize(data.get(key)); } break; } default: store = null; break; } return store; } else { return data; } } function decodeResponse(raw: any, encoding?: HttpResponseEncoding): any { let charsetName = 'UTF-8'; if (encoding === HttpResponseEncoding.GBK) { charsetName = 'GBK'; } return new java.lang.String(raw.array(), charsetName); } export function addHeader(headers: Headers, key: string, value: string): void { if (!headers[key]) { headers[key] = value; } else if (Array.isArray(headers[key])) { (<string[]>headers[key]).push(value); } else { const values: string[] = [<string>headers[key]]; values.push(value); headers[key] = values; } }
the_stack
* * == Background == * * Opstrace authentication and session management are both handled independently from * each other. * * We only use Auth0 as a way of proving who the user is and that they control the * email address used. Once this is done we check their email address against the list * of authorised Opstrace users - if present we create a session for them which grants * them access to the app. From then on we rely solely on the opstrace session and have * no further use of Auth0. Continued access to the website is granted based on the * Opstrace session not the Auth0 session. * * == WithSession == * * WithSession is a gatekeeper component and will only render props.children for users * with a valid Opstrace session. If they don't have one then WithSession will guide * users to authenticate with Auth0, checking they are authorised and then creating a * valid session for them. * * There are 3 flows / processes that WithSession caters for: * * 1. User already logged in, has a valid session * * WithSession has been optimised for this case - it attempts to as quickly as possible * determine if the user is logged in or not. It does not wait for Redux data, websocket * connections etc... to be setup. Upon mounting it immediately makes a direct call to * "/_/auth/status" to find out the the user's session status. * * 2. User does not have a valid Auth0 or Opstrace session * * WithSession redirects the user to be authenticated with Auth0 first, when they are * redirected back a valid Opstrace session is generated for them provided they pass the * authorisation check. * * 3. User logged into Auth0, but no valid Opstrace session * * In this case WithSession silently creates a valid Opstrace session for the user if * they are authorised to access the website. * * Note: users do not "signup" to Opstrace. * */ import * as rax from "retry-axios"; import axios, { AxiosResponse } from "axios"; import React, { useEffect, useState, useCallback, useRef } from "react"; import { useDispatch } from "react-redux"; import { Switch, Route, Redirect } from "react-router"; import { Auth0Provider, useAuth0 } from "@auth0/auth0-react"; import { setCurrentUser } from "state/user/actions"; import { OpstraceBuildInfo } from "state/opstrace-config/types"; import { updateOpstraceBuildInfo } from "state/opstrace-config/actions"; import { loginUrl, makeUrl } from "./paths"; import { LoadingPage, LoginPage, LogoutPage, AccessDeniedPage, LoginFailedPage } from "client/views/session"; const DEFAULT_PATHNAME = "/"; const AUTH0_AUDIENCE = "https://user-cluster.opstrace.io/api"; const CLUSTER_NAME = window.location.host.endsWith("opstrace.io") ? window.location.host.replace(".opstrace.io", "") : "localhost"; type AppState = { returnTo?: string; }; // TODO: "WithSession" re-mounts after user logs into Auth0 and creates a new session causing a subsequent status check // TODO: look to switching to using a "context" for passing things to children components type StatusData = { currentUserId: string | null; auth0Config: { domain: string; clientId: string }; buildInfo: OpstraceBuildInfo; }; export const WithSession = ({ children }: { children: React.ReactNode }) => { // Note(Nahum): need to double check that the UseAxios response doesn't expire and this status check isn't re-run after a while. // The reason for this is that "loadingStatus" would flip back to true and block the user for accessing the site while the // check is occuring. We only want to interrupt the user if their session with Auth0 actually expires - if the session // we create expires first it should silently be re-created without the user noticing const [getAuthStateErrorString, setGetAuthStateErrorString] = useState< string | null >(null); const [authState, setAuthState] = useState<StatusData | null>(null); useEffect(() => { (async () => { const [data, errmsg] = await authStatusRequestWithRetry(); if (errmsg !== undefined) { setGetAuthStateErrorString(errmsg); return; } // The following check is like an assertion: that has to be a guarantee // provided by `authStatusRequestWithRetry()`. The TS return type of // `authStatusRequestWithRetry()` can probably be tuned to make this // unnecessary. if (data !== undefined) { setAuthState(data); return; } throw new Error("authStatusRequestWithRetry() returned [undef, undef]"); })(); }, [setGetAuthStateErrorString, setAuthState]); // let [{ data, loading: loadingStatus, error: statusError }] = useAxios({ // url: "/_/auth/status", // method: "GET", // withCredentials: true // }); // // terrcin: ugh, don't know how to cast this in the above useAxios with typescript //data = data as StatusData; const appStateRef = useRef<AppState>({ returnTo: window.location.pathname }); const dispatch = useDispatch(); const handleUserLoadedSuccess = useCallback( (userId: string, newSession: boolean = false) => { dispatch(setCurrentUser(userId)); if (newSession) { let returnTo = appStateRef.current?.returnTo || DEFAULT_PATHNAME; if (returnTo === "/login") { // This covers the case of the user clicking "logout", being redirected to the login page, and then immediately // logging in again. The system will see them coming from "/login" so will think that's where they should be // redirected back there. This saves them a hop. returnTo = DEFAULT_PATHNAME; } // Can't use "history.push(returnTo)" here as it doesn't update the url, have not looked into "why" we can't window.location.href = makeUrl(returnTo); } }, [dispatch] ); useEffect(() => { if (authState?.currentUserId) { handleUserLoadedSuccess(authState.currentUserId); } }, [handleUserLoadedSuccess, authState?.currentUserId]); useEffect(() => { if (authState?.buildInfo) { dispatch(updateOpstraceBuildInfo({ buildInfo: authState.buildInfo })); } }, [authState?.buildInfo, dispatch]); const reloadAppState = (appState: AppState = {}) => { appStateRef.current = appState; }; // Note(JP): when `loadingStatus` is truthy then it means that the UI should // show that things are currently loading. It does not mean that the request // succeeded. In fact, when the request fails with a 504 response then // `data.auth0Config` is `undefined` and the Auth0 initializtion below blows // up. if (authState === null && getAuthStateErrorString === null) { // operation iss till in progress return <LoadingPage stage="status-check" />; } if (getAuthStateErrorString !== null) { // Loading current authentication status failed. For now, show the 'login // error' view, offering a 'try again' for login. return <LoginFailedPage errorString={getAuthStateErrorString} />; } // Being here means that `authState` is populated (with expected structure). if (authState === null) { // should not not happen, but that's not reflected by types. throw new Error( "programming err: getAuthStateErrorString and authState are both null" ); } // Handle: authentication state is: user is logged in. if (authState.currentUserId !== null) { return ( <Switch> <Route exact key="/logout" path="/logout" component={() => ( <Auth0Provider domain={authState.auth0Config.domain} clientId={authState.auth0Config.clientId} audience={AUTH0_AUDIENCE} redirectUri={loginUrl()} > <LogoutPage /> </Auth0Provider> )} /> <Redirect key="/login" from="/login" to={DEFAULT_PATHNAME} /> <Route key="app" path="*" component={() => <>{children}</>} /> </Switch> ); } // Handle: authentication state is: user is not logged in // (authState.currentUserId is null) return ( <Switch> <Route key="/login" path="/login" component={() => ( <Auth0Provider domain={authState.auth0Config.domain} clientId={authState.auth0Config.clientId} audience={AUTH0_AUDIENCE} redirectUri={loginUrl()} onRedirectCallback={reloadAppState} > <DetectUser userLoadedSuccess={handleUserLoadedSuccess} appState={appStateRef.current} /> </Auth0Provider> )} /> <Redirect from="*" to="/login" /> </Switch> ); }; const DetectUser = ({ userLoadedSuccess, appState }: { userLoadedSuccess: Function; appState: AppState; }) => { const { isLoading, isAuthenticated, loginWithRedirect } = useAuth0(); const loginHandler = useCallback(() => { loginWithRedirect({ appState }); }, [loginWithRedirect, appState]); if (isLoading) return <LoadingPage stage="auth0" />; else if (isAuthenticated) return <CreateSession userLoadedSuccess={userLoadedSuccess} />; else return <LoginPage onLogin={loginHandler} />; }; const CreateSession = ({ userLoadedSuccess }: { userLoadedSuccess: Function; }) => { const { getAccessTokenSilently } = useAuth0(); const [loginErrorString, setLoginErrorString] = useState<string | null>(null); const [accessDenied, setAccessDenied] = useState<boolean | null>(null); useEffect(() => { (async () => { let at: string; try { // Note(JP): `getAccessTokenSilently()` must have its own local error // handler. It involves a number of HTTP requests behind the scenes. // When this fails the login sequence failed and we should show a // "login failed" error, exposing the detail, offering a button "Try // again" at = await getAccessTokenSilently({ audience: AUTH0_AUDIENCE, opstraceClusterName: CLUSTER_NAME }); } catch (err: any) { setLoginErrorString(`could not get access token: ${err.message}`); // This like is retryable, and the user is supposed to trigger that via // the LoginError view. Let this blow up to show relevant detail in // console and in Sentry. throw err; } // Note(JP): this request exchanges the Auth0 access token into a session // secret. The request must have its own local error handler. Show an // "access denied" error (only!) when a 403 response comes in. let resp: AxiosResponse<{ currentUserId: string }>; try { resp = await loginRequestWithRetry(at); } catch (err: any) { if (err.response) { // non-2xx responses const r = err.response; if (r.status === 403) { // Display the rather specific 'access denied' error page only when // we get the unambiguous signal; which is a 403 response. note: // the response body may contain a reason -- log this? setAccessDenied(true); return; } // TODO: expose parts of the response body if structured err info is // present, in expected format. setLoginErrorString( `POST to /_/auth/session got an unexpected response with status code ${r.status}` ); return; } // timeout errors, transient errors etc // maybe even body deserialization errors when resp headers and body // mismatch setLoginErrorString(`POST to /_/auth/session failed: ${err.message}`); return; } // When we are here, `resp` should not be `undefined` (rely on axios // error handling to ensure that. Filter for expected response body // structure Axios does the JSON deserialization for us. if (resp.data && resp.data.currentUserId) { userLoadedSuccess(resp.data.currentUserId, true); return; } // The response body did not have the expected structure. setLoginErrorString( `POST to /_/auth/session got 2xx response with unexpected body: ${JSON.stringify( resp.data, null, 2 ).slice(0, 500)}` ); })(); }, [ getAccessTokenSilently, userLoadedSuccess, setLoginErrorString, setAccessDenied ]); if (loginErrorString) { return <LoginFailedPage errorString={loginErrorString} />; } if (accessDenied) { return <AccessDeniedPage />; } return <LoadingPage stage="create-session" />; }; /** * Perform GET request to /_/auth/status to get current authentication (and * configuration?) state. Perform a little bit of retrying for what appear to * be transient issues. Goal is to quickly heal short network hiccups but to * still fail reasonably fast if those retries didn't help. * * @returns 2-tuple * [data, errmsg] * `data` is either undefined or validated to be of type `StatusData`; * `errmsg` is a string if `data` is `undefined`, otherwise it is `undefined` * @throws: not expected to throw an error */ async function authStatusRequestWithRetry(): Promise< [StatusData, undefined] | [undefined, string] > { // Use a custom retrying config. Do that by creating a local Axios instance // and then attach the rax logic to it. The outcome is that axios is _not_ // affected globally. // // `timeout`: in Axios, `timeout` controls the entire HTTP request (no more // fine-grained control available). Expect the HTTP request handler in web // app to be reasonably fast; it may however need a tiny bit of time for JWKS // (re)fetching. After ~10 seconds we can and should retry. // //`retry`: retry count for requests that return a response. // `noResponseRetries` is for scenarios where request not sent, response not // received. // // Use default for `statusCodesToRetry`: 100-199, 429, 500-599 // Retry for POST, which is the only method used here. const httpclient = axios.create({ timeout: 5000 }); httpclient.defaults.raxConfig = { instance: httpclient, retry: 3, noResponseRetries: 3, backoffType: "static", retryDelay: 2000, httpMethodsToRetry: ["GET"], onRetryAttempt: err => { const cfg = rax.getConfig(err); console.log( `GET to /_/auth/status: retry attempt #${ cfg!.currentRetryAttempt } after: ${err.message}` ); } }; rax.attach(httpclient); let resp: AxiosResponse<any>; try { resp = await httpclient.request({ method: "GET", url: "/_/auth/status", // really required? is that a cross-site request? goal is to send cookies for current context withCredentials: true }); } catch (err: any) { if (err.response) { // non-2xx responses const r = err.response; return [ undefined, `GET /_/auth/status failed: got an unexpected response with status code ${r.status}` ]; // TODO: expose parts of the response body if structured err info is // present, in expected format. } // timeout errors, transient errors etc. maybe even body deserialization // errors when resp headers and body mismatch return [undefined, `GET /_/auth/status failed: ${err.message}`]; } // When we are here, `resp` should not be `undefined` (rely on axios error // handling to ensure that). Axios does the JSON deserialization for us. // Validate the structure briefly (schema-based validation would be more // rigorous). if (resp.data === undefined) { return [undefined, `GET /_/auth/status failed: response body missing`]; } // type StatusData = { // currentUserId?: string; // auth0Config: { domain: string; clientId: string }; // buildInfo: OpstraceBuildInfo; // }; const d = resp.data; for (const p of ["currentUserId", "auth0Config", "buildInfo"]) { if (!(p in d)) { return [ undefined, `GET /_/auth/status failed: property '${p}' missing in response structure` ]; } } // Data object in response looks good. return [d, undefined]; } /** * Perform POST request to /_/auth/session to exchange Auth0 access token into * session secret. Perform a little bit of retrying for what appear to be * transient issues. Goal is to quickly heal short network hiccups but to still * fail reasonably fast if those retries didn't help. * * @param auth0AccessToken * @returns * axios response upon 2xx HTTP response, no validation on response body * @throws * - axios errors: * - when response is available (err response) * - when no response is available (if retrying didn't heal) */ async function loginRequestWithRetry( auth0AccessToken: string ): Promise<AxiosResponse<any>> { // Use a custom retrying config. Do that by creating a local Axios instance // and then attach the rax logic to it. The outcome is that axios is _not_ // affected globally. // // `timeout`: in Axios, `timeout` controls the entire HTTP request (no more // fine-grained control available). Expect the HTTP request handler in web // app to be reasonably fast; it may however need a tiny bit of time for JWKS // (re)fetching. After ~10 seconds we can and should retry. // //`retry`: retry count for requests that return a response. // `noResponseRetries` is for scenarios where request not sent, response not // received. // // Use default for `statusCodesToRetry`: 100-199, 429, 500-599 // Retry for POST, which is the only method used here. // // Set constant delay between attempts. `retryDelay` (in ms) applies only for // the `static` strategy. Wait about one second between attempts. Goal is to // quickly heal short network hiccups / reconnects, but not try forever. log // detail about those scenarios that leads to retrying. const httpclient = axios.create({ timeout: 10000 }); httpclient.defaults.raxConfig = { instance: httpclient, retry: 3, noResponseRetries: 3, backoffType: "static", retryDelay: 1000, httpMethodsToRetry: ["POST"], onRetryAttempt: err => { const cfg = rax.getConfig(err); console.log( `POST to /_/auth/session: retry attempt #${ cfg!.currentRetryAttempt } after: ${err.message}` ); } }; rax.attach(httpclient); const resp: AxiosResponse<any> = await httpclient.request({ method: "POST", url: "/_/auth/session", headers: { Authorization: `Bearer ${auth0AccessToken}` } }); return resp; }
the_stack
import Color from 'color' import {Draft, immerable} from 'immer' // @ts-ignore import * as deepcopy from 'deepcopy' import {EffectiveItemInfo} from './data-store' import { dateToDayID, dayIDToDate, daysInMonth, dowOfDayID, } from '../util/time-util' import {Task} from './data-analyzer' import {arrayToMap} from '../util/util' import { quickDeserialize, quickDeserializeRequired, SerializedObject, SerializedObjectMap, } from '../util/serialization' export type ItemID = number export type DayID = number export const NEG_INF_DAY_ID = -100000000 export const INF_DAY_ID = 100000000 export class DisplayDate { /** * @param year * @param month 1 represents January * @param day 1 represents first day * @param dow 0 represents Sunday */ constructor( public readonly year: number, public readonly month: number, public readonly day: number, public readonly dow: number, ) { } } export enum ItemStatus { ACTIVE, COMPLETED, } export enum SessionType { COMPLETED, SCHEDULED, PROJECTED, } /** * NOTE: All repeat types must be interface extending this interface, and be * deep-copyable. * Also, each repeat type should be plain objects that are directly * SerializedObjects. */ export interface RepeatType { readonly type: string } export function serializeRepeatTypeToObject(value: RepeatType) { return value as unknown as SerializedObject } export function deserializeRepeatTypeFromObject(obj: SerializedObject) { return obj as unknown as RepeatType } export class RepeatTypeFactory<T extends RepeatType> { /** * @param type Must match the type of the repeat type it creates. * @param create Factory function. */ constructor( readonly type: string, readonly create: () => T, ) { } } export interface DailyRepeatType extends RepeatType { readonly type: 'day' } export interface WeeklyRepeatType extends RepeatType { readonly type: 'week' dayOfWeek: number[] } export interface MonthlyRepeatType extends RepeatType { readonly type: 'month' dayOfMonth: number[] } export interface YearlyRepeatType extends RepeatType { readonly type: 'year' } export const REPEAT_TYPE_FACTORIES: RepeatTypeFactory<RepeatType>[] = [ new RepeatTypeFactory<DailyRepeatType>('day', () => ({ type: 'day', })), new RepeatTypeFactory<WeeklyRepeatType>('week', () => ({ type: 'week', dayOfWeek: [], })), new RepeatTypeFactory<MonthlyRepeatType>('month', () => ({ type: 'month', dayOfMonth: [], })), new RepeatTypeFactory<YearlyRepeatType>('year', () => ({ type: 'year', })), ] export const REPEAT_TYPE_FACTORY_BY_TYPE = (() => { const result = new Map<string, RepeatTypeFactory<RepeatType>>() REPEAT_TYPE_FACTORIES.forEach(factory => { result.set(factory.type, factory) }) return result })() export class Item { [immerable] = true /** * The maximum of self cost and children effective cost */ effectiveCost: number /** * Effective cost subtracted by children effective cost */ residualCost: number constructor( public readonly id: ItemID, public readonly name: string = '', public readonly status: ItemStatus = ItemStatus.ACTIVE, public readonly cost: number = 1, public readonly autoAdjustPriority: boolean = true, public readonly childrenIDs: ItemID[] = [], public readonly tryUseParentColor: boolean = true, public readonly color: Color, public readonly parentID?: ItemID, public readonly deferDate?: DayID, public readonly dueDate?: DayID, public readonly repeat?: RepeatType, public readonly repeatInterval: number = 1, public readonly repeatEndDate?: DayID, public readonly repeatOnCompletion: boolean = false, public readonly repeatDeferOffset?: number, ) { this.repeat = deepcopy(repeat) this.effectiveCost = cost this.residualCost = cost } toDraft() { return new ItemDraft( this.id, this.name, this.status, this.cost, this.autoAdjustPriority, this.tryUseParentColor, this.color, this.parentID, this.deferDate, this.dueDate, this.repeat, this.repeatInterval, this.repeatEndDate, this.repeatOnCompletion, this.repeatDeferOffset, ) } static serializeToObject(value: Item): SerializedObject { return { effectiveCost: value.effectiveCost, residualCost: value.residualCost, id: value.id, name: value.name, status: value.status, cost: value.cost, autoAdjustPriority: value.autoAdjustPriority, childrenIDs: value.childrenIDs, tryUseParentColor: value.tryUseParentColor, color: value.color.hex(), parentID: value.parentID, deferDate: value.deferDate, dueDate: value.dueDate, repeat: value.repeat === undefined ? undefined : serializeRepeatTypeToObject(value.repeat), repeatInterval: value.repeatInterval, repeatEndDate: value.repeatEndDate, repeatOnCompletion: value.repeatOnCompletion, repeatDeferOffset: value.repeatDeferOffset, } } static deserializeFromObject(obj: SerializedObject): Item { const map = obj as SerializedObjectMap const result = new Item( quickDeserializeRequired(map.id), quickDeserializeRequired(map.name), quickDeserializeRequired(map.status), quickDeserializeRequired(map.cost), quickDeserializeRequired(map.autoAdjustPriority), quickDeserializeRequired(map.childrenIDs), quickDeserializeRequired(map.tryUseParentColor), Color(map.color as string), quickDeserialize(map.parentID, undefined), quickDeserialize(map.deferDate, undefined), quickDeserialize(map.dueDate, undefined), map.repeat === undefined ? undefined : deserializeRepeatTypeFromObject(map.repeat), quickDeserializeRequired(map.repeatInterval), quickDeserialize(map.repeatEndDate, undefined), quickDeserializeRequired(map.repeatOnCompletion), quickDeserialize(map.repeatDeferOffset, undefined), ) result.effectiveCost = quickDeserializeRequired(map.effectiveCost) result.residualCost = quickDeserializeRequired(map.residualCost) return result } } const BLACK = Color(0, 0, 0) export class ItemDraft { constructor( public id: ItemID = -1, public name: string = '', public status: ItemStatus = ItemStatus.ACTIVE, public cost: number = 1, public autoAdjustPriority: boolean = true, public tryUseParentColor: boolean = true, public color: Color = BLACK, public parentID?: ItemID, public deferDate?: DayID, public dueDate?: DayID, public repeat?: RepeatType, public repeatInterval: number = 1, public repeatEndDate?: DayID, public repeatOnCompletion: boolean = false, public repeatDeferOffset?: number, ) { this.repeat = deepcopy(repeat) } toNewItem(id: ItemID) { return new Item( id, this.name, this.status, this.cost, this.autoAdjustPriority, [], this.tryUseParentColor, this.color, this.parentID, this.deferDate, this.dueDate, this.repeat, this.repeatInterval, this.repeatEndDate, this.repeatOnCompletion, this.repeatDeferOffset, ) } applyToItem(item: Draft<Item>) { item.name = this.name item.status = this.status item.cost = this.cost item.autoAdjustPriority = this.autoAdjustPriority item.tryUseParentColor = this.tryUseParentColor item.color = this.color item.parentID = this.parentID item.deferDate = this.deferDate item.dueDate = this.dueDate item.repeat = deepcopy(this.repeat) item.repeatInterval = this.repeatInterval item.repeatEndDate = this.repeatEndDate item.repeatOnCompletion = this.repeatOnCompletion item.repeatDeferOffset = this.repeatDeferOffset } } export const SESSION_TYPE_TO_ICON = { [SessionType.COMPLETED]: 'check_circle', [SessionType.SCHEDULED]: 'schedule', [SessionType.PROJECTED]: 'flash_on', } export type Repeater = (firstTask: Task, itemInfo: EffectiveItemInfo, maxProjectionEndDate: DayID) => () => Task | undefined /** * NOTE: * - Due date is assumed to always exist, otherwise repeat is not allowed. * * TODO: refactor to reuse code between repeaters */ export const DEFAULT_REPEATERS: { type: string, repeater: Repeater, }[] = [ { type: 'day', repeater: (firstTask, itemInfo, maxProjectionEndDate) => { /* * Currently the defer date is always set to last due date + 1. * If needed, the logic to use startToEnd offset: * * const startToEnd = (firstTask.start !== undefined ? * firstTask.end - firstTask.start : undefined) * * Then set each task's start to: * * start: startToEnd === undefined ? lastEnd + 1 : * Math.max(lastEnd + 1, end - startToEnd), */ if (firstTask.end === undefined) return () => undefined let end = firstTask.end const repeatInterval = itemInfo.repeatInterval if (repeatInterval <= 0) return () => undefined let lastEnd = end return () => { // This ensures that there's at least one task after max date if (end > maxProjectionEndDate) return undefined end += repeatInterval if (itemInfo.repeatEndDate !== undefined && end > itemInfo.repeatEndDate) { return undefined } const result = { itemID: firstTask.itemID, cost: firstTask.cost, start: lastEnd + 1, end, } lastEnd = end return result } }, }, { type: 'week', repeater: (firstTask, itemInfo, maxProjectionEndDate) => { if (firstTask.end === undefined) return () => undefined let end = firstTask.end const repeatInterval = itemInfo.repeatInterval if (repeatInterval <= 0) return () => undefined let lastEnd = end const r = itemInfo.repeat as WeeklyRepeatType const dayOfWeek = r.dayOfWeek.slice() dayOfWeek.sort((a, b) => a - b) const simpleRepeat = dayOfWeek.length === 0 let dayOfWeekPtr = -1 return () => { // This ensures that there's at least one task after max date if (end > maxProjectionEndDate) return undefined if (simpleRepeat) { end += repeatInterval * 7 } else { const endDOW = dowOfDayID(end) const endStartOfWeek = end - endDOW if (dayOfWeekPtr === -1) { let nextDOW = -1 dayOfWeekPtr = 0 const count = dayOfWeek.length for (let i = 0; i < count; i++) { const dow = dayOfWeek[i] if (dow <= endDOW) continue nextDOW = dow dayOfWeekPtr = i break } if (nextDOW === -1) { end = endStartOfWeek + repeatInterval * 7 + dayOfWeek[0] } else { end = endStartOfWeek + nextDOW } // dayOfWeekPtr will point to where end is at } else { dayOfWeekPtr++ if (dayOfWeekPtr >= dayOfWeek.length) { end = endStartOfWeek + repeatInterval * 7 + dayOfWeek[0] dayOfWeekPtr = 0 } else { end = endStartOfWeek + dayOfWeek[dayOfWeekPtr] } } } if (itemInfo.repeatEndDate !== undefined && end > itemInfo.repeatEndDate) { return undefined } const result = { itemID: firstTask.itemID, cost: firstTask.cost, start: lastEnd + 1, end, } lastEnd = end return result } }, }, { type: 'month', repeater: (firstTask, itemInfo, maxProjectionEndDate) => { if (firstTask.end === undefined) return () => undefined let end = firstTask.end const repeatInterval = itemInfo.repeatInterval if (repeatInterval <= 0) return () => undefined let lastEnd = end // TODO dayOfMonth is currently not supported const endDate = dayIDToDate(end) const year = endDate.getFullYear() let month = endDate.getMonth() const day = endDate.getDate() return () => { // This ensures that there's at least one task after max date if (end > maxProjectionEndDate) return undefined month += repeatInterval end = dateToDayID( new Date(year, month, Math.min(day, daysInMonth(year, month)))) if (itemInfo.repeatEndDate !== undefined && end > itemInfo.repeatEndDate) { return undefined } const result = { itemID: firstTask.itemID, cost: firstTask.cost, start: lastEnd + 1, end, } lastEnd = end return result } }, }, { type: 'year', repeater: (firstTask, itemInfo, maxProjectionEndDate) => { if (firstTask.end === undefined) return () => undefined let end = firstTask.end const repeatInterval = itemInfo.repeatInterval if (repeatInterval <= 0) return () => undefined let lastEnd = end const endDate = dayIDToDate(end) let year = endDate.getFullYear() const month = endDate.getMonth() const day = endDate.getDate() return () => { // This ensures that there's at least one task after max date if (end > maxProjectionEndDate) return undefined year += repeatInterval end = dateToDayID( new Date(year, month, Math.min(day, daysInMonth(year, month)))) if (itemInfo.repeatEndDate !== undefined && end > itemInfo.repeatEndDate) { return undefined } const result = { itemID: firstTask.itemID, cost: firstTask.cost, start: lastEnd + 1, end, } lastEnd = end return result } }, }, ] export const DEFAULT_REPEATER_BY_TYPE = (() => { const result = new Map<string, Repeater>() DEFAULT_REPEATERS.forEach(({type, repeater}) => { result.set(type, repeater) }) return result })() export type QuotaRuleID = number /** * NOTE: All quota rules must be interface extending this interface, and be * deep-copyable. * Also, they should be serialized objects just by themselves. */ export interface QuotaRule { readonly type: string id: QuotaRuleID firstDate?: DayID lastDate?: DayID } export function serializeQuotaRuleToObject(quotaRule: QuotaRule): SerializedObject { return quotaRule as unknown as SerializedObject } export function deserializeQuotaRuleFromObject(obj: SerializedObject): QuotaRule { return obj as unknown as QuotaRule } export interface ConstantQuotaRule extends QuotaRule { readonly type: 'constant' value: number dayOfWeek: number[] // Empty means everyday } export type QuotaRuleDraft<T extends QuotaRule> = { [K in keyof T]: T[K] } export function quotaRuleToDraft<T extends QuotaRule>(quotaRule: T) { return deepcopy(quotaRule) as unknown as QuotaRuleDraft<T> } export function draftToQuotaRule<T extends QuotaRule>(draft: QuotaRuleDraft<T>) { return deepcopy(draft) as unknown as T } export function isConstantQuotaRule(quotaRule: QuotaRule): quotaRule is ConstantQuotaRule { return quotaRule.type === 'constant' } export const DEFAULT_QUOTA_RULE_APPLIERS: { type: string, apply(rule: QuotaRule, rangeFirst: DayID, rangeLast: DayID, result: Map<DayID, number>), }[] = [ { type: 'constant', apply(rule, rangeFirst, rangeLast, result) { const {firstDate, lastDate, value, dayOfWeek} = rule as ConstantQuotaRule if (firstDate !== undefined && lastDate !== undefined && firstDate === lastDate) { // Single-day rule if (firstDate >= rangeFirst && firstDate <= rangeLast) { result.set(firstDate, value) } return } const dayOfWeekSet = dayOfWeek.length === 0 ? undefined : new Set(dayOfWeek) if (firstDate !== undefined) { rangeFirst = Math.max(rangeFirst, firstDate) } if (lastDate !== undefined) { rangeLast = Math.min(rangeLast, lastDate) } for (let d = rangeFirst; d <= rangeLast; d++) { if (dayOfWeekSet === undefined || dayOfWeekSet.has(dowOfDayID(d))) { result.set(d, value) } } }, }, ] export const DEFAULT_QUOTA_RULE_APPLIER_BY_TYPE = arrayToMap( DEFAULT_QUOTA_RULE_APPLIERS, item => item.type)
the_stack
import {assert} from '../platform/assert-web.js'; import {ArcId, IdGenerator, Id} from './id.js'; import {Manifest} from './manifest.js'; import {Recipe, Particle} from './recipe/lib-recipe.js'; import {Runtime} from './runtime.js'; import {Dictionary} from '../utils/lib-utils.js'; import {newRecipe} from './recipe/lib-recipe.js'; import {VolatileStorageKey} from './storage/drivers/volatile.js'; import {Capabilities} from './capabilities.js'; import {ArcInfo, StartArcOptions, DeserializeArcOptions, ArcInfoOptions, NewArcInfoOptions, RunArcOptions} from './arc-info.js'; import {ArcHost, ArcHostFactory, SingletonArcHostFactory} from './arc-host.js'; import {Exists} from './storage/drivers/driver.js'; import {StoreInfo} from './storage/store-info.js'; import {Type} from '../types/lib-types.js'; export interface Allocator { registerArcHost(factory: ArcHostFactory); startArc(options: StartArcOptions): Promise<ArcInfo>; // TODO(b/182410550): Callers should pass RunArcOptions to runPlanInArc, // if initially calling startArc with no planName. runPlanInArc(arcInfo: ArcInfo, plan: Recipe, arcOptions?: RunArcOptions, reinstantiate?: boolean): Promise<void[]>; deserialize(options: DeserializeArcOptions): Promise<ArcInfo>; stopArc(arcId: ArcId); // TODO(b/182410550): This method is only called externally when speculating. // It should become private, once Planning is incorporated into Allocator APIs. // Once private, consider not returning a value. assignStorageKeys(arcId: ArcId, plan: Recipe, idGenerator?: IdGenerator): Promise<Recipe>; cloneArc(arcId: ArcId, options: StartArcOptions): Promise<ArcInfo>; } export class AllocatorImpl implements Allocator { protected readonly arcHostFactories: ArcHostFactory[] = []; protected readonly arcInfoById = new Map<ArcId, ArcInfo>(); protected readonly hostById: Dictionary<ArcHost> = {}; constructor(protected readonly runtime: Runtime) {} registerArcHost(factory: ArcHostFactory) { this.arcHostFactories.push(factory); } protected newArcInfo(options: NewArcInfoOptions & RunArcOptions): ArcInfo { assert(options.arcId || options.arcName); let arcId = null; let idGenerator = null; if (options.arcId) { arcId = options.arcId; } else { idGenerator = IdGenerator.newSession(); arcId = options.outerArcId ? this.arcInfoById.get(options.outerArcId).generateID(options.arcName) : idGenerator.newArcId(options.arcName); } assert(arcId); idGenerator = idGenerator || IdGenerator.newSession(); if (!this.arcInfoById.has(arcId)) { assert(idGenerator, 'or maybe need to create one anyway?'); this.arcInfoById.set(arcId, new ArcInfo(this.buildArcInfoOptions(arcId, idGenerator, options.outerArcId, options.isSpeculative))); } return this.arcInfoById.get(arcId); } private buildArcInfoOptions(id: ArcId, idGenerator? : IdGenerator, outerArcId?: ArcId, isSpeculative?: boolean): ArcInfoOptions { return { id, context: this.runtime.context, capabilitiesResolver: this.runtime.getCapabilitiesResolver(id), idGenerator, outerArcId, isSpeculative }; } public async startArc(options: StartArcOptions): Promise<ArcInfo> { const arcInfo = this.newArcInfo(options); if (options.planName) { const plan = this.runtime.context.allRecipes.find(r => r.name === options.planName); assert(plan); await this.runPlanInArc(arcInfo, plan, options); } return arcInfo; } async runPlanInArc(arcInfo: ArcInfo, plan: Recipe, arcOptions?: RunArcOptions, reinstantiate?: boolean): Promise<void[]> { assert(plan.tryResolve(), `Cannot run an unresolved recipe: ${plan.toString({showUnresolved: true})}.`); if (arcOptions?.modality) { assert(plan.isCompatible(arcOptions?.modality), `Cannot instantiate recipe ${plan.toString()} with [${plan.modality.names}] modalities in '${arcOptions?.modality.names}' arc`); } const partitionByFactory = new Map<ArcHostFactory, Particle[]>(); // Partition the `plan` into particles by ArcHostFactory. for (const particle of plan.particles) { const hostFactory = [...this.arcHostFactories.values()].find( factory => factory.isHostForParticle(particle)); assert(hostFactory); if (!partitionByFactory.has(hostFactory)) { partitionByFactory.set(hostFactory, []); } partitionByFactory.get(hostFactory).push(particle); } plan = await this.assignStorageKeys(arcInfo.id, plan); // Start all partitions. const res = Promise.all([...partitionByFactory.keys()].map(async factory => { const host = factory.createHost(); this.hostById[host.hostId] = host; const partial = newRecipe(); plan.mergeInto(partial); const partitionParticles = partitionByFactory.get(factory); plan.particles.forEach((particle, index) => { if (!partitionParticles.find(p => p.name === particle.name)) { plan.particles.splice(index, 1); } }); assert(partial.tryResolve()); const {particles, handles} = await arcInfo.instantiate(partial); const partition = { arcHostId: host.hostId, arcInfo, arcOptions, particles, handles, reinstantiate, modality: arcOptions?.modality }; arcInfo.partitions.push(partition); arcInfo.addSlotContainers(host.slotContainers); return host.start(partition); })); return res; } async assignStorageKeys(arcId: ArcId, plan: Recipe, idGenerator?: IdGenerator): Promise<Recipe> { // TODO(b/182410550): All internal caller(s) should pass non normalized recipe. // Remove this check, once the method is private, and don't return recipe. if (plan.isNormalized()) { plan = plan.clone(); } const arcInfo = this.arcInfoById.has(arcId) ? this.arcInfoById.get(arcId) : new ArcInfo(this.buildArcInfoOptions(arcId, idGenerator)); // Assign storage keys for all `create` & `copy` stores. for (const handle of plan.handles) { if (handle.immediateValue) continue; if (['copy', 'create'].includes(handle.fate)) { let type = handle.type; if (handle.fate === 'create') { assert(type.maybeResolve(), `Can't assign resolved type to ${type}`); } type = type.resolvedType(); assert(type.isResolved(), `Can't create handle for unresolved type ${type}`); handle.id = handle.fate === 'create' && !!handle.id ? handle.id : arcInfo.generateID().toString(); handle.fate = 'use'; handle.storageKey = await this.runtime.getCapabilitiesResolver(arcId) .createStorageKey(handle.capabilities || Capabilities.create(), type, handle.id); } } assert(plan.tryResolve()); return plan; } public stopArc(arcId: ArcId) { const arcInfo = this.arcInfoById.get(arcId); assert(arcInfo); for (const innerArcInfo of arcInfo.innerArcs) { this.stopArc(innerArcInfo.id); } for (const partition of arcInfo.partitions) { const host = this.hostById[partition.arcHostId]; assert(host); host.stop(arcId); } this.arcInfoById.delete(arcId); } async deserialize(options: DeserializeArcOptions): Promise<ArcInfo> { const {serialization, slotComposer, fileName, inspectorFactory} = options; const manifest = await this.runtime.parse(serialization, {fileName, context: this.runtime.context}); const arcId = Id.fromString(manifest.meta.name); const storageKey = this.runtime.storageKeyParser.parse(manifest.meta.storageKey); assert(!this.arcInfoById.has(arcId)); const idGenerator = IdGenerator.newSession(); const arcInfo = new ArcInfo(this.buildArcInfoOptions(arcId, idGenerator)); this.arcInfoById.set(arcId, arcInfo); await this.startArc({...options, arcId, idGenerator}); await this.createStoresAndCopyTags(arcId, manifest); await this.runPlanInArc(arcInfo, manifest.activeRecipe, {}, /* reinstantiate= */ true); return arcInfo; } protected async createStoresAndCopyTags(arcId: ArcId, manifest: Manifest): Promise<void[]> { // Temporarily this can only be implemented in SingletonAllocator subclass, // because it requires access to `host` and Arc's store creation API. return Promise.all([]); } async cloneArc(arcId: ArcId, options: StartArcOptions): Promise<ArcInfo> { const arcInfo = this.arcInfoById.get(arcId); assert(arcInfo); const clonedArcInfo = await this.startArc({arcId: arcInfo.generateID(), outerArcId: arcInfo.outerArcId, ...options}); // , isSpeculative: true const storeMap: Map<StoreInfo<Type>, StoreInfo<Type>> = new Map(); for (const storeInfo of arcInfo.stores) { // TODO(alicej): Should we be able to clone a StoreMux as well? const cloneInfo = await clonedArcInfo.createStoreInfo(storeInfo.type, { storageKey: new VolatileStorageKey(clonedArcInfo.id, storeInfo.id), exists: Exists.MayExist, id: storeInfo.id }); storeMap.set(storeInfo, cloneInfo); if (arcInfo.storeDescriptions.has(storeInfo)) { clonedArcInfo.storeDescriptions.set(cloneInfo, arcInfo.storeDescriptions.get(storeInfo)); } } await this.runPlanInArc(clonedArcInfo, arcInfo.activeRecipe.clone()); for (const innerArcInfo of arcInfo.innerArcs) { await this.cloneArc(innerArcInfo.id, options); } return clonedArcInfo; } } // Note: This is an interim solution. It is needed while stores are created directly on the Arc, // hence callers need the ability to access the Arc object before any recipes were instantiated // (and hence Arc object created in the Host). export class SingletonAllocator extends AllocatorImpl { constructor(public readonly runtime: Runtime, public readonly host: ArcHost) { super(runtime); this.registerArcHost(new SingletonArcHostFactory(host)); this.hostById[host.hostId] = host; } protected newArcInfo(options: NewArcInfoOptions & RunArcOptions): ArcInfo { const arcInfo = super.newArcInfo(options); arcInfo.addSlotContainers(this.host.slotContainers); const partition = { arcInfo, arcOptions: {...options}, arcHostId: this.host.hostId, particles: [], handles: [], modality: options.modality }; arcInfo.partitions.push(partition); this.host.start(partition); return arcInfo; } async createStoresAndCopyTags(arcId: ArcId, manifest: Manifest): Promise<void[]> { const arc = this.host.getArcById(arcId); return Promise.all(manifest.stores.map(async storeInfo => { const tags = [...manifest.storeTagsById[storeInfo.id]]; if (storeInfo.storageKey instanceof VolatileStorageKey) { arc.volatileMemory.deserialize(storeInfo.model, storeInfo.storageKey.unique); } const arcInfo = arc.arcInfo; await arcInfo.registerStore(storeInfo, tags); arcInfo.addHandleToActiveRecipe(storeInfo); const newHandle = arcInfo.activeRecipe.handles.find(h => h.id === storeInfo.id); const handle = manifest.activeRecipe.handles.find(h => h.id === storeInfo.id); assert(newHandle); assert(handle); for (const tag of handle.tags) { if (newHandle.tags.includes(tag)) { continue; } newHandle.tags.push(tag); } })); } }
the_stack
import { EventEmitter } from 'events'; import { IState } from './IState'; import { ClientType } from '../Client'; import { ClockSync } from '../ClockSync'; import { InteractiveError } from '../errors'; import { IClient } from '../IClient'; import { merge } from '../merge'; import { MethodHandlerManager } from '../methods/MethodHandlerManager'; import { Method, Reply } from '../wire/packets'; import { Group } from './Group'; import { IParticipant, IScene, ISceneDataArray } from './interfaces'; import { IControl } from './interfaces/controls/IControl'; import { IGroup, IGroupData, IGroupDataArray } from './interfaces/IGroup'; import { ISceneData } from './interfaces/IScene'; import { IRawValues } from '../interfaces'; import { Scene } from './Scene'; import { StateFactory } from './StateFactory'; /** * State is a store of all of the components of an interactive session. * * It contains Scenes, Groups and Participants and keeps them up to date by listening to * interactive events which update and change them. You can query State to * examine and alter components of the interactive session. */ export class State extends EventEmitter implements IState { /** * A Map of group ids to their corresponding Group Object. */ private groups = new Map<string, Group>(); /** * the ready state of this session, is the GameClient in this session ready to receive input? */ public isReady: boolean; private methodHandler = new MethodHandlerManager(); private stateFactory = new StateFactory(); private scenes = new Map<string, Scene>(); private world: any = {}; private client: IClient; private participants = new Map<string, IParticipant>(); private clockDelta: number = 0; private clockSyncer = new ClockSync({ sampleFunc: () => this.client.getTime(), }); /** * Constructs a new State instance. Based on the passed client type it will * hook into the appropriate methods for that type to keep itself up to date. */ constructor(private clientType: ClientType) { super(); this.methodHandler.addHandler('onReady', readyMethod => { this.isReady = readyMethod.params.isReady; this.emit('ready', this.isReady); }); // Scene Events this.methodHandler.addHandler('onSceneCreate', res => { res.params.scenes.forEach(scene => this.onSceneCreate(scene)); }); this.methodHandler.addHandler('onSceneDelete', res => { this.onSceneDelete(res.params.sceneID, res.params.reassignSceneID); }); this.methodHandler.addHandler('onSceneUpdate', res => { res.params.scenes.forEach(scene => this.onSceneUpdate(scene)); }); // Group Events this.methodHandler.addHandler('onGroupCreate', res => { res.params.groups.forEach(group => this.onGroupCreate(group)); }); this.methodHandler.addHandler('onGroupDelete', res => { this.onGroupDelete(res.params.groupID, res.params.reassignGroupID); }); this.methodHandler.addHandler('onGroupUpdate', res => { res.params.groups.forEach(group => this.onGroupUpdate(group)); }); // Control Events this.methodHandler.addHandler('onControlCreate', res => { const scene = this.scenes.get(res.params.sceneID); if (scene) { scene.onControlsCreated(res.params.controls); } }); this.methodHandler.addHandler('onControlDelete', res => { const scene = this.scenes.get(res.params.sceneID); if (scene) { scene.onControlsDeleted(res.params.controls); } }); this.methodHandler.addHandler('onControlUpdate', res => { const scene = this.scenes.get(res.params.sceneID); if (scene) { scene.onControlsUpdated(res.params.controls); } }); this.methodHandler.addHandler('onWorldUpdate', res => { // A WHOLE NEW WORLD // A NEW FANTASTIC POINT OF VIEW // Cloned to preserve original const newWorld = Object.assign({}, res.params); // Filter scenes out delete newWorld.scenes; this.onWorldUpdate(newWorld); res.params.scenes.forEach(scene => this.onSceneUpdate(scene)); }); this.clockSyncer.on('delta', (delta: number) => { this.clockDelta = delta; }); if (this.clientType === ClientType.GameClient) { this.addGameClientHandlers(); } else { this.addParticipantHandlers(); } } /** * Synchronize scenes takes a collection of scenes from the server * and hydrates the Scene store with them. */ public synchronizeScenes(data: ISceneDataArray): IScene[] { return data.scenes.map(scene => this.onSceneCreate(scene)); } public synchronizeGroups(data: IGroupDataArray): IGroup[] { return data.groups.map(group => this.onGroupCreate(group)); } private addParticipantHandlers() { // A participant only gets onParticipantUpdate/Join events for themselves. this.methodHandler.addHandler('onParticipantUpdate', res => { this.emit('selfUpdate', res.params.participants[0]); }); this.methodHandler.addHandler('onParticipantJoin', res => { this.emit('selfUpdate', res.params.participants[0]); }); } private addGameClientHandlers() { this.methodHandler.addHandler('onParticipantJoin', res => { res.params.participants.forEach(participant => { this.participants.set(participant.sessionID, participant); this.emit('participantJoin', participant); }); }); this.methodHandler.addHandler('onParticipantLeave', res => { res.params.participants.forEach(participant => { this.participants.delete(participant.sessionID); this.emit('participantLeave', participant.sessionID, participant); }); }); this.methodHandler.addHandler('onParticipantUpdate', res => { res.params.participants.forEach(participant => { merge(this.participants.get(participant.sessionID), participant); }); }); this.methodHandler.addHandler('giveInput', res => { const control = this.getControl(res.params.input.controlID); if (control) { const participant = this.getParticipantBySessionID(res.params.participantID); control.receiveInput(res.params, participant); } }); } public setClient(client: IClient) { this.client = client; this.client.on('open', () => this.clockSyncer.start()); this.client.on('close', () => this.clockSyncer.stop()); this.stateFactory.setClient(client); } /** * Processes a server side method using State's method handler. */ public processMethod(method: Method<any>): void | Reply { try { return this.methodHandler.handle(method); } catch (e) { if (e instanceof InteractiveError.Base) { return Reply.fromError(method.id, e); } throw e; } } /** * Returns the local time matched to the sync of the Mixer server clock. */ public synchronizeLocalTime(time: Date | number = Date.now()): Date { if (time instanceof Date) { time = time.getTime(); } return new Date(time - this.clockDelta); } /** * Returns the remote time matched to the local clock. */ public synchronizeRemoteTime(time: Date | number): Date { if (time instanceof Date) { time = time.getTime(); } return new Date(time + this.clockDelta); } /** * Completely clears this state instance emptying all Scene, Group and Participant records */ public reset() { this.scenes.forEach(scene => scene.destroy()); this.scenes.clear(); this.clockDelta = 0; this.isReady = false; this.participants.clear(); this.groups.clear(); } /** * Updates an existing scene in the game session. */ public onSceneUpdate(scene: ISceneData) { const targetScene = this.getScene(scene.sceneID); if (targetScene) { targetScene.update(scene); } } /** * Removes a scene and reassigns the groups that were on it. */ public onSceneDelete(sceneID: string, reassignSceneID: string) { const targetScene = this.getScene(sceneID); if (targetScene) { targetScene.destroy(); this.scenes.delete(sceneID); this.emit('sceneDeleted', sceneID, reassignSceneID); } } /** * Inserts a new scene into the game session. */ public onSceneCreate(data: ISceneData): IScene { let scene = this.scenes.get(data.sceneID); if (scene) { this.onSceneUpdate(data); return scene; } scene = this.stateFactory.createScene(data); if (data.controls) { scene.onControlsCreated(data.controls); } this.scenes.set(data.sceneID, scene); this.emit('sceneCreated', scene); return scene; } /** * Adds an array of Scenes to its state store. */ public addScenes(scenes: ISceneData[]): IScene[] { return scenes.map(scene => this.onSceneCreate(scene)); } /** * Updates an existing scene in the game session. */ public onGroupUpdate(group: IGroupData) { const targetGroup = this.getGroup(group.groupID); if (targetGroup) { targetGroup.update(group); } } /** * Removes a group and reassigns the participants that were in it. */ public onGroupDelete(groupID: string, reassignGroupID: string) { const targetGroup = this.getGroup(groupID); if (targetGroup) { targetGroup.destroy(); this.groups.delete(groupID); this.emit('groupDeleted', groupID, reassignGroupID); } } /** * Inserts a new group into the game session. */ public onGroupCreate(data: IGroupData): Group { let group = this.groups.get(data.groupID); if (group) { this.onGroupUpdate(data); return group; } group = new Group(data); this.groups.set(data.groupID, group); this.emit('groupCreated', group); return group; } /** * Merges in new world properties and emits an event to any listeners. */ public onWorldUpdate(data: IRawValues) { this.world = { ...this.world, ...data }; this.emit('worldUpdated', this.world); } public getWorld(): IRawValues { return this.world; } /** * Retrieve all groups. */ public getGroups(): Map<string, Group> { return this.groups; } /** * Retrieve a group with the matching ID from the group store. */ public getGroup(id: string): Group { return this.groups.get(id); } /** * Retrieve all scenes */ public getScenes(): Map<string, Scene> { return this.scenes; } /** * Retrieve a scene with the matching ID from the scene store. */ public getScene(id: string): IScene { return this.scenes.get(id); } /** * Searches through all stored Scenes to find a Control with the matching ID */ public getControl(id: string): IControl { let result: IControl; this.scenes.forEach(scene => { const found = scene.getControl(id); if (found) { result = found; } }); return result; } /** * Retrieve all participants. */ public getParticipants(): Map<string, IParticipant> { return this.participants; } private getParticipantBy<K extends keyof IParticipant>( field: K, value: IParticipant[K], ): IParticipant { let result; this.participants.forEach(participant => { if (participant[field] === value) { result = participant; } }); return result; } /** * Retrieve a participant by their Mixer UserId. */ public getParticipantByUserID(id: number): IParticipant { return this.getParticipantBy('userID', id); } /** * Retrieve a participant by their Mixer Username. */ public getParticipantByUsername(name: string): IParticipant { return this.getParticipantBy('username', name); } /** * Retrieve a participant by their sessionID with the current Interactive session. */ public getParticipantBySessionID(id: string): IParticipant { return this.participants.get(id); } }
the_stack
import { TMapAnyKeyGenericArray } from "./TMapAnyKeyGenericArray"; import { TMapAnyKeyGenericArrays } from "./TMapAnyKeyGenericArrays"; import { TMapAnyKeyGenericValue } from "./TMapAnyKeyGenericValue"; import { TMapAnyKeyGenericSet } from "./TMapAnyKeyGenericSet"; import { TMapNumberKeyGenericArray } from "./TMapNumberKeyGenericArray"; import { TMapNumberKeyGenericArrays } from "./TMapNumberKeyGenericArrays"; import { TMapNumberKeyGenericValue } from "./TMapNumberKeyGenericValue"; import { TMapNumberKeyGenericSet } from "./TMapNumberKeyGenericSet"; import { TMapGenericKeyGenericArray } from "./TMapGenericKeyGenericArray"; import { TMapGenericKeyGenericArrays } from "./TMapGenericKeyGenericArrays"; import { TMapGenericKeyGenericValue } from "./TMapGenericKeyGenericValue"; import { TMapGenericKeyGenericSet } from "./TMapGenericKeyGenericSet"; import { TMapStringKeyGenericArray } from "./TMapStringKeyGenericArray"; import { TMapStringKeyGenericArrays } from "./TMapStringKeyGenericArrays"; import { TMapStringKeyGenericValue } from "./TMapStringKeyGenericValue"; import { TMapStringKeyGenericSet } from "./TMapStringKeyGenericSet"; import { IDictionaryNumberIdGenericArray } from "../data_structure/IDictionaryNumberIdGenericArray"; import { IDictionaryNumberIdGenericArrays } from "../data_structure/IDictionaryNumberIdGenericArrays"; import { IDictionaryNumberIdGenericValue } from "../data_structure/IDictionaryNumberIdGenericValue"; import { IDictionaryNumberIdGenericSet } from "../data_structure/IDictionaryNumberIdGenericSet"; import { IDictionaryStringIdGenericArray } from "../data_structure/IDictionaryStringIdGenericArray"; import { IDictionaryStringIdGenericArrays } from "../data_structure/IDictionaryStringIdGenericArrays"; import { IDictionaryStringIdGenericValue } from "../data_structure/IDictionaryStringIdGenericValue"; import { IDictionaryStringIdGenericSet } from "../data_structure/IDictionaryStringIdGenericSet"; // tslint:disable-next-line: max-line-length import { ITextUtteranceLabelStringMapDataStructure } from "../label_structure/ITextUtteranceLabelStringMapDataStructure"; import { Utility } from "../utility/Utility"; export class DictionaryMapUtility { public static readonly UnknownLabel: string = "UNKNOWN"; public static readonly UnknownLabelSet: Set<string> = new Set<string>(["", "NONE", DictionaryMapUtility.UnknownLabel]); public static processUnknownSpuriousLabelsInUtteranceLabelsMap( utteranceLabels: ITextUtteranceLabelStringMapDataStructure): ITextUtteranceLabelStringMapDataStructure { const utteranceLabelsMap: Map<string, Set<string>> = utteranceLabels.utteranceLabelsMap; const utteranceLabelDuplicateMap: Map<string, Set<string>> = utteranceLabels.utteranceLabelDuplicateMap; if (utteranceLabelsMap) { for (const utteranceKey of utteranceLabelsMap.keys()) { if (utteranceKey) { try { const utteranceLabelSet: Set<string> = utteranceLabelsMap.get(utteranceKey) as Set<string>; const concreteLabels: string[] = [...utteranceLabelSet].filter( (label: string) => !DictionaryMapUtility.UnknownLabelSet.has(label.toUpperCase())); const hasConcreteLabel: boolean = concreteLabels.length > 0; utteranceLabelSet.clear(); // ---- NOTE ---- clear the set! if (hasConcreteLabel) { for (const label of concreteLabels) { utteranceLabelSet.add(label); } } else { utteranceLabelSet.add(DictionaryMapUtility.UnknownLabel); } } catch (error) { Utility.debuggingLog(`Utility.processUnknownSpuriousLabelsInUtteranceLabelsMap(), utteranceKey=${utteranceKey}, utteranceLabelsMap=${DictionaryMapUtility.jsonStringifyStringKeyGenericSetNativeMapArrayValue(utteranceLabelsMap)}`); throw error; } } } } if (utteranceLabelDuplicateMap) { utteranceLabelDuplicateMap.forEach((labelsSet: Set<string>, _: string) => { const labelsArray: string[] = [...labelsSet]; const concreteLabels: string[] = labelsArray.filter( (label: string) => !DictionaryMapUtility.UnknownLabelSet.has(label.toUpperCase())); const hasConcreteLabel: boolean = concreteLabels.length > 0; labelsSet.clear(); // ---- NOTE ---- clear the set! // eslint-disable-next-line max-depth if (hasConcreteLabel) { // eslint-disable-next-line max-depth for (const label of concreteLabels) { labelsSet.add(label); } } else { labelsSet.add(DictionaryMapUtility.UnknownLabel); } }); } return utteranceLabels; } public static processUnknownSpuriousLabelsInUtteranceLabelsMapUsingLabelSet( utteranceLabels: ITextUtteranceLabelStringMapDataStructure, labelSet: Set<string>): ITextUtteranceLabelStringMapDataStructure { const utteranceLabelsMap: Map<string, Set<string>> = utteranceLabels.utteranceLabelsMap; const utteranceLabelDuplicateMap: Map<string, Set<string>> = utteranceLabels.utteranceLabelDuplicateMap; if (utteranceLabelsMap) { for (const utteranceKey of utteranceLabelsMap.keys()) { if (utteranceKey) { try { const utteranceLabelSet: Set<string> = utteranceLabelsMap.get(utteranceKey) as Set<string>; const concreteLabels: string[] = [...utteranceLabelSet].filter( (label: string) => !DictionaryMapUtility.UnknownLabelSet.has(label.toUpperCase()) && labelSet.has(label)); const hasConcreteLabel: boolean = concreteLabels.length > 0; utteranceLabelSet.clear(); // ---- NOTE ---- clear the set! if (hasConcreteLabel) { for (const label of concreteLabels) { utteranceLabelSet.add(label); } } else { utteranceLabelSet.add(DictionaryMapUtility.UnknownLabel); } } catch (error) { Utility.debuggingLog(`Utility.processUnknownSpuriousLabelsInUtteranceLabelsMapUsingLabelSet(), utteranceKey=${utteranceKey}, utteranceLabelsMap=${DictionaryMapUtility.jsonStringifyStringKeyGenericSetNativeMapArrayValue(utteranceLabelsMap)}`); throw error; } } } } if (utteranceLabelDuplicateMap) { utteranceLabelDuplicateMap.forEach((labelsSet: Set<string>, _: string) => { const labelsArray: string[] = [...labelsSet]; const concreteLabels: string[] = labelsArray.filter( (label: string) => !DictionaryMapUtility.UnknownLabelSet.has(label.toUpperCase()) && labelSet.has(label)); const hasConcreteLabel: boolean = concreteLabels.length > 0; labelsSet.clear(); // ---- NOTE ---- clear the set! // eslint-disable-next-line max-depth if (hasConcreteLabel) { // eslint-disable-next-line max-depth for (const label of concreteLabels) { labelsSet.add(label); } } else { labelsSet.add(DictionaryMapUtility.UnknownLabel); } }); } return utteranceLabels; } public static jsonStringifyStringKeyGenericSetNativeMapArrayValue<T>( stringKeyGenericSetMap: Map<string, Set<T>>): string { return Utility.jsonStringify( DictionaryMapUtility.convertStringKeyGenericSetNativeMapToDictionaryArrayValue( stringKeyGenericSetMap)); } public static jsonStringifyStringKeyGenericSetNativeMap<T>( stringKeyGenericSetMap: Map<string, Set<T>>): string { return Utility.jsonStringify( DictionaryMapUtility.convertStringKeyGenericSetNativeMapToDictionary( stringKeyGenericSetMap)); } public static jsonStringifyStringKeyGenericValueNativeMap<T>( stringKeyGenericValueMap: Map<string, T>): string { return Utility.jsonStringify( DictionaryMapUtility.convertStringKeyGenericValueNativeMapToDictionary( stringKeyGenericValueMap)); } public static jsonStringifyNumberKeyGenericSetNativeMapArrayValue<T>( numberKeyGenericSetMap: Map<number, Set<T>>): string { return Utility.jsonStringify( DictionaryMapUtility.convertNumberKeyGenericSetNativeMapToDictionaryArrayValue( numberKeyGenericSetMap)); } public static jsonStringifyNumberKeyGenericSetNativeMap<T>( numberKeyGenericSetMap: Map<number, Set<T>>): string { return Utility.jsonStringify( DictionaryMapUtility.convertNumberKeyGenericSetNativeMapToDictionary( numberKeyGenericSetMap)); } public static jsonStringifyNumberKeyGenericValueNativeMap<T>( numberKeyGenericValueMap: Map<number, T>): string { return Utility.jsonStringify( DictionaryMapUtility.convertNumberKeyGenericValueNativeMapToDictionary( numberKeyGenericValueMap)); } public static jsonStringifyStringKeyGenericSetMapArrayValue<T>( stringKeyGenericSetMap: TMapStringKeyGenericSet<T>): string { return Utility.jsonStringify( DictionaryMapUtility.convertStringKeyGenericSetMapToDictionaryArrayValue( stringKeyGenericSetMap)); } public static jsonStringifyStringKeyGenericSetMap<T>( stringKeyGenericSetMap: TMapStringKeyGenericSet<T>): string { return Utility.jsonStringify( DictionaryMapUtility.convertStringKeyGenericSetMapToDictionary( stringKeyGenericSetMap)); } public static jsonStringifyStringKeyGenericValueMap<T>( stringKeyGenericValueMap: TMapStringKeyGenericValue<T>): string { return Utility.jsonStringify( DictionaryMapUtility.convertStringKeyGenericValueMapToDictionary( stringKeyGenericValueMap)); } public static jsonStringifyNumberKeyGenericSetMapArrayValue<T>( numberKeyGenericSetMap: TMapNumberKeyGenericSet<T>): string { return Utility.jsonStringify( DictionaryMapUtility.convertNumberKeyGenericSetMapToDictionaryArrayValue( numberKeyGenericSetMap)); } public static jsonStringifyNumberKeyGenericSetMap<T>( numberKeyGenericSetMap: TMapNumberKeyGenericSet<T>): string { return Utility.jsonStringify( DictionaryMapUtility.convertNumberKeyGenericSetMapToDictionary( numberKeyGenericSetMap)); } public static jsonStringifyNumberKeyGenericValueMap<T>( numberKeyGenericValueMap: TMapNumberKeyGenericValue<T>): string { return Utility.jsonStringify( DictionaryMapUtility.convertNumberKeyGenericValueMapToDictionary( numberKeyGenericValueMap)); } public static convertStringKeyGenericSetNativeMapToDictionaryArrayValue<T>( stringKeyGenericSetMap: Map<string, Set<T>>): { [id: string]: T[] } { const stringIdGenericSetDictionaryArrayValue: { [id: string]: T[] } = {}; for (const key of stringKeyGenericSetMap.keys()) { if (key) { const value: Set<T> = stringKeyGenericSetMap.get(key) as Set<T>; stringIdGenericSetDictionaryArrayValue[key] = [...value]; } } return stringIdGenericSetDictionaryArrayValue; } public static convertStringKeyGenericSetNativeMapToDictionary<T>( stringKeyGenericSetMap: Map<string, Set<T>>): { [id: string]: Set<T> } { const stringIdGenericSetDictionary: { [id: string]: Set<T> } = {}; for (const key of stringKeyGenericSetMap.keys()) { if (key) { const value: Set<T> = stringKeyGenericSetMap.get(key) as Set<T>; stringIdGenericSetDictionary[key] = value; } } return stringIdGenericSetDictionary; } public static convertStringKeyGenericValueNativeMapToDictionary<T>( stringKeyGenericValueMap: Map<string, T>): { [id: string]: T } { const stringIdGenericValueDictionary: { [id: string]: T } = {}; for (const key of stringKeyGenericValueMap.keys()) { if (key) { const value: T = stringKeyGenericValueMap.get(key) as T; stringIdGenericValueDictionary[key] = value; } } return stringIdGenericValueDictionary; } public static convertNumberKeyGenericSetNativeMapToDictionaryArrayValue<T>( numberKeyGenericSetMap: Map<number, Set<T>>): { [id: number]: T[] } { const numberIdGenericSetDictionaryArrayValue: { [id: number]: T[] } = {}; for (const key of numberKeyGenericSetMap.keys()) { if (key) { // ---- key is already a number, tslint is mistaken that it's a string const keyInNumber: number = Number(key); const value: Set<T> = numberKeyGenericSetMap.get(keyInNumber) as Set<T>; numberIdGenericSetDictionaryArrayValue[keyInNumber] = [...value]; } } return numberIdGenericSetDictionaryArrayValue; } public static convertNumberKeyGenericSetNativeMapToDictionary<T>( numberKeyGenericSetMap: Map<number, Set<T>>): { [id: number]: Set<T> } { const numberIdGenericSetDictionary: { [id: number]: Set<T> } = {}; for (const key of numberKeyGenericSetMap.keys()) { if (key) { // ---- key is already a number, tslint is mistaken that it's a string const keyInNumber: number = Number(key); const value: Set<T> = numberKeyGenericSetMap.get(keyInNumber) as Set<T>; numberIdGenericSetDictionary[keyInNumber] = value; } } return numberIdGenericSetDictionary; } public static convertNumberKeyGenericValueNativeMapToDictionary<T>( numberKeyGenericValueMap: Map<number, T>): { [id: number]: T } { const numberIdGenericValueDictionary: { [id: number]: T } = {}; for (const key of numberKeyGenericValueMap.keys()) { if (key) { // ---- key is already a number, tslint is mistaken that it's a string const keyInNumber: number = Number(key); const value: T = numberKeyGenericValueMap.get(keyInNumber) as T; numberIdGenericValueDictionary[keyInNumber] = value; } } return numberIdGenericValueDictionary; } public static convertStringKeyGenericSetMapToDictionaryArrayValue<T>( stringKeyGenericSetMap: TMapStringKeyGenericSet<T>): IDictionaryStringIdGenericArray<T> { const stringIdGenericSetDictionaryArrayValue: IDictionaryStringIdGenericArray<T> = {}; for (const key of stringKeyGenericSetMap.keys()) { if (key) { const value: Set<T> = stringKeyGenericSetMap.get(key) as Set<T>; stringIdGenericSetDictionaryArrayValue[key] = [...value]; } } return stringIdGenericSetDictionaryArrayValue; } public static convertStringKeyGenericSetMapToDictionary<T>( stringKeyGenericSetMap: TMapStringKeyGenericSet<T>): IDictionaryStringIdGenericSet<T> { const stringIdGenericSetDictionary: IDictionaryStringIdGenericSet<T> = {}; for (const key of stringKeyGenericSetMap.keys()) { if (key) { const value: Set<T> = stringKeyGenericSetMap.get(key) as Set<T>; stringIdGenericSetDictionary[key] = value; } } return stringIdGenericSetDictionary; } public static convertStringKeyGenericValueMapToDictionary<T>( stringKeyGenericValueMap: TMapStringKeyGenericValue<T>): IDictionaryStringIdGenericValue<T> { const stringIdGenericValueDictionary: IDictionaryStringIdGenericValue<T> = {}; for (const key of stringKeyGenericValueMap.keys()) { if (key) { const value: T = stringKeyGenericValueMap.get(key) as T; stringIdGenericValueDictionary[key] = value; } } return stringIdGenericValueDictionary; } public static convertNumberKeyGenericSetMapToDictionaryArrayValue<T>( numberKeyGenericSetMap: TMapNumberKeyGenericSet<T>): IDictionaryNumberIdGenericArray<T> { const numberIdGenericSetDictionaryArrayValue: IDictionaryNumberIdGenericArray<T> = {}; for (const key of numberKeyGenericSetMap.keys()) { if (key) { // ---- key is already a number, tslint is mistaken that it's a string const keyInNumber: number = Number(key); const value: Set<T> = numberKeyGenericSetMap.get(keyInNumber) as Set<T>; numberIdGenericSetDictionaryArrayValue[keyInNumber] = [...value]; } } return numberIdGenericSetDictionaryArrayValue; } public static convertNumberKeyGenericSetMapToDictionary<T>( numberKeyGenericSetMap: TMapNumberKeyGenericSet<T>): IDictionaryNumberIdGenericSet<T> { const numberIdGenericSetDictionary: IDictionaryNumberIdGenericSet<T> = {}; for (const key of numberKeyGenericSetMap.keys()) { if (key) { // ---- key is already a number, tslint is mistaken that it's a string const keyInNumber: number = Number(key); const value: Set<T> = numberKeyGenericSetMap.get(keyInNumber) as Set<T>; numberIdGenericSetDictionary[keyInNumber] = value; } } return numberIdGenericSetDictionary; } public static convertNumberKeyGenericValueMapToDictionary<T>( numberKeyGenericValueMap: TMapNumberKeyGenericValue<T>): IDictionaryNumberIdGenericValue<T> { const numberIdGenericValueDictionary: IDictionaryNumberIdGenericValue<T> = {}; for (const key of numberKeyGenericValueMap.keys()) { if (key) { // ---- key is already a number, tslint is mistaken that it's a string const keyInNumber: number = Number(key); const value: T = numberKeyGenericValueMap.get(keyInNumber) as T; numberIdGenericValueDictionary[keyInNumber] = value; } } return numberIdGenericValueDictionary; } public static insertStringPairToStringIdStringSetNativeDictionary( key: string, value: string, stringIdStringSetDictionary: { [id: string]: Set<string> }): { [id: string]: Set<string> } { if (!stringIdStringSetDictionary) { stringIdStringSetDictionary = {}; } if (stringIdStringSetDictionary.hasOwnProperty(key)) { const stringSet: Set<string> = stringIdStringSetDictionary[key]; stringSet.add(value); } else { const stringSet: Set<string> = new Set<string>(); stringIdStringSetDictionary[key] = stringSet; stringSet.add(value); } return stringIdStringSetDictionary; } public static insertNumberStringPairToNumberIdStringSetNativeDictionary( key: number, value: string, numberIdStringSetDictionary: { [id: number]: Set<string> }): { [id: number]: Set<string> } { if (!numberIdStringSetDictionary) { numberIdStringSetDictionary = {}; } if (numberIdStringSetDictionary.hasOwnProperty(key)) { const stringSet: Set<string> = numberIdStringSetDictionary[key]; stringSet.add(value); } else { const stringSet: Set<string> = new Set<string>(); numberIdStringSetDictionary[key] = stringSet; stringSet.add(value); } return numberIdStringSetDictionary; } public static insertStringPairToStringIdStringSetDictionary( key: string, value: string, stringIdStringSetDictionary: IDictionaryStringIdGenericSet<string>): IDictionaryStringIdGenericSet<string> { if (DictionaryMapUtility.isEmptyStringIdGenericSetDictionary<string>(stringIdStringSetDictionary)) { stringIdStringSetDictionary = {}; } if (stringIdStringSetDictionary.hasOwnProperty(key)) { const stringSet: Set<string> = stringIdStringSetDictionary[key]; stringSet.add(value); } else { const stringSet: Set<string> = new Set<string>(); stringIdStringSetDictionary[key] = stringSet; stringSet.add(value); } return stringIdStringSetDictionary; } public static insertNumberStringPairToNumberIdStringSetDictionary( key: number, value: string, numberIdStringSetDictionary: IDictionaryNumberIdGenericSet<string>): IDictionaryNumberIdGenericSet<string> { if (DictionaryMapUtility.isEmptyNumberIdGenericSetDictionary<string>(numberIdStringSetDictionary)) { numberIdStringSetDictionary = {}; } if (numberIdStringSetDictionary.hasOwnProperty(key)) { const stringSet: Set<string> = numberIdStringSetDictionary[key]; stringSet.add(value); } else { const stringSet: Set<string> = new Set<string>(); numberIdStringSetDictionary[key] = stringSet; stringSet.add(value); } return numberIdStringSetDictionary; } public static insertStringPairToStringIdStringSetNativeMap( key: string, value: string, stringKeyStringSetMap: Map<string, Set<string>>): Map<string, Set<string>> { if (!stringKeyStringSetMap) { stringKeyStringSetMap = new Map<string, Set<string>>(); } if (stringKeyStringSetMap.has(key)) { let stringSet: Set<string> = stringKeyStringSetMap.get(key) as Set<string>; if (!stringSet) { stringSet = new Set<string>(); stringKeyStringSetMap.set(key, stringSet); } stringSet.add(value); } else { const stringSet: Set<string> = new Set<string>(); stringKeyStringSetMap.set(key, stringSet); stringSet.add(value); } return stringKeyStringSetMap; } public static insertNumberStringPairToNumberIdStringSetNativeMap( key: number, value: string, numberKeyStringSetMap: Map<number, Set<string>>): Map<number, Set<string>> { if (!numberKeyStringSetMap) { numberKeyStringSetMap = new Map<number, Set<string>>(); } if (numberKeyStringSetMap.has(key)) { let stringSet: Set<string> = numberKeyStringSetMap.get(key) as Set<string>; if (!stringSet) { stringSet = new Set<string>(); numberKeyStringSetMap.set(key, stringSet); } stringSet.add(value); } else { const stringSet: Set<string> = new Set<string>(); numberKeyStringSetMap.set(key, stringSet); stringSet.add(value); } return numberKeyStringSetMap; } public static insertStringPairToStringIdStringSetMap( key: string, value: string, stringKeyStringSetMap: TMapStringKeyGenericSet<string>): TMapStringKeyGenericSet<string> { if (DictionaryMapUtility.isEmptyStringKeyGenericSetMap<string>(stringKeyStringSetMap)) { stringKeyStringSetMap = DictionaryMapUtility.newTMapStringKeyGenericSet<string>(); } if (stringKeyStringSetMap.has(key)) { let stringSet: Set<string> = stringKeyStringSetMap.get(key) as Set<string>; if (!stringSet) { stringSet = new Set<string>(); stringKeyStringSetMap.set(key, stringSet); } stringSet.add(value); } else { const stringSet: Set<string> = new Set<string>(); stringKeyStringSetMap.set(key, stringSet); stringSet.add(value); } return stringKeyStringSetMap; } public static insertNumberStringPairToNumberIdStringSetMap( key: number, value: string, numberKeyStringSetMap: TMapNumberKeyGenericSet<string>): TMapNumberKeyGenericSet<string> { if (DictionaryMapUtility.isEmptyNumberKeyGenericSetMap<string>(numberKeyStringSetMap)) { numberKeyStringSetMap = DictionaryMapUtility.newTMapNumberKeyGenericSet<string>(); } if (numberKeyStringSetMap.has(key)) { let stringSet: Set<string> = numberKeyStringSetMap.get(key) as Set<string>; if (!stringSet) { stringSet = new Set<string>(); numberKeyStringSetMap.set(key, stringSet); } stringSet.add(value); } else { const stringSet: Set<string> = new Set<string>(); numberKeyStringSetMap.set(key, stringSet); stringSet.add(value); } return numberKeyStringSetMap; } public static buildStringIdNumberValueDictionaryFromUniqueStringArrayFile( filename: string, delimiter: string = "\t"): { "stringArray": string[], "stringMap": IDictionaryStringIdGenericValue<number> } { const content: string = Utility.loadFile(filename); return DictionaryMapUtility.buildStringIdNumberValueDictionaryFromUniqueStringArrayContent( content, delimiter); } public static buildStringIdNumberValueDictionaryFromUniqueStringArrayContent( content: string, delimiter: string = "\t"): { "stringArray": string[], "stringMap": IDictionaryStringIdGenericValue<number> } { let stringArray: string[] = Utility.split(content, delimiter); stringArray = Utility.sortStringArray(stringArray); const stringMap: IDictionaryStringIdGenericValue<number> = DictionaryMapUtility.buildStringIdNumberValueDictionaryFromUniqueStringArray(stringArray); return { stringArray, stringMap }; } public static buildStringIdNumberValueDictionaryFromUniqueStringArray( inputStringArray: string[]): IDictionaryStringIdGenericValue<number> { inputStringArray = Utility.sortStringArray(inputStringArray); const stringMap: IDictionaryStringIdGenericValue<number> = { }; for (let index: number = 0; index < inputStringArray.length; index++) { stringMap[inputStringArray[index]] = index; } return stringMap; } public static buildStringIdNumberValueDictionaryFromStringArrayFile( filename: string, delimiter: string = "\t"): { "stringArray": string[], "stringMap": IDictionaryStringIdGenericValue<number> } { const content: string = Utility.loadFile(filename); return DictionaryMapUtility.buildStringIdNumberValueDictionaryFromStringArrayContent( content, delimiter); } public static buildStringIdNumberValueDictionaryFromStringArrayContent( content: string, delimiter: string = "\t"): { "stringArray": string[], "stringMap": IDictionaryStringIdGenericValue<number> } { const records: string[] = Utility.split(content, delimiter); return DictionaryMapUtility.buildStringIdNumberValueDictionaryFromStringArray(records); } public static buildStringIdNumberValueDictionaryFromStringArray( inputStringArray: string[]): { "stringArray": string[], "stringMap": IDictionaryStringIdGenericValue<number> } { const stringSet: Set<string> = new Set(inputStringArray); let stringArray: string[] = [...stringSet]; stringArray = Utility.sortStringArray(stringArray); const stringMap: IDictionaryStringIdGenericValue<number> = DictionaryMapUtility.buildStringIdNumberValueDictionaryFromUniqueStringArray(stringArray); return { stringArray, stringMap }; } public static buildStringIdNumberValueDictionaryFromStringArrays( inputStringArrays: string[][]): { "stringArray": string[], "stringMap": IDictionaryStringIdGenericValue<number> } { const stringSet: Set<string> = new Set(); for (const elementStringArray of inputStringArrays) { for (const elementString of elementStringArray) { stringSet.add(elementString); } } let stringArray: string[] = [...stringSet]; stringArray = Utility.sortStringArray(stringArray); const stringMap: IDictionaryStringIdGenericValue<number> = DictionaryMapUtility.buildStringIdNumberValueDictionaryFromUniqueStringArray(stringArray); return { stringArray, stringMap }; } public static validateStringArrayAndStringIdNumberValueDictionary( stringArray: string[], stringIdNumberValueDictionary: IDictionaryStringIdGenericValue<number>, throwIfNotLegal: boolean = true): boolean { if (stringArray === null) { if (throwIfNotLegal) { throw new Error("stringArray===null"); } return false; } if (stringIdNumberValueDictionary === null) { if (throwIfNotLegal) { throw new Error("stringIdNumberValueDictionary===null"); } return false; } if (stringArray.length !== DictionaryMapUtility.getStringIdGenericValueDictionaryLength(stringIdNumberValueDictionary)) { if (throwIfNotLegal) { throw new Error( `stringArray.length|${stringArray.length}|` + "!==stringIdNumberValueDictionary.length" + `|${DictionaryMapUtility.getStringIdGenericValueDictionaryLength(stringIdNumberValueDictionary)}|`); } return false; } for (const key in stringIdNumberValueDictionary) { if (key) { // ---- side effect is to remove TSLint warning for // ---- "in" statements must be filtered with an if statement. const keyId: number = stringIdNumberValueDictionary[key]; if ((keyId < 0) || (keyId > stringArray.length)) { if (throwIfNotLegal) { throw new Error(`(keyId<0)||(keyId|${keyId}|>stringArray.length|${stringArray.length}|)`); } return false; } const keyRetrieved = stringArray[keyId]; if (key !== keyRetrieved) { if (throwIfNotLegal) { throw new Error(`key|${key}|!==keyRetrieved|${keyRetrieved}|`); } return false; } } } return true; } public static validateNumberKeyIdInStringIdNumberValueDictionary( keyId: number, stringIdNumberValueDictionary: IDictionaryStringIdGenericValue<number>, throwIfNotLegal: boolean = true): boolean { if (keyId < 0) { if (throwIfNotLegal) { Utility.debuggingThrow( `keyId=${keyId}, small than 0`); } return false; } if (keyId >= DictionaryMapUtility.getStringIdGenericValueDictionaryLength(stringIdNumberValueDictionary)) { if (throwIfNotLegal) { Utility.debuggingThrow( `keyId=${keyId}, greater or equal to number of keys: ${stringIdNumberValueDictionary.size}`); } return false; } return true; } public static validateStringKeyInStringIdNumberValueDictionary( key: string, stringIdNumberValueDictionary: IDictionaryStringIdGenericValue<number>, throwIfNotLegal: boolean = true): boolean { if (stringIdNumberValueDictionary.hasOwnProperty(key)) { return true; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key=${key}, not in the dictionary: ${stringIdNumberValueDictionary}`); } return false; } } public static buildStringKeyNumberValueMapFromUniqueStringArrayFile( filename: string, delimiter: string = "\t"): { "stringArray": string[], "stringMap": TMapStringKeyGenericValue<number> } { const content: string = Utility.loadFile(filename); return DictionaryMapUtility.buildStringKeyNumberValueMapFromUniqueStringArrayContent( content, delimiter); } public static buildStringKeyNumberValueMapFromUniqueStringArrayContent( content: string, delimiter: string = "\t"): { "stringArray": string[], "stringMap": TMapStringKeyGenericValue<number> } { let stringArray: string[] = Utility.split(content, delimiter); stringArray = Utility.sortStringArray(stringArray); const stringMap: TMapStringKeyGenericValue<number> = DictionaryMapUtility.buildStringKeyNumberValueMapFromUniqueStringArray(stringArray); return { stringArray, stringMap }; } public static buildStringKeyNumberValueMapFromUniqueStringArray( inputStringArray: string[]): TMapStringKeyGenericValue<number> { inputStringArray = Utility.sortStringArray(inputStringArray); const stringMap: TMapStringKeyGenericValue<number> = DictionaryMapUtility.newTMapStringKeyGenericValue(); for (let index: number = 0; index < inputStringArray.length; index++) { stringMap.set(inputStringArray[index], index); } return stringMap; } public static buildStringKeyNumberValueMapFromStringArrayFile( filename: string, delimiter: string = "\t"): { "stringArray": string[], "stringMap": TMapStringKeyGenericValue<number> } { const content: string = Utility.loadFile(filename); return DictionaryMapUtility.buildStringKeyNumberValueMapFromStringArrayContent( content, delimiter); } public static buildStringKeyNumberValueMapFromStringArrayContent( content: string, delimiter: string = "\t"): { "stringArray": string[], "stringMap": TMapStringKeyGenericValue<number> } { const records: string[] = Utility.split(content, delimiter); return DictionaryMapUtility.buildStringKeyNumberValueMapFromStringArray(records); } public static buildStringKeyNumberValueMapFromStringArray( inputStringArray: string[]): { "stringArray": string[], "stringMap": TMapStringKeyGenericValue<number> } { const stringSet: Set<string> = new Set(inputStringArray); let stringArray: string[] = [...stringSet]; stringArray = Utility.sortStringArray(stringArray); const stringMap: TMapStringKeyGenericValue<number> = DictionaryMapUtility.buildStringKeyNumberValueMapFromUniqueStringArray(stringArray); return { stringArray, stringMap }; } public static buildStringKeyNumberValueMapFromStringArrays( inputStringArrays: string[][]): { "stringArray": string[], "stringMap": TMapStringKeyGenericValue<number> } { const stringSet: Set<string> = new Set(); for (const elementStringArray of inputStringArrays) { for (const elementString of elementStringArray) { stringSet.add(elementString); } } let stringArray: string[] = [...stringSet]; stringArray = Utility.sortStringArray(stringArray); const stringMap: TMapStringKeyGenericValue<number> = DictionaryMapUtility.buildStringKeyNumberValueMapFromUniqueStringArray(stringArray); return { stringArray, stringMap }; } public static validateStringArrayAndStringKeyNumberValueMap( stringArray: string[], stringKeyNumberValueMap: TMapStringKeyGenericValue<number>, throwIfNotLegal: boolean = true): boolean { if (stringArray === null) { if (throwIfNotLegal) { throw new Error("stringArray===null"); } return false; } if (stringKeyNumberValueMap === null) { if (throwIfNotLegal) { throw new Error("stringKeyNumberValueMap===null"); } return false; } if (stringArray.length !== DictionaryMapUtility.getStringKeyGenericValueMapLength(stringKeyNumberValueMap)) { if (throwIfNotLegal) { throw new Error( "stringArray.length|" + stringArray.length + "|!==stringKeyNumberValueMap.length|" + DictionaryMapUtility.getStringKeyGenericValueMapLength(stringKeyNumberValueMap) + "|"); } return false; } for (const key of stringKeyNumberValueMap.keys()) { if (key) { const keyId: number = stringKeyNumberValueMap.get(key) as number; // ==== NOTE-keyId-can-be-0 ==== // ---- side effect is to remove TSLint warning for // ==== NOTE-keyId-can-be-0 ==== // ---- "in" statements must be filtered with an if statement. // ==== NOTE-keyId-can-be-0 ==== if (keyId) { if ((keyId < 0) || (keyId > stringArray.length)) { if (throwIfNotLegal) { throw new Error("(keyId < 0) || (keyId > stringArray.length)"); } return false; } const keyRetrieved = stringArray[keyId]; if (key !== keyRetrieved) { if (throwIfNotLegal) { throw new Error("key !== keyRetrieved"); } return false; } // ==== NOTE-keyId-can-be-0 ==== } else { // ==== NOTE-keyId-can-be-0 ==== if (throwIfNotLegal) { // tslint:disable-next-line: max-line-length // ==== NOTE-keyId-can-be-0 ==== throw new Error("keyId is undefined in stringKeyNumberValueMap"); // ==== NOTE-keyId-can-be-0 ==== } // ==== NOTE-keyId-can-be-0 ==== return false; // ==== NOTE-keyId-can-be-0 ==== } } } return true; } public static validateNumberKeyIdInStringKeyNumberValueMap( keyId: number, stringKeyNumberValueMap: TMapStringKeyGenericValue<number>, throwIfNotLegal: boolean = true): boolean { if (keyId < 0) { if (throwIfNotLegal) { Utility.debuggingThrow( `keyId=${keyId}, small than 0`); } return false; } if (keyId >= DictionaryMapUtility.getStringKeyGenericValueMapLength(stringKeyNumberValueMap)) { if (throwIfNotLegal) { Utility.debuggingThrow( `keyId=${keyId}, greater or equal to number of keys, ${stringKeyNumberValueMap.size}`); } return false; } return true; } public static validateStringKeyInStringKeyNumberValueMap( key: string, stringKeyNumberValueMap: TMapStringKeyGenericValue<number>, throwIfNotLegal: boolean = true): boolean { if (stringKeyNumberValueMap.has(key)) { return true; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key=${key}, not in the map: ${Utility.mapToJsonSerialization(stringKeyNumberValueMap)}`); } return false; } } public static validateStringIdGenericValueDictionaryPair<T>( stringIdGenericValueDictionaryFirst: IDictionaryStringIdGenericValue<T>, stringIdGenericValueDictionarySecond: IDictionaryStringIdGenericValue<T>, throwIfNotLegal: boolean = true): boolean { if ((stringIdGenericValueDictionaryFirst == null) && (stringIdGenericValueDictionarySecond == null)) { return true; } if (stringIdGenericValueDictionaryFirst == null) { if (throwIfNotLegal) { Utility.debuggingThrow("stringIdGenericValueDictionaryFirst==null"); } return false; } if (stringIdGenericValueDictionarySecond == null) { if (throwIfNotLegal) { Utility.debuggingThrow("stringIdGenericValueDictionarySecond==null"); } return false; } const stringIdGenericValueDictionaryFirstLength: number = DictionaryMapUtility.getStringIdGenericValueDictionaryLength(stringIdGenericValueDictionaryFirst); const stringIdGenericValueDictionarySecondLength: number = DictionaryMapUtility.getStringIdGenericValueDictionaryLength(stringIdGenericValueDictionarySecond); if (stringIdGenericValueDictionaryFirstLength !== stringIdGenericValueDictionarySecondLength) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringIdGenericValueDictionaryFirstLength|${stringIdGenericValueDictionaryFirstLength}|` + `!=stringIdGenericValueDictionarySecondLength|${stringIdGenericValueDictionarySecondLength}|`); } return false; } for (const key in stringIdGenericValueDictionaryFirst) { if (key) { if (stringIdGenericValueDictionarySecond.hasOwnProperty(key)) { if (stringIdGenericValueDictionaryFirst[key] !== stringIdGenericValueDictionarySecond[key]) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringIdGenericValueDictionaryFirst[key]=${key}, ` + `stringIdGenericValueDictionarySecond[key]=${key}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in stringIdGenericValueDictionaryFirst, ` + `but not in stringIdGenericValueDictionarySecond`); } return false; } } } for (const key in stringIdGenericValueDictionarySecond) { if (key) { if (stringIdGenericValueDictionaryFirst.hasOwnProperty(key)) { if (stringIdGenericValueDictionaryFirst[key] !== stringIdGenericValueDictionarySecond[key]) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringIdGenericValueDictionaryFirst[key]=${key}, ` + `stringIdGenericValueDictionarySecond[key]=${key}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in stringIdGenericValueDictionarySecond, ` + `but not in stringIdGenericValueDictionaryFirst`); } return false; } } } return true; } public static validateNumberIdGenericValueDictionaryPair<T>( numberIdGenericValueDictionaryFirst: IDictionaryNumberIdGenericValue<T>, numberIdGenericValueDictionarySecond: IDictionaryNumberIdGenericValue<T>, throwIfNotLegal: boolean = true): boolean { if ((numberIdGenericValueDictionaryFirst == null) && (numberIdGenericValueDictionarySecond == null)) { return true; } if (numberIdGenericValueDictionaryFirst == null) { if (throwIfNotLegal) { Utility.debuggingThrow("numberIdGenericValueDictionaryFirst==null"); } return false; } if (numberIdGenericValueDictionarySecond == null) { if (throwIfNotLegal) { Utility.debuggingThrow("numberIdGenericValueDictionarySecond==null"); } return false; } const numberIdGenericValueDictionaryFirstLength: number = DictionaryMapUtility.getNumberIdGenericValueDictionaryLength(numberIdGenericValueDictionaryFirst); const numberIdGenericValueDictionarySecondLength: number = DictionaryMapUtility.getNumberIdGenericValueDictionaryLength(numberIdGenericValueDictionarySecond); if (numberIdGenericValueDictionaryFirstLength !== numberIdGenericValueDictionarySecondLength) { if (throwIfNotLegal) { Utility.debuggingThrow( `numberIdGenericValueDictionaryFirstLength|${numberIdGenericValueDictionaryFirstLength}|` + `!=numberIdGenericValueDictionarySecondLength|${numberIdGenericValueDictionarySecondLength}|`); } return false; } for (const key in numberIdGenericValueDictionaryFirst) { if (key) { if (numberIdGenericValueDictionarySecond.hasOwnProperty(key)) { if (numberIdGenericValueDictionaryFirst[key] !== numberIdGenericValueDictionarySecond[key]) { if (throwIfNotLegal) { Utility.debuggingThrow( `numberIdGenericValueDictionaryFirst[key]=${key}, ` + `numberIdGenericValueDictionarySecond[key]=${key}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in numberIdGenericValueDictionaryFirst, ` + `but not in numberIdGenericValueDictionarySecond`); } return false; } } } for (const key in numberIdGenericValueDictionarySecond) { if (key) { if (numberIdGenericValueDictionaryFirst.hasOwnProperty(key)) { if (numberIdGenericValueDictionaryFirst[key] !== numberIdGenericValueDictionarySecond[key]) { if (throwIfNotLegal) { Utility.debuggingThrow( `numberIdGenericValueDictionaryFirst[key]=${key}, ` + `numberIdGenericValueDictionarySecond[key]=${key}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in numberIdGenericValueDictionarySecond, ` + `but not in numberIdGenericValueDictionaryFirst`); } return false; } } } return true; } public static validateStringIdNumberValueDictionaryPair( stringIdNumberValueDictionaryFirst: IDictionaryStringIdGenericValue<number>, stringIdNumberValueDictionarySecond: IDictionaryStringIdGenericValue<number>, throwIfNotLegal: boolean = true): boolean { if ((stringIdNumberValueDictionaryFirst === null) && (stringIdNumberValueDictionarySecond === null)) { return true; } if (stringIdNumberValueDictionaryFirst === null) { if (throwIfNotLegal) { Utility.debuggingThrow("stringIdNumberValueDictionaryFirst==null"); } return false; } if (stringIdNumberValueDictionarySecond === null) { if (throwIfNotLegal) { Utility.debuggingThrow("stringIdNumberValueDictionarySecond==null"); } return false; } const stringKeyNumberValueDictionaryFirstLength: number = DictionaryMapUtility.getStringIdGenericValueDictionaryLength(stringIdNumberValueDictionaryFirst); const stringKeyNumberValueDictionarySecondLength: number = DictionaryMapUtility.getStringIdGenericValueDictionaryLength(stringIdNumberValueDictionarySecond); if (stringKeyNumberValueDictionaryFirstLength !== stringKeyNumberValueDictionarySecondLength) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringKeyNumberValueDictionaryFirstLength|${stringKeyNumberValueDictionaryFirstLength}|` + `!=stringKeyNumberValueDictionarySecondLength|${stringKeyNumberValueDictionarySecondLength}|`); } return false; } for (const key in stringIdNumberValueDictionaryFirst) { if (key) { if (stringIdNumberValueDictionarySecond.hasOwnProperty(key)) { if (stringIdNumberValueDictionaryFirst[key] !== stringIdNumberValueDictionarySecond[key]) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringKeyNumberValueDictionaryFirst[key]=${key}, ` + `stringKeyNumberValueDictionarySecond[key]=${key}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in stringKeyNumberValueDictionaryFirst, ` + `but not in stringKeyNumberValueDictionarySecond`); } return false; } } } for (const key in stringIdNumberValueDictionarySecond) { if (key) { if (stringIdNumberValueDictionaryFirst.hasOwnProperty(key)) { if (stringIdNumberValueDictionaryFirst[key] !== stringIdNumberValueDictionarySecond[key]) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringKeyNumberValueDictionaryFirst[key]=${key}, ` + `stringKeyNumberValueDictionarySecond[key]=${key}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in stringKeyNumberValueDictionarySecond, ` + `but not in stringKeyNumberValueDictionaryFirst`); } return false; } } } return true; } public static validateGenericKeyGenericValueMapPair<I, T>( genericKeyGenericValueMapFirst: TMapGenericKeyGenericValue<I, T>, genericKeyGenericValueMapSecond: TMapGenericKeyGenericValue<I, T>, throwIfNotLegal: boolean = true): boolean { if ((genericKeyGenericValueMapFirst == null) && (genericKeyGenericValueMapSecond == null)) { return true; } if (genericKeyGenericValueMapFirst == null) { if (throwIfNotLegal) { Utility.debuggingThrow("genericKeyGenericValueMapFirst==null"); } return false; } if (genericKeyGenericValueMapSecond == null) { if (throwIfNotLegal) { Utility.debuggingThrow("genericKeyGenericValueMapSecond==null"); } return false; } const genericKeyGenericValueMapFirstLength: number = DictionaryMapUtility.getGenericKeyGenericValueMapLength(genericKeyGenericValueMapFirst); const genericKeyGenericValueMapSecondLength: number = DictionaryMapUtility.getGenericKeyGenericValueMapLength(genericKeyGenericValueMapSecond); if (genericKeyGenericValueMapFirstLength !== genericKeyGenericValueMapSecondLength) { if (throwIfNotLegal) { Utility.debuggingThrow( `genericKeyGenericValueMapFirstLength|${genericKeyGenericValueMapFirstLength}|` + `!=genericKeyGenericValueMapSecondLength|${genericKeyGenericValueMapSecondLength}|`); } return false; } for (const key of genericKeyGenericValueMapFirst.keys()) { if (key) { if (genericKeyGenericValueMapSecond.has(key)) { if (genericKeyGenericValueMapFirst.get(key) !== genericKeyGenericValueMapSecond.get(key)) { if (throwIfNotLegal) { Utility.debuggingThrow( `genericKeyGenericValueMapFirst.get(key)=${genericKeyGenericValueMapFirst.get(key)}, ` + `genericKeyGenericValueMapSecond.get(key)=${genericKeyGenericValueMapSecond.get(key)}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in genericKeyGenericValueMapFirst, ` + `but not in genericKeyGenericValueMapSecond`); } return false; } } } for (const key of genericKeyGenericValueMapSecond.keys()) { if (key) { if (genericKeyGenericValueMapFirst.has(key)) { if (genericKeyGenericValueMapFirst.get(key) !== genericKeyGenericValueMapSecond.get(key)) { if (throwIfNotLegal) { Utility.debuggingThrow( `genericKeyGenericValueMapFirst.get(key)=${genericKeyGenericValueMapFirst.get(key)}, ` + `genericKeyGenericValueMapSecond.get(key)=${genericKeyGenericValueMapSecond.get(key)}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in genericKeyGenericValueMapSecond, ` + `but not in genericKeyGenericValueMapFirst`); } return false; } } } return true; } public static validateStringKeyGenericValueMapPair<T>( stringKeyGenericValueMapFirst: TMapStringKeyGenericValue<T>, stringKeyGenericValueMapSecond: TMapStringKeyGenericValue<T>, throwIfNotLegal: boolean = true): boolean { if ((stringKeyGenericValueMapFirst == null) && (stringKeyGenericValueMapSecond == null)) { return true; } if (stringKeyGenericValueMapFirst == null) { if (throwIfNotLegal) { Utility.debuggingThrow("stringKeyGenericValueMapFirst==null"); } return false; } if (stringKeyGenericValueMapSecond == null) { if (throwIfNotLegal) { Utility.debuggingThrow("stringKeyGenericValueMapSecond==null"); } return false; } const stringKeyGenericValueMapFirstLength: number = DictionaryMapUtility.getGenericKeyGenericValueMapLength(stringKeyGenericValueMapFirst); const stringKeyGenericValueMapSecondLength: number = DictionaryMapUtility.getGenericKeyGenericValueMapLength(stringKeyGenericValueMapSecond); if (stringKeyGenericValueMapFirstLength !== stringKeyGenericValueMapSecondLength) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringKeyGenericValueMapFirstLength|${stringKeyGenericValueMapFirstLength}|` + `!=stringKeyGenericValueMapSecondLength|${stringKeyGenericValueMapSecondLength}|`); } return false; } for (const key of stringKeyGenericValueMapFirst.keys()) { if (key) { if (stringKeyGenericValueMapSecond.has(key)) { if (stringKeyGenericValueMapFirst.get(key) !== stringKeyGenericValueMapSecond.get(key)) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringKeyGenericValueMapFirst.get(key)=${stringKeyGenericValueMapFirst.get(key)}, ` + `stringKeyGenericValueMapSecond.get(key)=${stringKeyGenericValueMapSecond.get(key)}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in stringKeyGenericValueMapFirst, ` + `but not in stringKeyGenericValueMapSecond`); } return false; } } } for (const key of stringKeyGenericValueMapSecond.keys()) { if (key) { if (stringKeyGenericValueMapFirst.has(key)) { if (stringKeyGenericValueMapFirst.get(key) !== stringKeyGenericValueMapSecond.get(key)) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringKeyGenericValueMapFirst.get(key)=${stringKeyGenericValueMapFirst.get(key)}, ` + `stringKeyGenericValueMapSecond.get(key)=${stringKeyGenericValueMapSecond.get(key)}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in stringKeyGenericValueMapSecond, ` + `but not in stringKeyGenericValueMapFirst`); } return false; } } } return true; } public static validateStringKeyNumberValueMapPair( stringKeyNumberValueMapFirst: TMapStringKeyGenericValue<number>, stringKeyNumberValueMapSecond: TMapStringKeyGenericValue<number>, throwIfNotLegal: boolean = true): boolean { if ((stringKeyNumberValueMapFirst == null) && (stringKeyNumberValueMapSecond == null)) { return true; } if (stringKeyNumberValueMapFirst == null) { if (throwIfNotLegal) { Utility.debuggingThrow("stringKeyNumberValueMapFirst==null"); } return false; } if (stringKeyNumberValueMapSecond == null) { if (throwIfNotLegal) { Utility.debuggingThrow("stringKeyNumberValueMapSecond==null"); } return false; } const stringKeyNumberValueMapFirstLength: number = DictionaryMapUtility.getStringKeyGenericValueMapLength(stringKeyNumberValueMapFirst); const stringKeyNumberValueMapSecondLength: number = DictionaryMapUtility.getStringKeyGenericValueMapLength(stringKeyNumberValueMapSecond); if (stringKeyNumberValueMapFirstLength !== stringKeyNumberValueMapSecondLength) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringKeyNumberValueMapFirstLength|${stringKeyNumberValueMapFirstLength}|` + `!=stringKeyNumberValueMapSecondLength|${stringKeyNumberValueMapSecondLength}|`); } return false; } for (const key of stringKeyNumberValueMapFirst.keys()) { if (key) { if (stringKeyNumberValueMapSecond.has(key)) { if (stringKeyNumberValueMapFirst.get(key) !== stringKeyNumberValueMapSecond.get(key)) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringKeyNumberValueMapFirst.get(key)=${stringKeyNumberValueMapFirst.get(key)}, ` + `stringKeyNumberValueMapSecond.get(key)=${stringKeyNumberValueMapSecond.get(key)}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in stringKeyNumberValueMapFirst, ` + `but not in stringKeyNumberValueMapSecond`); } return false; } } } for (const key of stringKeyNumberValueMapSecond.keys()) { if (key) { if (stringKeyNumberValueMapFirst.has(key)) { if (stringKeyNumberValueMapFirst.get(key) !== stringKeyNumberValueMapSecond.get(key)) { if (throwIfNotLegal) { Utility.debuggingThrow( `stringKeyNumberValueMapFirst.get(key)=${stringKeyNumberValueMapFirst.get(key)}, ` + `stringKeyNumberValueMapSecond.get(key)=${stringKeyNumberValueMapSecond.get(key)}`); } return false; } continue; } else { if (throwIfNotLegal) { Utility.debuggingThrow( `key|${key}| is in stringKeyNumberValueMapSecond, ` + `but not in stringKeyNumberValueMapFirst`); } return false; } } } return true; } public static isEmptyStringIdGenericSetDictionary<T>( stringIdGenericSetMap: IDictionaryStringIdGenericSet<T>): boolean { return !(stringIdGenericSetMap && DictionaryMapUtility.getStringIdGenericSetDictionaryLength(stringIdGenericSetMap) > 0); } public static isEmptyStringIdGenericValueDictionary<T>( stringIdGenericValueMap: IDictionaryStringIdGenericValue<T>): boolean { return !(stringIdGenericValueMap && DictionaryMapUtility.getStringIdGenericValueDictionaryLength(stringIdGenericValueMap) > 0); } public static isEmptyStringIdGenericArrayDictionary<T>( stringIdGenericArrayMap: IDictionaryStringIdGenericArray<T>): boolean { return !(stringIdGenericArrayMap && DictionaryMapUtility.getStringIdGenericArrayDictionaryLength(stringIdGenericArrayMap) > 0); } public static isEmptyStringIdGenericArraysDictionary<T>( stringIdGenericArraysMap: IDictionaryStringIdGenericArrays<T>): boolean { return !(stringIdGenericArraysMap && DictionaryMapUtility.getStringIdGenericArraysDictionaryLength(stringIdGenericArraysMap) > 0); } public static isEmptyNumberIdGenericSetDictionary<T>( numberIdGenericSetMap: IDictionaryNumberIdGenericSet<T>): boolean { return !(numberIdGenericSetMap && DictionaryMapUtility.getNumberIdGenericSetDictionaryLength(numberIdGenericSetMap) > 0); } public static isEmptyNumberIdGenericValueDictionary<T>( numberIdGenericValueMap: IDictionaryNumberIdGenericValue<T>): boolean { return !(numberIdGenericValueMap && DictionaryMapUtility.getNumberIdGenericValueDictionaryLength(numberIdGenericValueMap) > 0); } public static isEmptyNumberIdGenericArrayDictionary<T>( numberIdGenericArrayMap: IDictionaryNumberIdGenericArray<T>): boolean { return !(numberIdGenericArrayMap && DictionaryMapUtility.getNumberIdGenericArrayDictionaryLength(numberIdGenericArrayMap) > 0); } public static isEmptyNumberIdGenericArraysDictionary<T>( numberIdGenericArraysMap: IDictionaryNumberIdGenericArrays<T>): boolean { return !(numberIdGenericArraysMap && DictionaryMapUtility.getNumberIdGenericArraysDictionaryLength(numberIdGenericArraysMap) > 0); } public static isEmptyAnyKeyGenericSetMap<T>( anyKeyGenericSetMap: TMapAnyKeyGenericSet<T>): boolean { return !(anyKeyGenericSetMap && DictionaryMapUtility.getAnyKeyGenericSetMapLength(anyKeyGenericSetMap) > 0); } public static isEmptyAnyKeyGenericValueMap<T>( anyKeyGenericValueMap: TMapAnyKeyGenericValue<T>): boolean { return !(anyKeyGenericValueMap && DictionaryMapUtility.getAnyKeyGenericValueMapLength(anyKeyGenericValueMap) > 0); } public static isEmptyAnyKeyGenericArrayMap<T>( anyKeyGenericArrayMap: TMapAnyKeyGenericArray<T>): boolean { return !(anyKeyGenericArrayMap && DictionaryMapUtility.getAnyKeyGenericArrayMapLength(anyKeyGenericArrayMap) > 0); } public static isEmptyAnyKeyGenericArraysMap<T>( anyKeyGenericArraysMap: TMapAnyKeyGenericArrays<T>): boolean { return !(anyKeyGenericArraysMap && DictionaryMapUtility.getAnyKeyGenericArraysMapLength(anyKeyGenericArraysMap) > 0); } public static isEmptyGenericKeyGenericSetMap<I, T>( genericKeyGenericSetMap: TMapGenericKeyGenericSet<I, T>): boolean { return !(genericKeyGenericSetMap && DictionaryMapUtility.getGenericKeyGenericSetMapLength(genericKeyGenericSetMap) > 0); } public static isEmptyGenericKeyGenericValueMap<I, T>( genericKeyGenericValueMap: TMapGenericKeyGenericValue<I, T>): boolean { return !(genericKeyGenericValueMap && DictionaryMapUtility.getGenericKeyGenericValueMapLength(genericKeyGenericValueMap) > 0); } public static isEmptyGenericKeyGenericArrayMap<I, T>( genericKeyGenericArrayMap: TMapGenericKeyGenericArray<I, T>): boolean { return !(genericKeyGenericArrayMap && DictionaryMapUtility.getGenericKeyGenericArrayMapLength(genericKeyGenericArrayMap) > 0); } public static isEmptyGenericKeyGenericArraysMap<I, T>( genericKeyGenericArraysMap: TMapGenericKeyGenericArrays<I, T>): boolean { return !(genericKeyGenericArraysMap && DictionaryMapUtility.getGenericKeyGenericArraysMapLength(genericKeyGenericArraysMap) > 0); } public static isEmptyNumberKeyGenericSetMap<T>( numberKeyGenericSetMap: TMapNumberKeyGenericSet<T>): boolean { return !(numberKeyGenericSetMap && DictionaryMapUtility.getNumberKeyGenericSetMapLength(numberKeyGenericSetMap) > 0); } public static isEmptyNumberKeyGenericValueMap<T>( numberKeyGenericValueMap: TMapNumberKeyGenericValue<T>): boolean { return !(numberKeyGenericValueMap && DictionaryMapUtility.getNumberKeyGenericValueMapLength(numberKeyGenericValueMap) > 0); } public static isEmptyNumberKeyGenericArrayMap<T>( numberKeyGenericArrayMap: TMapNumberKeyGenericArray<T>): boolean { return !(numberKeyGenericArrayMap && DictionaryMapUtility.getNumberKeyGenericArrayMapLength(numberKeyGenericArrayMap) > 0); } public static isEmptyNumberKeyGenericArraysMap<T>( numberKeyGenericArraysMap: TMapNumberKeyGenericArrays<T>): boolean { return !(numberKeyGenericArraysMap && DictionaryMapUtility.getNumberKeyGenericArraysMapLength(numberKeyGenericArraysMap) > 0); } public static isEmptyStringKeyGenericSetMap<T>( stringKeyGenericSetMap: TMapStringKeyGenericSet<T>): boolean { return !(stringKeyGenericSetMap && DictionaryMapUtility.getStringKeyGenericSetMapLength(stringKeyGenericSetMap) > 0); } public static isEmptyStringKeyGenericValueMap<T>( stringKeyGenericValueMap: TMapStringKeyGenericValue<T>): boolean { return !(stringKeyGenericValueMap && DictionaryMapUtility.getStringKeyGenericValueMapLength(stringKeyGenericValueMap) > 0); } public static isEmptyStringKeyGenericArrayMap<T>( stringKeyGenericArrayMap: TMapStringKeyGenericArray<T>): boolean { return !(stringKeyGenericArrayMap && DictionaryMapUtility.getStringKeyGenericArrayMapLength(stringKeyGenericArrayMap) > 0); } public static isEmptyStringKeyGenericArraysMap<T>( stringKeyGenericArraysMap: TMapStringKeyGenericArrays<T>): boolean { return !(stringKeyGenericArraysMap && DictionaryMapUtility.getStringKeyGenericArraysMapLength(stringKeyGenericArraysMap) > 0); } public static getStringIdGenericSetDictionaryLength<T>(map: IDictionaryStringIdGenericSet<T>): number { return (Object.keys(map).length); } public static getNumberIdGenericSetDictionaryLength<T>(map: IDictionaryNumberIdGenericSet<T>): number { return (Object.keys(map).length); } public static getStringIdGenericValueDictionaryLength<T>(map: IDictionaryStringIdGenericValue<T>): number { return (Object.keys(map).length); } public static getNumberIdGenericValueDictionaryLength<T>(map: IDictionaryNumberIdGenericValue<T>): number { return (Object.keys(map).length); } public static getStringIdGenericArrayDictionaryLength<T>(map: IDictionaryStringIdGenericArray<T>): number { return (Object.keys(map).length); } public static getNumberIdGenericArrayDictionaryLength<T>(map: IDictionaryNumberIdGenericArray<T>): number { return (Object.keys(map).length); } public static getStringIdGenericArraysDictionaryLength<T>(map: IDictionaryStringIdGenericArrays<T>): number { return (Object.keys(map).length); } public static getNumberIdGenericArraysDictionaryLength<T>(map: IDictionaryNumberIdGenericArrays<T>): number { return (Object.keys(map).length); } public static getAnyKeyGenericSetMapLength<T>(map: TMapAnyKeyGenericSet<T>): number { return map.size; } public static getGenericKeyGenericSetMapLength<I, T>(map: TMapGenericKeyGenericSet<I, T>): number { return map.size; } public static getNumberKeyGenericSetMapLength<T>(map: TMapNumberKeyGenericSet<T>): number { return map.size; } public static getStringKeyGenericSetMapLength<T>(map: TMapStringKeyGenericSet<T>): number { return map.size; } public static getAnyKeyGenericValueMapLength<T>(map: TMapAnyKeyGenericValue<T>): number { return map.size; } public static getGenericKeyGenericValueMapLength<I, T>(map: TMapGenericKeyGenericValue<I, T>): number { return map.size; } public static getNumberKeyGenericValueMapLength<T>(map: TMapNumberKeyGenericValue<T>): number { return map.size; } public static getStringKeyGenericValueMapLength<T>(map: TMapStringKeyGenericValue<T>): number { return map.size; } public static getAnyKeyGenericArrayMapLength<T>(map: TMapAnyKeyGenericArray<T>): number { return map.size; } public static getGenericKeyGenericArrayMapLength<I, T>(map: TMapGenericKeyGenericArray<I, T>): number { return map.size; } public static getNumberKeyGenericArrayMapLength<T>(map: TMapNumberKeyGenericArray<T>): number { return map.size; } public static getStringKeyGenericArrayMapLength<T>(map: TMapStringKeyGenericArray<T>): number { return map.size; } public static getAnyKeyGenericArraysMapLength<T>(map: TMapAnyKeyGenericArrays<T>): number { return map.size; } public static getGenericKeyGenericArraysMapLength<I, T>(map: TMapGenericKeyGenericArrays<I, T>): number { return map.size; } public static getNumberKeyGenericArraysMapLength<T>(map: TMapNumberKeyGenericArrays<T>): number { return map.size; } public static getStringKeyGenericArraysMapLength<T>(map: TMapStringKeyGenericArrays<T>): number { return map.size; } public static newTMapAnyKeyGenericSet<T>(): TMapAnyKeyGenericSet<T> { return new Map<any, Set<T>>(); } public static newTMapGenericKeyGenericSet<I, T>(): TMapGenericKeyGenericSet<I, T> { return new Map<I, Set<T>>(); } public static newTMapNumberKeyGenericSet<T>(): TMapNumberKeyGenericSet<T> { return new Map<number, Set<T>>(); } public static newTMapStringKeyGenericSet<T>(): TMapStringKeyGenericSet<T> { return new Map<string, Set<T>>(); } public static newTMapAnyKeyGenericValue<T>(): TMapAnyKeyGenericValue<T> { return new Map<any, T>(); } public static newTMapGenericKeyGenericValue<I, T>(): TMapGenericKeyGenericValue<I, T> { return new Map<I, T>(); } public static newTMapNumberKeyGenericValue<T>(): TMapNumberKeyGenericValue<T> { return new Map<number, T>(); } public static newTMapStringKeyGenericValue<T>(): TMapStringKeyGenericValue<T> { return new Map<string, T>(); } public static newTMapAnyKeyGenericArray<T>(): TMapAnyKeyGenericArray<T> { return new Map<any, T[]>(); } public static newTMapGenericKeyGenericArray<I, T>(): TMapGenericKeyGenericArray<I, T> { return new Map<I, T[]>(); } public static newTMapNumberKeyGenericArray<T>(): TMapNumberKeyGenericArray<T> { return new Map<number, T[]>(); } public static newTMapStringKeyGenericArray<T>(): TMapStringKeyGenericArray<T> { return new Map<string, T[]>(); } public static newTMapAnyKeyGenericArrays<T>(): TMapAnyKeyGenericArrays<T> { return new Map<any, T[][]>(); } public static newTMapGenericKeyGenericArrays<I, T>(): TMapGenericKeyGenericArrays<I, T> { return new Map<I, T[][]>(); } public static newTMapNumberKeyGenericArrays<T>(): TMapNumberKeyGenericArrays<T> { return new Map<number, T[][]>(); } public static newTMapStringKeyGenericArrays<T>(): TMapStringKeyGenericArrays<T> { return new Map<string, T[][]>(); } }
the_stack
import { invariant } from '@algomart/shared/utils' import type { Account, Transaction, TransactionSigner } from 'algosdk' import { loadSDK } from './utils' export type MultisigMetadata = { version: number threshold: number addrs: string[] } /** * Wallet transaction type based on ARC-1. * @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0001.md#interface-wallettransaction */ export type WalletTransaction = { txn: string // Additional field to avoid the need to decode the transaction txID: string signers?: string[] message?: string authAddr?: string msig?: MultisigMetadata stxn?: string groupMessage?: string } /** * Encodes an unsigned transaction to base64 for storage/asynchronous processing based on ARC-1. * * @note This does not support `msig` or `authAddr` at this time. * @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0001.md * @param txn Transaction to be encoded * @param signers Optional signers that should sign the transaction. Leave empty to sign based on the transaction's configuration. * @param message Optional message to be included * @returns Base64 encoded transaction */ export async function encodeTransaction( txn: Transaction, signers?: string[], message?: string ): Promise<WalletTransaction> { const { encodeUnsignedTransaction } = await loadSDK() return { txn: Buffer.from(encodeUnsignedTransaction(txn)).toString('base64'), txID: txn.txID(), signers, message, } } /** * Encodes a list of transactions to base64 for storage/asynchronous processing based on ARC-1. * Also assigns group ID. Does not set `signers`, so must be set manually by the caller if needed. * * @note This does not support `msig` or `authAddr` at this time. * @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0001.md * @param txns Transactions to encode * @param messages Optional messages to include, should be the same length as `txns` * @returns A list of encoded transactions */ export async function encodeTransactions( txns: Transaction[], messages?: string[] ): Promise<WalletTransaction[]> { const { assignGroupID } = await loadSDK() if (txns.length > 1) assignGroupID(txns) return Promise.all( txns.map((txn, i) => encodeTransaction(txn, undefined, messages?.[i])) ) } /** * Encodes an unsigned transaction to base64 for storage/asynchronous processing based on ARC-1. * Also signs the transaction and encodes the signed transaction. * Be sure to use this **after** assigning the group ID, if needed. * * @note This does not support `msig` or `authAddr` at this time. * @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0001.md * @param txn Transaction to be signed an encoded * @param signer The transaction signer to use * @param message Optional message to be included * @returns Base64 encoded signed transaction */ export async function encodeSignedTransaction( txn: Transaction, signer: TransactionSigner, message?: string ): Promise<WalletTransaction> { const { txn: txnBase64 } = await encodeTransaction(txn) const [signedTxn] = await signer([txn], [0]) return { txn: txnBase64, txID: txn.txID(), signers: [], stxn: Buffer.from(signedTxn).toString('base64'), message, } } /** * Encodes a signed transaction as a base64 string. * @param stxn The signed transaction to encode * @returns Base64 encoded signed transaction */ export function encodeRawSignedTransaction(stxn: Uint8Array): string { return Buffer.from(stxn).toString('base64') } /** * Decodes a base64 encoded signed transaction. * @param stxn The signed transaction to decode * @returns Raw signed transaction */ export function decodeRawSignedTransaction(stxn: string): Uint8Array { return new Uint8Array(Buffer.from(stxn, 'base64')) } /** * Encodes a list of transactions to base64 for storage/asynchronous processing based on ARC-1. * Also assigns group ID and signs the transactions. * * @note This does not support `msig` or `authAddr` at this time. * @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0001.md * @param txns Transactions to be signed and encoded * @param signers Signers to use, must match the length of `txns` * @param messages Optional messages to use, indexes must batch `txns` * @returns List of base64 encoded signed transactions */ export async function encodeSignedTransactions( txns: Transaction[], signers: TransactionSigner[], messages?: string[] ): Promise<WalletTransaction[]> { const { assignGroupID } = await loadSDK() if (txns.length > 1) assignGroupID(txns) invariant( txns.length === signers.length, 'txns and signers must be the same length' ) return Promise.all( txns.map((txn, i) => encodeSignedTransaction(txn, signers[i], messages?.[i]) ) ) } /** * Decodes an unsigned transaction from base64. * @param txn Encoded transaction to decode * @returns Decoded transaction */ export async function decodeTransaction(txn: string): Promise<Transaction> { const { decodeUnsignedTransaction } = await loadSDK() return decodeUnsignedTransaction(new Uint8Array(Buffer.from(txn, 'base64'))) } enum WalletErrorCode { UserRejectedRequest = 4001, Unauthorized = 4100, UnsupportedOperation = 4200, TooManyTransactions = 4201, UninitializedWallet = 4202, InvalidInput = 4300, } export class WalletError extends Error { constructor(message: string, public code: WalletErrorCode) { super(message) this.name = 'WalletError' } } /** * Custom invariant for wallet errors. * * @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0001.md#error-standards * @param condition Condition to check * @param message Message to display if condition is false * @param code Wallet error code to use */ export function walletInvariant( condition: unknown, message: string, code: WalletErrorCode ): asserts condition { if (!condition) { throw new WalletError(message, code) } } /** * Create a function to sign encoded transactions based on ARC-1. * * @note This does not yet support `msig`. * @see https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0001.md * @param accounts List of accounts that are available for this session * @returns A function that can sign encoded transactions */ export async function configureSignTxns(accounts: Account[]) { const { isValidAddress, encodeAddress, decodeSignedTransaction } = await loadSDK() const accountLookup = new Map<string, Account>( accounts.map((account) => [account.addr, account]) ) function signTxnUsingAddress(txn: Transaction, addr: string) { const account = accountLookup.get(addr) walletInvariant( account, `signer ${addr} not found`, WalletErrorCode.Unauthorized ) const signedTxn = txn.signTxn(account.sk) return Buffer.from(signedTxn).toString('base64') } async function signTxn( { txn, stxn, signers, msig, authAddr }: WalletTransaction, groupID?: Buffer ): Promise<string | null> { const decodedTransaction = await decodeTransaction(txn) walletInvariant( !groupID || (decodedTransaction.group && decodedTransaction.group.equals(groupID)), 'group mismatch', WalletErrorCode.InvalidInput ) if (authAddr) { walletInvariant( isValidAddress(authAddr), 'authAddr must be a valid address', WalletErrorCode.InvalidInput ) } if (signers) { walletInvariant( signers.every((signer) => isValidAddress(signer)), 'signers must be valid addresses', WalletErrorCode.InvalidInput ) if (signers.length === 0) { // Should not sign this transaction if (stxn) { // Validate inner txn const signedTxn = decodeSignedTransaction( new Uint8Array(Buffer.from(stxn, 'base64')) ) walletInvariant( signedTxn.txn.txID() === decodedTransaction.txID(), 'Invalid inner transaction', WalletErrorCode.InvalidInput ) return stxn } else { // Skip entirely return null } } else if (signers.length === 1) { // TODO: Support multisig walletInvariant( !msig, 'multisig is not supported', WalletErrorCode.UnsupportedOperation ) const signer = authAddr || signers[0] if (authAddr) { walletInvariant( authAddr === signers[0], 'authAddr must match the signer', WalletErrorCode.InvalidInput ) } return signTxnUsingAddress(decodedTransaction, signer) } // Should not end up here, because multiple signers implies msig must have been set walletInvariant( false, `badly formatted transaction ${decodedTransaction.txID()}`, WalletErrorCode.InvalidInput ) } else { // No signers provided, lookup the signer specified in the transaction's `from` field const signer = authAddr || encodeAddress(decodedTransaction.from.publicKey) return signTxnUsingAddress(decodedTransaction, signer) } } return async function signTxns( txns: WalletTransaction[] ): Promise<(string | null)[]> { walletInvariant( txns.length > 0, 'no transactions provided', WalletErrorCode.InvalidInput ) walletInvariant( txns.length <= 16, 'too many transactions', WalletErrorCode.TooManyTransactions ) // Require that multiple transactions belong to the same group. Does not support the optional // specified here: https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0001.md#group-validation const groupID = (await decodeTransaction(txns[0].txn)).group walletInvariant( txns.length === 1 || !!groupID, 'group must be set for multiple transactions', WalletErrorCode.InvalidInput ) return Promise.all(txns.map((txn) => signTxn(txn, groupID))) } }
the_stack
import { ModelManager, ModelFile } from 'composer-common'; import { EditorFile } from './editor-file'; import * as sinon from 'sinon'; describe('EditorFile', () => { let file; beforeEach(() => { file = new EditorFile('fileID', 'fileDisplayID', 'fileContent', 'fileType'); }); describe('EditorFile', () => { it('should create a file', () => { file['id'].should.equal('fileID'); file['displayID'].should.equal('fileDisplayID'); file['content'].should.equal('fileContent'); file['type'].should.equal('fileType'); }); it('should return the ID of a file', () => { file.getId().should.equal('fileID'); }); it('should return the content of a file', () => { file.getContent().should.equal('fileContent'); }); it('should return the type of a file', () => { file.getType().should.equal('fileType'); }); it('should set the ID of a file', () => { file.setId('newFileId'); file.getId().should.equal('newFileId'); }); it('should set the content of a file', () => { file.setContent('newFileContent'); file.getContent().should.equal('newFileContent'); }); it('should set the JSON content of a file', () => { file.setJsonContent({content: 'newFileContent'}); file.getContent().should.equal('{\n "content": "newFileContent"\n}'); }); it('should set deisplay id', () => { file.setDisplayID('newDisplayId'); file['displayID'].should.equal('newDisplayId'); }); it('should set the type of a file', () => { file.setType('newFileType'); file.getType().should.equal('newFileType'); }); it('should get if model type', () => { file['type'] = 'model'; file.isModel().should.equal(true); }); it('should get if not model type', () => { file['type'] = 'bob'; file.isModel().should.equal(false); }); it('should get if script type', () => { file['type'] = 'script'; file.isScript().should.equal(true); }); it('should get if not script type', () => { file['type'] = 'bob'; file.isScript().should.equal(false); }); it('should get if acl type', () => { file['type'] = 'acl'; file.isAcl().should.equal(true); }); it('should get if not acl type', () => { file['type'] = 'bob'; file.isAcl().should.equal(false); }); it('should get if query type', () => { file['type'] = 'query'; file.isQuery().should.equal(true); }); it('should get if not query type', () => { file['type'] = 'bob'; file.isQuery().should.equal(false); }); it('should get if readme type', () => { file['type'] = 'readme'; file.isReadMe().should.equal(true); }); it('should get if not readme type', () => { file['type'] = 'bob'; file.isReadMe().should.equal(false); }); it('should get if package type', () => { file['type'] = 'package'; file.isPackage().should.equal(true); }); it('should get if not package type', () => { file['type'] = 'bob'; file.isPackage().should.equal(false); }); }); describe('getModelNamespace', () => { it('should get the namespace of the model file', () => { file['content'] = `/** * Sample business network definition. */ namespace org.acme.sample `; file.getModelNamespace().should.equal('org.acme.sample'); }); }); describe('validate', () => { it('should validate a model file', () => { const model1 = ` namespace org.acme.ext asset MyAsset2 identified by assetId { o String assetId }`; const model2 = ` namespace org.acme import org.acme.ext.MyAsset2 asset MyAsset identified by assetId { o String assetId }`; let modelManager = new ModelManager(); let modelFile1 = new ModelFile(modelManager, model1); modelManager.addModelFiles([modelFile1], [modelFile1.getName()]); file['type'] = 'model'; file['content'] = model2; (() => file.validate(modelManager)).should.not.throw(); }); it('should throw error with invalid model file', () => { const model1 = ` namespace org.acme.ext asset MyAsset2 identified by assetId { o String assetId }`; const model2 = ` namespace org.acme import org.acme.ext.MyAsset2 ast MyAsset identified by assetId { o String assetId }`; let modelManager = new ModelManager(); let modelFile1 = new ModelFile(modelManager, model1); modelManager.addModelFiles([modelFile1], [modelFile1.getName()]); file['type'] = 'model'; file['content'] = model2; (() => file.validate(modelManager)).should.throw(); }); it('should validate script file', () => { const model = `/** * Sample business network definition. */ namespace org.acme.sample asset SampleAsset identified by assetId { o String assetId --> SampleParticipant owner o String value } participant SampleParticipant identified by participantId { o String participantId o String firstName o String lastName } transaction SampleTransaction { --> SampleAsset asset o String newValue } event SampleEvent { --> SampleAsset asset o String oldValue o String newValue }`; const script = `function sampleTransaction(tx) { // Save the old value of the asset. var oldValue = tx.asset.value; // Update the asset with the new value. tx.asset.value = tx.newValue; // Get the asset registry for the asset. return getAssetRegistry('org.acme.sample.SampleAsset') .then(function (assetRegistry) { // Update the asset in the asset registry. return assetRegistry.update(tx.asset); }) .then(function () { // Emit an event for the modified asset. var event = getFactory().newEvent('org.acme.sample', 'SampleEvent'); event.asset = tx.asset; event.oldValue = oldValue; event.newValue = tx.newValue; emit(event); }); }`; file['content'] = script; file['type'] = 'script'; let modelManager = new ModelManager(); let modelFile = new ModelFile(modelManager, model); modelManager.addModelFile(modelFile); (() => file.validate(modelManager)).should.not.throw(); }); it('should throw error on invalid script file', () => { const model = `/** * Sample business network definition. */ namespace org.acme.sample asset SampleAsset identified by assetId { o String assetId --> SampleParticipant owner o String value } participant SampleParticipant identified by participantId { o String participantId o String firstName o String lastName } transaction SampleTransaction { --> SampleAsset asset o String newValue }`; const script = `funn sampleTransaction(tx) { // Save the old value of the asset. var oldValue = tx.asset.value; // Update the asset with the new value. tx.asset.value = tx.newValue; // Get the asset registry for the asset. return getRegistry('org.acme.sample.SampleAsset') .then(function (assetRegistry) { // Update the asset in the asset registry. return assetRegistry.update(tx.asset); }) .then(function () { // Emit an event for the modified asset. var event = getFactory().newEvent('org.acme.sample', 'SampleEvent'); event.asset = tx.asset; event.oldValue = oldValue; event.newValue = tx.newValue; emit(event); }); }`; file['content'] = script; file['type'] = 'script'; let modelManager = new ModelManager(); let modelFile = new ModelFile(modelManager, model); modelManager.addModelFile(modelFile); (() => file.validate(modelManager)).should.throw(); }); it('should validate a query file', () => { const model = `/** * Commodity trading network */ namespace org.acme.trading asset Commodity identified by tradingSymbol { o String tradingSymbol o String description o String mainExchange o Double quantity --> Trader owner } participant Trader identified by tradeId { o String tradeId o String firstName o String lastName }`; const query = ` query selectCommodities { description: "Select all commodities" statement: SELECT org.acme.trading.Commodity }`; file['content'] = query; file['type'] = 'query'; let modelManager = new ModelManager(); let modelFile = new ModelFile(modelManager, model); modelManager.addModelFile(modelFile); (() => file.validate(modelManager)).should.not.throw(); }); it('should throw error on invalid query file', () => { const model = `/** * Commodity trading network */ namespace org.acme.trading asset Commodity identified by tradingSymbol { o String tradingSymbol o String description o String mainExchange o Double quantity --> Trader owner } participant Trader identified by tradeId { o String tradeId o String firstName o String lastName }`; const query = ` query selectCommodities { description: "Select all commodities" statement: SELBOBECT org.acme.trading.Commodity }`; file['content'] = query; file['type'] = 'query'; let modelManager = new ModelManager(); let modelFile = new ModelFile(modelManager, model); modelManager.addModelFile(modelFile); (() => file.validate(modelManager)).should.throw(); }); it('should validate acl file', () => { const model = `/** * Sample business network definition. */ namespace org.acme.sample asset SampleAsset identified by assetId { o String assetId --> SampleParticipant owner o String value } participant SampleParticipant identified by participantId { o String participantId o String firstName o String lastName } transaction SampleTransaction { --> SampleAsset asset o String newValue }`; const acl = `rule SystemACL { description: "System ACL to permit all access" participant: "org.hyperledger.composer.system.Participant" operation: ALL resource: "org.hyperledger.composer.system.**" action: ALLOW }`; file['content'] = acl; file['type'] = 'acl'; let modelManager = new ModelManager(); let modelFile = new ModelFile(modelManager, model); modelManager.addModelFile(modelFile); (() => file.validate(modelManager)).should.not.throw(); }); it('should throw error on invalid acl file', () => { const model = `/** * Sample business network definition. */ namespace org.acme.sample asset SampleAsset identified by assetId { o String assetId --> SampleParticipant owner o String value } participant SampleParticipant identified by participantId { o String participantId o String firstName o String lastName } transaction SampleTransaction { --> SampleAsset asset o String newValue }`; const acl = `rule SystemACL { description: "System ACL to permit all access" participant: "org.hyperledger.composer.system.Participant" operation: ALL resource: "org.hyperledger.composer.system.**" action: BOB }`; file['content'] = acl; file['type'] = 'acl'; let modelManager = new ModelManager(); let modelFile = new ModelFile(modelManager, model); modelManager.addModelFile(modelFile); (() => file.validate(modelManager)).should.throw(); }); it('should not do anything if not a type we deal with', () => { let validateModelSpy = sinon.spy(file, 'validateModelFile'); let validateScriptSpy = sinon.spy(file, 'validateScriptFile'); let validateAclSpy = sinon.spy(file, 'validateAclFile'); let validateQuerySpy = sinon.spy(file, 'validateQueryFile'); let modelManager = new ModelManager(); file['type'] = 'banana'; file.validate(); validateAclSpy.should.not.have.been.called; validateModelSpy.should.not.have.been.called; validateScriptSpy.should.not.have.been.called; validateQuerySpy.should.not.have.been.called; }); }); describe('getDisplayId', () => { it('should get the display id', () => { let result = file.getDisplayId(); result.should.equal('fileDisplayID'); }); }); });
the_stack
export type Json = string | number | boolean | null | undefined | JsonObject | Json[]; export type JsonObject = { [key: string]: Json }; export type JsonData = JsonObject | Json[]; export type DnaForEachCallback = (elem: JQuery, index: number) => void; export type DnaPluginAction = 'bye' | 'clone-sub' | 'destroy' | 'down' | 'refresh' | 'up'; declare global { interface JQuery { forEach: (fn: DnaForEachCallback) => JQuery, dna: (action: DnaPluginAction, ...params: unknown[]) => JQuery, } } export type DnaModel = JsonData; export type DnaDataObject = JsonObject; export type DnaOptionsClone<T> = { fade?: boolean, top?: boolean, clones?: number, html?: boolean, empty?: boolean, holder?: JQuery, container?: JQuery | null, formatter?: DnaFormatter | null, transform?: DnaTransformFn<T> | null, callback?: DnaCallbackFn<T> | null, }; export type DnaOptionsArrayPush = { fade?: boolean, top?: boolean, }; export type DnaOptionsGetModel = { main?: boolean, }; export type DnaOptionsEmpty = { fade?: boolean, }; export type DnaOptionsInsert<T> = { fade?: boolean, html?: boolean, transform?: DnaTransformFn<T>, callback?: DnaCallbackFn<T>, }; export type DnaOptionsRefresh = { data?: unknown, main?: boolean, html?: boolean, }; export type DnaOptionsRefreshAll = { data?: unknown, main?: boolean, html?: boolean, }; export type DnaOptionsRecount = { html?: boolean, }; export type DnaOptionsDestroy<T> = { main?: boolean, fade?: boolean, callback?: DnaCallbackFn<T> | null, }; export type DnaOptionsGetClone = { main?: boolean, }; export type DnaOptionsGetIndex = { main?: boolean, }; export type DnaOptionsRegisterInitializer = { selector?: string | null, params?: DnaDataObject | unknown[] | null, onDocLoad?: boolean, }; export type DnaFormatter = <T>(value: DnaFormatterValue, model?: T) => string; export type DnaFormatterValue = number | string | boolean; export type DnaMSec = number | string; //milliseconds UTC (or ISO 8601 string) export type DnaCallback = (...args: unknown[]) => unknown; export interface DnaTransformFn<T> { (data: T): void } export interface DnaCallbackFn<T> { (elem: JQuery, data?: T): void } export interface DnaInitializerFn { (elem: JQuery, ...params: unknown[]): void } export type DnaElemEventIndex = JQuery | JQuery.EventBase | number; export type DnaInitializer = { fn: DnaFunctionName | DnaInitializerFn, selector: string | null, params: DnaDataObject | unknown[] | null, }; export type DnaTemplate = { name: string, elem: JQuery, container: JQuery, nested: boolean, separators: number, wrapped: boolean, }; export type DnaTemplateDb = { [name: string]: DnaTemplate }; export type DnaTemplateName = string; export type DnaContext = { [app: string]: { [field: string]: unknown } | DnaCallback }; export type DnaFieldName = string; export type DnaFunctionName = string; export type DnaClassName = string; export type DnaAttrName = string; export type DnaAttrParts = [string, DnaFieldName | 1 | 2, string]; export type DnaAttrs = (DnaAttrName | DnaAttrParts)[]; export type DnaPropName = string; export type DnaProps = (DnaPropName | DnaFieldName)[]; export type DnaLoop = { name: string, field: DnaFieldName }; export type DnaRules = { template?: DnaTemplateName, array?: DnaFieldName, text?: boolean, val?: boolean, attrs?: DnaAttrs, props?: DnaProps, option?: DnaFieldName, formatter?: DnaFormatter | null, transform?: DnaFunctionName, callback?: DnaFunctionName, class?: [DnaFieldName, DnaClassName, DnaClassName][], require?: DnaFieldName, missing?: DnaFieldName, true?: DnaFieldName, false?: DnaFieldName, loop?: DnaLoop, }; export type DnaInfo = { version: string, templates: number, clones: number, subs: number, names: string[], store: DnaTemplateDb, initializers: DnaInitializer[], panels: string[], }; const dnaArray = { find: <T, V>(array: T[], value: V, key = 'code'): { index: number, item: T | null } => { // Returns the index and a reference to the first array element with a key equal to the // supplied value. The default key is "code". // Examples: // const array = [{ code: 'a', word: 'Ant' }, { code: 'b', word: 'Bat' }]; // result = dna.array.find(array, 'b'); //{ index: 1, item: { code: 'b', word: 'Bat' } } // result = dna.array.find(array, 'x'); //{ index: -1, item: null } const valid = Array.isArray(array); let i = 0; if (valid) while (i < array.length && array[i]?.[key] !== value) i++; return valid && i < array.length ? { index: i, item: array[i]! } : { index: -1, item: null }; }, last: <T>(array: T[]): T | undefined => { // Returns the last element of the array (or undefined if not possible). // Example: // dna.array.last([3, 21, 7]) === 7; return Array.isArray(array) ? array[array.length - 1] : undefined; }, fromMap: (map: JsonObject, options?: { key?: string, kebabCodes?: boolean }): JsonObject[] => { // Converts an object (hash map) into an array of objects. The default key is "code". // Example: // dna.array.fromMap({ a: { word: 'Ant' }, b: { word: 'Bat' } }) // converts: // { a: { word: 'Ant' }, b: { word: 'Bat' } } // to: // [{ code: 'a', word: 'Ant' }, { code: 'b', word: 'Bat' }] const defaults = { key: 'code', kebabCodes: false }; const settings = { ...defaults, ...options }; const codeValue = (key: string): string => settings.kebabCodes ? dna.util.toKebab(key) : key; const toObj = (item: Json) => dna.util.isObj(item) ? <JsonObject>item : { value: item }; return Object.keys(map).map(key => ({ ...{ [settings.key]: codeValue(key) }, ...toObj(map[key]!) })); }, toMap: (array: DnaDataObject[], options?: { key: string, camelKeys: boolean }): DnaDataObject => { // Converts an array of objects into an object (hash map). The default key is "code". // Example: // dna.array.toMap([{ code: 'a', word: 'Ant' }, { code: 'b', word: 'Bat' }]) // converts: // [{ code: 'a', word: 'Ant' }, { code: 'b', word: 'Bat' }] // to: // { a: { code: 'a', word: 'Ant' }, b: { code: 'b', word: 'Bat' } } const defaults = { key: 'code', camelKeys: false }; const settings = { ...defaults, ...options }; const map = <DnaDataObject>{}; const addObj = (obj: DnaDataObject) => map[<string | number>obj[settings.key]] = obj; const addObjCamelKey = (obj: DnaDataObject) => map[dna.util.toCamel(<string>obj[settings.key])] = obj; array.forEach(settings.camelKeys ? addObjCamelKey : addObj); return map; }, wrap: <T>(itemOrItems: T | T[]): T[] => { // Always returns an array. const isNothing = itemOrItems === null || itemOrItems === undefined; return isNothing ? [] : Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems]; }, }; const dnaBrowser = { getUrlParams: (): { [param: string]: string } => { // Returns the query parameters as an object literal. // Example: // https://example.com?lang=jp&code=7 ==> { lang: 'jp', code: '7' } const params: { [param: string]: string } = {}; const addParam = (parts: [string, string]) => params[parts[0]] = parts[1]; const addPair = (pair: string) => pair && addParam(<[string, string]>pair.split('=')); window.location.search.slice(1).split('&').forEach(addPair); return params; }, }; const dnaPageToken = { // A simple key/value store specific to the page (URL path) that is cleared out when the // user's browser session ends. put: (key: string, value: Json): Json => { // Example: // dna.pageToken.put('favorite', 7); //saves 7 window.sessionStorage[key + window.location.pathname] = JSON.stringify(value); return value; }, get: (key: string, defaultValue: Json): Json => { // Example: // dna.pageToken.get('favorite', 0); //returns 0 if not set const value = window.sessionStorage[key + window.location.pathname]; return value === undefined ? defaultValue : JSON.parse(value); }, }; const dnaUi = { deleteElem: function<T>(elemOrEventOrIndex: DnaElemEventIndex, callback?: DnaCallbackFn<T> | null): JQuery { // A flexible function for removing a jQuery element. // Example: // $('.box').fadeOut(dna.ui.deleteElem); const elem = dna.ui.toElem(elemOrEventOrIndex, this); return dna.core.remove(elem, callback); }, focus: (elem: JQuery): JQuery => { // Sets focus on an element. return elem.trigger('focus'); }, getAttrs: (elem: JQuery): Attr[] => { // Returns the attributes of the DOM node in a regular array. return elem[0] ? Object.values(elem[0].attributes) : []; }, getComponent: (elem: JQuery): JQuery => { // Returns the component (container element with a <code>data-component</code> attribute) to // which the element belongs. return elem.closest('[data-component]'); }, pulse: (elem: JQuery, options?: { duration: number, interval: number, out: number }): JQuery => { // Fades in an element after hiding it to create a single smooth flash effect. The optional // interval fades out the element. const defaults = { duration: 400, interval: 0, out: 5000 }; const settings = { ...defaults, ...options }; const css = { hide: { opacity: 0 }, show: { opacity: 1 } }; elem.stop(true).slideDown().css(css.hide).animate(css.show, settings.duration); if (settings.interval) elem.animate(css.show, settings.interval).animate(css.hide, settings.out); return elem; }, slideFade: <T>(elem: JQuery, callback?: DnaCallbackFn<T> | null, show?: boolean): JQuery => { // Smooth slide plus fade effect. const obscure = { opacity: 0, transition: 'opacity 0s' }; const easeIn = { opacity: 1, transition: 'opacity 400ms' }; const easeOut = { opacity: 0, transition: 'opacity 400ms' }; const reset = { transition: 'opacity 0s' }; const doEaseIn = () => elem.css(easeIn); const clearTransition = () => elem.css(reset); if (show && window.setTimeout(doEaseIn, 200)) elem.css(obscure).hide().delay(100).slideDown(callback || undefined); else elem.css(easeOut).delay(100).slideUp(callback || undefined); elem.delay(200).promise().then(clearTransition); //keep clean for other animations return elem; }, slideFadeIn: <T>(elem: JQuery, callback?: DnaCallbackFn<T> | null): JQuery => { // Smooth slide plus fade effect. return dna.ui.slideFade(elem, callback, true); }, slideFadeOut: <T>(elem: JQuery, callback?: DnaCallbackFn<T> | null): JQuery => { // Smooth slide plus fade effect. return dna.ui.slideFade(elem, callback, false); }, slideFadeToggle: <T>(elem: JQuery, callback?: DnaCallbackFn<T> | null): JQuery => { // Smooth slide plus fade effect. return dna.ui.slideFade(elem, callback, elem.is(':hidden')); }, slideFadeDelete: <T>(elem: JQuery, callback?: DnaCallbackFn<T> | null): JQuery => { // Smooth slide plus fade effect. return dna.ui.slideFadeOut(elem, () => dna.ui.deleteElem(elem, callback)); }, smoothHeightSetBaseline: (container: JQuery): JQuery => { // See: smoothHeightAnimate below const body = $('body'); const elem = body.data().dnaCurrentContainer = container || body; const height = <number>elem.outerHeight(); return elem.css({ minHeight: height, maxHeight: height, overflow: 'hidden' }); }, smoothHeightAnimate: (delay: number, container: JQuery): JQuery => { // Smoothly animates the height of a container element from a beginning height to a final // height. const elem = container || $('body').data().dnaCurrentContainer; const animate = () => { elem.css({ minHeight: 0, maxHeight: '100vh' }); const turnOffTransition = () => elem.css({ transition: 'none', maxHeight: 'none' }); window.setTimeout(turnOffTransition, 1000); //allow 1s transition to finish }; window.setTimeout(animate, delay || 50); //allow container time to draw const setAnimationLength = () => elem.css({ transition: 'all 1s' }); window.setTimeout(setAnimationLength, 10); //allow baseline to lock in height return elem; }, smoothMove: <T>(elem: JQuery, up?: boolean, callback?: DnaCallbackFn<T> | null): JQuery => { // Uses animation to smoothly slide an element up or down one slot amongst its siblings. const fn = typeof callback === 'function' ? callback : null; const move = () => { const ghostElem = submissiveElem.clone(true); if (up) elem.after(submissiveElem.hide()).before(ghostElem); else elem.before(submissiveElem.hide()).after(ghostElem); let finishes = 0; const finish = () => finishes++ && fn && fn(elem); const animate = () => { dna.ui.slideFadeIn(submissiveElem, finish); dna.ui.slideFadeDelete(ghostElem, finish); }; window.setTimeout(animate); }; const submissiveElem = up ? elem.prev() : elem.next(); if (submissiveElem.length) move(); else if (fn) fn(elem); return elem; }, smoothMoveUp: <T>(elem: JQuery, callback?: DnaCallbackFn<T> | null): JQuery => { // Uses animation to smoothly slide an element up one slot amongst its siblings. return dna.ui.smoothMove(elem, true, callback); }, smoothMoveDown: <T>(elem: JQuery, callback?: DnaCallbackFn<T> | null): JQuery => { // Uses animation to smoothly slide an element down one slot amongst its siblings. return dna.ui.smoothMove(elem, false, callback); }, toElem: (elemOrEventOrIndex: DnaElemEventIndex, that?: unknown): JQuery => { // A flexible way to get the jQuery element whether it is passed in directly, is a DOM // element, is the target of an event, or comes from the jQuery context. const elem = elemOrEventOrIndex instanceof $ && <JQuery>elemOrEventOrIndex; const target = elemOrEventOrIndex && (<JQuery.EventBase>elemOrEventOrIndex).target; return elem || $(target || elemOrEventOrIndex || that); }, }; const dnaUtil = { apply: <T>(fn: string | DnaCallbackFn<T> | DnaInitializerFn, params?: unknown | JQuery): unknown => { // Calls fn (string name or actual function) passing in params. // Usage: // dna.util.apply('app.cart.buy', 7); ==> app.cart.buy(7); const args = dna.array.wrap(params); const elem = args[0] instanceof $ ? <JQuery>args[0] : null; let result; const contextApply = (context: DnaCallback | { [name: string]: unknown } | Window, names: string[]) => { const getFn = (): DnaCallback => <DnaCallback>(<{ [name: string]: unknown }>context)[<string>names[0]]; const missing = !context || names.length === 1 && typeof (<DnaDataObject>context)[<string>names[0]] !== 'function'; dna.core.assert(!missing, 'Callback function not found', fn); if (names.length === 1) result = getFn().apply(elem, args); //'app.cart.buy' ==> window['app']['cart']['buy'] else contextApply(getFn(), names.slice(1)); }; const findFn = (names: string[]) => { if (elem) args.push(dna.ui.getComponent(elem)); const context = dna.events.getContextDb(); const name = <string>names[0]; const idPattern = /^[_$a-zA-Z][_$a-zA-Z0-9]*$/; const isUnknown = (): boolean => (window)[name] === undefined && !context[name]; const topLevelGet = (null, eval); const callable = (): boolean => ['object', 'function'].includes(topLevelGet('typeof ' + name)); if (idPattern.test(name) && isUnknown() && callable()) dna.registerContext(name, topLevelGet(name)); contextApply(context[name] ? context : window, names); }; if (elem && elem.length === 0) //noop for emply list of elems result = elem; else if (typeof fn === 'function') //run regular function with supplied arguments result = fn.apply(elem, <[JQuery, T]>args); else if (elem && (elem)[fn]) //run element's jQuery function result = (elem)[fn](args[1], args[2], args[3]); else if (typeof fn === 'string' && fn.length > 0) findFn(fn.split('.')); else if (fn === undefined || fn === null) result = null; else dna.core.assert(false, 'Invalid callback function', fn); return result; }, assign: (data: DnaDataObject, field: string | string[], value: Json): DnaDataObject => { // Sets the field in the data object to the new value and returns the updated data object. // Example: // dna.util.assign({ a: { b: 7 } }, 'a.b', 21); //{ a: { b: 21 } } const fields = typeof field === 'string' ? field.split('.') : field; const name = <string>fields[0]; const dataObj = $.isPlainObject(data) ? data : {}; const nestedData = (): DnaDataObject => dataObj[name] === undefined ? dataObj[name] = {} : <DnaDataObject>dataObj[name]; if (fields.length === 1) dataObj[name] = value; else dna.util.assign(nestedData(), fields.slice(1), value); return dataObj; }, printf: (format: string, ...values: unknown[]): string => { // Builds a formatted string by replacing the format specifiers with the supplied arguments. // Usage: // dna.util.printf('Items in %s: %s', 'cart', 3) === 'Items in cart: 3'; return values.reduce((output: string, value: unknown) => output.replace(/%s/, String(value)), format); }, realTruth: (value: unknown): boolean => { // Returns the "real" boolean truth of a value. // Examples: // const trues = [true, 1, '1', 't', 'T', 'TRue', 'Y', 'yes', 77, [5], {}, 'Colbert', Infinity]; // const falses = [false, 0, '0', 'f', 'F', 'faLSE', 'N', 'no', '', [], null, undefined, NaN]; const falseyStr = () => /^(f|false|n|no|0)$/i.test(String(value)); const emptyArray = () => value instanceof Array && value.length === 0; return !!value && !emptyArray() && !falseyStr(); }, toCamel: (kebabStr: string): string => { // Converts a kebab-case string (a code made of lowercase letters and dashes) to camelCase. // Example: // dna.util.toCamel('ready-set-go') === 'readySetGo' const hump = (match: string, letter: string): string => letter.toUpperCase(); return String(kebabStr).replace(/-(.)/g, hump); }, toKebab: (camelStr: string): string => { // Converts a camelCase string to kebab-case (a code made of lowercase letters and dashes). // Example: // dna.util.toKebab('readySetGo') === 'ready-set-go' const dash = (word: string) => '-' + word.toLowerCase(); return ('' + camelStr).replace(/([A-Z]+)/g, dash).replace(/\s|^-/g, ''); }, value: <T>(data: T, field: string | string[]): unknown => { // Returns the value of the field from the data object. // Example: // dna.util.value({ a: { b: 7 } }, 'a.b') === 7 if (typeof field === 'string') field = field.split('.'); return data === null || data === undefined || field === undefined ? null : field.length === 1 ? data[<string>field[0]] : dna.util.value(data[<string>field[0]], field.slice(1)); }, isObj: (value: unknown): boolean => { return !!value && typeof value === 'object' && !Array.isArray(value); }, }; const dnaFormat = { getCurrencyFormatter(iso4217: string, units = 1): DnaFormatter { // Returns a function to format monetary values into strings, like "¥2,499" and "$4.95". const currency = { style: 'currency', currency: iso4217.toUpperCase() }; const formatter = new Intl.NumberFormat([], currency).format; return (value: DnaFormatterValue) => formatter(Number(value) / units); }, getDateFormatter(format: string): DnaFormatter { // Returns a function to format dates into strings, like "2030-05-04 1:00am". const twoDigit = (value: number) => String(value).padStart(2, '0'); const generalDate = (date: Date) => `${date.getFullYear()}-${twoDigit(date.getMonth() + 1)}-${twoDigit(date.getDate())}`; const generalTime = (date: Date) => date.toLocaleString([], { hour: 'numeric', minute: '2-digit' }).replace(' ', '').toLowerCase(); const generalTimestamp = (date: Date) => generalDate(date) + ' ' + generalTime(date); const dateFormatters = <{ [format: string]: DnaFormatter }>{ //ex: 1904112000000 (msec) date: (msec: DnaMSec) => new Date(msec).toDateString(), //ex: 'Sat May 04 2030' general: (msec: DnaMSec) => generalTimestamp(new Date(msec)), //ex: '2030-05-04 1:00am' generalDate: (msec: DnaMSec) => generalDate(new Date(msec)), //ex: '2030-05-04' generalTime: (msec: DnaMSec) => generalTime(new Date(msec)), //ex: '1:00am' iso: (msec: DnaMSec) => new Date(msec).toISOString(), //ex: '2030-05-04T08:00:00.000Z' locale: (msec: DnaMSec) => new Date(msec).toLocaleString(), //ex: '5/4/2030, 1:00:00 AM' localeDate: (msec: DnaMSec) => new Date(msec).toLocaleDateString(), //ex: '5/4/2030' localeTime: (msec: DnaMSec) => new Date(msec).toLocaleTimeString(), //ex: '1:00:00 AM' string: (msec: DnaMSec) => new Date(msec).toString(), //ex: 'Sat May 04 2030 01:00:00 GMT-0700 (PDT)' time: (msec: DnaMSec) => new Date(msec).toTimeString(), //ex: '01:00:00 GMT-0700 (PDT)' utc: (msec: DnaMSec) => new Date(msec).toUTCString(), //ex: 'Sat, 04 May 2030 08:00:00 GMT' }; const formatter = dateFormatters[dna.util.toCamel(format)]; dna.core.assert(formatter, 'Unknown date format code', format); return <DnaFormatter>formatter; }, getNumberFormatter(format: string): DnaFormatter { // Returns a function to format numeric values into strings, like "1,000.000" and "3.14", // based on the supplied fixed-point notation format ("#", "#.#", "#.##", "#.###", ...). dna.core.assert(/^#([.]#+)?$/.test(format), 'Unknown numeric format code', format); const digits = format === '#' ? 0 : format.length - 2; const numeric = { minimumFractionDigits: digits, maximumFractionDigits: digits }; return <DnaFormatter>new Intl.NumberFormat([], numeric).format; }, getPercentFormatter(format: string): DnaFormatter { // Returns a function to format floats (generally from 0 to 1) into strings, like "82%" // and "12.57%", representing a percent value based on the supplied fixed-point notation // format ("#", "#.#", "#.##", "#.###", ...). dna.core.assert(/^#([.]#+)?$/.test(format), 'Unknown percent format code', format); const digits = format === '#' ? 0 : format.length - 2; const percent = { style: 'percent', minimumFractionDigits: digits, maximumFractionDigits: digits }; return <DnaFormatter>new Intl.NumberFormat([], percent).format; }, getFormatter(fn: string): DnaFormatter { return <T>(value: DnaFormatterValue, data: T) => String(dna.util.apply(fn, [value, data])); }, }; const dnaPlaceholder = { //TODO: optimize // A template placeholder is only shown when its corresponding template is empty (has zero // clones). The "data-placeholder" attribute specifies the name of the template. setup: (): JQuery => { $('option.dna-template').closest('select').addClass('dna-hide'); const fade = (elem: JQuery) => dna.getClones(elem.stop(true).data().placeholder).length ? elem.fadeOut() : elem.fadeIn(); return $('[data-placeholder]').forEach(fade); }, }; const dnaPanels = { // Each click of a menu item displays its corresponding panel and optionally passes the panel // element and hash to the function specified by the "data-callback" attribute. // Usage: // <nav class=dna-menu data-nav={NAME} data-callback={CALLBACK}> // <button>See X1</button> // <button>See X2</button> // </nav> // <div class=dna-panels data-nav={NAME}> // <section data-hash=x1>The X1</section> // <section data-hash=x2>The X2</section> // </div> // The optional "data-hash" attribute specifies the hash (URL fragment ID) and updates the // location bar. The "data-nav" attributes can be omitted if the ".dna-panels" element // immediately follows the ".dna-menu" element. display: (menu: JQuery, location?: number, updateUrl?: boolean): JQuery => { // Shows the panel at the given location (index). const panels = menu.data().dnaPanels; const navName = menu.data().nav; const menuItems = menu.find('.menu-item'); const bound = (loc: number) => Math.max(0, Math.min(loc, menuItems.length - 1)); const index = bound( location === undefined ? <number>dna.pageToken.get(navName, 0) : <number>location); const dropDownElemType = 'SELECT'; if ((<HTMLElement>menu[0]).nodeName === dropDownElemType) (<HTMLSelectElement>menu[0]).selectedIndex = index; menuItems.removeClass('selected').addClass('unselected'); menuItems.eq(index).addClass('selected').removeClass('unselected'); panels.hide().removeClass('displayed').addClass('hidden'); const panel = panels.eq(index).fadeIn().addClass('displayed').removeClass('hidden'); const hash = panel.data().hash; dna.pageToken.put(navName, index); if (updateUrl && hash) window.history.pushState(null, '', '#' + hash); dna.util.apply(menu.data().callback, [panel, hash]); return panel; }, clickRotate: (event: JQuery.EventBase): JQuery => { // Moves to the selected panel. const item = $(event.target).closest('.menu-item'); const menu = item.closest('.dna-menu'); return dna.panels.display(menu, menu.find('.menu-item').index(item), true); }, selectRotate: (event: JQuery.EventBase): JQuery => { // Moves to the selected panel. const menu = $(event.target); return dna.panels.display(menu, menu.find('option:selected').index(), true); }, initialize: (panelHolder: JQuery): JQuery => { const initialized = 'dna-panels-initialized'; const generateNavName = (): string => { const navName = 'dna-panels-' + $('body').data().dnaPanelNextNav++; panelHolder.attr('data-nav', navName).prev('.dna-menu').attr('data-nav', navName); return navName; }; const init = () => { const navName = panelHolder.data().nav || generateNavName(); const menu = $('.dna-menu[data-nav=' + navName + ']').addClass(initialized); const panels = panelHolder.addClass(initialized).children().addClass('panel'); const hash = window.location.hash.replace(/[^\w-]/g, ''); //remove leading "#" const hashIndex = (): number => panels.filter('[data-hash=' + hash + ']').index(); const savedIndex = (): number => <number>dna.pageToken.get(navName, 0); const loc = hash && panels.first().data().hash ? hashIndex() : savedIndex(); dna.core.assert(menu.length, 'Menu not found for panels', navName); menu.data().dnaPanels = panels; if (!menu.find('.menu-item').length) //set .menu-item elems if not set in the html menu.children().addClass('menu-item'); dna.panels.display(menu, loc); }; const isInitialized = !panelHolder.length || panelHolder.hasClass(initialized); if (!isInitialized && !panelHolder.children().hasClass('dna-template')) init(); return panelHolder; }, setup: (): JQuery => { $('body').data().dnaPanelNextNav = 1; const panels = $('.dna-panels').forEach(dna.panels.initialize); $(window.document).on({ click: dna.panels.clickRotate }, '.dna-menu .menu-item'); $(window.document).on({ change: dna.panels.selectRotate }, '.dna-menu'); return panels; }, }; const dnaCompile = { // Pre-compile Example Post-compile class + data().dnaRules // ----------- -------------------------------- ------------------------------------ // template <p id=x1 class=dna-template> class=dna-clone // array <p data-array=~~tags~~> class=dna-nucleotide + array='tags' // field <p>~~tag~~</p> class=dna-nucleotide + text='tag' // attribute <p id=~~num~~> class=dna-nucleotide + attrs=['id', ['', 'num', '']] // rule <p data-true=~~on~~> class=dna-nucleotide + true='on' // attr rule <p data-attr-src=~~url~~> class=dna-nucleotide + attrs=['src', ['', 'url', '']] // prop rule <input data-prop-checked=~~on~~> class=dna-nucleotide + props=['checked', 'on'] // select rule <select data-option=~~day~~> class=dna-nucleotide + option='day' // transform <p data-transform=app.enhance> class=dna-nucleotide + transform='app.enhance' // format <p data-format-date=iso> class=dna-nucleotide + formatter=fn() // callback <p data-callback=app.configure> class=dna-nucleotide + callback='app.configure' // // Rules data().dnaRules // ----------------------------------------- --------------- // data-class=~~field,name-true,name-false~~ class=[['field','name-true','name-false']] // data-attr-{NAME}=pre~~field~~post attrs=['{NAME}', ['pre', 'field', 'post']] // data-prop-{NAME}=pre~~field~~post props=['{NAME}', 'field'] // data-option=~~field~~ option='field' // data-require=~~field~~ require='field' // data-missing=~~field~~ missing='field' // data-true=~~field~~ true='field' // data-false=~~field~~ false='field' // data-format=fn formatter=fn() // data-transform=fn transform='fn' // data-callback=fn callback='fn' // regex: { dnaField: /^[\s]*(~~|\{\{).*(~~|\}\})[\s]*$/, //example: ~~title~~ dnaBasePair: /~~|{{|}}/, //matches the '~~' string dnaBasePairs: /~~|\{\{|\}\}/g, //matches the two '~~' strings so they can be removed }, setupNucleotide: (elem: JQuery): JQuery => { if (!elem.data().dnaRules) elem.data().dnaRules = <DnaRules>{}; return elem.addClass('dna-nucleotide'); }, isDnaField: (index: number, node: HTMLElement): boolean => { const firstNode = <ChildNode>node.childNodes[0]; const matches = (): boolean => !!firstNode.nodeValue?.match(dna.compile.regex.dnaField); return firstNode && !!firstNode.nodeValue && matches(); }, addFieldClass: (elem: JQuery): JQuery => { const field = elem.data().dnaField; const htmlCase = () => dna.util.toKebab(field).replace(/[[\]]/g, '').replace(/[.]/g, '-'); return field ? elem.addClass('dna-field-' + htmlCase()) : elem; }, field: (elem: JQuery): void => { // Examples: // <p>~~name~~</p> ==> // <p class=dna-nucleotide data-dnaField=name data-dnaRules={ text: true }></p> // <textarea>~~address~~</textarea> ==> // <textarea class=dna-nucleotide data-dnaField=address data-dnaRules={ val: true }></p> dna.compile.setupNucleotide(elem); elem.data().dnaField = elem.text().replace(dna.compile.regex.dnaBasePairs, '').trim(); dna.compile.addFieldClass(elem); if (elem.is('textarea')) elem.addClass('dna-update-model').data().dnaRules.val = true; else elem.data().dnaRules.text = true; elem.empty(); }, propsAndAttrs: (elem: JQuery): void => { // Examples: // <p id=~~num~~> ==> <p class=dna-nucleotide + data-dnaRules={ attrs: ['id', ['', 'num', '']] }> // <p data-attr-src=~~url~~> ==> <p class=dna-nucleotide + data-dnaRules={ attrs: ['src', ['', 'url', '']] }> // <p data-tag=~~[count]~~> ==> <p class=dna-nucleotide + data-dnaRules={ attrs: ['data-tag', ['', 1, '']] }> // <p data-tag=~~[value]~~> ==> <p class=dna-nucleotide + data-dnaRules={ attrs: ['data-tag', ['', 2, '']] }> // <input type=checkbox data-prop-checked=~~set~~> // ==> <option class=dna-nucleotide + data-dnaRules={ props: ['selected', 'set'] }> // <select data-option=~~color~~> ==> <select class=dna-nucleotide + data-dnaRules={ val: true } + data-dnaField=color> const props: DnaProps = []; const attrs: DnaAttrs = []; const names: string[] = []; const compileProp = (key: string, value: string) => { names.push(key); key = key.replace(/^data-prop-/, '').toLowerCase(); value = value.replace(dna.compile.regex.dnaBasePairs, ''); props.push(key, value); if (key === 'checked' && elem.is('input')) elem.addClass('dna-update-model').data().dnaField = value; }; const compileAttr = (key: string, value: string) => { const parts = <DnaAttrParts>value.split(dna.compile.regex.dnaBasePair); if (parts[1] === '[count]') parts[1] = 1; else if (parts[1] === '[value]') parts[1] = 2; attrs.push(key.replace(/^data-attr-/, ''), parts); names.push(key); const makeUpdatable = () => { dna.compile.setupNucleotide(elem).addClass('dna-update-model'); elem.data().dnaField = parts[1]; elem.data().dnaRules.val = true; }; const hasTextVal = elem.is('input:not(:checkbox, :radio)') && key === 'value' && parts[0] === '' && parts[2] === ''; if (hasTextVal || elem.is('select') && key === 'data-option') makeUpdatable(); }; const compile = (attr: Attr) => { if (/^data-prop-/.test(attr.name)) compileProp(attr.name, attr.value); else if (attr.value.split(dna.compile.regex.dnaBasePair).length === 3) compileAttr(attr.name, attr.value); }; dna.ui.getAttrs(elem).forEach(compile); const getRules = (): DnaRules => dna.compile.setupNucleotide(elem).data().dnaRules; if (props.length > 0) getRules().props = props; if (attrs.length > 0) getRules().attrs = attrs; if (elem.data().formatCurrency) getRules().formatter = dnaFormat.getCurrencyFormatter(elem.data().formatCurrency); if (elem.data().formatCurrency100) getRules().formatter = dnaFormat.getCurrencyFormatter(elem.data().formatCurrency100, 100); if (elem.data().formatCurrency1000) getRules().formatter = dnaFormat.getCurrencyFormatter(elem.data().formatCurrency100, 1000); if (elem.data().formatDate) getRules().formatter = dnaFormat.getDateFormatter(elem.data().formatDate); if (elem.data().formatNumber) getRules().formatter = dnaFormat.getNumberFormatter(elem.data().formatNumber); if (elem.data().formatPercent) getRules().formatter = dnaFormat.getPercentFormatter(elem.data().formatPercent); if (elem.data().format) getRules().formatter = dnaFormat.getFormatter(elem.data().format); if (elem.data().transform) //TODO: Determine if it's better to process only at top-level of clone getRules().transform = elem.data().transform; //TODO: string to fn if (elem.data().callback) getRules().callback = elem.data().callback; dna.compile.addFieldClass(elem); elem.removeAttr(names.join(' ')); }, getDataField: (elem: JQuery, type: string): string => { // Example: // <p data-array=~~tags~~>, 'array' ==> 'tags' return elem.data(type).replace(dna.compile.regex.dnaBasePairs, '').trim(); }, subTemplateName: (holder: JQuery | string, arrayField: string, index: number): string => { //holder can be element or template name // Example: // subTemplateName('book', 'authors') ==> 'book-authors--2' const getRules = (): DnaRules => dna.getClone(<JQuery>holder, { main: true }).data().dnaRules; const templateName = holder instanceof $ ? getRules().template : holder; return templateName + '-' + arrayField + '--' + String(index); }, rules: (elems: JQuery, type: string, isLists?: boolean): JQuery => { // Example: // <p data-require=~~title~~>, 'require' ==> <p data-dnaRules={ require: 'title' }> const addRule = (elem: JQuery) => { dna.compile.setupNucleotide(elem); const field = dna.compile.getDataField(elem, type); const makeLists = () => field.split(';').map((list: string) => list.split(',')); elem.data().dnaRules[type] = isLists ? makeLists() : field; }; return elems.filter('[data-' + type + ']').forEach(addRule).removeAttr('data-' + type); }, separators: (elem: JQuery): JQuery => { // Convert: data-separator=", " ==> <span class=dna-separator>, </span> const isWhitespaceNode = (index: number, node: Node): boolean => node.nodeType === 3 && !/\S/.test(<string>node.nodeValue); const append = (templateElem: JQuery, text: string, className: string) => { const doAppend = () => { templateElem.contents().last().filter(isWhitespaceNode).remove(); templateElem.append($('<span>').addClass(className).html(text)); }; return text && doAppend(); }; const processTemplate = (elem: JQuery) => { append(elem, elem.data().separator, 'dna-separator'); append(elem, elem.data().lastSeparator, 'dna-last-separator'); }; const clones = elem.find('.dna-template, .dna-sub-clone').addBack(); clones.forEach(processTemplate); return clones; }, template: (name: string): DnaTemplate => { //prepare and stash template so it can be cloned const elem = $('#' + name); dna.core.assert(elem.length, 'Template not found', name); const saveName = (elem: JQuery) => elem.data().dnaRules = <DnaRules>{ template: elem.attr('id'), subs: [] }; const initSubs = (elem: JQuery) => elem.data().dnaRules.subs = []; elem.find('.dna-template').addBack().forEach(saveName).removeAttr('id').forEach(initSubs); const elems = elem.find('*').addBack(); elems.filter(dna.compile.isDnaField).forEach(dna.compile.field).addClass('dna-field'); dna.compile.rules(elems, 'array').addClass('dna-sub-clone').forEach(initSubs); dna.compile.rules(elems, 'class', true); dna.compile.rules(elems, 'require'); dna.compile.rules(elems, 'missing'); dna.compile.rules(elems, 'true'); dna.compile.rules(elems, 'false'); elems.forEach(dna.compile.propsAndAttrs); dna.compile.separators(elem); //support html5 values for "type" attribute const setTypeAttr = (inputElem: JQuery) => inputElem.attr({ type: inputElem.data().attrType }); $('input[data-attr-type]').forEach(setTypeAttr); return dna.store.stash(elem); }, }; const dnaStore = { // Handles storage and retrieval of templates. getTemplateDb: (): DnaTemplateDb => { const store = $('body').data(); const initStore = () => store.dnaTemplateDb = {}; return store.dnaTemplateDb || initStore(); }, stash: (elem: JQuery): DnaTemplate => { const name = elem.data().dnaRules.template; const move = (elem: JQuery) => { const name = elem.data().dnaRules.template; const container = elem.parent(); const wrapped = container.children().length === 1 && !container.hasClass('dna-container'); const compileSiblings = () => { container.data().dnaContents = true; const templateName = (node: HTMLElement): boolean => { const elem = $(node); const compileToName = (id?: string) => id ? dna.compile.template(id).name : name; return elem.hasClass('dna-template') ? compileToName(elem.attr('id')) : elem.hasClass('dna-sub-clone') ? elem.data().dnaRules.template : false; }; container.data().dnaContents = container.children().toArray().map(templateName); }; if (!wrapped && !container.data().dnaContents) compileSiblings(); const template = <DnaTemplate>{ name: name, elem: elem, container: container.addClass('dna-container').addClass('dna-contains-' + name), nested: container.closest('.dna-clone').length !== 0, separators: elem.find('.dna-separator, .dna-last-separator').length, wrapped: wrapped }; dna.store.getTemplateDb()[name] = template; elem.removeClass('dna-template').addClass('dna-clone').addClass(name).detach(); }; const prepLoop = (elem: JQuery) => { // Pre (sub-template array loops -- data-array): // class=dna-sub-clone data().dnaRules.array='field' // Post (elem): // data().dnaRules.template='{NAME}-{FIELD}--{INDEX}' // Post (container) // class=dna-nucleotide + // data().dnaRules.loop={ name: '{NAME}-{FIELD}--{INDEX}', field: 'field' } const rules = elem.data().dnaRules; const parent = dna.compile.setupNucleotide(elem.parent()).addClass('dna-array'); const containerRules = parent.closest('.dna-clone, .dna-sub-clone').data().dnaRules; rules.template = dna.compile.subTemplateName(name, rules.array, containerRules.subs.length); parent.data().dnaRules.loop = { name: rules.template, field: rules.array }; containerRules.subs.push(rules.array); }; elem.find('.dna-template').addBack().forEach(move); elem.find('.dna-sub-clone').forEach(prepLoop).forEach(move); return <DnaTemplate>dna.store.getTemplateDb()[name]; }, getTemplate: (name: string): DnaTemplate => { return dna.store.getTemplateDb()[name] || dna.compile.template(name); }, }; const dnaEvents = { getContextDb: (): DnaContext => { const store = $('body').data(); const initStore = () => store.dnaContextDb = {}; return store.dnaContextDb || initStore(); //storage to register callbacks when dna.js is module loaded without window scope (webpack) }, getInitializers: (): DnaInitializer[] => { const store = $('body').data(); const initStore = () => store.dnaInitializers = []; return store.dnaInitializers || initStore(); //example: [{ func: 'app.bar.setup', selector: '.progress-bar' }] }, runOnLoads: (): JQuery => { // Example: // <p data-on-load=app.cart.setup> const elems = $('[data-on-load]').not('.dna-loaded'); const run = (elem: JQuery) => dna.util.apply(elem.data().onLoad, elem); return elems.forEach(run).addClass('dna-loaded'); }, runInitializers: (root: JQuery): JQuery => { // Executes the data-callback functions plus registered initializers. const init = (initializer: DnaInitializer) => { const find = (selector: string): JQuery => root.find(selector).addBack(selector); const elems = initializer.selector ? find(initializer.selector) : root; const params = [elems.addClass('dna-initialized'), ...dna.array.wrap(initializer.params)]; dna.util.apply(initializer.fn, params); }; dna.events.getInitializers().forEach(init); return root; }, setup: (): JQuery => { const runner = (elem: JQuery, type: string, event: JQuery.EventBase) => { // Finds elements for the given event type and executes the callback passing in the // element, event, and component (container element with "data-component" attribute). // Types: click|change|input|key-up|key-down|key-press|enter-key const target = elem.closest('[data-' + type + ']'); const fn = target.data(type); const isLink = target[0] && target[0].nodeName === 'A'; if (type === 'click' && isLink && fn && fn.match(/^dna[.]/)) event.preventDefault(); const nextClickTarget = target.parent().closest('[data-click]'); if (type === 'click' && nextClickTarget.length) runner(nextClickTarget, type, event); return dna.util.apply(fn, [target, event]); }; const handleEvent = (event: JQuery.EventBase) => { const target = $(event.target); const updateField = (elem: JQuery, calc: DnaCallback) => dna.util.assign(<DnaDataObject>dna.getModel(elem), elem.data().dnaField, <Json>calc(elem)); const getValue = (elem: JQuery) => elem.val(); const isChecked = (elem: JQuery): boolean => elem.is(':checked'); const updateOption = (elem: JQuery) => updateField(elem, <DnaCallback>isChecked); const updateModel = () => { const mainClone = dna.getClone(target, { main: true }); if (mainClone.length === 0) { //TODO: figure out why some events are captured on the template instead of the clone //console.log('Error -- event not on clone:', event.timeStamp, event.type, target); return; } if (target.is('input:checkbox')) updateField(target, <DnaCallback>isChecked); else if (target.is('input:radio')) $('input:radio[name=' + target.attr('name') + ']').forEach(updateOption); else if (target.data().dnaRules.val) updateField(target, <DnaCallback>getValue); dna.refresh(mainClone); }; if (target.hasClass('dna-update-model')) updateModel(); return runner(target, event.type.replace('key', 'key-'), event); }; const handleEnterKey = (event: JQuery.EventBase) => { return event.key === 'Enter' && runner($(event.target), 'enter-key', event); }; const handleSmartUpdate = (event: JQuery.EventBase) => { const defaultThrottle = 1000; //default 1 second delay between callbacks const elem = $(event.target); const data = elem.data(); const doCallback = () => { data.dnaLastUpdated = Date.now(); data.dnaLastValue = elem.val(); data.dnaTimeoutId = null; runner(elem, 'smart-update', event); }; const handleChange = () => { const throttle = data.smartThrottle ? +data.smartThrottle : defaultThrottle; if (Date.now() < data.dnaLastUpdated + throttle) data.dnaTimeoutId = window.setTimeout(doCallback, throttle); else doCallback(); }; const checkForValueChange = () => { if (elem.val() !== data.dnaLastValue && !data.dnaTimeoutId) handleChange(); }; const processSmartUpdate = () => { if (event.type === 'keydown' && data.dnaLastValue === undefined) data.dnaLastValue = elem.val(); window.setTimeout(checkForValueChange); //requeue so elem.val() is ready on paste event }; if (data.smartUpdate) processSmartUpdate(); }; const jumpToUrl = (event: JQuery.EventBase) => { // Usage: // <button data-href=https://dnajs.org>dna.js</button> // If element (or parent) has the class "external-site", page will be opened in a new tab. const elem = $(event.target).closest('[data-href]'); const iOS = /iPad|iPhone|iPod/.test(window.navigator.userAgent) && /Apple/.test(window.navigator.vendor); const target = elem.closest('.external-site').length ? '_blank' : '_self'; window.open(elem.data().href, iOS ? '_self' : elem.data().target || target); }; const makeEventHandler = (type: string) => (event: JQuery.EventBase) => runner($(event.target), type, event); const events = { click: handleEvent, change: handleEvent, keydown: handleEvent, keypress: handleEvent, keyup: handleEvent, input: handleEvent }; const smartUpdateEvents = { keydown: handleSmartUpdate, keyup: handleSmartUpdate, change: handleSmartUpdate, cut: handleSmartUpdate, paste: handleSmartUpdate }; $(window.document) .on(events) .on(smartUpdateEvents) .on({ keyup: handleEnterKey }) .on({ click: jumpToUrl }, '[data-href]') .on({ focusin: makeEventHandler('focus-in') }, '[data-focus-in]') .on({ focusout: makeEventHandler('focus-out') }, '[data-focus-out]') .on({ mouseenter: makeEventHandler('hover-in') }, '[data-hover-in]') .on({ mouseleave: makeEventHandler('hover-out') }, '[data-hover-out]'); return dna.events.runOnLoads(); }, }; const dnaCore = { inject: <T>(clone: JQuery, data: T, count: number, settings: DnaOptionsClone<T>): JQuery => { // Inserts data into a clone and executes its rules. const injectField = (elem: JQuery, field: string, dnaRules: DnaRules) => { //example: <h2>~~title~~</h2> const value = field === '[count]' ? count : field === '[value]' ? data : dna.util.value(data, field); const formatted = () => dnaRules.formatter ? dnaRules.formatter(<DnaFormatterValue>value, data) : String(value); if (['string', 'number', 'boolean'].includes(typeof value)) elem = settings.html ? elem.html(formatted()) : elem.text(formatted()); }; const injectValue = (elem: JQuery, field: string) => { const value = field === '[count]' ? count : field === '[value]' ? data : dna.util.value(data, field); if (value !== null && value !== elem.val()) elem.val(String(value)); }; const injectProps = (elem: JQuery, props: DnaProps) => { //example props: ['selected', 'set'] for (let prop = 0; prop < props.length/2; prop++) //each prop has a key and a field name elem.prop(props[prop*2]!, dna.util.realTruth(dna.util.value(data, props[prop*2 + 1]!))); }; const injectAttrs = (elem: JQuery, dnaRules: DnaRules) => { const attrs = dnaRules.attrs!; //example attrs: ['data-tag', ['', 'tag', '']] const inject = (key: DnaAttrName, parts: DnaAttrParts) => { //example parts: 'J~~code.num~~' ==> ['J', 'code.num', ''] const field = parts[1]; const core = field === 1 ? count : field === 2 ? data : dna.util.value(data, field); const value = [parts[0], core, parts[2]].join(''); const formatted = dnaRules.formatter ? dnaRules.formatter(<DnaFormatterValue>value, data) : value; elem.attr(key, formatted); if (/^data-./.test(key)) elem.data(key.substring(5), formatted); if (key === 'value' && value !== elem.val()) //set elem val for input fields (example: <input value=~~tag~~>) elem.val(value); }; for (let i = 0; i < attrs.length / 2; i++) //each attr has a key and parts inject(<DnaAttrName>attrs[i*2], <DnaAttrParts>attrs[i*2 + 1]); }; const injectClass = (elem: JQuery, classLists: string[][]) => { // classLists = [['field', 'class-true', 'class-false'], ...] const process = (classList: string[]) => { const value = dna.util.value(data, <string>classList[0]); const truth = dna.util.realTruth(value); const setBooleanClasses = () => { elem.toggleClass(<string>classList[1], truth); if (classList[2]) elem.toggleClass(classList[2], !truth); }; if (classList.length === 1) elem.addClass(String(value)); else if (classList.length > 1) setBooleanClasses(); }; classLists.forEach(process); }; const fieldExists = (fieldName: string): boolean => { const value = dna.util.value(data, fieldName); return value !== undefined && value !== null; }; const processLoop = (elem: JQuery, loop: DnaLoop) => { const dataArray = <T[]>dna.util.value(data, loop.field); const subClones = elem.children('.' + loop.name.replace(/[.]/g, '\\.')); const injectSubClone = (elem: JQuery, index: number) => { if (!elem.is('option')) //prevent select from closing on chrome dna.core.inject(elem, dataArray[index]!, index + 1, settings); }; const rebuildSubClones = () => { subClones.remove(); dna.clone(loop.name, dataArray, { container: elem, html: !!settings.html }); }; if (!dataArray) (data[loop.field]) = []; else if (dataArray.length === subClones.length) subClones.forEach(injectSubClone); else rebuildSubClones(); }; const process = (elem: JQuery) => { const dnaRules = <DnaRules>elem.data().dnaRules; if (dnaRules.transform) //alternate version of the "transform" option dna.util.apply(dnaRules.transform, data); if (dnaRules.loop) processLoop(elem, dnaRules.loop); if (dnaRules.text) injectField(elem, elem.data().dnaField, dnaRules); if (dnaRules.val) injectValue(elem, elem.data().dnaField); if (dnaRules.props) injectProps(elem, dnaRules.props); if (dnaRules.attrs) injectAttrs(elem, dnaRules); if (dnaRules.class) injectClass(elem, dnaRules.class); if (dnaRules.require) elem.toggle(fieldExists(dnaRules.require)); if (dnaRules.missing) elem.toggle(!fieldExists(dnaRules.missing)); if (dnaRules.true) elem.toggle(dna.util.realTruth(dna.util.value(data, dnaRules.true))); if (dnaRules.false) elem.toggle(!dna.util.realTruth(dna.util.value(data, dnaRules.false))); if (dnaRules.callback) dna.util.apply(dnaRules.callback, elem); }; const dig = (elems: JQuery) => { elems.filter('.dna-nucleotide').forEach(process); if (elems.length) dig(elems.children().not('.dna-sub-clone')); }; if (settings.transform) //alternate version of data-transform settings.transform(data); dig(clone); clone.data().dnaModel = data; clone.data().dnaCount = count; return clone; }, replicate: <T>(template: DnaTemplate, data: T, settings: DnaOptionsClone<T>): JQuery => { // Creates and sets up a clone. const displaySeparators = () => { const clones = container.children('.' + template.name); clones.find('.dna-separator').show().end().last().find('.dna-separator').hide(); clones.find('.dna-last-separator').hide().end().eq(-2).find('.dna-last-separator').show() .closest('.dna-clone').find('.dna-separator').hide(); }; const selector = '.dna-contains-' + template.name.replace(/[.]/g, '\\.'); const container = settings.container ? settings.container.find(selector).addBack(selector) : template.container; const clone = template.elem.clone(true, true); const name = clone.data().dnaRules.template; if (!container.data().dnaCountsMap) container.data().dnaCountsMap = {}; const countsMap = container.data().dnaCountsMap; countsMap[name] = (countsMap[name] || 0) + 1; dna.core.inject(clone, data, countsMap[name], settings); const intoUnwrapped = () => { const firstClone = () => { const contents = container.data().dnaContents; const i = contents.indexOf(template.name); const adjustment = (clonesAbove: number, name: string) => clonesAbove + (name && contents.indexOf(name) < i ? allClones.filter('.' + name).length - 1 : 0); const target = container.children().eq(i + contents.reduce(adjustment, 0)); if (target.length) target.before(clone); else container.append(clone); }; const allClones = container.children('.dna-clone'); const sameClones = allClones.filter('.' + template.name); if (!sameClones.length) firstClone(); else if (settings.top) sameClones.first().before(clone); else sameClones.last().after(clone); }; if (!template.wrapped) intoUnwrapped(); else if (settings.top) container.prepend(clone); else container.append(clone); if (template.separators) displaySeparators(); dna.events.runInitializers(clone); if (settings.callback) settings.callback(clone, data); if (settings.fade) dna.ui.slideFadeIn(clone); return clone; }, getArrayName: (subClone: JQuery): string | null => { return subClone.hasClass('dna-sub-clone') ? subClone.data().dnaRules.array : null; }, updateModelArray: (container: JQuery): JQuery => { // Sets the array field of the clone's data model to the list of sub-clone data models. dna.core.assert(container.hasClass('dna-array'), 'Invalid array container', container.attr('class')); const array = container.data().dnaRules.loop; const subs = container.children('.' + array.name); const model = <DnaDataObject>dna.getModel(container); const nodeToModel = (node: HTMLElement) => dna.getModel($(node)); model[array.field] = <Json[]>subs.toArray().map(nodeToModel); return container; }, remove: <T>(clone: JQuery, callback?: DnaCallbackFn<T> | null): JQuery => { const container = clone.parent(); clone.detach(); if (clone.hasClass('dna-sub-clone')) dna.core.updateModelArray(container); dna.placeholder.setup(); clone.remove(); if (callback) callback(clone, <T>dna.getModel(clone)); return clone; }, assert: (ok: boolean | unknown, message: string, info: unknown): void => { // Oops, file a tps report. try { if (!ok) throw Error('dna.js ~~ ' + message + ' [' + String(info) + ']'); } catch (e) { console.error((<Error>e).stack); throw Error((<Error>e).message); } }, plugin: (): void => { $.fn.forEach = function(fn: DnaForEachCallback): JQuery { // Usage: // const addRandomNumber = (elem) => elem.text(Math.random()); // elems.forEach(addRandomNumber).fadeIn(); const elems = <JQuery><unknown>this; return elems.each((index, node) => fn($(node), index)); }; $.fn.dna = function(action: DnaPluginAction, ...params: unknown[]) { //any additional parameters are passed to the api call // Example: // dna.getClone(elem).dna('up'); // Supported actions: // 'bye', 'clone-sub', 'destroy', 'down', 'refresh', 'up' const elems = <JQuery><unknown>this; const dnaApi = dna[dna.util.toCamel(action)]; dna.core.assert(dnaApi, 'Unknown plugin action', action); const callApi = (elem: JQuery) => dnaApi(elem, ...params); return elems.forEach(callApi); }; }, setup: (): unknown => { const setupBrowser = () => { dna.core.plugin(); $(dna.placeholder.setup); $(dna.panels.setup); $(dna.events.setup); }; if (typeof window === 'object' && typeof $ === 'function') setupBrowser(); return dna; }, }; const dna = { version: '~~~version~~~', // API: // dna.clone() // dna.arrayPush() // dna.createTemplate() // dna.templateExists() // dna.getModel() // dna.empty() // dna.insert() // dna.refresh() // dna.refreshAll() // dna.updateField() // dna.recount() // dna.destroy() // dna.getClone() // dna.getClones() // dna.getIndex() // dna.up() // dna.down() // dna.bye() // dna.registerInitializer() // dna.registerContext() // dna.info() // See: https://dnajs.org/docs/#api clone<T>(name: string, data: T | T[], options?: DnaOptionsClone<T>): JQuery { // Generates a copy of the template and populates the fields, attributes, and // classes from the supplied data. const defaults = { fade: false, top: false, container: null, empty: false, clones: 1, html: false, transform: null, callback: null }; const settings = { ...defaults, ...options }; const template = dna.store.getTemplate(name); const missing = template.nested && !settings.container; dna.core.assert(!missing, 'Container missing for nested template', name); if (settings.empty) dna.empty(name); const list = [].concat(...Array(settings.clones).fill(data)); let clones = $(); const addClone = (model: T) => clones = clones.add(dna.core.replicate(template, model, settings)); list.forEach(addClone); dna.placeholder.setup(); dna.panels.initialize(clones.first().closest('.dna-panels')); clones.first().parents('.dna-hide').removeClass('dna-hide').addClass('dna-unhide'); return clones; }, arrayPush<T>(holderClone: JQuery, arrayField: string, data: T | T[], options?: DnaOptionsArrayPush): JQuery { // Clones a sub-template to append onto an array loop. const cloneSub = (field: string, index: number) => { const clone = () => { const name = dna.compile.subTemplateName(holderClone, arrayField, index); const selector = '.dna-contains-' + name; const settings = { container: holderClone.find(selector).addBack(selector) }; dna.clone(name, data, { ...settings, ...options }); dna.core.updateModelArray(settings.container); }; if (field === arrayField) clone(); }; holderClone.data().dnaRules.subs.forEach(cloneSub); return holderClone; }, cloneSub<T>(holderClone: JQuery, arrayField: string, data: T | T[], options?: DnaOptionsArrayPush): JQuery { console.log('DEPRECATED: Function dna.cloneSub() has been renamed to dna.arrayPush().'); return dna.arrayPush(holderClone, arrayField, data, options); }, createTemplate(name: string, html: string, holder: JQuery): DnaTemplate { // Generates a template from an HTML string. $(html).attr({ id: name }).addClass('dna-template').appendTo(holder); return dna.store.getTemplate(name); }, templateExists(name: string): boolean { return !!dna.store.getTemplateDb()[name] || $('.dna-template#' + name).length > 0; }, getModel<T>(elemOrName: JQuery | string, options?: DnaOptionsGetModel): T | T[] | undefined { // Returns the underlying data of the clone. const getOne = (elem: JQuery) => dna.getClone($(elem), options).data('dnaModel'); const getAll = (name: string) => dna.getClones(name).toArray().map(node => getOne($(node))); return typeof elemOrName === 'string' ? getAll(elemOrName) : getOne(elemOrName); }, empty(name: string, options?: DnaOptionsEmpty): JQuery { // Deletes all clones generated from the template. const defaults = { fade: false, callback: null }; const settings = { ...defaults, ...options }; const template = dna.store.getTemplate(name); const clones = template.container.children('.dna-clone'); if (template.container.data().dnaCountsMap) template.container.data().dnaCountsMap[name] = 0; const fadeDelete = () => dna.ui.slideFadeDelete(clones, settings.callback); return settings.fade ? fadeDelete() : dna.core.remove(clones, settings.callback); }, insert<T>(name: string, data: T, options?: DnaOptionsInsert<T>): JQuery { // Updates the first clone if it already exists otherwise creates the first clone. const clone = dna.getClones(name).first(); return clone.length ? dna.refresh(clone, { data: data, html: !!options?.html }) : dna.clone(name, data, options); }, refresh(clone: JQuery, options?: DnaOptionsRefresh): JQuery { // Updates an existing clone to reflect changes to the data model. const defaults = { html: false }; const settings = { ...defaults, ...options }; const elem = dna.getClone(clone, options); const data = settings.data ? settings.data : dna.getModel(elem); return dna.core.inject(elem, data, elem.data().dnaCount, settings); }, refreshAll(name: string, options?: DnaOptionsRefreshAll): JQuery { // Updates all the clones of the specified template. const clones = dna.getClones(name); const refresh = (node: HTMLElement) => { dna.refresh($(node), options); }; clones.toArray().forEach(refresh); return clones; }, updateField(inputElem: JQuery, value: Json): JQuery { const field = inputElem.data() && inputElem.data().dnaField; const update = () => { if (inputElem.is('input:checkbox')) inputElem.prop('checked', !!value); else if (inputElem.is('input:radio')) inputElem.prop('checked', !!value); //TOOD: if true, deselect other buttons in model else if (inputElem.is('input, select, textarea')) inputElem.val(String(value)); const model = <DnaDataObject>dna.getModel(inputElem); model[field] = value; }; if (field) update(); return inputElem; }, recount(clone: JQuery, options?: DnaOptionsRecount): JQuery { // Renumbers the counters starting from 1 for the clone and its siblings based on DOM order. clone = dna.getClone(clone); const renumber = () => { const name = clone.data().dnaRules.template; const update = (elem: JQuery, index: number) => { elem.data().dnaCount = index + 1; dna.refresh(elem, options); }; const container = clone.parent(); const clones = container.children('.dna-clone.' + name).forEach(update); container.data().dnaCountsMap = container.data().dnaCountsMap || {}; container.data().dnaCountsMap[name] = clones.length; }; if (clone.length) renumber(); return clone; }, destroy<T>(clone: JQuery, options?: DnaOptionsDestroy<T>): JQuery { // Removes an existing clone from the DOM. const defaults = { main: false, fade: false, callback: null }; const settings = { ...defaults, ...options }; clone = dna.getClone(clone, options); const arrayField = dna.core.getArrayName(clone); if (arrayField) (<DnaModel>dna.getModel(clone.parent()))[arrayField].splice(dna.getIndex(clone), 1); const fadeDelete = () => dna.ui.slideFadeDelete(clone, settings.callback); return settings.fade ? fadeDelete() : dna.core.remove(clone, settings.callback); }, getClone(elem: JQuery, options?: DnaOptionsGetClone): JQuery { // Returns the clone (or sub-clone) for the specified element. const defaults = { main: false }; const settings = { ...defaults, ...options }; const selector = settings.main ? '.dna-clone:not(.dna-sub-clone)' : '.dna-clone'; return elem instanceof $ ? elem.closest(selector) : $(); }, getClones(name: string): JQuery { // Returns an array of all the existing clones for the given template. return dna.store.getTemplate(name).container.children('.dna-clone.' + name); }, getIndex(elem: JQuery, options?: DnaOptionsGetIndex): number { // Returns the index of the clone. const clone = dna.getClone(elem, options); return clone.parent().children('.dna-clone.' + clone.data().dnaRules.template).index(clone); }, up<T>(elemOrEventOrIndex: DnaElemEventIndex, callback?: DnaCallbackFn<T>): JQuery { // Smoothly moves a clone up one slot effectively swapping its position with the previous // clone. const elem = dna.ui.toElem(elemOrEventOrIndex, this); return dna.ui.smoothMoveUp(dna.getClone(elem), callback); }, down<T>(elemOrEventOrIndex: DnaElemEventIndex, callback?: DnaCallbackFn<T>): JQuery { // Smoothly moves a clone down one slot effectively swapping its position with the next // clone. const elem = dna.ui.toElem(elemOrEventOrIndex, this); return dna.ui.smoothMoveDown(dna.getClone(elem), callback); }, bye<T>(elemOrEventOrIndex: DnaElemEventIndex, callback?: DnaCallbackFn<T>): JQuery { // Performs a sliding fade out effect on the clone and then removes the element. const elem = dna.ui.toElem(elemOrEventOrIndex, this); const fn = typeof callback === 'function' ? callback : null; return dna.destroy(elem, { fade: true, callback: fn }); }, registerInitializer(fn: DnaFunctionName | DnaInitializerFn, options?: DnaOptionsRegisterInitializer): DnaInitializer[] { // Adds a callback function to the list of initializers that are run on all DOM elements. const defaults = { selector: null, params: null, onDocLoad: true }; const settings = { ...defaults, ...options }; const rootSelector = settings.selector; const onDocLoadElems = () => !rootSelector ? $(window.document) : $(rootSelector).not('.dna-template').not(rootSelector).addClass('dna-initialized'); if (settings.onDocLoad) dna.util.apply(fn, [onDocLoadElems(), ...dna.array.wrap(settings.params)]); const initializer = { fn: fn, selector: rootSelector, params: settings.params }; dna.events.getInitializers().push(initializer); return dna.events.getInitializers(); }, clearInitializers(): DnaInitializer[] { // Deletes all initializers. return dna.events.getInitializers().splice(0); }, registerContext(contextName: string, contextObjOrFn: { [name: string]: unknown } | DnaCallback): DnaContext { // Registers an application object or individual function to enable it to be used for event // callbacks. Registration is needed when global namespace is not available to dna.js, such // as when using webpack to load dna.js as a module. dna.events.getContextDb()[contextName] = contextObjOrFn; return dna.events.getContextDb(); }, initGlobal(thisWindow: Window & typeof globalThis, thisJQuery: JQueryStatic): unknown { const jQuery$ = String('$'); thisWindow[jQuery$] = thisJQuery; thisWindow['dna'] = dna; const writable = (prop: string): boolean => !globalThis[prop] || !!Object.getOwnPropertyDescriptor(globalThis, prop)?.writable; if (writable('window')) globalThis.window = thisWindow; if (writable('document')) globalThis.document = thisWindow.document; if (writable(jQuery$)) globalThis[jQuery$] = thisJQuery; if (writable('dna')) globalThis['dna'] = dna; return dna.core.setup(); }, info(): DnaInfo { // Returns status information about templates on the current web page. const names = Object.keys(dna.store.getTemplateDb()); const panels = $('.dna-menu.dna-panels-initialized'); return { version: dna.version, templates: names.length, clones: $('.dna-clone:not(.dna-sub-clone)').length, subs: $('.dna-sub-clone').length, names: names, store: dna.store.getTemplateDb(), initializers: dna.events.getInitializers(), panels: panels.toArray().map(elem => <string>$(elem).attr('data-nav')), }; }, array: dnaArray, browser: dnaBrowser, pageToken: dnaPageToken, ui: dnaUi, util: dnaUtil, format: dnaFormat, placeholder: dnaPlaceholder, panels: dnaPanels, compile: dnaCompile, store: dnaStore, events: dnaEvents, core: dnaCore, }; dna.core.setup(); export { dna };
the_stack
// clang-format off import {AccountStorageOptInStateChangedListener, CredentialsChangedListener, PasswordCheckInteraction, PasswordCheckReferrer, PasswordCheckStatusChangedListener, PasswordExceptionListChangedListener, PasswordManagerProxy, PasswordsFileExportProgressListener, SavedPasswordListChangedListener} from 'chrome://settings/settings.js'; import {assertEquals} from 'chrome://webui-test/chai_assert.js'; import {TestBrowserProxy} from 'chrome://webui-test/test_browser_proxy.js'; import {makePasswordCheckStatus} from './passwords_and_autofill_fake_data.js'; // clang-format on export class PasswordManagerExpectations { requested: { passwords: number, exceptions: number, plaintextPassword: number, accountStorageOptInState: number, }; removed: { passwords: number, exceptions: number, }; listening: { passwords: number, exceptions: number, accountStorageOptInState: number, }; constructor() { this.requested = { passwords: 0, exceptions: 0, plaintextPassword: 0, accountStorageOptInState: 0, }; this.removed = { passwords: 0, exceptions: 0, }; this.listening = { passwords: 0, exceptions: 0, accountStorageOptInState: 0, }; } } /** * Test implementation */ export class TestPasswordManagerProxy extends TestBrowserProxy implements PasswordManagerProxy { private actual_: PasswordManagerExpectations; data: { passwords: chrome.passwordsPrivate.PasswordUiEntry[], exceptions: chrome.passwordsPrivate.ExceptionEntry[], leakedCredentials: chrome.passwordsPrivate.InsecureCredential[], weakCredentials: chrome.passwordsPrivate.InsecureCredential[], checkStatus: chrome.passwordsPrivate.PasswordCheckStatus, }; lastCallback: { addPasswordCheckStatusListener: PasswordCheckStatusChangedListener|null, addSavedPasswordListChangedListener: SavedPasswordListChangedListener|null, addExceptionListChangedListener: PasswordExceptionListChangedListener|null, addCompromisedCredentialsListener: CredentialsChangedListener|null, addWeakCredentialsListener: CredentialsChangedListener|null, addAccountStorageOptInStateListener: AccountStorageOptInStateChangedListener|null, addPasswordsFileExportProgressListener: PasswordsFileExportProgressListener| null, }; private plaintextPassword_: string = ''; private isOptedInForAccountStorage_: boolean = false; private isAccountStoreDefault_: boolean = false; private getUrlCollectionResponse_: chrome.passwordsPrivate.UrlCollection| null = null; constructor() { super([ 'requestPlaintextPassword', 'startBulkPasswordCheck', 'stopBulkPasswordCheck', 'getCompromisedCredentials', 'getWeakCredentials', 'getPasswordCheckStatus', 'getPlaintextInsecurePassword', 'changeInsecureCredential', 'removeInsecureCredential', 'recordPasswordCheckInteraction', 'recordPasswordCheckReferrer', 'isOptedInForAccountStorage', 'removeSavedPassword', 'removeSavedPasswords', 'movePasswordsToAccount', 'removeException', 'removeExceptions', 'changeSavedPassword', 'isAccountStoreDefault', 'getUrlCollection', 'addPassword', ]); /** @private {!PasswordManagerExpectations} */ this.actual_ = new PasswordManagerExpectations(); // Set these to have non-empty data. this.data = { passwords: [], exceptions: [], leakedCredentials: [], weakCredentials: [], checkStatus: makePasswordCheckStatus(), }; // Holds the last callbacks so they can be called when needed/ this.lastCallback = { addPasswordCheckStatusListener: null, addSavedPasswordListChangedListener: null, addExceptionListChangedListener: null, addCompromisedCredentialsListener: null, addWeakCredentialsListener: null, addAccountStorageOptInStateListener: null, addPasswordsFileExportProgressListener: null, }; } addSavedPasswordListChangedListener(listener: SavedPasswordListChangedListener) { this.actual_.listening.passwords++; this.lastCallback.addSavedPasswordListChangedListener = listener; } removeSavedPasswordListChangedListener(_listener: SavedPasswordListChangedListener) { this.actual_.listening.passwords--; } getSavedPasswordList(callback: SavedPasswordListChangedListener) { this.actual_.requested.passwords++; callback(this.data.passwords); } recordPasswordsPageAccessInSettings() {} removeSavedPassword(id: number) { this.actual_.removed.passwords++; this.methodCalled('removeSavedPassword', id); } movePasswordsToAccount(ids: Array<number>) { this.methodCalled('movePasswordsToAccount', ids); } removeSavedPasswords(ids: Array<number>) { this.actual_.removed.passwords += ids.length; this.methodCalled('removeSavedPasswords', ids); } addExceptionListChangedListener(listener: PasswordExceptionListChangedListener) { this.actual_.listening.exceptions++; this.lastCallback.addExceptionListChangedListener = listener; } removeExceptionListChangedListener(_listener: PasswordExceptionListChangedListener) { this.actual_.listening.exceptions--; } getExceptionList(callback: PasswordExceptionListChangedListener) { this.actual_.requested.exceptions++; callback(this.data.exceptions); } removeException(id: number) { this.actual_.removed.exceptions++; this.methodCalled('removeException', id); } removeExceptions(ids: Array<number>) { this.actual_.removed.exceptions += ids.length; this.methodCalled('removeExceptions', ids); } requestPlaintextPassword( id: number, reason: chrome.passwordsPrivate.PlaintextReason) { this.methodCalled('requestPlaintextPassword', {id, reason}); if (!this.plaintextPassword_) { return Promise.reject(new Error('Could not obtain plaintext password')); } return Promise.resolve(this.plaintextPassword_); } setPlaintextPassword(plaintextPassword: string) { this.plaintextPassword_ = plaintextPassword; } // Sets the return value of isOptedInForAccountStorage calls and notifies // the last added listener. setIsOptedInForAccountStorageAndNotify(optIn: boolean) { this.isOptedInForAccountStorage_ = optIn; if (this.lastCallback.addAccountStorageOptInStateListener) { this.lastCallback.addAccountStorageOptInStateListener( this.isOptedInForAccountStorage_); } } addAccountStorageOptInStateListener( listener: AccountStorageOptInStateChangedListener) { this.actual_.listening.accountStorageOptInState++; this.lastCallback.addAccountStorageOptInStateListener = listener; } removeAccountStorageOptInStateListener( _listener: AccountStorageOptInStateChangedListener) { this.actual_.listening.accountStorageOptInState--; } isOptedInForAccountStorage() { this.methodCalled('isOptedInForAccountStorage'); this.actual_.requested.accountStorageOptInState++; return Promise.resolve(this.isOptedInForAccountStorage_); } /** * Verifies expectations. */ assertExpectations(expected: PasswordManagerExpectations) { const actual = this.actual_; assertEquals(expected.requested.passwords, actual.requested.passwords); assertEquals(expected.requested.exceptions, actual.requested.exceptions); assertEquals( expected.requested.plaintextPassword, actual.requested.plaintextPassword); assertEquals( expected.requested.accountStorageOptInState, actual.requested.accountStorageOptInState); assertEquals(expected.removed.passwords, actual.removed.passwords); assertEquals(expected.removed.exceptions, actual.removed.exceptions); assertEquals(expected.listening.passwords, actual.listening.passwords); assertEquals(expected.listening.exceptions, actual.listening.exceptions); assertEquals( expected.listening.accountStorageOptInState, actual.listening.accountStorageOptInState); } startBulkPasswordCheck() { this.methodCalled('startBulkPasswordCheck'); if (this.data.checkStatus.state === chrome.passwordsPrivate.PasswordCheckState.NO_PASSWORDS) { return Promise.reject(new Error('error')); } return Promise.resolve(); } stopBulkPasswordCheck() { this.methodCalled('stopBulkPasswordCheck'); } getCompromisedCredentials() { this.methodCalled('getCompromisedCredentials'); return Promise.resolve(this.data.leakedCredentials); } getWeakCredentials() { this.methodCalled('getWeakCredentials'); return Promise.resolve(this.data.weakCredentials); } getPasswordCheckStatus() { this.methodCalled('getPasswordCheckStatus'); return Promise.resolve(this.data.checkStatus); } addCompromisedCredentialsListener(listener: CredentialsChangedListener) { this.lastCallback.addCompromisedCredentialsListener = listener; } removeCompromisedCredentialsListener(_listener: CredentialsChangedListener) {} addWeakCredentialsListener(listener: CredentialsChangedListener) { this.lastCallback.addWeakCredentialsListener = listener; } removeWeakCredentialsListener(_listener: CredentialsChangedListener) {} addPasswordCheckStatusListener(listener: PasswordCheckStatusChangedListener) { this.lastCallback.addPasswordCheckStatusListener = listener; } removePasswordCheckStatusListener(_listener: PasswordCheckStatusChangedListener) {} getPlaintextInsecurePassword( credential: chrome.passwordsPrivate.InsecureCredential, reason: chrome.passwordsPrivate.PlaintextReason) { this.methodCalled('getPlaintextInsecurePassword', {credential, reason}); if (!this.plaintextPassword_) { return Promise.reject(new Error('Could not obtain plaintext password')); } const newCredential = /** @type {chrome.passwordsPrivate.InsecureCredential} */ ( Object.assign({}, credential)); newCredential.password = this.plaintextPassword_; return Promise.resolve(newCredential); } changeInsecureCredential( credential: chrome.passwordsPrivate.InsecureCredential, newPassword: string) { this.methodCalled('changeInsecureCredential', {credential, newPassword}); return Promise.resolve(); } removeInsecureCredential(insecureCredential: chrome.passwordsPrivate.InsecureCredential) { this.methodCalled('removeInsecureCredential', insecureCredential); } recordPasswordCheckInteraction(interaction: PasswordCheckInteraction) { this.methodCalled('recordPasswordCheckInteraction', interaction); } recordPasswordCheckReferrer(referrer: PasswordCheckReferrer) { this.methodCalled('recordPasswordCheckReferrer', referrer); } changeSavedPassword( ids: Array<number>, newUsername: string, newPassword: string) { this.methodCalled('changeSavedPassword', {ids, newUsername, newPassword}); return Promise.resolve(); } /** * Sets the value to be returned by isAccountStoreDefault. */ setIsAccountStoreDefault(isDefault: boolean) { this.isAccountStoreDefault_ = isDefault; } isAccountStoreDefault() { this.methodCalled('isAccountStoreDefault'); return Promise.resolve(this.isAccountStoreDefault_); } /** * Sets the value to be returned by getUrlCollection. */ setGetUrlCollectionResponse(urlCollection: chrome.passwordsPrivate.UrlCollection) { this.getUrlCollectionResponse_ = urlCollection; } getUrlCollection(url: string) { this.methodCalled('getUrlCollection', url); return Promise.resolve(this.getUrlCollectionResponse_); } addPassword(options: chrome.passwordsPrivate.AddPasswordOptions) { this.methodCalled('addPassword', options); return Promise.resolve(); } addPasswordsFileExportProgressListener( listener: PasswordsFileExportProgressListener) { this.lastCallback.addPasswordsFileExportProgressListener = listener; } cancelExportPasswords() {} exportPasswords(_callback: () => void) {} importPasswords() {} optInForAccountStorage(_optIn: boolean) {} removePasswordsFileExportProgressListener( _listener: PasswordsFileExportProgressListener) {} requestExportProgressStatus( _callback: (status: chrome.passwordsPrivate.ExportProgressStatus) => void) {} undoRemoveSavedPasswordOrException() {} }
the_stack
import { Component, OnInit, AfterViewInit, AfterContentInit, ViewEncapsulation, ViewChild, ElementRef } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { JhiAlertService, JhiEventManager } from 'ng-jhipster'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { Gateway } from 'app/shared/model/gateway.model'; import { IMessage } from 'app/shared/model/messsage.model'; import { IBroker } from 'app/shared/model/broker.model'; import { GatewayService } from './../gateway'; import { BrokerService } from './../broker'; import { FormBuilder, FormArray, FormControl, FormGroup } from '@angular/forms'; import { Components } from '../../shared/camel/component-type'; import * as moment from 'moment'; import * as ace from 'ace-builds'; import 'brace'; import 'brace/mode/text'; import 'brace/mode/json'; import 'brace/theme/eclipse'; @Component({ selector: 'jhi-broker-message-sender', templateUrl: './broker-message-sender.component.html' }) export class BrokerMessageSenderComponent implements OnInit { @ViewChild('editor', { read: ElementRef, static: false }) editor: ElementRef; messages: IMessage[]; message: IMessage; brokers: IBroker[]; brokerType: string; endpointName: string; endpointType: string; headers: FormArray; jmsHeaders: FormArray; requestDestination: string; requestExchangePattern: string; requestNumberOfTimes: string; requestHeaders: string; requestBody: string; responseBody: string; requestEditorMode: string = 'text'; responseEditorMode: string = 'text'; alert: string; numberOfMessages: number; numberOfSuccesfulMessages; number; numberOfFailedMessages: number; sendingMessages: string; successfulMessages: string; failedMessages: string; active; disabled = true; isSending: boolean; isSuccessful: boolean = false; isFailed: boolean = false; isAlert = false; isSaving: boolean; finished = false; gateways: Gateway[]; createRoute: number; predicate: any; reverse: any; destinationPopoverMessage: string; exchangePatternPopoverMessage: string; numberOfTimesPopoverMessage: string; messageSenderForm: FormGroup; messageFromFile = false; serviceType: Array<string> = []; upload: any; fileName: string; subtitle: string; dateTime: string; modalRef: NgbModalRef | null; constructor( private eventManager: JhiEventManager, private gatewayService: GatewayService, private brokerService: BrokerService, private jhiAlertService: JhiAlertService, private formBuilder: FormBuilder, private route: ActivatedRoute, public components: Components, private element: ElementRef ) {} ngOnInit() { this.initializeForm(); this.load(); this.setBrokerType(); this.setPopoverMessages(); this.finished = true; } public ngAfterViewInit(): void { this.editor.nativeElement.focus(); const aceEditor = ace.edit(this.editor.nativeElement); aceEditor.focus(); aceEditor.moveCursorTo(1, 1); } load() { this.isSending = false; this.createRoute = 0; this.active = '0'; this.headers = this.messageSenderForm.get('headers') as FormArray; this.route.params.subscribe(params => { this.endpointType = params['endpointType']; this.endpointName = params['endpointName']; this.brokerType = params['brokerType']; this.messageSenderForm.controls.destination.setValue(this.endpointName); }); this.subtitle = 'Sending to ' + this.endpointType + ' ' + this.endpointName; this.messageSenderForm.controls.exchangepattern.setValue('FireAndForget'); } initializeForm() { this.messageSenderForm = this.formBuilder.group({ id: new FormControl(''), destination: new FormControl(''), exchangepattern: new FormControl('FireAndForget'), numberoftimes: new FormControl('1'), requestbody: new FormControl(''), headers: new FormArray([this.initializeHeader(null, null)]), jmsHeaders: new FormArray([this.initializeHeader(null, null)]) }); } initializeHeader(keyVal, valueVal): FormGroup { return this.formBuilder.group({ key: new FormControl(keyVal), value: new FormControl(valueVal) }); } initializeJmsHeader(keyVal, valueVal): FormGroup { return this.formBuilder.group({ key: new FormControl(keyVal), value: new FormControl(valueVal) }); } updateForm() { this.updateTemplateData(); } updateTemplateData() { this.messageSenderForm.patchValue({ name: '', destination: '', exchangePattern: '', numberoftimes: '', requestbody: '' }); } addHeader(headerType: string) { this.headers = this.messageSenderForm.get(headerType) as FormArray; this.headers.push(this.initializeHeader(null, null)); } removeHeader(headerType: string, index, force: boolean) { this.headers = this.messageSenderForm.get(headerType) as FormArray; if (index === 0 && !force) { this.headers .at(index) .get('key') .patchValue(''); this.headers .at(index) .get('value') .patchValue(''); } else { this.headers.removeAt(index); } } createHeader(): FormGroup { return this.initializeHeader(null, null); } setPopoverMessages() { this.destinationPopoverMessage = `Name of the queue or topic`; this.exchangePatternPopoverMessage = `Fire and Forget (Send only) or Request and Reply (Send and wait for response)`; this.numberOfTimesPopoverMessage = `Number of messages send (1 by default). This setting is only for FireAndForget pattern`; } cancel() { window.history.back(); } send(close: boolean) { if (!this.messageSenderForm.valid) { this.isSending = false; return; } this.isSending = true; this.isAlert = true; this.isSending = true; this.isFailed = false; this.isSuccessful = false; this.numberOfMessages = 1; this.numberOfSuccesfulMessages = 0; this.numberOfFailedMessages = 0; if (this.messages && this.messages.length > 1) { for (var i = 0; i < this.messages.length; i++) { this.numberOfMessages = this.messages.length; this.sendingMessages = i + 1 + ' of ' + this.numberOfMessages; this.setRequestFromArray(this.messages[i]); this.sendMessage(close); } } else { this.sendingMessages = '1 of ' + this.numberOfMessages; this.setRequestFromForm(); this.sendMessage(close); } } setRequestFromForm() { this.headers = this.messageSenderForm.get('headers') as FormArray; this.jmsHeaders = this.messageSenderForm.get('jmsHeaders') as FormArray; this.requestDestination = this.messageSenderForm.controls.destination.value; this.requestExchangePattern = this.messageSenderForm.controls.exchangepattern.value == null ? 'FireAndForget' : this.messageSenderForm.controls.exchangepattern.value; this.requestNumberOfTimes = this.messageSenderForm.controls.numberoftimes.value == null ? 1 : this.messageSenderForm.controls.numberoftimes.value; this.requestBody = this.messageSenderForm.controls.requestbody.value; if (!this.requestBody) { this.requestBody = ' '; } const headersJson = this.formArrayToJson(this.headers); const jmsHeadersJson = this.formArrayToJson(this.jmsHeaders); const allHeadersJson = { ...headersJson, ...jmsHeadersJson }; this.requestHeaders = JSON.stringify(allHeadersJson); } setRequestFromArray(message: IMessage) { let allHeadersJson = {}; if (this.messageFromFile) { this.headers = message.headers == null ? {} : message.headers; this.jmsHeaders = message.jmsHeaders == null ? {} : message.jmsHeaders; allHeadersJson = { ...this.headers, ...this.jmsHeaders }; } else { this.headers = this.messageSenderForm.get('headers') as FormArray; this.jmsHeaders = this.messageSenderForm.get('jmsHeaders') as FormArray; const headersJson = this.formArrayToJson(this.headers); const jmsHeadersJson = this.formArrayToJson(this.jmsHeaders); allHeadersJson = { ...headersJson, ...jmsHeadersJson }; } this.requestDestination = this.messageSenderForm.controls.destination.value; this.requestExchangePattern = this.messageSenderForm.controls.exchangepattern.value == null ? 'FireAndForget' : this.messageSenderForm.controls.exchangepattern.value; this.requestNumberOfTimes = this.messageSenderForm.controls.numberoftimes.value == null ? 1 : this.messageSenderForm.controls.numberoftimes.value; this.requestBody = message.body == null ? ' ' : message.body; this.requestHeaders = JSON.stringify(allHeadersJson); } sendMessage(close: boolean) { if (this.requestExchangePattern === 'FireAndForget') { this.brokerService.sendMessage(this.brokerType, this.requestDestination, this.requestHeaders, this.requestBody).subscribe( res => { this.handleSendResponse(res.body, false); if (close) { window.history.back(); } }, res => { this.handleSendError(res.error); } ); } else if (this.requestExchangePattern === 'RequestAndReply') { this.brokerService.sendMessage(this.brokerType, this.requestDestination, this.requestHeaders, this.requestBody).subscribe( res => { this.handleSendResponse(res.body, true); }, res => { this.handleSendError(res.error); } ); } } formArrayToJson(formArray: FormArray) { let json: any = {}; formArray.controls.forEach((element, index) => { const key = element.get('key').value; const value = element.get('value').value; if (key) { json[key] = value; } }); return json; } handleSendResponse(body: string, showResponse: boolean) { let now = moment(); this.dateTime = new Date().toLocaleString(); this.isSuccessful = true; this.numberOfSuccesfulMessages = this.numberOfSuccesfulMessages + 1; this.successfulMessages = ' | Messages: ' + this.numberOfSuccesfulMessages + ' of ' + this.numberOfMessages + ' | Last time: ' + this.dateTime; this.isSending = false; /* uncomment when using responses if (showResponse) { this.setEditorMode(body); //this.responseBody = body; //this.active = '2'; } else { //this.responseBody = body; }*/ } handleSendError(body: any) { this.dateTime = new Date().toLocaleString(); this.isSending = false; this.isFailed = true; this.numberOfFailedMessages = this.numberOfFailedMessages + 1; this.failedMessages = ' | Messages: ' + this.numberOfFailedMessages + ' of ' + this.numberOfMessages + ' | Last time: ' + this.dateTime + '| Error: ' + body; } setVersion() { let now = moment(); } setBrokerType() { if (!this.brokerType) { this.brokerService.getBrokers().subscribe( data => { if (data) { for (let i = 0; i < data.body.length; i++) { this.brokers.push(data.body[i]); } this.brokerType = this.brokers[0].type; if (this.brokerType == null) { console.log('Unknown broker: set brokertype to artemis'); this.brokerType = 'artemis'; } } }, error => console.log(error) ); } } //Get currrent scroll position findPos(obj) { var curtop = 0; if (obj.offsetParent) { do { curtop += obj.offsetTop; } while ((obj = obj.offsetParent)); return curtop; } } goBack() { window.history.back(); } setEditorMode(str: string) { if (str.startsWith('{') || str.startsWith('[')) { this.responseEditorMode = 'json'; } else if (str.startsWith('<')) { this.responseEditorMode = 'xml'; } else { this.responseEditorMode = 'text'; } } allowDrop(e) { e.stopPropagation(); e.preventDefault(); } drop(e) { e.preventDefault(); const file = e.dataTransfer.files[0]; this.readFile(file); } readFile(file: File) { var reader = new FileReader(); reader.onload = () => { this.requestBody = reader.result.toString(); }; reader.readAsText(file); } onError(error) { this.jhiAlertService.error(error.message, null, null); } openFile(event) { const reader = new FileReader(); reader.onload = () => { this.upload = reader.result; this.setUploadMessages(); }; reader.readAsBinaryString(event.target.files[0]); this.fileName = event.target.files[0].name; } openDirectory(event) { this.messages = []; this.messageFromFile = false; for (var i = 0; i < event.target.files.length; i++) { let reader = new FileReader(); reader.onload = () => { this.message = {}; this.message.body = reader.result.toString(); this.messages.push(this.message); }; reader.readAsBinaryString(event.target.files[i]); } this.messageSenderForm.controls.requestbody.setValue('Uploaded ' + event.target.files.length + ' files from directory'); } setUploadMessages() { //reset the form this.initializeForm(); this.load(); this.messageFromFile = true; //set the uploaded messages try { //try to parse via json let data = JSON.parse(this.upload); if (data.messages.message) { if (data.messages.message.length === 1) { const body = data.messages.message[0].body; const headers = data.messages.message[0].headers; const jmsHeaders = data.messages.message[0].jmsHeaders; this.messageSenderForm.controls.requestbody.setValue(body); this.requestEditorMode = this.getFileType(body); for (var key in headers) { if (headers.hasOwnProperty(key)) { this.headers = this.messageSenderForm.get('headers') as FormArray; this.headers.push(this.initializeHeader(key, headers[key])); } } if (Object.keys(headers).length > 0) { this.removeHeader('headers', 0, true); } for (var key in jmsHeaders) { if (jmsHeaders.hasOwnProperty(key)) { this.headers = this.messageSenderForm.get('jmsHeaders') as FormArray; this.headers.push(this.initializeHeader(key, jmsHeaders[key])); } } if (Object.keys(jmsHeaders).length) { this.removeHeader('jmsHeaders', 0, true); } } else { this.messages = []; for (var i = 0; i < data.messages.message.length; i++) { this.message = {}; this.message.headers = data.messages.message[i].headers; this.message.body = data.messages.message[i].body; this.messages.push(this.message); } this.messageSenderForm.controls.requestbody.setValue( 'Uploaded file ' + this.fileName + ' with ' + data.messages.message.length + ' messages' ); } } else { this.requestEditorMode = 'json'; this.messageSenderForm.controls.requestbody.setValue(this.upload); } } catch (e) { this.messageSenderForm.controls.requestbody.setValue(this.upload); this.requestEditorMode = this.getFileType(this.upload); } } getFileType(doc) { try { //try to parse via json let a = JSON.parse(doc); return 'json'; } catch (e) { try { //try xml parsing let parser = new DOMParser(); var xmlDoc = parser.parseFromString(doc, 'application/xml'); if (xmlDoc.documentElement.nodeName == '' || xmlDoc.documentElement.nodeName == 'parsererror') return 'txt'; else return 'xml'; } catch (e) { return 'txt'; } } } }
the_stack
import { Stage } from "./Stage"; import { Element } from "./Element"; export class Texture { private manager = this.stage.textureManager; private id: number = Texture.id++; public static id = 0; // All enabled elements that use this texture object (either as texture or displayedTexture). private elements = new Set<Element>(); // The number of enabled elements that are active. private _activeCount: number = 0; private _source?: TextureSource = undefined; // Texture clipping coordinates. private _x: number = 0; private _y: number = 0; private _w: number = 0; private _h: number = 0; // Render precision (0.5 = fuzzy, 1 = normal, 2 = sharp even when scaled twice, etc.). private _pixelRatio: number = 1; /** * The (maximum) expected texture source dimensions. Used for within bounds determination while texture is not yet loaded. * If not set, 2048 is used by ElementCore.update. */ public mw: number = 0; public mh: number = 0; // Flag that indicates that this texture uses clipping. private clipping: boolean = false; // Indicates whether this texture must update (when it becomes used again). private _mustUpdate: boolean = true; constructor(protected stage: Stage) {} private get source(): TextureSource | undefined { return this.getUpdatedSource(); } getUpdatedSource(): TextureSource | undefined { if (this._mustUpdate || this.stage.hasUpdateTexture(this)) { this._performUpdateSource(true); this.stage.removeUpdateTexture(this); } return this._source; } getSource(): TextureSource | undefined { return this._source; } addElement(v: Element) { if (!this.elements.has(v)) { this.elements.add(v); if (this.elements.size === 1) { if (this._source) { this._source.addTexture(this); } } if (v.active) { this.incActiveCount(); } } } removeElement(v: Element) { if (this.elements.delete(v)) { if (this.elements.size === 0) { if (this._source) { this._source.removeTexture(this); } } if (v.active) { this.decActiveCount(); } } } getElements() { return this.elements; } incActiveCount() { // Ensure that texture source's activeCount has transferred ownership. const source = this.source; if (source) { this._checkForNewerReusableTextureSource(); } this._activeCount++; if (this._activeCount === 1) { this.becomesUsed(); } } decActiveCount() { const source = this.getUpdatedSource(); // Force updating the source. this._activeCount--; if (!this._activeCount) { this.becomesUnused(); } } becomesUsed() { const source = this.getUpdatedSource(); source?.incActiveTextureCount(); } onLoad() { this.elements.forEach((element) => { if (element.active) { element.onTextureSourceLoaded(); } }); } _checkForNewerReusableTextureSource() { // When this source became unused and cleaned up, it may have disappeared from the reusable texture map. // In the meantime another texture may have been generated loaded with the same lookup id. // If this is the case, use that one instead to make sure only one active texture source per lookup id exists. const source = this.source!; if (!source.isLoaded()) { const reusable = this._getReusableTextureSource(); if (reusable && reusable.isLoaded() && reusable !== source) { this._replaceTextureSource(reusable); } } } private becomesUnused() { if (this.source) { this.source.decActiveTextureCount(); } } isUsed() { return this._activeCount > 0; } // Returns the lookup id for the current texture settings, to be able to reuse it. protected _getLookupId(): string | undefined { // Default: do not reuse texture. return undefined; } /** * Generates a loader function that is able to generate the texture for the current settings of this texture. * The loader itself may return a Function that is called when loading of the texture is cancelled. This can be used * to stop fetching an image when it is no longer in element, for example. */ protected _getSourceLoader(): TextureSourceLoader { throw new Error("Texture.generate must be implemented."); } get isValid() { return this._getIsValid(); } /** * If texture is not 'valid', no source can be created for it. */ protected _getIsValid(): boolean { return true; } /** * This must be called when the texture source must be re-generated. */ _changed() { // If no element is actively using this texture, ignore it altogether. if (this.isUsed()) { this._updateSource(); } else { this._mustUpdate = true; } } private _updateSource() { // We delay all updateSource calls to the next drawFrame, so that we can bundle them. // Otherwise we may reload a texture more often than necessary, when, for example, patching multiple text // properties. this.stage.addUpdateTexture(this); } _performUpdateSource(force = false) { // If, in the meantime, the texture was no longer used, just remember that it must update until it becomes used // again. if (force || this.isUsed()) { this._mustUpdate = false; const source = this._getTextureSource(); this._replaceTextureSource(source); } } private _getTextureSource(): TextureSource | undefined { let source; if (this._getIsValid()) { const lookupId = this._getLookupId(); source = this._getReusableTextureSource(lookupId); if (!source) { source = this.manager.getTextureSource(this._getSourceLoader(), lookupId); } } return source; } private _getReusableTextureSource(lookupId = this._getLookupId()): TextureSource | undefined { if (this._getIsValid()) { if (lookupId) { return this.manager.getReusableTextureSource(lookupId); } } return undefined; } private _replaceTextureSource(newSource: TextureSource | undefined) { const oldSource = this._source; this._source = newSource; if (oldSource) { if (this._activeCount) { oldSource.decActiveTextureCount(); } oldSource.removeTexture(this); } if (newSource) { // Must happen before setDisplayedTexture to ensure sprite map texcoords are used. newSource.addTexture(this); if (this._activeCount) { newSource.incActiveTextureCount(); } } if (this.isUsed()) { if (newSource) { if (newSource.isLoaded()) { this.elements.forEach((element) => { if (element.active) { element.setDisplayedTexture(this); } }); } else { const loadError = newSource.loadError; if (loadError) { this.elements.forEach((element) => { if (element.active) { element.onTextureSourceLoadError(loadError); } }); } } } else { this.elements.forEach((element) => { if (element.active) { element.setDisplayedTexture(undefined); } }); } } } load() { // Make sure that source is up to date. if (this.source) { if (!this.isLoaded()) { this.source.load(); } } } isLoaded() { return this._source ? this._source.isLoaded() : false; } get loadError() { return this._source ? this._source.loadError : undefined; } free() { if (this._source) { this._source.free(); } } hasClipping() { return this.clipping; } private _updateClipping() { this.clipping = !!(this._x || this._y || this._w || this._h); this.elements.forEach((element) => { // Ignore if not the currently displayed texture. if (element.displayedTexture === this) { element.onDisplayedTextureClippingChanged(); } }); } private _updatePixelRatio() { this.elements.forEach((element) => { // Ignore if not the currently displayed texture. if (element.displayedTexture === this) { element.onPixelRatioChanged(); } }); } getNonDefaults(): any { const nonDefaults: Record<string, any> = {}; nonDefaults["type"] = this.constructor.name; if (this.x !== 0) nonDefaults["x"] = this.x; if (this.y !== 0) nonDefaults["y"] = this.y; if (this.w !== 0) nonDefaults["w"] = this.w; if (this.h !== 0) nonDefaults["h"] = this.h; if (this.pixelRatio !== 1) nonDefaults["pixelRatio"] = this.pixelRatio; return nonDefaults; } get px() { return this._x * this._pixelRatio; } get py() { return this._y * this._pixelRatio; } get pw() { return this._w * this._pixelRatio; } get ph() { return this._h * this._pixelRatio; } get x() { return this._x; } set x(v) { if (this._x !== v) { this._x = v; this._updateClipping(); } } get y() { return this._y; } set y(v) { if (this._y !== v) { this._y = v; this._updateClipping(); } } get w() { return this._w; } set w(v: number) { if (this._w !== v) { this._w = v; this._updateClipping(); } } get h() { return this._h; } set h(v: number) { if (this._h !== v) { this._h = v; this._updateClipping(); } } get pixelRatio() { return this._pixelRatio; } set pixelRatio(v) { if (this._pixelRatio !== v) { this._pixelRatio = v; this._updatePixelRatio(); } } isAutosizeTexture() { return true; } getRenderWidth() { if (!this.isAutosizeTexture()) { // In case of the rectangle texture, we'd prefer to not cause a 1x1 w,h as it would interfere with flex layout fit-to-contents. return 0; } let w = this._w; if (this._source) { // Max out to edge of source texture. const sourceW = this._source.getRenderWidth() / this._pixelRatio; if (w) { w = Math.min(sourceW, w); } else { w = sourceW; } w -= this._x; } else { w = 0; } return w; } getRenderHeight() { if (!this.isAutosizeTexture()) { return 0; } let h = this._h; if (this._source) { // Max out to edge of source texture. const sourceH = this._source.getRenderHeight() / this._pixelRatio; if (h) { h = Math.min(sourceH, h); } else { h = sourceH; } h -= this._y; } else { h = 0; } return h; } static getLookupIdFromSettings(obj: object): string { if (Array.isArray(obj)) { return obj.map((o) => this.getLookupIdFromSettings(o)).join(","); } else if (Utils.isObjectLiteral(obj)) { const parts = []; for (const [key, value] of Object.entries(obj)) { parts.push(key + "=" + this.getLookupIdFromSettings(value)); } return parts.join("|"); } else if (obj === undefined) { return ""; } else { return "" + obj; } } } export type TextureSourceLoader = ( cb: TextureSourceCallback, textureSource: TextureSource, ) => TextureSourceCancelFunction | void; export type TextureSourceCallback = (error: Error | undefined, options?: TextureSourceOptions) => void; export type TextureSourceCancelFunction = () => void; export type TextureDrawableSource = Uint8Array | Uint8ClampedArray | WebGLTexture | TexImageSource; export type TextureSourceOptions = { source: TextureDrawableSource; width?: number; height?: number; permanent?: boolean; hasAlpha?: boolean; premultiplyAlpha?: boolean; renderInfo?: any; texParams?: Record<GLenum, GLenum>; texOptions?: { format?: number; internalFormat?: number; type?: GLenum; }; }; import { TextureSource } from "./TextureSource"; import { Utils } from "./Utils";
the_stack
import React, { FC, VFC, useEffect, useState, useRef, useLayoutEffect } from 'react'; import styles from './editor.module.css'; import { editorContextState, editorState } from './state'; import { editorContext } from '.'; import { useProxy } from 'valtio'; import { replaceShaderChunks, generateOBc } from './helpers/formatter'; import Editor, { DiffEditor, loader } from '@monaco-editor/react'; import * as shaderLanguage from './cshader'; import { EditorTabs } from './components/tabs/tabs'; import { Menu } from './components/menu/menu'; import { FullScreen } from './fullscreen'; import { getNameForEditorMaterial } from './helpers/shaderToMaterial'; import Monokai from './helpers/themes/Monokai.json'; // const epoch = Date.now(); export const checkIfModifications = () => { const oModel = editorContext.monacoRef.editor.getModel( editorState.activeMaterial.model + '_orig' ); const mModel = editorContext.monacoRef.editor.getModel( editorState.activeMaterial.model ); if (oModel && mModel) { var origin = oModel.getValue(); var modif = mModel.getValue(); } editorState.activeMaterial.isModif = origin !== modif; }; export const updateActiveShader = (value: any, type: string) => { if (!editorState.activeMaterial.model) { return } const activeMat = editorContext.activeMaterialRef[editorState.activeMaterial.model] const material: any = activeMat.material; editorContext.monacoRef.editor.setModelMarkers( editorContext.editor.getModel(), editorState.activeMaterial.model, value ); if (material) { if (material.isEffect) { material.vertexShader = type === 'vert' ? value : material.vertexShader; material.fragmentShader = type === 'frag' ? value : material.fragmentShader; activeMat.effect.recompile(editorContext.gl) } else { material.editorOnBeforeCompile = (shader: any) => { shader.vertexShader = type === 'vert' ? value : material.vertexShader; shader.fragmentShader = type === 'frag' ? value : material.fragmentShader; }; } checkIfModifications(); // if (type === 'vert') { // material.setOption({ // vertexMainOutro: value // }) // } else if (type === 'frag') { // material.setOption({ // fragmentColorTransform: value // }) material.needsUpdate = true; editorState.triggerUpdate++; material.customProgramCacheKey = () => { return editorState.triggerUpdate }; } }; export const MaterialEditor: FC = () => { const [instanceReady, setinstanceReady] = useState(false) useLayoutEffect(() => { if (typeof window !== "undefined" && !editorContext.monacoRef) { loader .init() .then(monacoInstance => { editorContext.monacoRef = monacoInstance; editorContext.monacoRef.editor.defineTheme('monokai', Monokai); setinstanceReady(true) monacoInstance.languages.register({ id: 'cshader' }); monacoInstance.languages.setLanguageConfiguration( 'cshader', shaderLanguage.conf ); monacoInstance.languages.setMonarchTokensProvider( 'cshader', shaderLanguage.language ); }) .catch(error => console.error('An error occurred during initialization of Monaco: ', error) ); } }) return <>{instanceReady && <EditorDom />}</>; }; const handleEditorValidation = () => { const diagnostics: any = editorState.diagnostics; if (!editorState.activeMaterial.model) { return } const material: any = editorContext.activeMaterialRef[editorState.activeMaterial.model].material; if (diagnostics && diagnostics.fragmentShader && !diagnostics.runnable && editorContext.monacoRef) { const error = diagnostics.fragmentShader.log === '' ? diagnostics.vertexShader : diagnostics.fragmentShader; const errs: string[] = error.log.split('\n'); // to count the margin const prefix: string[] = error.prefix.split('\n'); errs.pop(); let errorfromEffectAdjust = 0 const markets = errs.map(err => { if (material && material.isEffect && editorContext.editor) { const type = editorState.activeMaterial.type; const getVoidEffectLine = type === 'frag' ? `e${material.id}MainImage` : `e${material.id}MainUv` const fullProg = type === 'frag' ? diagnostics.frag : diagnostics.vert const progArr: string[] = fullProg.split('\n'); errorfromEffectAdjust = progArr.findIndex((el) => { return el.includes(getVoidEffectLine) }) const model = editorContext.editor.getModel() if (model) { const editorTxtArr: string[] = model.getValue().split('\n'); const getVoidEditorLine = type === 'frag' ? `mainImage` : `mainUv` const adjustUniforms = editorTxtArr.findIndex((el) => { return el.includes(getVoidEditorLine) }) errorfromEffectAdjust -= adjustUniforms } } const re = new RegExp('[^0-9]+ ([0-9]+):([0-9]+):'); const rl: any = err.match(re) || []; const message = err.split(':'); message[2] = (parseInt(message[2]) - (material.isEffect ? errorfromEffectAdjust : prefix.length) || '').toString(); const pos = parseInt(rl[1] || 1); const lin = parseInt(rl[2] || 1) - (material.isEffect ? errorfromEffectAdjust : prefix.length); return { startLineNumber: lin, startColumn: pos, endLineNumber: lin, endColumn: 1000, message: message.join(':'), severity: editorContext.monacoRef.MarkerSeverity.Error, }; }); editorContext.monacoRef.editor.setModelMarkers( editorContext.editor.getModel(), editorState.activeMaterial.model, markets ); } }; export const HandleError = () => { const snapshot = useProxy(editorState); useEffect(() => { // const diagnostics: any = snapshot.diagnostics // if (diagnostics && diagnostics.fragmentShader && !diagnostics.runnable) { handleEditorValidation(); // } }, [snapshot.diagnostics]); return null; }; const EditorDom = () => { const dom = useRef(null); const snapshot = useProxy(editorState); editorContext.dom = dom; return ( <div ref={dom} className={`${styles.editor_c} ${ snapshot.showEditor ? '' : styles.editor_h } ${snapshot.showEditor && snapshot.fullScreen ? styles.full : ''} ${ editorState.className }`} > <Menu /> {editorContextState.gl && <FullScreen />} {snapshot.showEditor && <EditorText />} </div> ); }; const EditorEdit = () => { const snapshot = useProxy(editorState); const [isEditorReady, setIsEditorReady] = useState(false); function handleEditorDidMount(editor: any, _: any) { editorContext.editor = editor; setIsEditorReady(true); } useEffect(() => { // at initialization of any new active material set the 2 models if (editorState.activeMaterial && editorContext.activeMaterialRef && editorContext.monacoRef && editorState.activeMaterial.model) { const type = editorState.activeMaterial.type; const activeMat = editorContext.activeMaterialRef[editorState.activeMaterial.model] if (!activeMat) { return } const material: any = activeMat.material; const program: any = activeMat.program; if (isEditorReady && material) { const name = getNameForEditorMaterial(material, program) let textContent: string | undefined; if (type === 'frag') { textContent = replaceShaderChunks(material.fragmentShader); } else { textContent = replaceShaderChunks(material.vertexShader); } if ( !editorContext.monacoRef.editor.getModel(`urn:${name}.${type}_orig`) ) { editorContext.monacoRef.editor.createModel( textContent, 'cshader', `urn:${name}.${type}_orig` ); // TODO ADD OPTION if (material.type !== 'ShaderMaterial' && material.type !== 'RawShaderMaterial' && !material.isEffect) { editorContext.editor.trigger('fold', 'editor.foldLevel1'); } } } } }, [isEditorReady, snapshot.activeMaterial, editorContext.monacoRef]); const getText = () => { if (!editorState.activeMaterial.model) { return '' } let textContent: string | undefined; const type = editorState.activeMaterial.type; const model = editorState.activeMaterial.model; const activeMat = editorContext.activeMaterialRef[editorState.activeMaterial.model]; if (activeMat) { const program = activeMat.program; const material: any = activeMat.material; if (type === 'frag') { textContent = replaceShaderChunks(material ? material.fragmentShader : program.fragmentShader); } else if (type === 'vert') { textContent = replaceShaderChunks(material ? material.vertexShader : program.vertexShader); } } if (model === 'urn:obc_result' && editorState.obcMode) { const result = generateOBc(textContent) if (editorContext.monacoRef.editor.getModel('urn:obc_result')) { editorContext.monacoRef.editor.getModel('urn:obc_result').setValue(result) } return result; } return textContent; }; return ( <Editor className={styles.editor} language="cshader" theme={'vs-dark'} onMount={handleEditorDidMount} height={'100%'} keepCurrentModel={true} path={snapshot.activeMaterial.model + ''} defaultLanguage={ snapshot.activeMaterial.model === 'urn:obc_result' ? 'javascript' : 'cshader' } defaultValue={getText()} onChange={frag => { if (editorState.obcMode) { return false; } updateActiveShader(frag, snapshot.activeMaterial.type); return false; }} // onValidate={handleEditorValidation} options={{ formatOnType: true, foldingHighlight: false, folding: true, foldingStrategy: 'auto' }} /> ); }; const GetDiff = () => { const model: any = editorState.activeMaterial.model; const [isEditorReady, setIsEditorReady] = useState(false); function handleEditorDidMount(editor: any, _: any) { editorContext.diffEditor = editor; setIsEditorReady(true); } var originalModel = editorContext.monacoRef.editor.getModel(model + '_orig'); var modifiedModel = editorContext.monacoRef.editor.getModel(model); useEffect(() => { if (isEditorReady) { if (!editorContext.monacoRef.editor.getModel('diff_1')) { editorContext.monacoRef.editor.createModel( originalModel.getValue(), 'cshader', `diff_1` ); } if (!editorContext.monacoRef.editor.getModel('diff_2')) { editorContext.monacoRef.editor.createModel( modifiedModel.getValue(), 'cshader', `diff_2` ); } editorContext.diffEditor.setModel({ original: editorContext.monacoRef.editor.getModel('diff_1'), modified: editorContext.monacoRef.editor.getModel('diff_2'), }); } return () => { if ( editorContext.editor.getModel() && editorContext.diffEditor.getModel().modified.getValue() ) { // send the update in the diff to the basic text editor editorContext.monacoRef.editor .getModel(editorState.activeMaterial.model) .setValue(editorContext.diffEditor.getModel().modified.getValue()); } var navi = editorContext.monacoRef.editor.createDiffNavigator(editorContext.diffEditor, { followsCaret: true, // resets the navigator state when the user selects something in the editor ignoreCharChanges: true // jump from line to line }); navi.next() }; }, [isEditorReady, modifiedModel, originalModel]); return ( <DiffEditor className={styles.editor} onMount={handleEditorDidMount} theme={'vs-dark'} height={'100%'} options={{ formatOnType: true, }} /> ); }; const EditorText: VFC = () => { const snapshot = useProxy(editorState); // implement multi-tab for vertex and frag using createModel return snapshot.showEditor ? ( <> {snapshot.activeMaterial.type && ( <> <HandleError /> <EditorTabs /> </> )} {Object.keys(snapshot.tabs).length > 0 && <EditorEdit />} {snapshot.showEditor && snapshot.diffMode && snapshot.activeMaterial.type && <GetDiff />} </> ) : null; }; export default MaterialEditor;
the_stack
import { ContextData, FloatingContext, FloatingFocusManager, FloatingOverlay, FloatingPortal, ReferenceType, autoUpdate, detectOverflow, flip, offset, size, useClick, useDismiss, useFloating, useInteractions, useListNavigation, useRole, useTypeahead, } from '@floating-ui/react-dom-interactions' import { useCallbackRef } from '@radix-ui/react-use-callback-ref' import { usePrevious } from '@radix-ui/react-use-previous' import { useComposedRefs } from '@tamagui/compose-refs' import { GetProps, SizeTokens, Text, VariantSpreadExtras, VariantSpreadFunction, composeEventHandlers, getVariableValue, styled, useIsomorphicLayoutEffect, withStaticProperties, } from '@tamagui/core' // import { useDirection } from '@tamagui/react-direction' // import { DismissableLayer } from '@tamagui/react-dismissable-layer' // import { FocusScope } from '@tamagui/react-focus-scope' import { useId } from '@tamagui/core' import { createContextScope } from '@tamagui/create-context' import type { Scope } from '@tamagui/create-context' import { clamp } from '@tamagui/helpers' import { ListItem, ListItemProps } from '@tamagui/list-item' // import { useLabelContext } from '@tamagui/react-label' import { Portal } from '@tamagui/portal' import { Separator } from '@tamagui/separator' import { ThemeableStack, XStack, YStack, YStackProps } from '@tamagui/stacks' import { Paragraph } from '@tamagui/text' // import { Primitive } from '@tamagui/react-primitive' // import type * as Radix from '@tamagui/react-primitive' import { useControllableState } from '@tamagui/use-controllable-state' // import { useLayoutEffect } from '@tamagui/react-use-layout-effect' // import { usePrevious } from '@tamagui/react-use-previous' // import { VisuallyHidden } from '@tamagui/core' // import { hideOthers } from 'aria-hidden' import * as React from 'react' import * as ReactDOM from 'react-dom' import { View } from 'react-native' // import { RemoveScroll } from 'react-remove-scroll' type TamaguiElement = HTMLElement | View // Cross browser fixes for pinch-zooming/backdrop-filter 🙄 const userAgent = (typeof navigator !== 'undefined' && navigator.userAgent) || '' const isFirefox = userAgent.toLowerCase().includes('firefox') if (isFirefox) { document.body.classList.add('firefox') } function getVisualOffsetTop() { return !/^((?!chrome|android).)*safari/i.test(userAgent) ? visualViewport.offsetTop : 0 } const getSelectItemSize = (val: SizeTokens, { tokens }: VariantSpreadExtras<any>) => { const padding = getVariableValue(tokens.size[val]) return { paddingHorizontal: padding / 2, paddingVertical: padding / 4, } } /* ------------------------------------------------------------------------------------------------- * SelectContext * -----------------------------------------------------------------------------------------------*/ const SELECT_NAME = 'Select' const WINDOW_PADDING = 8 const SCROLL_ARROW_VELOCITY = 8 const SCROLL_ARROW_THRESHOLD = 8 const MIN_HEIGHT = 80 const FALLBACK_THRESHOLD = 16 interface SelectContextValue { value: any selectedIndex: number setSelectedIndex: (index: number) => void activeIndex: number | null setActiveIndex: (index: number | null) => void setValueAtIndex: (index: number, value: string) => void listRef: React.MutableRefObject<Array<HTMLElement | null>> floatingRef: React.MutableRefObject<HTMLElement | null> open: boolean setOpen: (open: boolean) => void onChange: (value: string) => void dataRef: React.MutableRefObject<ContextData> controlledScrolling: boolean valueNode: Element | null onValueNodeChange(node: HTMLElement): void valueNodeHasChildren: boolean onValueNodeHasChildrenChange(hasChildren: boolean): void canScrollUp: boolean canScrollDown: boolean floatingContext: FloatingContext<ReferenceType> increaseHeight: (floating: HTMLElement, amount?: any) => number | undefined forceUpdate: React.DispatchWithoutAction interactions: { getReferenceProps: (userProps?: React.HTMLProps<Element> | undefined) => any getFloatingProps: (userProps?: React.HTMLProps<HTMLElement> | undefined) => any getItemProps: (userProps?: React.HTMLProps<HTMLElement> | undefined) => any } } type ScopedProps<P> = P & { __scopeSelect?: Scope } const [createSelectContext, createSelectScope] = createContextScope(SELECT_NAME) const [SelectProvider, useSelectContext] = createSelectContext<SelectContextValue>(SELECT_NAME) // const [SelectContentContextProvider, useSelectContentContext] = // createSelectContext<SelectContentContextValue>(CONTENT_NAME); type GenericElement = HTMLElement | View type Direction = 'ltr' | 'rtl' const OPEN_KEYS = [' ', 'Enter', 'ArrowUp', 'ArrowDown'] const SELECTION_KEYS = [' ', 'Enter'] /* ------------------------------------------------------------------------------------------------- * SelectTrigger * -----------------------------------------------------------------------------------------------*/ const TRIGGER_NAME = 'SelectTrigger' export type SelectTriggerProps = ListItemProps export const SelectTrigger = React.forwardRef<GenericElement, SelectTriggerProps>( (props: ScopedProps<SelectTriggerProps>, forwardedRef) => { const { __scopeSelect, disabled = false, // @ts-ignore 'aria-labelledby': ariaLabelledby, ...triggerProps } = props const context = useSelectContext(TRIGGER_NAME, __scopeSelect) // const composedRefs = useComposedRefs(forwardedRef, context.onTriggerChange) // const getItems = useCollection(__scopeSelect) // const labelId = useLabelContext(context.trigger) // const labelledBy = ariaLabelledby || labelId return ( <ListItem backgrounded radiused hoverable pressable focusable tabIndex={-1} borderWidth={1} componentName={TRIGGER_NAME} // aria-controls={context.contentId} aria-expanded={context.open} aria-autocomplete="none" // aria-labelledby={labelledBy} // dir={context.dir} disabled={disabled} data-disabled={disabled ? '' : undefined} {...triggerProps} ref={forwardedRef} {...context.interactions.getReferenceProps()} /> ) } ) SelectTrigger.displayName = TRIGGER_NAME /* ------------------------------------------------------------------------------------------------- * SelectValue * -----------------------------------------------------------------------------------------------*/ const VALUE_NAME = 'SelectValue' const SelectValueFrame = styled(Paragraph, { name: VALUE_NAME, }) type SelectValueProps = GetProps<typeof SelectValueFrame> & { placeholder?: React.ReactNode } const SelectValue = SelectValueFrame.extractable( React.forwardRef<TamaguiElement, SelectValueProps>( ({ __scopeSelect, children, placeholder }: ScopedProps<SelectValueProps>, forwardedRef) => { // We ignore `className` and `style` as this part shouldn't be styled. const context = useSelectContext(VALUE_NAME, __scopeSelect) const { onValueNodeHasChildrenChange } = context const hasChildren = children !== undefined const composedRefs = useComposedRefs(forwardedRef, context.onValueNodeChange) React.useLayoutEffect(() => { onValueNodeHasChildrenChange(hasChildren) }, [onValueNodeHasChildrenChange, hasChildren]) return ( <SelectValueFrame ref={composedRefs} // we don't want events from the portalled `SelectValue` children to bubble // through the item they came from pointerEvents="none" > {context.value === undefined && placeholder !== undefined ? placeholder : children} </SelectValueFrame> ) } ) ) SelectValue.displayName = VALUE_NAME /* ------------------------------------------------------------------------------------------------- * SelectIcon * -----------------------------------------------------------------------------------------------*/ export const SelectIcon = styled(XStack, { name: 'SelectIcon', // @ts-ignore 'aria-hidden': true, children: <Paragraph>▼</Paragraph>, }) /* ------------------------------------------------------------------------------------------------- * SelectContent * -----------------------------------------------------------------------------------------------*/ const CONTENT_NAME = 'SelectContent' type SelectContentElement = any type SelectContentProps = any const SelectContent = React.forwardRef<SelectContentElement, SelectContentProps>( ({ children, __scopeSelect }: ScopedProps<SelectContentProps>, forwardedRef) => { const context = useSelectContext(CONTENT_NAME, __scopeSelect) return ( <FloatingPortal> {context.open ? ( <FloatingOverlay lockScroll>{children}</FloatingOverlay> ) : ( <div style={{ display: 'none' }}>{children}</div> )} </FloatingPortal> ) } ) /* ------------------------------------------------------------------------------------------------- * SelectViewport * -----------------------------------------------------------------------------------------------*/ const VIEWPORT_NAME = 'SelectViewport' export const SelectViewportFrame = styled(ThemeableStack, { name: VIEWPORT_NAME, backgroundColor: '$background', elevate: true, overflow: 'hidden', // works on web just not typed // @ts-ignore userSelect: 'none', variants: { size: { '...size': (val, { tokens }) => { return { borderRadius: tokens.size[val] ?? val, } }, }, }, defaultVariants: { size: '$2', }, }) export type SelectViewportProps = GetProps<typeof SelectViewportFrame> const SelectViewport = React.forwardRef<TamaguiElement, SelectViewportProps>( (props: ScopedProps<SelectViewportProps>, forwardedRef) => { const { __scopeSelect, children, ...viewportProps } = props const context = useSelectContext(VIEWPORT_NAME, __scopeSelect) const composedRefs = useComposedRefs( forwardedRef // contentContext.onViewportChange ) const prevScrollTopRef = React.useRef(0) return ( <> {/* Hide scrollbars cross-browser and enable momentum scroll for touch devices */} <style dangerouslySetInnerHTML={{ __html: `[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}`, }} /> <FloatingFocusManager context={context.floatingContext} preventTabbing> <div {...context.interactions.getFloatingProps()}> <SelectViewportFrame data-radix-select-viewport="" // @ts-ignore role="presentation" {...viewportProps} ref={composedRefs} > {children} </SelectViewportFrame> </div> </FloatingFocusManager> </> ) } ) SelectViewport.displayName = VIEWPORT_NAME /* ------------------------------------------------------------------------------------------------- * SelectItem * -----------------------------------------------------------------------------------------------*/ const ITEM_NAME = 'SelectItem' type SelectItemContextValue = { value: string textId: string isSelected: boolean onItemTextChange(node: TamaguiElement | null): void } const [SelectItemContextProvider, useSelectItemContext] = createSelectContext<SelectItemContextValue>(ITEM_NAME) interface SelectItemProps extends YStackProps { value: string index: number disabled?: boolean textValue?: string } // const SelectItemFrame = styled(YStack, { // name: ITEM_NAME, // tag: 'li', // // @ts-ignore // role: 'option', // width: '100%', // hoverStyle: { // backgroundColor: '$backgroundHover', // }, // focusStyle: { // backgroundColor: '$backgroundFocus', // }, // variants: { // size: { // '...size': getSelectItemSize, // }, // }, // defaultVariants: { // size: '$4', // }, // }) const SelectItem = React.forwardRef<TamaguiElement, SelectItemProps>( (props: ScopedProps<SelectItemProps>, forwardedRef) => { const { __scopeSelect, value, disabled = false, textValue: textValueProp, index, ...itemProps } = props const context = useSelectContext(ITEM_NAME, __scopeSelect) const isSelected = context.value === value const [textValue, setTextValue] = React.useState(textValueProp ?? '') const [isFocused, setIsFocused] = React.useState(false) const textId = useId() const { selectedIndex, setSelectedIndex, listRef, open, setOpen, onChange, activeIndex, setActiveIndex, setValueAtIndex, dataRef, } = context const composedRefs = useComposedRefs( forwardedRef, (node) => { if (node instanceof HTMLElement) { listRef.current[index] = node } } // isSelected ? context.onSelectedItemChange : undefined ) React.useEffect(() => { setValueAtIndex(index, value) }, [index]) const timeoutRef = React.useRef<any>() const [allowMouseUp, setAllowMouseUp] = React.useState(false) function handleSelect() { setSelectedIndex(index) onChange(value) setOpen(false) } React.useEffect(() => { clearTimeout(timeoutRef.current) if (open) { if (selectedIndex !== index) { setAllowMouseUp(true) } else { timeoutRef.current = setTimeout(() => { setAllowMouseUp(true) }, 300) } } else { setAllowMouseUp(false) } }, [open, index, setActiveIndex, selectedIndex]) function handleKeyDown(event: React.KeyboardEvent) { if (event.key === 'Enter' || (event.key === ' ' && !dataRef.current.typing)) { event.preventDefault() handleSelect() } } const selectItemProps = context.interactions.getItemProps({ onClick: allowMouseUp ? handleSelect : undefined, onMouseUp: allowMouseUp ? handleSelect : undefined, onKeyDown: handleKeyDown, }) return ( <SelectItemContextProvider scope={__scopeSelect} value={value} textId={textId || ''} isSelected={isSelected} onItemTextChange={React.useCallback((node) => { // setTextValue((prevTextValue) => prevTextValue || (node?.textContent ?? '').trim()) }, [])} > <ListItem backgrounded hoverable pressable focusable componentName={ITEM_NAME} ref={composedRefs} aria-labelledby={textId} // `isFocused` caveat fixes stuttering in VoiceOver aria-selected={isSelected && isFocused} data-state={isSelected ? 'active' : 'inactive'} aria-disabled={disabled || undefined} data-disabled={disabled ? '' : undefined} tabIndex={disabled ? undefined : -1} {...itemProps} {...selectItemProps} /> </SelectItemContextProvider> ) } ) SelectItem.displayName = ITEM_NAME /* ------------------------------------------------------------------------------------------------- * SelectItemText * -----------------------------------------------------------------------------------------------*/ const ITEM_TEXT_NAME = 'SelectItemText' const SelectItemTextFrame = styled(Paragraph, { name: ITEM_TEXT_NAME, cursor: 'default', }) type SelectItemTextProps = GetProps<typeof SelectItemTextFrame> const SelectItemText = React.forwardRef<TamaguiElement, SelectItemTextProps>( (props: ScopedProps<SelectItemTextProps>, forwardedRef) => { // We ignore `className` and `style` as this part shouldn't be styled. const { __scopeSelect, className, style, ...itemTextProps } = props const context = useSelectContext(ITEM_TEXT_NAME, __scopeSelect) const itemContext = useSelectItemContext(ITEM_TEXT_NAME, __scopeSelect) const ref = React.useRef<TamaguiElement | null>(null) const composedRefs = useComposedRefs( forwardedRef, ref, itemContext.onItemTextChange // itemContext.isSelected ? contentContext.onSelectedItemTextChange : undefined ) return ( <> <SelectItemTextFrame id={itemContext.textId} {...itemTextProps} ref={composedRefs} /> {/* Portal the select item text into the trigger value node */} {itemContext.isSelected && context.valueNode && !context.valueNodeHasChildren ? ReactDOM.createPortal(itemTextProps.children, context.valueNode) : null} {/* Portal an option in the bubble select */} {/* {context.bubbleSelect ? ReactDOM.createPortal( // we use `.textContent` because `option` only support `string` or `number` <option value={itemContext.value}>{ref.current?.textContent}</option>, context.bubbleSelect ) : null} */} </> ) } ) SelectItemText.displayName = ITEM_TEXT_NAME /* ------------------------------------------------------------------------------------------------- * SelectItemIndicator * -----------------------------------------------------------------------------------------------*/ const ITEM_INDICATOR_NAME = 'SelectItemIndicator' const SelectItemIndicatorFrame = styled(XStack, { name: ITEM_TEXT_NAME, }) type SelectItemIndicatorProps = GetProps<typeof SelectItemIndicatorFrame> const SelectItemIndicator = React.forwardRef<TamaguiElement, SelectItemIndicatorProps>( (props: ScopedProps<SelectItemIndicatorProps>, forwardedRef) => { const { __scopeSelect, ...itemIndicatorProps } = props const itemContext = useSelectItemContext(ITEM_INDICATOR_NAME, __scopeSelect) return itemContext.isSelected ? ( <SelectItemIndicatorFrame aria-hidden {...itemIndicatorProps} ref={forwardedRef} /> ) : null } ) SelectItemIndicator.displayName = ITEM_INDICATOR_NAME /* ------------------------------------------------------------------------------------------------- * SelectGroup * -----------------------------------------------------------------------------------------------*/ const GROUP_NAME = 'SelectGroup' type SelectGroupContextValue = { id: string } const [SelectGroupContextProvider, useSelectGroupContext] = createSelectContext<SelectGroupContextValue>(GROUP_NAME) const SelectGroupFrame = styled(YStack, { name: GROUP_NAME, width: '100%', }) type SelectGroupProps = GetProps<typeof SelectGroupFrame> const SelectGroup = React.forwardRef<TamaguiElement, SelectGroupProps>( (props: ScopedProps<SelectGroupProps>, forwardedRef) => { const { __scopeSelect, ...groupProps } = props const groupId = useId() return ( <SelectGroupContextProvider scope={__scopeSelect} id={groupId || ''}> <SelectGroupFrame // @ts-ignore role="group" aria-labelledby={groupId} {...groupProps} ref={forwardedRef} /> </SelectGroupContextProvider> ) } ) SelectGroup.displayName = GROUP_NAME /* ------------------------------------------------------------------------------------------------- * SelectLabel * -----------------------------------------------------------------------------------------------*/ const LABEL_NAME = 'SelectLabel' export type SelectLabelProps = ListItemProps const SelectLabel = React.forwardRef<TamaguiElement, SelectLabelProps>( (props: ScopedProps<SelectLabelProps>, forwardedRef) => { const { __scopeSelect, ...labelProps } = props const groupContext = useSelectGroupContext(LABEL_NAME, __scopeSelect) return ( <ListItem componentName={LABEL_NAME} fontWeight="800" id={groupContext.id} {...labelProps} // @ts-expect-error ref={forwardedRef} /> ) } ) SelectLabel.displayName = LABEL_NAME /* ------------------------------------------------------------------------------------------------- * SelectScrollUpButton * -----------------------------------------------------------------------------------------------*/ const SCROLL_UP_BUTTON_NAME = 'SelectScrollUpButton' interface SelectScrollButtonProps extends Omit<SelectScrollButtonImplProps, 'dir' | 'componentName'> {} const SelectScrollUpButton = React.forwardRef<TamaguiElement, SelectScrollButtonProps>( (props: ScopedProps<SelectScrollButtonProps>, forwardedRef) => { return ( <SelectScrollButtonImpl componentName={SCROLL_UP_BUTTON_NAME} {...props} dir="up" ref={forwardedRef} /> ) } ) SelectScrollUpButton.displayName = SCROLL_UP_BUTTON_NAME /* ------------------------------------------------------------------------------------------------- * SelectScrollDownButton * -----------------------------------------------------------------------------------------------*/ const SCROLL_DOWN_BUTTON_NAME = 'SelectScrollDownButton' const SelectScrollDownButton = React.forwardRef<TamaguiElement, SelectScrollButtonProps>( (props: ScopedProps<SelectScrollButtonProps>, forwardedRef) => { return ( <SelectScrollButtonImpl componentName={SCROLL_DOWN_BUTTON_NAME} {...props} dir="down" ref={forwardedRef} /> ) } ) SelectScrollDownButton.displayName = SCROLL_DOWN_BUTTON_NAME type SelectScrollButtonImplElement = TamaguiElement interface SelectScrollButtonImplProps extends YStackProps { dir: 'up' | 'down' componentName: string } const SelectScrollButtonImpl = React.forwardRef< SelectScrollButtonImplElement, SelectScrollButtonImplProps >((props: ScopedProps<SelectScrollButtonImplProps>, forwardedRef) => { const { __scopeSelect, dir, componentName, ...scrollIndicatorProps } = props const { floatingRef, increaseHeight, forceUpdate, ...context } = useSelectContext( componentName, __scopeSelect ) const intervalRef = React.useRef<any>() const loopingRef = React.useRef(false) const isVisible = context[dir === 'down' ? 'canScrollDown' : 'canScrollUp'] const { x, y, reference, floating, strategy, update, refs } = useFloating({ strategy: 'fixed', placement: dir === 'up' ? 'top' : 'bottom', middleware: [offset(({ rects }) => -rects.floating.height)], }) const composedRefs = useComposedRefs(forwardedRef, floating) React.useLayoutEffect(() => { reference(floatingRef.current) // eslint-disable-next-line react-hooks/exhaustive-deps }, [reference, floatingRef.current]) React.useEffect(() => { if (!refs.reference.current || !refs.floating.current || !isVisible) { return } const cleanup = autoUpdate(refs.reference.current, refs.floating.current, update, { animationFrame: true, }) return () => { clearInterval(intervalRef.current) loopingRef.current = false cleanup() } }, [isVisible, update, refs.floating, refs.reference]) if (!isVisible) { return null } const handleScrollArrowChange = () => { const floating = floatingRef.current const isUp = dir === 'up' if (floating) { const value = isUp ? -SCROLL_ARROW_VELOCITY : SCROLL_ARROW_VELOCITY const multi = (isUp && floating.scrollTop <= SCROLL_ARROW_THRESHOLD * 2) || (!isUp && floating.scrollTop >= floating.scrollHeight - floating.clientHeight - SCROLL_ARROW_THRESHOLD * 2) ? 2 : 1 floating.scrollTop += multi * (isUp ? -SCROLL_ARROW_VELOCITY : SCROLL_ARROW_VELOCITY) increaseHeight(floating, multi === 2 ? value * 2 : value) // Ensure derived data (scroll arrows) is fresh forceUpdate() } } return ( <YStack ref={composedRefs} componentName={componentName} aria-hidden {...scrollIndicatorProps} // @ts-expect-error position={strategy} left={x || 0} top={y || 0} width={`calc(${(floatingRef.current?.offsetWidth ?? 0) - 2}px)`} background={`linear-gradient(to ${ dir === 'up' ? 'bottom' : 'top' }, #29282b 50%, rgba(53, 54, 55, 0.01))`} onPointerMove={() => { if (!loopingRef.current) { intervalRef.current = setInterval(handleScrollArrowChange, 1000 / 60) loopingRef.current = true } }} onPointerLeave={() => { loopingRef.current = false clearInterval(intervalRef.current) }} /> ) }) /* ------------------------------------------------------------------------------------------------- * SelectSeparator * -----------------------------------------------------------------------------------------------*/ export const SelectSeparator = styled(Separator, { name: 'SelectSeparator', }) /* ------------------------------------------------------------------------------------------------- * Select * -----------------------------------------------------------------------------------------------*/ export interface SelectProps { children?: React.ReactNode value?: string defaultValue?: string onValueChange?(value: string): void open?: boolean defaultOpen?: boolean onOpenChange?(open: boolean): void dir?: Direction name?: string autoComplete?: string } export const Select = withStaticProperties( (props: ScopedProps<SelectProps>) => { const { __scopeSelect, children, open: openProp, defaultOpen, onOpenChange, value: valueProp, defaultValue, onValueChange, dir, name, autoComplete, } = props // const [trigger, setTrigger] = React.useState<SelectTriggerElement | null>(null) const [open, setOpen] = useControllableState({ prop: openProp, defaultProp: defaultOpen || false, onChange: onOpenChange, }) const [value, setValue] = useControllableState({ prop: valueProp, defaultProp: defaultValue || '', onChange: onValueChange, }) const [activeIndex, setActiveIndex] = React.useState<number | null>(null) const selectedIndexRef = React.useRef<number | null>(null) const activeIndexRef = React.useRef<number | null>(null) const prevActiveIndex = usePrevious<number | null>(activeIndex) const [showArrows, setShowArrows] = React.useState(false) const [scrollTop, setScrollTop] = React.useState(0) const listItemsRef = React.useRef<Array<HTMLElement | null>>([]) const listContentRef = React.useRef<string[]>([]) const [selectedIndex, setSelectedIndex] = React.useState( Math.max(0, listContentRef.current.indexOf(value)) ) const [controlledScrolling, setControlledScrolling] = React.useState(false) const [middlewareType, setMiddlewareType] = React.useState<'align' | 'fallback'>('align') useIsomorphicLayoutEffect(() => { selectedIndexRef.current = selectedIndex activeIndexRef.current = activeIndex }) // Wait for scroll position to settle before showing arrows to prevent // interference with pointer events. React.useEffect(() => { const frame = requestAnimationFrame(() => { setShowArrows(open) if (!open) { setScrollTop(0) setMiddlewareType('align') setActiveIndex(null) setControlledScrolling(false) } }) return () => { cancelAnimationFrame(frame) } }, [open]) function getFloatingPadding(floating: HTMLElement | null) { if (!floating) { return 0 } return Number(getComputedStyle(floating).paddingLeft?.replace('px', '')) } const { x, y, reference, floating, strategy, context, refs, middlewareData, update } = useFloating({ open, onOpenChange: setOpen, placement: 'bottom', middleware: middlewareType === 'align' ? [ offset(({ rects }) => { const index = activeIndexRef.current ?? selectedIndexRef.current if (index == null) { return 0 } const item = listItemsRef.current[index] if (item == null) { return 0 } const offsetTop = item.offsetTop const itemHeight = item.offsetHeight const height = rects.reference.height return -offsetTop - height - (itemHeight - height) / 2 }), // Custom `size` that can handle the opposite direction of the // placement { name: 'size', async fn(args) { const { elements: { floating }, rects: { reference }, middlewareData, } = args const overflow = await detectOverflow(args, { padding: WINDOW_PADDING, }) const top = Math.max(0, overflow.top) const bottom = Math.max(0, overflow.bottom) const nextY = args.y + top if (middlewareData.size?.skip) { return { y: nextY, data: { y: middlewareData.size.y, }, } } Object.assign(floating.style, { maxHeight: `${floating.scrollHeight - Math.abs(top + bottom)}px`, minWidth: `${reference.width + getFloatingPadding(floating) * 2}px`, }) return { y: nextY, data: { y: top, skip: true, }, reset: { rects: true, }, } }, }, ] : [ offset(5), flip(), size({ apply({ rects, availableHeight, elements }) { Object.assign(elements.floating.style, { width: `${rects.reference.width}px`, maxHeight: `${availableHeight}px`, }) }, padding: WINDOW_PADDING, }), ], }) const floatingRef = refs.floating const forceUpdate = React.useReducer(() => ({}), {})[1] const showUpArrow = showArrows && scrollTop > SCROLL_ARROW_THRESHOLD const showDownArrow = showArrows && floatingRef.current && scrollTop < floatingRef.current.scrollHeight - floatingRef.current.clientHeight - SCROLL_ARROW_THRESHOLD const interactions = useInteractions([ useClick(context, { pointerDown: true }), useRole(context, { role: 'listbox' }), useDismiss(context), useListNavigation(context, { listRef: listItemsRef, activeIndex, selectedIndex, onNavigate: setActiveIndex, }), useTypeahead(context, { listRef: listContentRef, onMatch: open ? setActiveIndex : setSelectedIndex, selectedIndex, activeIndex, }), ]) const increaseHeight = React.useCallback( (floating: HTMLElement, amount = 0) => { if (middlewareType === 'fallback') { return } const currentMaxHeight = Number(floating.style.maxHeight.replace('px', '')) const currentTop = Number(floating.style.top.replace('px', '')) const rect = floating.getBoundingClientRect() const rectTop = rect.top const rectBottom = rect.bottom const visualMaxHeight = visualViewport.height - WINDOW_PADDING * 2 if ( amount < 0 && selectedIndexRef.current != null && Math.round(rectBottom) < Math.round(visualViewport.height + getVisualOffsetTop() - WINDOW_PADDING) ) { floating.style.maxHeight = `${Math.min(visualMaxHeight, currentMaxHeight - amount)}px` } if ( amount > 0 && Math.round(rectTop) > Math.round(WINDOW_PADDING - getVisualOffsetTop()) && floating.scrollHeight > floating.offsetHeight ) { const nextTop = Math.max(WINDOW_PADDING + getVisualOffsetTop(), currentTop - amount) const nextMaxHeight = Math.min(visualMaxHeight, currentMaxHeight + amount) Object.assign(floating.style, { maxHeight: `${nextMaxHeight}px`, top: `${nextTop}px`, }) if (nextTop - WINDOW_PADDING > getVisualOffsetTop()) { floating.scrollTop -= nextMaxHeight - currentMaxHeight + getFloatingPadding(floating) } return currentTop - nextTop } }, [middlewareType] ) const touchPageYRef = React.useRef<number | null>(null) const handleWheel = React.useCallback( (event: WheelEvent | TouchEvent) => { const pinching = event.ctrlKey const currentTarget = event.currentTarget as HTMLElement function isWheelEvent(event: any): event is WheelEvent { return typeof event.deltaY === 'number' } function isTouchEvent(event: any): event is TouchEvent { return event.touches != null } if ( Math.abs( (currentTarget?.offsetHeight ?? 0) - (visualViewport.height - WINDOW_PADDING * 2) ) > 1 && !pinching ) { event.preventDefault() } else if (isWheelEvent(event) && isFirefox) { // Firefox needs this to propagate scrolling // during momentum scrolling phase if the // height reached its maximum (at boundaries) currentTarget.scrollTop += event.deltaY } if (!pinching) { let delta = 5 if (isTouchEvent(event)) { const currentPageY = touchPageYRef.current const pageY = event.touches[0]?.pageY if (pageY != null) { touchPageYRef.current = pageY if (currentPageY != null) { delta = currentPageY - pageY } } } increaseHeight(currentTarget, isWheelEvent(event) ? event.deltaY : delta) setScrollTop(currentTarget.scrollTop) // Ensure derived data (scroll arrows) is fresh forceUpdate() } }, [increaseHeight, forceUpdate] ) // Handle `onWheel` event in an effect to remove the `passive` option so we // can .preventDefault() it React.useEffect(() => { function onTouchEnd() { touchPageYRef.current = null } const floating = floatingRef.current if (open && floating && middlewareType === 'align') { floating.addEventListener('wheel', handleWheel) floating.addEventListener('touchmove', handleWheel) floating.addEventListener('touchend', onTouchEnd, { passive: true }) return () => { floating.removeEventListener('wheel', handleWheel) floating.removeEventListener('touchmove', handleWheel) floating.removeEventListener('touchend', onTouchEnd) } } }, [open, floatingRef, handleWheel, middlewareType]) // Ensure the menu remains attached to the reference element when resizing. React.useEffect(() => { window.addEventListener('resize', update) return () => { window.removeEventListener('resize', update) } }, [update]) // Scroll the active or selected item into view when in `controlledScrolling` // mode (i.e. arrow key nav). React.useLayoutEffect(() => { const floating = floatingRef.current if (open && controlledScrolling && floating) { const item = activeIndex != null ? listItemsRef.current[activeIndex] : selectedIndex != null ? listItemsRef.current[selectedIndex] : null if (item && prevActiveIndex != null) { const itemHeight = listItemsRef.current[prevActiveIndex]?.offsetHeight ?? 0 const floatingHeight = floating.offsetHeight const top = item.offsetTop const bottom = top + itemHeight if (top < floating.scrollTop + 20) { const diff = floating.scrollTop - top + 20 floating.scrollTop -= diff if (activeIndex != selectedIndex && activeIndex != null) { increaseHeight(floating, -diff) } } else if (bottom > floatingHeight + floating.scrollTop - 20) { const diff = bottom - floatingHeight - floating.scrollTop + 20 floating.scrollTop += diff if (activeIndex != selectedIndex && activeIndex != null) { floating.scrollTop -= increaseHeight(floating, diff) ?? 0 } } } } }, [ open, controlledScrolling, prevActiveIndex, activeIndex, selectedIndex, floatingRef, increaseHeight, ]) // Sync the height and the scrollTop values and device whether to use fallback // positioning. React.useLayoutEffect(() => { const floating = refs.floating.current const reference = refs.reference.current if (open && floating && reference && floating.offsetHeight < floating.scrollHeight) { const referenceRect = reference.getBoundingClientRect() if (middlewareType === 'fallback') { const item = listItemsRef.current[selectedIndex] if (item) { floating.scrollTop = item.offsetTop - floating.clientHeight + referenceRect.height } return } floating.scrollTop = middlewareData.size?.y const closeToBottom = visualViewport.height + getVisualOffsetTop() - referenceRect.bottom < FALLBACK_THRESHOLD const closeToTop = referenceRect.top < FALLBACK_THRESHOLD if (floating.offsetHeight < MIN_HEIGHT || closeToTop || closeToBottom) { setMiddlewareType('fallback') } } }, [ open, increaseHeight, selectedIndex, middlewareType, refs.floating, refs.reference, // Always re-run this effect when the position has been computed so the // .scrollTop change works with fresh sizing. middlewareData, ]) React.useLayoutEffect(() => { if (open && selectedIndex != null) { requestAnimationFrame(() => { listItemsRef.current[selectedIndex]?.focus({ preventScroll: true }) }) } }, [listItemsRef, selectedIndex, open]) // Wait for scroll position to settle before showing arrows to prevent // interference with pointer events. React.useEffect(() => { const frame = requestAnimationFrame(() => { setShowArrows(open) if (!open) { setScrollTop(0) setMiddlewareType('align') setActiveIndex(null) setControlledScrolling(false) } }) return () => cancelAnimationFrame(frame) }, [open]) // We set this to true by default so that events bubble to forms without JS (SSR) // const isFormControl = trigger ? Boolean(trigger.closest('form')) : true // const [bubbleSelect, setBubbleSelect] = React.useState<HTMLSelectElement | null>(null) // const triggerPointerDownPosRef = React.useRef<{ x: number; y: number } | null>(null) const [valueNode, setValueNode] = React.useState<HTMLElement | null>(null) const [valueNodeHasChildren, setValueNodeHasChildren] = React.useState(false) return ( <SelectProvider scope={__scopeSelect} increaseHeight={increaseHeight} forceUpdate={forceUpdate} floatingRef={floatingRef} valueNode={valueNode} onValueNodeChange={setValueNode} valueNodeHasChildren={valueNodeHasChildren} onValueNodeHasChildrenChange={setValueNodeHasChildren} setValueAtIndex={(index, value) => { listContentRef.current[index] = value }} interactions={{ ...interactions, getReferenceProps() { return interactions.getReferenceProps({ ref: reference, className: 'SelectTrigger', onKeyDown(event) { if ( event.key === 'Enter' || (event.key === ' ' && !context.dataRef.current.typing) ) { event.preventDefault() setOpen(true) } }, }) }, getFloatingProps() { return interactions.getFloatingProps({ ref: floating, className: 'Select', style: { position: strategy, top: y ?? '', left: x ?? '', }, onPointerEnter() { setControlledScrolling(false) }, onPointerMove() { setControlledScrolling(false) }, onKeyDown() { setControlledScrolling(true) }, onScroll(event) { setScrollTop(event.currentTarget.scrollTop) }, }) }, }} floatingContext={context} activeIndex={activeIndex} canScrollDown={!!showDownArrow} canScrollUp={!!showUpArrow} controlledScrolling dataRef={context.dataRef} listRef={listItemsRef} onChange={setValue} selectedIndex={0} setActiveIndex={setActiveIndex} setOpen={setOpen} setSelectedIndex={setSelectedIndex} value={value} // trigger={trigger} // onTriggerChange={setTrigger} // contentId={useId() || ''} // value={value} // onValueChange={setValue} open={open} // onOpenChange={setOpen} // TODO // dir={'rtl'} //direction} // bubbleSelect={bubbleSelect} // triggerPointerDownPosRef={triggerPointerDownPosRef} > {/* <Collection.Provider scope={__scopeSelect}>{children}</Collection.Provider> */} {children} {/* {isFormControl ? ( <BubbleSelect ref={setBubbleSelect} aria-hidden tabIndex={-1} name={name} autoComplete={autoComplete} value={value} // enable form autofill onChange={(event) => setValue(event.target.value)} /> ) : null} */} </SelectProvider> ) }, { Content: SelectContent, Group: SelectGroup, Icon: SelectIcon, Item: SelectItem, ItemIndicator: SelectItemIndicator, ItemText: SelectItemText, Label: SelectLabel, ScrollDownButton: SelectScrollDownButton, ScrollUpButton: SelectScrollUpButton, Trigger: SelectTrigger, Value: SelectValue, Viewport: SelectViewport, } ) // @ts-ignore Select.displayName = SELECT_NAME export { createSelectScope }
the_stack
import { AppInstanceInfo, Node } from "@counterfactual/types"; import { Zero } from "ethers/constants"; import { JsonRpcNotification, JsonRpcResponse } from "rpc-server"; import { AppInstance } from "../src/app-instance"; import { NODE_REQUEST_TIMEOUT, Provider } from "../src/provider"; import { ErrorEventData, EventType, InstallEventData, RejectInstallEventData } from "../src/types"; import { CONVENTION_FOR_ETH_TOKEN_ADDRESS, TEST_XPUBS, TestNodeProvider } from "./fixture"; describe("CF.js Provider", () => { let nodeProvider: TestNodeProvider; let provider: Provider; const TEST_APP_INSTANCE_INFO: AppInstanceInfo = { identityHash: "TEST_ID", abiEncodings: { actionEncoding: "uint256", stateEncoding: "uint256" }, appDefinition: "0x1515151515151515151515151515151515151515", initiatorDeposit: Zero, responderDeposit: Zero, timeout: Zero, proposedByIdentifier: TEST_XPUBS[0], proposedToIdentifier: TEST_XPUBS[1], initiatorDepositTokenAddress: CONVENTION_FOR_ETH_TOKEN_ADDRESS, responderDepositTokenAddress: CONVENTION_FOR_ETH_TOKEN_ADDRESS }; beforeEach(() => { nodeProvider = new TestNodeProvider(); provider = new Provider(nodeProvider); }); it("throws generic errors coming from Node", async () => { expect.assertions(1); nodeProvider.onMethodRequest( Node.RpcMethodName.GET_APP_INSTANCES, request => { nodeProvider.simulateMessageFromNode({ jsonrpc: "2.0", id: request.id as number, result: { type: Node.ErrorType.ERROR, data: { errorName: "music_too_loud", message: "Music too loud" } } }); } ); try { await provider.getAppInstances(); } catch (e) { expect(e.result.data.message).toBe("Music too loud"); } }); it("emits an error event for orphaned responses", async () => { expect.assertions(2); provider.on(EventType.ERROR, e => { expect(e.type).toBe(EventType.ERROR); expect((e.data as ErrorEventData).errorName).toBe("orphaned_response"); }); nodeProvider.simulateMessageFromNode({ jsonrpc: "2.0", result: { type: Node.RpcMethodName.INSTALL, result: { appInstanceId: "" } }, id: 3 }); }); it( "throws an error on timeout", async () => { try { await provider.getAppInstances(); } catch (err) { expect(err.data.errorName).toBe("request_timeout"); } }, NODE_REQUEST_TIMEOUT + 1000 // This could be done with fake timers. ); // Test disabled until event type validations are refactored. it.skip("throws an error for unexpected event types", async () => { expect.assertions(2); provider.on(EventType.ERROR, e => { expect(e.type).toBe(EventType.ERROR); expect((e.data as ErrorEventData).errorName).toBe( "unexpected_event_type" ); }); // @ts-ignore Ignoring compiler on purpose to simulate an invalid event type. provider.callRawNodeMethod("notARealEventType", {}); }); // Test disabled until event type validations are refactored. it.skip("throws an error when subscribing to an unknown event", async () => { expect.assertions(3); ["on", "once", "off"].forEach(methodName => { expect(() => provider[methodName]("fakeEvent", () => {})).toThrowError( '"fakeEvent" is not a valid event' ); }); }); describe("Node methods", () => { it("can query app instances and return them", async () => { expect.assertions(3); nodeProvider.onMethodRequest( Node.RpcMethodName.GET_APP_INSTANCES, request => { expect(request.methodName).toBe(Node.RpcMethodName.GET_APP_INSTANCES); nodeProvider.simulateMessageFromNode({ jsonrpc: "2.0", result: { type: Node.RpcMethodName.GET_APP_INSTANCES, result: { appInstances: [TEST_APP_INSTANCE_INFO] } }, id: request.id as number }); } ); const instances = await provider.getAppInstances(); expect(instances).toHaveLength(1); expect(instances[0].identityHash).toBe( TEST_APP_INSTANCE_INFO.identityHash ); }); it("can install an app instance", async () => { expect.assertions(4); nodeProvider.onMethodRequest(Node.RpcMethodName.INSTALL, request => { expect(request.methodName).toBe(Node.RpcMethodName.INSTALL); expect((request.parameters as Node.InstallParams).appInstanceId).toBe( TEST_APP_INSTANCE_INFO.identityHash ); nodeProvider.simulateMessageFromNode({ jsonrpc: "2.0", result: { result: { appInstance: TEST_APP_INSTANCE_INFO }, type: Node.RpcMethodName.INSTALL }, id: request.id as number }); }); const appInstance = await provider.install( TEST_APP_INSTANCE_INFO.identityHash ); expect(appInstance.identityHash).toBe( TEST_APP_INSTANCE_INFO.identityHash ); expect(appInstance.appDefinition).toBe( TEST_APP_INSTANCE_INFO.appDefinition ); }); it("can install an app instance virtually", async () => { expect.assertions(7); const expectedHubIdentifier = "0x6001600160016001600160016001600160016001"; nodeProvider.onMethodRequest( Node.RpcMethodName.INSTALL_VIRTUAL, request => { expect(request.methodName).toBe(Node.RpcMethodName.INSTALL_VIRTUAL); const params = request.parameters as Node.InstallVirtualParams; expect(params.appInstanceId).toBe( TEST_APP_INSTANCE_INFO.identityHash ); expect(params.intermediaryIdentifier).toBe(expectedHubIdentifier); nodeProvider.simulateMessageFromNode({ jsonrpc: "2.0", result: { result: { appInstance: { intermediaryIdentifier: expectedHubIdentifier, ...TEST_APP_INSTANCE_INFO } }, type: Node.RpcMethodName.INSTALL_VIRTUAL }, id: request.id as number }); } ); const appInstance = await provider.installVirtual( TEST_APP_INSTANCE_INFO.identityHash, expectedHubIdentifier ); expect(appInstance.identityHash).toBe( TEST_APP_INSTANCE_INFO.identityHash ); expect(appInstance.appDefinition).toBe( TEST_APP_INSTANCE_INFO.appDefinition ); expect(appInstance.isVirtual).toBeTruthy(); expect(appInstance.intermediaryIdentifier).toBe(expectedHubIdentifier); }); it("can reject installation proposals", async () => { nodeProvider.onMethodRequest( Node.RpcMethodName.REJECT_INSTALL, request => { expect(request.methodName).toBe(Node.RpcMethodName.REJECT_INSTALL); const { appInstanceId } = request.parameters as Node.RejectInstallParams; expect(appInstanceId).toBe(TEST_APP_INSTANCE_INFO.identityHash); nodeProvider.simulateMessageFromNode({ jsonrpc: "2.0", result: { type: Node.RpcMethodName.REJECT_INSTALL, result: {} }, id: request.id as number }); } ); await provider.rejectInstall(TEST_APP_INSTANCE_INFO.identityHash); }); }); describe("Node events", () => { it("can unsubscribe from events", async done => { const callback = () => done.fail("Unsubscribed event listener was fired"); provider.on(EventType.REJECT_INSTALL, callback); provider.off(EventType.REJECT_INSTALL, callback); nodeProvider.simulateMessageFromNode({ jsonrpc: "2.0", result: { result: { appInstanceId: "TEST" }, type: Node.RpcMethodName.REJECT_INSTALL } }); setTimeout(done, 100); }); it("can subscribe to rejectInstall events", async () => { expect.assertions(3); provider.once(EventType.REJECT_INSTALL, e => { expect(e.type).toBe(EventType.REJECT_INSTALL); const appInstance = (e.data as RejectInstallEventData).appInstance; expect(appInstance).toBeInstanceOf(AppInstance); expect(appInstance.identityHash).toBe( TEST_APP_INSTANCE_INFO.identityHash ); }); nodeProvider.simulateMessageFromNode({ jsonrpc: "2.0", result: { type: Node.EventName.REJECT_INSTALL, data: { appInstance: TEST_APP_INSTANCE_INFO } } }); }); it("can subscribe to install events", async () => { expect.assertions(3); provider.once(EventType.INSTALL, e => { expect(e.type).toBe(EventType.INSTALL); const appInstance = (e.data as InstallEventData).appInstance; expect(appInstance).toBeInstanceOf(AppInstance); expect(appInstance.identityHash).toBe( TEST_APP_INSTANCE_INFO.identityHash ); }); await provider.getOrCreateAppInstance( TEST_APP_INSTANCE_INFO.identityHash, TEST_APP_INSTANCE_INFO ); nodeProvider.simulateMessageFromNode({ jsonrpc: "2.0", result: { type: Node.EventName.INSTALL, data: { appInstanceId: TEST_APP_INSTANCE_INFO.identityHash } } }); }); }); describe("AppInstance management", () => { it("can expose the same AppInstance instance for a unique app instance ID", async () => { expect.assertions(1); let savedInstance: AppInstance; provider.on(EventType.REJECT_INSTALL, e => { const eventInstance = (e.data as RejectInstallEventData).appInstance; if (!savedInstance) { savedInstance = eventInstance; } else { expect(savedInstance).toBe(eventInstance); } }); const msg = { jsonrpc: "2.0", result: { type: Node.EventName.REJECT_INSTALL, data: { appInstance: TEST_APP_INSTANCE_INFO } } } as JsonRpcNotification; nodeProvider.simulateMessageFromNode(msg); nodeProvider.simulateMessageFromNode(msg); }); it("can load app instance details on-demand", async () => { expect.assertions(4); provider.on(EventType.UPDATE_STATE, e => { expect((e.data as InstallEventData).appInstance.identityHash).toBe( TEST_APP_INSTANCE_INFO.identityHash ); }); nodeProvider.simulateMessageFromNode({ jsonrpc: "2.0", result: { type: Node.EventName.UPDATE_STATE, data: { appInstanceId: TEST_APP_INSTANCE_INFO.identityHash, newState: { someState: "3" } } } }); expect(nodeProvider.postedMessages).toHaveLength(1); const [detailsRequest] = nodeProvider.postedMessages; expect(detailsRequest.methodName).toBe( Node.RpcMethodName.GET_APP_INSTANCE_DETAILS ); expect( (detailsRequest.parameters as Node.GetAppInstanceDetailsParams) .appInstanceId ).toBe(TEST_APP_INSTANCE_INFO.identityHash); nodeProvider.simulateMessageFromNode({ jsonrpc: "2.0", result: { type: Node.RpcMethodName.GET_APP_INSTANCE_DETAILS, result: { appInstance: TEST_APP_INSTANCE_INFO } }, id: detailsRequest.id } as JsonRpcResponse); // NOTE: For some reason the event won't fire unless we wait for a bit await new Promise(r => setTimeout(r, 50)); }); }); });
the_stack
import { Promise } from 'es6-promise'; import * as nano from 'nano'; import * as moment from 'moment'; import * as winston from 'winston'; import config from '../config'; import * as Cloudant from '@cloudant/cloudant'; import tweets = require('../data/SampleTweets'); import { EnrichmentPipeline } from '../util/EnrichmentPipeline'; import cloudantConfig from '../data/cloudant.config'; import { ClassificationSummary, EmotionalToneOverTime, SentimentOverTime, SentimentSummary, CloudantOptions } from '../model/CRMModel'; import logger from '../util/Logger'; export class CloudantDAO { public static getInstance(options: CloudantOptions, enrichmentPipeline: EnrichmentPipeline) { if (this.cloudantDao === undefined) { this.cloudantDao = new CloudantDAO(cloudantConfig, options, enrichmentPipeline); } return this.cloudantDao; } private static cloudantDao: CloudantDAO; private cloudantDB!: Cloudant.DocumentScope<{}>; private options: CloudantOptions = {} as CloudantOptions; private maxBufferSize: number; private bulkSaveBuffer: nano.BulkModifyDocsWrapper; private duplicateDetectionCache: any; private duplicateDetectionCacheThreshold: number; private cloudant: Cloudant.ServerScope; private dbName!: string; private enrichmentPipeline: EnrichmentPipeline; private dbConfig: any; private status: any; private LOGGER = winston.createLogger({ level: config.log_level, transports: [ new (winston.transports.Console)({ format: winston.format.simple() })], }); /** * @param cloudant * @param dbname * @param options */ private constructor(dbConfig: any, options: CloudantOptions, enrichmentPipeline: EnrichmentPipeline) { this.dbConfig = dbConfig; const cloudant = Cloudant({ account: config.cloudant_username, password: config.cloudant_password, plugins: { retry: { retryErrors: false, retryStatusCodes: [429] } }, }); this.cloudant = cloudant; this.enrichmentPipeline = enrichmentPipeline; // options settings this.bulkSaveBuffer = { docs: [], }; this.options = options; this.maxBufferSize = this.options.maxBufferSize ? this.options.maxBufferSize : 1; // Initialize the duplicate tweet detection cache. this.duplicateDetectionCache = { tweetIdCache: {}, tweetTextCache: {}, }; // Once you reach this limit, start removing some of the old entries. this.duplicateDetectionCacheThreshold = 50; } public listByView(design: string, view: string, limit: number, skip: number, params: nano.DocumentViewParams) { return new Promise((resolve, reject) => { try { params = { reduce: false, descending: true, include_docs: true, limit: !limit ? 5 : limit, skip: !skip ? 0 : skip, }; this.cloudantDB.view(design, view, params, (err, resp) => { if (err) { return reject(err); } // Map the results to the response for the client const response = { total: resp.total_rows, data: resp.rows, }; resolve(response); }); } catch (err) { reject(err); } }); } public bulk(bulkRequest: nano.BulkModifyDocsWrapper) { return new Promise((resolve, reject) => { this.cloudantDB.bulk(bulkRequest, (err, resp) => { if (err) { return reject(err); } resolve(resp); }); }); } public saveToCloudant(data: any, force: boolean) { return new Promise((resolve, reject) => { try { if (data && data.text) { this.bulkSaveBuffer.docs.push(data); } this.LOGGER.debug('Length of Buffer: : ' + this.bulkSaveBuffer.docs.length); // If the bulk buffer threshold is reached, or the force flag is true, // Then save the buffer to cloudant. if (this.bulkSaveBuffer.docs.length >= this.maxBufferSize || force) { // Throttle the save to not exceed Cloudant free plan limits this.LOGGER.debug('Saving to Cloudant...'); this.cloudantDB.bulk(this.bulkSaveBuffer, (err, result) => { if (err) { this.LOGGER.error('Error while saving to database::' + err); reject(err); } else { this.LOGGER.debug('Successfully saved ' + this.bulkSaveBuffer.docs.length + ' docs to Cloudant.'); this.bulkSaveBuffer.docs = []; resolve(); } }); } } catch (err) { reject(err); } }); } /** This function will check for duplicate tweets in a memory cache and if not found, * will then check in Cloudant if the output type is cloudant. */ public duplicateCheck(tweet: any) { return new Promise((resolve, reject) => { try { this.LOGGER.debug('In Duplicate Detection.'); if (this.duplicateDetectionCache.tweetIdCache[tweet.id_str.toString()]) { this.LOGGER.info('Duplicate Tweet ID found.'); return reject(); } this.duplicateDetectionCache.tweetIdCache[tweet.id_str.toString()] = true; if (Object.keys(this.duplicateDetectionCache.tweetIdCache).length > this.duplicateDetectionCacheThreshold) { this.trimCache(this.duplicateDetectionCacheThreshold, this.duplicateDetectionCache.tweetIdCache); } // Now check if the text of the tweet is in the cache. if (this.duplicateDetectionCache.tweetTextCache[tweet.text]) { this.LOGGER.info('Duplicate Tweet Text found.'); return reject(); } this.duplicateDetectionCache.tweetTextCache[tweet.text] = true; if (Object.keys(this.duplicateDetectionCache.tweetTextCache).length > this.duplicateDetectionCacheThreshold) { this.trimCache(this.duplicateDetectionCacheThreshold, this.duplicateDetectionCache.tweetTextCache); } this.LOGGER.info('Checking in Cloudant.'); this.cloudantDuplicateCheck(tweet).then(() => { resolve(); }).catch((err) => { if (err) { reject(err); } else { reject(); } }); } catch (err) { this.LOGGER.error(err); reject(err); } }); } public cloudantDuplicateCheck(tweet: any) { return new Promise((resolve, reject) => { try { if (!tweet) { return resolve(); } this.LOGGER.info('In Cloudant Duplicate Tweet Check.'); // First check if the tweet was already processed const selector = { selector: { tweet_id: tweet.id } }; this.cloudantDB.find(selector, (err, result) => { if (err) { return reject(err); } this.LOGGER.info('Result of tweet id check = ' + JSON.stringify(result)); if (result.docs.length > 0) { this.LOGGER.info('Duplicate detected... Ignoring the tweet...'); return reject(); } // Check for duplicate tweets based on the tweet text to avoid any spamming const query: {} = { q: 'tweet_text:"' + tweet.text + '"' }; this.cloudantDB.search('analysis-db', 'tweet-text-search', query, (error, response) => { if (error) { return reject(error); } this.LOGGER.info('Result of duplicate tweet text check = ' + JSON.stringify(result)); if (response && response.total_rows > 0) { this.LOGGER.info('Tweet is filtered because of duplicate tweet text detection'); return reject(); } resolve(); }); }); } catch (err) { this.LOGGER.log(err); reject(err); } }); } /** * Remove the a quarter of the cached entries from the duplicate detection cache. * @param threshold * @param cacheObject */ public trimCache(threshold: number, cacheObject: string[]) { const count = Math.round(threshold / 4); this.LOGGER.debug('Trimming ' + count + ' items from the cache.'); const itemsToDelete: string[] = []; for (const key in cacheObject) { if (itemsToDelete.length < count) { itemsToDelete.push(key); } else { break; } } for (const key in itemsToDelete) { if (itemsToDelete.hasOwnProperty(key)) { delete itemsToDelete[key]; } } } public bulkBufferLength() { return this.bulkSaveBuffer.docs.length; } /** * Check Cloudant against the cloudant-config.json file. */ public checkCloudant() { const dbDefinitions = this.dbConfig['db-definitions']; return new Promise((resolve, reject) => { try { this.LOGGER.info('Checking cloudant...'); const dbCheckPromises = []; for (const dbName of Object.keys(dbDefinitions)) { const dbConfig = dbDefinitions[dbName]; dbCheckPromises.push(this.checkDatabase(dbName, dbConfig)); } this.LOGGER.info('Number of databases in configuration that will be checked : ' + dbCheckPromises.length); Promise.all(dbCheckPromises).then((dbResult) => { this.LOGGER.info('Done checking cloudant...'); resolve(dbResult); }).catch((err) => { this.LOGGER.info('Error checking cloudant : ' + err); reject(err); }); } catch (err) { this.LOGGER.info('Error checking cloudant : ' + err); reject(err); } }); } /** Utility functionto tell you whether you need to sync the db config */ public needSync(checkResult: any) { try { this.LOGGER.info('*** Checking if cloudant sync is required. ***'); let needSync = false; for (let i = 0; i < checkResult.length; i++) { if (!checkResult[i].exist) { needSync = true; break; } else { for (let j = 0; j < checkResult[i].design.length; j++) { if (!checkResult[i].design[j].exist) { needSync = true; break; } } } } this.LOGGER.info('*** Cloudant sync is' + (needSync ? ' required ' : ' not required. ***')); return needSync; } catch (err) { this.LOGGER.info('Error checking if cloudant sync is required : ' + err); return false; } } /** Sync the cloudant instance with the configuration in the cloudant-config.json file. */ public syncCloudantConfig(checkResult: any) { const dbDefinitions = this.dbConfig['db-definitions']; return new Promise((resolve, reject) => { try { this.LOGGER.info('Syncing cloudant configuration...'); const createHash = this.getCreateManifest(checkResult); const dbCreatePromises = []; for (const dbName of Object.keys(dbDefinitions)) { const dbConfig = dbDefinitions[dbName]; dbCreatePromises.push(this.createCloudantDB(dbName, dbConfig, createHash)); } Promise.all(dbCreatePromises).then((dbResult: any) => { this.LOGGER.info('Done syncing cloudant configuration'); const db = dbResult[0].dbName; this.dbName = db; this.cloudantDB = this.cloudant.use(db); resolve(dbResult); }).catch((err) => { reject(err); }); } catch (err) { this.LOGGER.info('Error syncing cloudant configuration : ' + err); reject(err); } }); } /** Print the results of the check out */ public printCheckResults(checkResult: any) { try { for (let i = 0; i < checkResult.length; i++) { // tslint:disable:max-line-length this.LOGGER.info('Database ' + checkResult[i].dbName + (checkResult[i].exist ? ' exist' : ' does not exist')); for (let j = 0; j < checkResult[i].design.length; j++) { if (checkResult[i].design[j].type === 'index') { // tslint:disable:max-line-length this.LOGGER.info('> Index ' + checkResult[i].design[j].name + (checkResult[i].design[j].exist ? ' exist' : ' does not exist')); } else { // tslint:disable:max-line-length this.LOGGER.info('> Design ' + checkResult[i].design[j].name + (checkResult[i].design[j].exist ? ' exist' : ' does not exist')); } } } } catch (err) { this.LOGGER.info('Error printing check result : ' + err); return false; } } public checkDatabase(dbName: string, dbConfig: any) { return new Promise((resolve, reject) => { try { this.cloudant.db.get(dbName, (err, body) => { let designs: any = {}; let designName: string = ''; if (err) { // No database exist const result: any = { dbName, exist: false, rows: 0, design: [], }; // if the database doesn't exist, nothing else will, so set it up that way designs = dbConfig.design ? dbConfig.design : []; for (const design of designs) { designName = design.name; result.design.push({ type: 'design', name: designName, exist: false }); } const indexes = dbConfig.index ? dbConfig.index : []; for (const index of indexes) { result.design.push({ type: 'index', name: index.name, exist: false }); } resolve(result); } else { // if the database exists then initialize the cloudant db this.dbName = body.db_name; this.cloudantDB = this.cloudant.use(this.dbName); designs = dbConfig.design ? dbConfig.design : []; const designCheckPromises = []; for (const design of designs) { designName = design.name; designCheckPromises.push(this.checkDesign(designName)); } const indexes = dbConfig.index ? dbConfig.index : []; for (const index of indexes) { designCheckPromises.push(this.checkIndex(index.name)); } Promise.all(designCheckPromises).then((designResult) => { const options = { endkey: '_', }; this.cloudantDB.list(options, (error, rowResult) => { if (error) { reject(error); } else { const dbResult: any = { dbName: this.dbName, exist: true, rows: rowResult.rows.length, design: [] }; dbResult.design = designResult; resolve(dbResult); } }); }, (error1) => { this.LOGGER.info('Error returned from checking design documents : ' + error1); }); } }); } catch (err) { this.LOGGER.info('Error in checking databases : ' + err); reject(err); } }); } public checkDesign(designName: string) { return new Promise((resolve, reject) => { try { this.LOGGER.info('Checking for design ' + designName + ' in database ' + this.dbName); this.cloudantDB.get('_design/' + designName, (err, body) => { if (!err) { resolve({ type: 'design', name: designName, exist: true }); } else { resolve({ type: 'design', name: designName, exist: false }); } }); } catch (err) { this.LOGGER.info('Error in checking for design : ' + err); reject(err); } }); } public checkIndex(indexName: string) { return new Promise((resolve, reject) => { try { this.LOGGER.info('Checking for index ' + indexName + ' in database ' + this.dbName); this.cloudantDB.index((err: any, body: any) => { if (!err) { const indexes = body.indexes; let found = false; for (let i = 0; i < indexes.length; i++) { if (indexes[i].name === indexName) { this.LOGGER.info('Index ' + indexName + ' already exist.'); found = true; break; } } resolve({ type: 'index', name: indexName, exist: found }); } else { resolve({ type: 'index', name: indexName, exist: false }); } }); } catch (err) { this.LOGGER.info('Error in checking for index : ' + err); reject(err); } }); } public createCloudantDB(dbName: string, dbConfig: any, createHash: any) { return new Promise((resolve, reject) => { try { const createDb = createHash.db[dbName]; if (createDb) { this.LOGGER.info('Creating cloudant database ' + dbName); this.cloudant.db.create(dbName, (err) => { if (err) { // tslint:disable:max-line-length this.LOGGER.info('Error returned from cloudant trying to create a database : ' + JSON.stringify(err)); resolve({ dbName, exist: false }); } else { this.cloudantDB = this.cloudant.use(dbName); this.dbName = dbName; // Now create any design docs that might be defined const designCreatePromises = this.buildDesignCreatePromiseArray(dbName, dbConfig, createHash); Promise.all(designCreatePromises).then((designResult) => { const dbResult: any = { dbName, exist: true, design: [] }; dbResult.design = designResult; resolve(dbResult); }); } }); } else { this.LOGGER.info('Database ' + dbName + ' already exist, creating designs'); // Now create any design docs that might be defined const designCreatePromises = this.buildDesignCreatePromiseArray(dbName, dbConfig, createHash); Promise.all(designCreatePromises).then((designResult) => { const dbResult: any = { dbName, exist: true, design: [] }; dbResult.design = designResult; resolve(dbResult); }); } } catch (err) { this.LOGGER.info('Error in creating cloudant database : ' + err); reject(err); } }); } public buildDesignCreatePromiseArray(dbName: string, dbConfig: any, createHash: any) { const designs = dbConfig.design ? dbConfig.design : []; const designCreatePromises = []; for (const design of designs) { const designName = design.name; designCreatePromises.push(this.createCloudantDesign(dbName, designName, design, createHash)); } const indexes = dbConfig.index ? dbConfig.index : []; for (const index of indexes) { const indexName = index.name; designCreatePromises.push(this.createCloudantIndex(dbName, indexName, index, createHash)); } return designCreatePromises; } public createCloudantIndex(dbName: string, indexName: string, indexDef: any, createHash: any) { return new Promise((resolve, reject) => { try { this.LOGGER.info('Creating cloudant index with name ' + indexName + ' in database ' + dbName); const createIndex = createHash.design[dbName + '-' + indexName + '-index']; if (createIndex) { this.cloudantDB.index(indexDef, (err: any, body: any) => { if (!err) { resolve({ type: 'index', name: indexName, exist: true }); } else { this.LOGGER.info('Error returned from cloudant trying to create an index : ' + JSON.stringify(err)); resolve({ type: 'index', name: indexName, exist: false }); } }); } else { resolve({ indexName, exist: true }); } } catch (err) { this.LOGGER.info('Error creating index : ' + err); reject(err); } }); } public createCloudantDesign(dbName: string, designName: string, design: any, createHash: any) { return new Promise((resolve, reject) => { try { this.LOGGER.info('Creating cloudant design document ' + designName + ' in database ' + dbName); const createDesign = createHash.design[dbName + '-' + designName + '-design']; if (createDesign) { this.cloudantDB.insert(design, '_design/' + designName, (err, body) => { if (!err) { resolve({ type: 'design', name: designName, exist: true }); } else { this.LOGGER.info('Error returned from cloudant trying to create a design document : ' + JSON.stringify(err)); resolve({ type: 'design', name: designName, exist: false }); } }); } else { resolve({ designName, exist: true }); } } catch (err) { this.LOGGER.info('Error creating cloudant design document : ' + err); reject(err); } }); } public getCreateManifest(checkResult: any) { const createHash: any = { db: {}, design: {}, }; try { for (let i = 0; i < checkResult.length; i++) { createHash.db[checkResult[i].dbName] = !checkResult[i].exist; for (let j = 0; j < checkResult[i].design.length; j++) { const name = checkResult[i].dbName + '-' + checkResult[i].design[j].name + '-' + checkResult[i].design[j].type; createHash.design[name] = !checkResult[i].design[j].exist; } } return createHash; } catch (err) { this.LOGGER.info('Error in building the sync manifest : ' + err); } } public setupCloudant() { return new Promise((resolve, reject) => { // Instanciate the Cloudant Initializer this.checkCloudant().then((checkResult) => { const needSync = this.needSync(checkResult); if (needSync) { this.syncCloudantConfig(checkResult).then((createResult) => { this.printCheckResults(createResult); this.LOGGER.info('*** Synchronization completed. ***'); this.insertSampleTweets().then((dataResult) => { this.LOGGER.info('*** Sample tweet data inserted successfully. ***' + dataResult); resolve(); }).catch((err) => { this.LOGGER.info('*** Error while saving sample tweets to database ***'); reject(err); }); }); } else { this.printCheckResults(checkResult); this.LOGGER.info('*** Synchronization not required. ***'); resolve(); } }, (err) => { this.LOGGER.info(err); reject(); }); }); } /** * insert sample tweets * @param {*} tweets */ public insertSampleTweets() { return new Promise((resolve, reject) => { try { let i = 1; const dataLoadPromises: any = []; for (const tweet of tweets.default) { // needed to add these as sample tweets don't haec all the details const tweetToDb: any = tweet; tweetToDb.post_by = 'system'; tweetToDb.source = 'system'; tweetToDb.tweet_id = i++; this.enrichmentPipeline.enrich(tweet.text).then((enrichments) => { // Then save it to something... /* this.cloudantDAO.saveToCloudant(enrichedData, false).then(() => { this.LOGGER.info("*** Saved " + JSON.stringify(enrichedData) + " to the database."); }).catch((err) => { this.LOGGER.info("Error saving to cloudant: " + err); }); */ tweetToDb.enrichments = enrichments; dataLoadPromises.push(this.saveToCloudant(tweetToDb, false)); }).catch((err) => { this.status.lastError = err; this.status.errors++; // If it's not an unsupported text language error, then we pause the listener. if (err.indexOf('unsupported text language') === -1) { this.LOGGER.info('An enrichment error occurred' + err); } reject(err); }); } Promise.all(dataLoadPromises).then((loadDataResult) => { this.LOGGER.info('Done syncing cloudant data'); resolve(loadDataResult); }).catch((err) => { reject(err); }); } catch (err) { this.LOGGER.info('Error in saving tweets to database : ' + err); reject(err); } }); } public listByPostDate(skip: number, limit: number, cb: (err?: Error, result?: any) => void) { try { const params = {}; this.listByView(this.dbName, 'created-at-view', limit, skip, params) .then((result) => { cb(undefined, result); }) .catch((err) => { cb(err, undefined); }); } catch (error) { cb(error, undefined); } } public sentimentSummary(cb: (err?: Error, result?: any) => void) { try { const params: nano.DocumentViewParams = { group: true, }; // doc.enrichments.nlu.sentiment.document.label, doc.enrichments.nlu.sentiment.document.score this.cloudantDB.view(this.dbName, 'sentiment-view', params, (err, sot) => { if (err) { return cb(err); } // Map the results to a format better suited for the client const response: SentimentSummary = {} as SentimentSummary; for (const row of sot.rows) { response.total += row.value as number; const dataKey = row.key as string; switch (dataKey) { case 'positive': { response.positive = row.value as number; break; } case 'neutral': { response.neutral = row.value as number; break; } case 'negative': { response.negative = row.value as number; break; } } } cb(undefined, response); }); } catch (err) { cb(err, undefined); } } public sentimentOvertime(cb: (err?: Error, result?: any) => void) { try { const endKey = moment().subtract(7, 'days'); const params = { group: true, descending: true, // endkey: [endKey.year(), endKey.month(), endKey.date()] }; const response: SentimentOverTime = {} as SentimentOverTime; response.date = []; response.negative = []; response.positive = []; response.neutral = []; // [d.getFullYear(), d.getMonth(), d.getDate(), doc.enrichments.nlu.sentiment.document.label], 1 this.cloudantDB.view(this.dbName, 'sentiment-overtime-view', params, (err, result) => { if (err) { return cb(err); } for (const row of result.rows) { if (row.key[3] === 'unknown') { continue; } // Label is in format MM-DD-YYYY const month: number = Number(row.key[1]) + 1; const label = month + '-' + row.key[2] + '-' + row.key[0]; if (response.date.indexOf(label) < 0) { response.date.unshift(label); } const sentiment = row.key[3] as string; switch (sentiment) { case 'positive': { response.positive.unshift(row.value as number); break; } case 'neutral': { response.neutral.unshift(row.value as number); break; } case 'negative': { response.negative.unshift(row.value as number); break; } } } cb(undefined, response); }); } catch (err) { cb(err); } } public classificationSummary(cb: (err?: Error, result?: any) => void) { try { const params = { group: true, }; this.cloudantDB.view(this.dbName, 'classification-view', params, (err, result) => { if (err) { return cb(err); } let rows = result.rows; rows.sort((a, b) => { if (a.value < b.value) { return 1; } if (a.value > b.value) { return -1; } return 0; }); rows = rows.slice(0, 5); const response: ClassificationSummary[] = []; for (const row of rows) { const cs: ClassificationSummary = {} as ClassificationSummary; cs.key = row.key; cs.value = row.value as number; response.push(cs); } cb(undefined, response); }); } catch (err) { cb(err); } } public emotionalToneOvertime(cb: (err?: Error, result?: any) => void) { try { const endKey = moment().subtract(7, 'days'); const params = { group: true, descending: true, // endkey: [endKey.year(), endKey.month(), endKey.date()] }; const response: EmotionalToneOverTime = {} as EmotionalToneOverTime; response.date = []; response.anger = []; response.fear = []; response.disgust = []; response.joy = []; response.sadness = []; // top score of doc.enrichments.nlu.emotion.document.emotion over time this.cloudantDB.view(this.dbName, 'emotional-overtime-view', params, (err, result) => { if (err) { return cb(err); } for (const row of result.rows) { if (row.key[3] === 'unknown') { continue; } // Label is in format MM-DD-YYYY const label = (Number(row.key[1]) + 1) + '-' + row.key[2] + '-' + row.key[0]; if (response.date.indexOf(label) < 0) { response.date.unshift(label); } const emotion = row.key[3]; // eto.[emotion].unshift(row.value) switch (emotion) { case 'anger': { response.anger.unshift(row.value as number); break; } case 'disgust': { response.disgust.unshift(row.value as number); break; } case 'fear': { response.fear.unshift(row.value as number); break; } case 'joy': { response.joy.unshift(row.value as number); break; } case 'sadness': { response.sadness.unshift(row.value as number); break; } } } cb(undefined, response); }); } catch (err) { cb(err); } } public entitiesSummary(cb: (err?: Error, result?: any) => void) { try { const params = { group: true, }; this.cloudantDB.view(this.dbName, 'entities-view', params, (err, result) => { if (err) { return cb(err); } const rows = result.rows; rows.sort((a, b) => { if (a.value < b.value) { return 1; } if (a.value > b.value) { return -1; } return 0; }); rows.slice(0, 10); cb(undefined, { rows }); }); } catch (err) { cb(err); } } public keywordsSummary(cb: (err?: Error, result?: any) => void) { try { const params = { group: true, }; this.cloudantDB.view(this.dbName, 'keywords-view', params, (err, result) => { if (err) { return cb(err); } const rows = result.rows; rows.sort((a, b) => { if (a.value < b.value) { return 1; } if (a.value > b.value) { return -1; } return 0; }); const response = { data: rows.slice(0, 100), }; cb(undefined, response); }); } catch (err) { cb(err); } } public sentimentTrend(cb: (err?: Error, result?: any) => void) { try { const params = { reduce: false, descending: true, include_docs: true, limit: 300, }; this.cloudantDB.view(this.dbName, 'created-at-view', params, (err, result) => { if (err) { return cb(err); } cb(undefined, result); }); } catch (err) { cb(err); } } }
the_stack
import { observer } from "mobx-react-lite" import { useCallback, useEffect, useMemo, useState } from "react" import { cloneDeep } from "lodash" import { FormInstance } from "antd" // @Types import { SourceConnector as CatalogSourceConnector } from "@jitsu/catalog/sources/types" import { SetSourceEditorDisabledTabs, SetSourceEditorState, SourceEditorState } from "./SourceEditor" // @Components import { SourceEditorFormConfigurationStaticFields } from "./SourceEditorFormConfigurationStaticFields" import { SourceEditorFormConfigurationConfigurableLoadableFields } from "./SourceEditorFormConfigurationConfigurableLoadableFields" import { SourceEditorFormConfigurationConfigurableFields } from "./SourceEditorFormConfigurationConfigurableFields" // @Utils import { useServices } from "hooks/useServices" import { useLoaderAsObject } from "hooks/useLoader" import { OAUTH_FIELDS_NAMES } from "constants/oauth" import { SourceEditorOauthButtons } from "../Common/SourceEditorOauthButtons/SourceEditorOauthButtons" import { sourcePageUtils } from "ui/pages/SourcesPage/SourcePage.utils" import { useUniqueKeyState } from "hooks/useUniqueKeyState" import { FormSkeleton } from "ui/components/FormSkeleton/FormSkeleton" export type SourceEditorFormConfigurationProps = { editorMode: "add" | "edit" initialSourceData: Optional<Partial<SourceData>> sourceDataFromCatalog: CatalogSourceConnector disabled?: boolean setSourceEditorState: SetSourceEditorState handleSetControlsDisabled: (disabled: boolean | string, setterId: string) => void handleSetTabsDisabled: SetSourceEditorDisabledTabs handleReloadStreams: VoidFunction | AsyncVoidFunction } export type ValidateGetErrorsCount = () => Promise<number> export type PatchConfig = ( key: string, allValues: PlainObjectWithPrimitiveValues, options?: { /** * Whether to tell the parent component to update the UI. * Needed to distinguish the state updates caused by the user and updates made internally. **/ doNotSetStateChanged?: boolean /** Whether to reset configuration tab errors count. False by default */ resetErrorsCount?: boolean } ) => void export type SetFormReference = ( key: string, form: FormInstance, patchConfigOnFormValuesChange?: (values: PlainObjectWithPrimitiveValues) => void ) => void type Forms = { [key: string]: { form: FormInstance<PlainObjectWithPrimitiveValues> patchConfigOnFormValuesChange?: (values: PlainObjectWithPrimitiveValues) => void } } const initialValidator: () => ValidateGetErrorsCount = () => async () => 0 const SourceEditorFormConfiguration: React.FC<SourceEditorFormConfigurationProps> = ({ editorMode, initialSourceData, sourceDataFromCatalog, disabled, setSourceEditorState, handleSetControlsDisabled, handleSetTabsDisabled, handleReloadStreams, }) => { const services = useServices() const [forms, setForms] = useState<Forms>({}) const isInitiallySignedIn = editorMode === "edit" const [fillAuthDataManually, setFillAuthDataManually] = useState<boolean>(true) const [isOauthStatusReady, setIsOauthStatusReady] = useState<boolean>(false) const [isOauthFlowCompleted, setIsOauthFlowCompleted] = useState<boolean>(isInitiallySignedIn) const [staticFieldsValidator, setStaticFieldsValidator] = useState<ValidateGetErrorsCount>(initialValidator) const [configurableFieldsValidator, setConfigurableFieldsValidator] = useState<ValidateGetErrorsCount>(initialValidator) const [configurableLoadableFieldsValidator, setConfigurableLoadableFieldsValidator] = useState<ValidateGetErrorsCount>(initialValidator) const [resetKey, resetFormUi] = useUniqueKeyState() // pass a key to a component, then re-mount component by calling `resetFormUi` const setFormReference = useCallback<SetFormReference>((key, form, patchConfigOnFormValuesChange) => { setForms(forms => ({ ...forms, [key]: { form, patchConfigOnFormValuesChange } })) }, []) const sourceConfigurationSchema = useMemo(() => { switch (sourceDataFromCatalog.protoType) { case "airbyte": const airbyteId = sourceDataFromCatalog.id.replace("airbyte-", "") return { backendId: airbyteId, hideOauthFields: true, loadableFieldsEndpoint: "test", invisibleStaticFields: { "config.docker_image": sourceDataFromCatalog.id.replace("airbyte-", ""), }, } case "singer": const tapId = sourceDataFromCatalog.id.replace("singer-", "") return { backendId: tapId, hideOauthFields: true, configurableFields: sourceDataFromCatalog.configParameters, invisibleStaticFields: { "config.tap": tapId, }, } default: // native source const id = sourceDataFromCatalog.id return { backendId: id, hideOauthFields: true, configurableFields: sourceDataFromCatalog.configParameters, } } }, []) const { data: availableBackendSecrets, isLoading: isLoadingBackendSecrets } = useLoaderAsObject< string[] >(async () => { const { backendId, hideOauthFields } = sourceConfigurationSchema if (!hideOauthFields) return [] return await services.oauthService.getAvailableBackendSecrets(backendId, services.activeProject.id) }, []) const hideFields = useMemo<string[]>(() => { const { hideOauthFields } = sourceConfigurationSchema return fillAuthDataManually || !hideOauthFields ? [] : [...OAUTH_FIELDS_NAMES, ...(availableBackendSecrets ?? [])] }, [fillAuthDataManually, availableBackendSecrets]) const handleResetOauth = useCallback<() => void>(() => { setIsOauthFlowCompleted(false) }, []) const handleOauthSupportedStatusChange = useCallback((oauthSupported: boolean) => { setIsOauthStatusReady(true) setFillAuthDataManually(!oauthSupported) }, []) const handleFillAuthDataManuallyChange = (fillManually: boolean) => { setFillAuthDataManually(fillManually) if (!fillManually) { resetFormUi() // reset form if user switched from manual auth back to oauth setIsOauthFlowCompleted(false) // force user to push the 'Authorize' button one more time } } const setOauthSecretsToForms = useCallback<(secrets: PlainObjectWithPrimitiveValues) => void>( secrets => { const success = sourcePageUtils.applyOauthValuesToAntdForms(forms, secrets) success && setIsOauthFlowCompleted(true) }, [forms] ) const patchConfig = useCallback<PatchConfig>((key, allValues, options) => { setSourceEditorState(state => { const newState: SourceEditorState = { ...state, configuration: { ...state.configuration, config: { ...state.configuration.config, [key]: allValues } }, } if (!options?.doNotSetStateChanged) newState.stateChanged = true if (options.resetErrorsCount) newState.configuration.errorsCount = 0 return newState }) }, []) useEffect(() => { const validateConfigAndCountErrors = async (): Promise<number> => { const staticFieldsErrorsCount = await staticFieldsValidator() const configurableFieldsErrorsCount = await configurableFieldsValidator() const configurableLoadableFieldsErrorsCount = await configurableLoadableFieldsValidator() return staticFieldsErrorsCount + configurableLoadableFieldsErrorsCount + configurableFieldsErrorsCount } setSourceEditorState(state => { const newState = cloneDeep(state) newState.configuration.validateGetErrorsCount = validateConfigAndCountErrors return newState }) }, [staticFieldsValidator, configurableFieldsValidator, configurableLoadableFieldsValidator]) /** * Sets source type specific fields that are not configurable by user */ useEffect(() => { const { invisibleStaticFields } = sourceConfigurationSchema if (invisibleStaticFields) patchConfig("invisibleStaticFields", invisibleStaticFields, { doNotSetStateChanged: true, }) }, []) const isLoadingOauth = !isOauthStatusReady || isLoadingBackendSecrets useEffect(() => { if (isLoadingOauth) handleSetControlsDisabled(true, "byOauthFlow") else if (fillAuthDataManually) handleSetControlsDisabled(false, "byOauthFlow") else if (!isOauthFlowCompleted) { handleSetControlsDisabled("Please, either grant Jitsu access or fill auth credentials manually", "byOauthFlow") handleSetTabsDisabled(["streams"], "disable") } else { handleSetControlsDisabled(false, "byOauthFlow") handleSetTabsDisabled(["streams"], "enable") } }, [isLoadingOauth, fillAuthDataManually, isOauthFlowCompleted]) return ( <> <div className={`flex justify-center items-start w-full h-full ${isLoadingOauth ? "" : "hidden"}`}> <FormSkeleton /> </div> <div className={isLoadingOauth ? "hidden" : ""}> <SourceEditorOauthButtons key="oauth" sourceDataFromCatalog={sourceDataFromCatalog} disabled={disabled} isSignedIn={isOauthFlowCompleted} onIsOauthSupportedCheckSuccess={handleOauthSupportedStatusChange} onFillAuthDataManuallyChange={handleFillAuthDataManuallyChange} setOauthSecretsToForms={setOauthSecretsToForms} /> <div key={resetKey}> <SourceEditorFormConfigurationStaticFields editorMode={editorMode} initialValues={initialSourceData} patchConfig={patchConfig} setValidator={setStaticFieldsValidator} setFormReference={setFormReference} /> {sourceConfigurationSchema.configurableFields && ( <SourceEditorFormConfigurationConfigurableFields initialValues={initialSourceData} configParameters={sourceConfigurationSchema.configurableFields} availableOauthBackendSecrets={availableBackendSecrets} hideFields={hideFields} patchConfig={patchConfig} setValidator={setConfigurableFieldsValidator} setFormReference={setFormReference} /> )} {sourceConfigurationSchema.loadableFieldsEndpoint && ( <SourceEditorFormConfigurationConfigurableLoadableFields editorMode={editorMode} initialValues={initialSourceData} sourceDataFromCatalog={sourceDataFromCatalog} hideFields={hideFields} patchConfig={patchConfig} handleSetControlsDisabled={handleSetControlsDisabled} handleSetTabsDisabled={handleSetTabsDisabled} setValidator={setConfigurableLoadableFieldsValidator} setFormReference={setFormReference} handleResetOauth={handleResetOauth} handleReloadStreams={handleReloadStreams} /> )} </div> </div> </> ) } const Wrapped = observer(SourceEditorFormConfiguration) Wrapped.displayName = "SourceEditorFormConfiguration" export { Wrapped as SourceEditorFormConfiguration }
the_stack
import $$observable from 'symbol-observable'; import Cache, { ICache, CacheOptions, mutateKeysLayer, prefixLayer, DataCache } from '@wora/cache-persist'; import isPlainObject from './redux/utils/isPlainObject'; import ActionTypes from './redux/utils/actionTypes'; import { filterKeys } from '@wora/cache-persist/lib/layers/filterKeys'; export const REHYDRATE = `@@redux/REHYDRATE`; // added export const REHYDRATE_ERROR = `@@redux/REHYDRATE_ERROR`; // added /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} [enhancer] The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ export type CacheOptionsRedux = CacheOptions & { version?: number; key?: string; whitelist?: Array<string>; blacklist?: Array<string>; migrate?: (s: any, v: number) => Promise<any>; stateReconciler?: (s: any, o: any, r: any, c: any) => any; }; function createStore(reducer: any, preloadedState?: any, enhancer?: any, persistOptions?: CacheOptionsRedux) { //TODO TYPING if ( (typeof preloadedState === 'function' && typeof enhancer === 'function') || (typeof enhancer === 'function' && typeof arguments[3] === 'function') ) { throw new Error('CREATE1'); } if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('CREATE2'); } return enhancer(createStore)(reducer, preloadedState, undefined, persistOptions); } if (typeof reducer !== 'function') { throw new Error('CREATE3'); } let promiseRestore; const { disablePersist = !persistOptions, version = -1, key = 'root', // TODO verify whitelist = undefined, blacklist = undefined, mutateKeys = undefined, mutateValues = undefined, migrate = (s: any, v: number) => Promise.resolve(s), stateReconciler = (s: any, o: any, r: any, c: any) => s, } = persistOptions || {}; const prefix = `persist:${key}`; const reduxPersistKey = `redux-persist`; const migrateReduxPersistKey = mutateKeysLayer( (key) => (key === `${prefix}.${reduxPersistKey}` ? prefix : key), (key) => (key === prefix ? `${prefix}.${reduxPersistKey}` : key), ); const internalMutateKeys = [migrateReduxPersistKey, prefixLayer(prefix)]; if (whitelist) { internalMutateKeys.push(filterKeys((key) => whitelist.includes(key))); } if (blacklist) { internalMutateKeys.push(filterKeys((key) => !blacklist.includes(key))); } const customMutateKeys = mutateKeys ? internalMutateKeys.concat(mutateKeys) : internalMutateKeys; const cache: ICache = new Cache({ disablePersist, prefix: null, mutateKeys: customMutateKeys, mutateValues, initialState: preloadedState, mergeState: async (originalRestoredState = {}, initialState = {}) => { const restoredState = originalRestoredState[reduxPersistKey] || originalRestoredState; const haveStoredState = !!restoredState && !!restoredState._persist; const state = haveStoredState ? await migrate(restoredState, version).then((mState: any) => stateReconciler(mState, initialState, initialState, persistOptions), ) : initialState; return { ...state, _persist: { version, rehydrated: true, wora: true } }; }, ...persistOptions, }); if (disablePersist) { promiseRestore = Promise.resolve(); } let currentReducer = reducer; let isDispatching = false; /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { if (isDispatching) { throw new Error('GETSTATE1'); } return cache.getState(); } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener: any) { return cache.subscribe(listener); } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action: any) { if (!isPlainObject(action)) { throw new Error('DISPATCH1'); } if (typeof action.type === 'undefined') { throw new Error('DISPATCH2'); } if (isDispatching) { throw new Error('DISPATCH3'); } try { isDispatching = true; const { _persist, ...prevState } = cache.getState(); const state = currentReducer(prevState, action); Object.keys(state).forEach((key) => { if (state[key] !== prevState[key]) { cache.set(key, state[key]); } }); } finally { isDispatching = false; } cache.notify({ state: getState(), action }); return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer: any) { if (typeof nextReducer !== 'function') { throw new Error('REPLACE1'); } currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT. // Any reducers that existed in both the new and old rootReducer // will receive the previous state. This effectively populates // the new state tree with any relevant data from the old one. dispatch({ type: ActionTypes.REPLACE }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/tc39/proposal-observable */ function observable() { const outerSubscribe = subscribe; return { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe(observer: any) { if (typeof observer !== 'object' || observer === null) { throw new TypeError('OBSERVER1'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); const unsubscribe = outerSubscribe(observeState); return { unsubscribe }; }, [$$observable]() { return this; }, }; } function isRehydrated(): boolean { return disablePersist || cache.isRehydrated(); } function restore(): Promise<DataCache> { if (promiseRestore) { return promiseRestore; } promiseRestore = cache.restore(); return promiseRestore; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); restore() .then(() => dispatch({ type: REHYDRATE })) .catch((error) => dispatch({ type: REHYDRATE_ERROR, error })); return { dispatch, subscribe, getState, replaceReducer, restore, isRehydrated, [$$observable]: observable, }; } export default createStore;
the_stack
import * as classifierCache from "../../model/classifierCache"; export enum Language { TypeScript, EcmaScript5 } export function createTokenizationSupport(language:Language): monaco.languages.TokensProvider { var classifier = ts.createClassifier(), bracketTypeTable = language === Language.TypeScript ? tsBracketTypeTable : jsBracketTypeTable, tokenTypeTable = language === Language.TypeScript ? tsTokenTypeTable : jsTokenTypeTable; return { getInitialState: function() { return new State({ language, eolState: ts.EndOfLineState.None, inJsDocComment: false, lineNumber: 0, lineStartIndex: 0, }); }, tokenize: (line, state, filePath) => tokenize(bracketTypeTable, tokenTypeTable, classifier, <State> state, line, filePath) }; } class State implements monaco.languages.IState { /** * Adding a new thing here? * - add to ctor * - add to equals * - Fix other compile errors :) */ public language: Language; public eolState: ts.EndOfLineState; public inJsDocComment: boolean; public lineNumber: number; public lineStartIndex: number; constructor(config: { language: Language, eolState: ts.EndOfLineState, inJsDocComment: boolean, lineNumber: number, lineStartIndex: number }) { this.language = config.language; this.eolState = config.eolState; this.inJsDocComment = config.inJsDocComment; this.lineNumber = config.lineNumber; this.lineStartIndex = config.lineStartIndex; } public clone(): State { return new State(this); } public equals(other: monaco.languages.IState): boolean { if (other === this) { return true; } if (!other || !(other instanceof State)) { return false; } return this.eolState === other.eolState && this.inJsDocComment === other.inJsDocComment && this.lineNumber === other.lineNumber && this.lineStartIndex === other.lineStartIndex ; } } function tokenize(bracketTypeTable: { [i: number]: string }, tokenTypeTable: { [i: number]: string }, classifier: ts.Classifier, state: State, text: string, filePath?: string): monaco.languages.ILineTokens { // Create result early and fill in tokens var ret = { tokens: <monaco.languages.IToken[]>[], endState: new State({ language: state.language, eolState: ts.EndOfLineState.None, inJsDocComment: false, lineNumber: state.lineNumber + 1, lineStartIndex: state.lineStartIndex + text.length + 1, }) }; function appendFn(startIndex:number, type:string):void { if(ret.tokens.length === 0 || ret.tokens[ret.tokens.length - 1].scopes !== type) { ret.tokens.push({ startIndex: startIndex, scopes: type }); } } var isTypeScript = state.language === Language.TypeScript; if (isTypeScript) { // Note: we are still keeping the classiferCache in sync (from docCache) // But disabled using it here for pref + requirement to use it for hovers // WARNING: we might eventually use the js language to tokenize stuff like `hovers` // So probably only use this function for .ts files // Alternatively we could create a new language 'jshover' and use that for hovers etc return tokenizeTs(state, ret, text, filePath); } if (!isTypeScript && checkSheBang(0, text, appendFn)) { return ret; } var result = classifier.getClassificationsForLine(text, state.eolState, true), offset = 0; ret.endState.eolState = result.finalLexState; ret.endState.inJsDocComment = result.finalLexState === ts.EndOfLineState.InMultiLineCommentTrivia && (state.inJsDocComment || /\/\*\*.*$/.test(text)); for (let entry of result.entries) { var type: string; if (entry.classification === ts.TokenClass.Punctuation) { // punctions: check for brackets: (){}[] var ch = text.charCodeAt(offset); type = bracketTypeTable[ch] || tokenTypeTable[entry.classification]; appendFn(offset, type); } else if (entry.classification === ts.TokenClass.Comment) { // comments: check for JSDoc, block, and line comments if (ret.endState.inJsDocComment || /\/\*\*.*\*\//.test(text.substr(offset, entry.length))) { appendFn(offset, isTypeScript ? 'comment.doc.ts' : 'comment.doc.js'); } else { appendFn(offset, isTypeScript ? 'comment.ts' : 'comment.js'); } } else { // everything else appendFn(offset, tokenTypeTable[entry.classification] || ''); } offset += entry.length; } return ret; } interface INumberStringDictionary { [idx: number]: string; } var tsBracketTypeTable:INumberStringDictionary = Object.create(null); tsBracketTypeTable['('.charCodeAt(0)] = 'delimiter.parenthesis.ts'; tsBracketTypeTable[')'.charCodeAt(0)] = 'delimiter.parenthesis.ts'; tsBracketTypeTable['{'.charCodeAt(0)] = 'delimiter.bracket.ts'; tsBracketTypeTable['}'.charCodeAt(0)] = 'delimiter.bracket.ts'; tsBracketTypeTable['['.charCodeAt(0)] = 'delimiter.array.ts'; tsBracketTypeTable[']'.charCodeAt(0)] = 'delimiter.array.ts'; var tsTokenTypeTable:INumberStringDictionary = Object.create(null); tsTokenTypeTable[ts.TokenClass.Identifier] = 'identifier.ts'; tsTokenTypeTable[ts.TokenClass.Keyword] = 'keyword.ts'; tsTokenTypeTable[ts.TokenClass.Operator] = 'delimiter.ts'; tsTokenTypeTable[ts.TokenClass.Punctuation] = 'delimiter.ts'; tsTokenTypeTable[ts.TokenClass.NumberLiteral] = 'number.ts'; tsTokenTypeTable[ts.TokenClass.RegExpLiteral] = 'regexp.ts'; tsTokenTypeTable[ts.TokenClass.StringLiteral] = 'string.ts'; var jsBracketTypeTable:INumberStringDictionary = Object.create(null); jsBracketTypeTable['('.charCodeAt(0)] = 'delimiter.parenthesis.js'; jsBracketTypeTable[')'.charCodeAt(0)] = 'delimiter.parenthesis.js'; jsBracketTypeTable['{'.charCodeAt(0)] = 'delimiter.bracket.js'; jsBracketTypeTable['}'.charCodeAt(0)] = 'delimiter.bracket.js'; jsBracketTypeTable['['.charCodeAt(0)] = 'delimiter.array.js'; jsBracketTypeTable[']'.charCodeAt(0)] = 'delimiter.array.js'; var jsTokenTypeTable:INumberStringDictionary = Object.create(null); jsTokenTypeTable[ts.TokenClass.Identifier] = 'identifier.js'; jsTokenTypeTable[ts.TokenClass.Keyword] = 'keyword.js'; jsTokenTypeTable[ts.TokenClass.Operator] = 'delimiter.js'; jsTokenTypeTable[ts.TokenClass.Punctuation] = 'delimiter.js'; jsTokenTypeTable[ts.TokenClass.NumberLiteral] = 'number.js'; jsTokenTypeTable[ts.TokenClass.RegExpLiteral] = 'regexp.js'; jsTokenTypeTable[ts.TokenClass.StringLiteral] = 'string.js'; function checkSheBang(deltaOffset: number, line: string, appendFn: (startIndex: number, type: string) => void): boolean { if (line.indexOf('#!') === 0) { appendFn(deltaOffset, 'comment.shebang'); return true; } } function tokenizeTs(state: State, ret: {tokens: monaco.languages.IToken[], endState: State}, text: string, filePath: string) : monaco.languages.ILineTokens { const classifications = classifierCache.getClassificationsForLine(filePath, state.lineStartIndex, text); // DEBUG classifications // console.log('%c'+text,"font-size: 20px"); // console.table(classifications.map(c=> ({ str: c.string, cls: c.classificationTypeName,startInLine:c.startInLine }))); let startIndex = 0; const lineHasJSX = filePath.endsWith('x') && classifications.some(classification => { return classification.classificationType === ts.ClassificationType.jsxOpenTagName || classification.classificationType === ts.ClassificationType.jsxCloseTagName || classification.classificationType === ts.ClassificationType.jsxSelfClosingTagName || classification.classificationType === ts.ClassificationType.jsxText || classification.classificationType === ts.ClassificationType.jsxAttribute }); classifications.forEach((classifiedSpan) => { ret.tokens.push({ startIndex, scopes: getStyleForToken(classifiedSpan, text, startIndex, lineHasJSX) + '.ts' }) startIndex = startIndex + classifiedSpan.string.length }); return ret; } function getStyleForToken( token: classifierCache.ClassifiedSpan, /** Full contents of the line */ line: string, /** Start position for this token in the line */ startIndex: number, /** Only relevant for a `.tsx` file */ lineHasJSX: boolean ): string { var ClassificationType = ts.ClassificationType; let nextStr: string; // setup only if needed const loadNextStr = () => nextStr || (nextStr = line.substr(startIndex + token.string.length).replace(/\s+/g, '')); /** used for both variable and its puncutation */ const decoratorClassification = 'punctuation.tag'; switch (token.classificationType) { case ClassificationType.numericLiteral: return 'constant.numeric'; case ClassificationType.stringLiteral: return 'string'; case ClassificationType.regularExpressionLiteral: return 'constant.character'; case ClassificationType.operator: return 'keyword.operator'; // The atom grammar does keyword+operator and I actually like that case ClassificationType.comment: return 'comment'; case ClassificationType.className: case ClassificationType.enumName: case ClassificationType.interfaceName: case ClassificationType.moduleName: case ClassificationType.typeParameterName: case ClassificationType.typeAliasName: return 'variable-2'; case ClassificationType.keyword: switch (token.string) { case 'string': case 'number': case 'void': case 'bool': case 'boolean': return 'variable-2'; case 'static': case 'public': case 'private': case 'protected': case 'get': case 'set': return 'qualifier'; case 'function': case 'var': case 'let': case 'const': return 'qualifier'; case 'this': return 'constant.language'; default: return 'keyword'; } case ClassificationType.identifier: let lastToken = line.substr(0, startIndex).trim(); if (token.string === "undefined") { return 'keyword'; } else if (lastToken.endsWith('@')){ return decoratorClassification; } else if ( lastToken.endsWith('type') || lastToken.endsWith('extends') ) { return 'variable-2'; } else if ( lastToken.endsWith('let') || lastToken.endsWith('const') || lastToken.endsWith('var')) { return 'def'; } else if ( ( (loadNextStr()).startsWith('(') || nextStr.startsWith('=(') || nextStr.startsWith('=function') ) && ( !lastToken.endsWith('.') ) ) { return 'entity.name.function'; } // // Show types (indentifiers in PascalCase) as variable-2, other types (camelCase) as variable // else if (token.string.charAt(0).toLowerCase() !== token.string.charAt(0) // && (lastToken.endsWith(':') || lastToken.endsWith('.')) /* :foo.Bar or :Foo */) { // return 'variable-2'; // } else { return 'variable'; } case ClassificationType.parameterName: return 'variable.parameter'; case ClassificationType.punctuation: // Only get punctuation for JSX. Otherwise these would be operator if (lineHasJSX && (token.string == '>' || token.string == '<' || token.string == '>')) { // NOTE: would be good to get `meta.begin` vs. `meta.end` for tag matching return 'punctuation.definition.meta.tag'; // A nice blue color } if (token.string == '/') { return 'punctuation.definition.meta.end.tag'; // A nice blue color } if (token.string === '{' || token.string === '}') return 'delimiter.bracket'; if (token.string === '(' || token.string === ')') return 'delimiter.parenthesis'; if (token.string === '=>') return 'operator.keyword'; if (token.string === '@') return decoratorClassification; return 'bracket'; case ClassificationType.jsxOpenTagName: case ClassificationType.jsxCloseTagName: case ClassificationType.jsxSelfClosingTagName: return 'entity.name.tag'; case ClassificationType.jsxAttribute: return 'entity.other.attribute-name'; case ClassificationType.jsxAttributeStringLiteralValue: return 'string'; case ClassificationType.whiteSpace: default: return null; } }
the_stack
import m from 'mithril' import { commonNotification } from '../api' import models from '../models' import ProjectEditSaveBtn from '../c/project-edit-save-btn' import { useEffect, useRef, useState, withHooks } from 'mithril-hooks' import { HTMLRenderer } from '../shared/components/html-renderer' import projectVM from '../vms/project-vm' import subscriptionVM from '../vms/subscription-vm' import rewardVM from '../vms/reward-vm' import userVM from '../vms/user-vm' import { ProjectDetails, ProjectDetailsUser, RewardDetails, Subscription, SubscriptionPayment, UserDetails } from '../entities' import { getUserDetailsWithUserId } from '../shared/services/user/get-updated-current-user' import { If } from '../shared/components/if' import { ObjectTree } from '../shared/components/object-tree' import _ from 'underscore' import { cleanUndefinedFromObject } from '../utils/clean-undefined-from-object' import { AdminNotificationsList } from './admin-notifications-list' import { Loader } from '../shared/components/loader' export default withHooks(_AdminNotifications) async function loadTemplates() { const templates = commonNotification.paginationVM(models.notificationTemplates, 'label.asc') await templates.firstPage({}) return templates.collection() } function _AdminNotifications() { const [templates, setTemplates] = useState<NotificationTemplate[]>([]) const [errorMessage, setErrorMessage] = useState('') const [selectedNotification, setSelectedNotification] = useState<NotificationTemplate | undefined>() const [isSaving, setIsSaving] = useState(false) const [isLoadingTemplates, setIsLoadingTemplates] = useState(true) const [subject, setSubject] = useState('') const [body, setBody] = useState('') function onSelectTemplate(notificationTemplate?: NotificationTemplate) { setSelectedNotification(notificationTemplate) if (notificationTemplate) { setSubject(notificationTemplate.subject || notificationTemplate.default_subject) setBody(notificationTemplate.template || notificationTemplate.default_template) } } async function updateSelectedTemplate(event: Event) { try { setIsSaving(true) event?.preventDefault() const updateData = { data: { label: selectedNotification.label, subject, template: body, }, } await models.commonNotificationTemplate.postWithToken(updateData, null, {}) await loadTemplatesList() } catch (error) { setErrorMessage(`Failed to save template: ${error.message}.`) } finally { setIsSaving(false) } } async function loadTemplatesList() { try { setIsLoadingTemplates(true) setTemplates(await loadTemplates()) } catch (error) { setErrorMessage(`Failed to load templates: ${error.message}.`) } finally { setIsLoadingTemplates(false) } } useEffect(() => { loadTemplatesList() }, []) if (isLoadingTemplates) return <Loader /> return ( <> <div id="notifications-admin"> <div class="section"> <div class="w-container"> <div class="w-row"> <div class="w-col w-col-3"></div> <div class="w-col w-col-6"> <div class="w-form"> <NotificationSelect list={templates} onSelect={onSelectTemplate} /> </div> </div> <div class="w-col w-col-3"></div> </div> </div> </div> <div class="divider"></div> <AdminNotificationsList templates={templates}/> <div class="divider"></div> {selectedNotification && ( <> <NotificationTemplateEditor label={selectedNotification.label} subject={subject} body={body} onChangeTemplateSubject={setSubject} onChangeTemplateBody={setBody} /> <footer style="height: 100px"> <ProjectEditSaveBtn loading={() => isSaving} onSubmit={updateSelectedTemplate} hideMarginLeft={true} /> </footer> </> )} </div> </> ) } export type NotificationTemplate = { created_at: string default_subject: string default_template: string label: string subject: string template: string } type NotificationSelectProps = { list: NotificationTemplate[] onSelect(item?: NotificationTemplate): void } const NotificationSelect = withHooks<NotificationSelectProps>(_NotificationSelect) function _NotificationSelect(props: NotificationSelectProps) { const { list, onSelect } = props return ( <form> <div class="fontsize-larger u-marginbottom-10 u-text-center">Notificações</div> <select oninput={event => onSelect(findNotificationByLabel(list, event.target.value))} class="medium text-field w-select"> <option value={undefined}>Selectione uma notificação</option> {list.map(item => ( <option value={item.label}>{item.label}</option> ))} </select> </form> ) } function findNotificationByLabel(list: NotificationTemplate[], label: string) { return list.find(item => item.label === label) } type NotificationTemplateEditorProps = { label: string subject: string body: string onChangeTemplateSubject(subjectTemplate: string): void onChangeTemplateBody(bodyTemplate: string): void } const NotificationTemplateEditor = withHooks<NotificationTemplateEditorProps>(_NotificationTemplateEditor) function _NotificationTemplateEditor(props: NotificationTemplateEditorProps) { const { label, subject, body, onChangeTemplateSubject, onChangeTemplateBody } = props if (!label || !subject || !body) return <Loader /> const [variables, setVariables] = useState<LoadVariablesResult>() const [showIdFields, setShowIdFields] = useState(false) return ( <div class="u-marginbottom-80 bg-gray section"> <div class="w-container"> <div class="w-row"> <div class="w-col w-col-6"> <div class="fontsize-base fontweight-semibold u-marginbottom-20 u-text-center"> <span class="fa fa-code"></span> HTML </div> <div class="w-form"> <form> <div class="u-marginbottom-20 w-row"> <div class="w-col w-col-2"> <label class="fontsize-small">Label</label> </div> <div class="w-col w-col-10"> <div class="fontsize-small">{label}</div> </div> </div> <div class="w-row"> <div class="w-col w-col-2"> <label class="fontsize-small">Subject</label> </div> <div class="w-col w-col-10"> <input type="text" class="positive text-field w-input" value={subject} oninput={e => onChangeTemplateSubject(e.target.value)} /> </div> </div> <label class="fontsize-small"> Content <a class="alt-link u-right" onclick={e => { e.preventDefault() setShowIdFields(!showIdFields) }} > Ver variáveis </a> <If condition={showIdFields}> <VariablesLoader objectRefTree={{ project_id: ['project', 'project_owner'], user_id: ['user'], subscription_id: ['subscription'], reward_id: ['reward'], payment_id: ['payment'], }} variablesIdNames={['project_id', 'subscription_id', 'reward_id', 'payment_id', 'user_id']} onLoad={setVariables} /> </If> </label> <textarea rows="20" class="positive text-field w-input" value={body} oninput={e => onChangeTemplateBody(e.target.value)} ></textarea> </form> </div> </div> <div class="w-col w-col-6"> <div class="fontsize-base fontweight-semibold u-marginbottom-20 u-text-center"> <span class="fa fa-eye"></span> Visualização </div> <HTMLRenderer html={subject} variables={variables} /> <HTMLRenderer html={body} variables={variables} /> </div> </div> </div> </div> ) } const VariablesLoader = withHooks<VariablesLoaderProps>(_VariablesLoader) type VariablesLoaderProps = { variablesIdNames: string[] objectRefTree: { [key: string]: string[] } onLoad(result: LoadVariablesResult): void } function _VariablesLoader(props: VariablesLoaderProps) { const { objectRefTree, variablesIdNames, onLoad } = props const idsMap = useRef<Map<string, string>>() const [variables, setVariables] = useState<LoadVariablesResult>({}) const [variablesMap, setVariablesMap] = useState() useEffect(() => { idsMap.current = new Map<string, string>() for (const idName of variablesIdNames) { idsMap.current.set(idName, '') } }, []) async function loadAllVariables(e: Event, id?: string) { e.preventDefault() e.stopPropagation() try { const idsObject = id ? { [id]: idsMap.current.get(id) } : variablesIdNames.reduce((memo, idName) => ({ ...memo, [idName]: idsMap.current.get(idName) }), {}) const response = await loadBasicVariables(idsObject) const result = cleanUndefinedFromObject(response) const nextSetVariables = { ...variables, ...result } onLoad(nextSetVariables) setVariables(nextSetVariables) } catch (error) { console.log('Error', error) } } return ( <div class='w-row'> {idsMap.current && variablesIdNames.map(idName => ( <div class='w-row'> <div class='w-row u-marginbottom-5'> <div class='w-col w-col-10'> <input class="positive text-field w-input" placeholder={idName} type="text" value={idsMap.current.get(idName)} oninput={e => idsMap.current.set(idName, e.target.value)} /> </div> <div class='w-col w-col-2'> <button class='btn btn-medium' onclick={e => loadAllVariables(e, idName)}> <i class='fa fa-refresh'></i> </button> </div> </div> <div class='w-row'> {objectRefTree[idName].map(mapField => ( <ObjectTree path={mapField} root={variables[mapField] } /> ))} </div> </div> ))} <div class='w-row'> <button class='btn btn-medium u-marginbottom-20' onclick={loadAllVariables}> Recarregar todas as variáveis </button> </div> </div> ) } type LoadVariablesConfigIds = { [id: string]: string } type LoadVariablesResult = { project?: ProjectDetails project_owner?: ProjectDetailsUser subscription?: Subscription reward?: RewardDetails payment?: SubscriptionPayment user?: UserDetails } async function loadBasicVariables(config: LoadVariablesConfigIds): Promise<LoadVariablesResult> { const { project_id, subscription_id, reward_id, payment_id, user_id } = config // from project id let project let project_owner if (project_id) { try { project = await projectVM.fetchProject(project_id, false).then(_.first) project_owner = project?.user } catch (error) { // TODO: set an error message to the screen console.error('error', error) } } // from subscription id let subscription if (subscription_id) { try { subscription = await subscriptionVM.getSubscription(subscription_id).then(_.first) } catch (error) { // TODO: set an error message to the screen console.error('error', error) } } // from reward id let reward if (reward_id) { try { reward = await rewardVM.rewardLoader(reward_id).then(_.first) } catch (error) { // TODO: set an error message to the screen console.error('error', error) } } // from payment id let payment if (payment_id) { try { payment = await subscriptionVM.getPayment(payment_id).then(_.first) } catch (error) { // TODO: set an error message to the screen console.error('error', error) } } // from user id let user if (user_id) { try { user = await getUserDetailsWithUserId(Number(user_id)).then(user => user['_user']) } catch (error) { // TODO: set an error message to the screen console.error('error', error) } } return { project, project_owner, subscription, payment, reward, user, } }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview Code that handles propagation of refresh events to targets. */ namespace VRS { /** * The settings that can be passed when creating a new instance of RefreshTarget */ export interface RefreshTarget_Settings { /** * The element of the target. */ targetJQ: JQuery; /** * The method to call when the target needs to be refreshed. */ onRefresh: () => void; /** * The object to set 'this' to when calling onRefresh. */ onRefreshThis?: Object; } export class RefreshTarget { // Kept as public fields for backwards compatibility targetJQ: JQuery; onRefresh: () => void; onRefreshThis: Object; constructor(settings: RefreshTarget_Settings) { this.targetJQ = settings.targetJQ; this.onRefresh = settings.onRefresh; this.onRefreshThis = settings.onRefreshThis || window; } /** * Ensures that any resources held by the object are released. */ dispose() { this.targetJQ = null; this.onRefresh = null; this.onRefreshThis = null; } /** * Calls onRefresh with the appropriate this parameter. */ callOnRefresh = function() { this.onRefresh.call(this.onRefreshThis); } } /** * The settings that need to be passed in when creating a new instance of RefreshOwner */ export interface RefreshOwner_Settings { /** * The element of the owner. */ ownerJQ: JQuery; /** * The array of targets to initialise with. */ targets?: RefreshTarget[]; } /** * Describes the owner of a list of targets. More than one owner could potentially own a target, and owners can also * be targets of something else. */ export class RefreshOwner { private _Targets: RefreshTarget[]; // Kept as public field for backwards compatibility ownerJQ: JQuery; constructor(settings: RefreshOwner_Settings) { this.ownerJQ = settings.ownerJQ; this._Targets = settings.targets || []; } /** * Ensures that any resources held by the object are released. */ dispose() { this.ownerJQ = null; this._Targets = []; } /** * Causes all of the targets to be refreshed. */ refreshTargets() { var length = this._Targets.length; for(var i = 0;i < length;++i) { this._Targets[i].callOnRefresh(); } } /** * Returns the VRS.RefreshTarget for the jQuery element passed across or null if no such target exists. */ getTarget(elementJQ: JQuery) : RefreshTarget { var index = this.getTargetIndex(elementJQ); return index === -1 ? null : this._Targets[index]; }; /** * Returns the VRS.RefreshTarget for the jQuery element passed across or -1 if no such target exists. */ getTargetIndex(elementJQ: JQuery) : number { var result = -1; var length = this._Targets.length; for(var i = 0;i < length;++i) { var target = this._Targets[i]; if(target.targetJQ.is(elementJQ)) { result = i; break; } } return result; } /** * Adds the target to the list of known targets for the owner. */ addTarget(target: RefreshTarget) { if(this.getTargetIndex(target.targetJQ) === -1) { this._Targets.push(target); } } /** * Removes the target from the list of known targets for the owner. */ removeTarget(target: RefreshTarget) { var index = this.getTargetIndex(target.targetJQ); if(index !== -1) this._Targets.splice(index, 1); } /** * Removes all targets from the owner. */ removeAllTargets() { this._Targets = []; } } /** * The object that can record maintain lists of targets and owners and ensure that the correct targets are told to * refresh themselves when an owner indicates that they need to do so. */ export class RefreshManager { /** * An array of every targets known to the manager. */ private _Targets: RefreshTarget[] = []; /** * An array of every owner known to the manager. */ private _Owners: RefreshOwner[] = []; /** * Registers a target with the manager. It is attached to any existing owners that are a parent of the targetJQ * and such any new owner be registered in the future, and the target is a child of the new owner, it automatically * gets registered with them. * @param {jQuery} elementJQ The jQuery element for the target. * @param {function()} onRefresh The function to call when the target is to be refreshed. * @param {*} [onRefreshThis] The object to use for 'this' when calling onRefresh. */ registerTarget(elementJQ: JQuery, onRefresh: () => void, onRefreshThis?: Object) { if(this.getTargetIndex(elementJQ) === -1) { var target = new VRS.RefreshTarget({ targetJQ: elementJQ, onRefresh: onRefresh, onRefreshThis: onRefreshThis }); this._Targets.push(target); var allOwners = this.buildOwners(elementJQ); var length = allOwners.length; for(var i = 0;i < length;++i) { var owner = allOwners[i]; owner.addTarget(target); // It is safe to call this even if the target is already registered. } } } /** * Removes the registration for a target. The onRefresh method will no longer be called for any owners that the * target has as a parent. */ unregisterTarget(elementJQ: JQuery) { var index = this.getTargetIndex(elementJQ); if(index !== -1) { var target = this._Targets[index]; var length = this._Owners.length; for(var i = 0;i < length;++i) { this._Owners[i].removeTarget(target); // It is safe to call this even if the target is not registered to the owner. } this._Targets.splice(index, 1); target.dispose(); } } /** * Registers an element as an owner. Any existing targets that have this element as a parent are automatically * registered as targets for the owner, and any future targets registered that have this element as the parent * will automatically become attached to the owner. */ registerOwner(elementJQ: JQuery) { if(this.getOwnerIndex(elementJQ) === -1) { var targets = []; var targetLength = this._Targets.length; for(var i = 0;i < targetLength;++i) { var target = this._Targets[i]; target.targetJQ.parents().each(function(idx, parentElement) { var continueEach = true; if(elementJQ.is(parentElement)) { targets.push(target); continueEach = false; } return continueEach; }); } var owner = new VRS.RefreshOwner({ ownerJQ: elementJQ, targets: targets }); this._Owners.push(owner); } } /** * Removes the registration of an owner. Any targets attached to the owner will no longer be attached and the * owner is forgotten about. */ unregisterOwner(elementJQ: JQuery) { var index = this.getOwnerIndex(elementJQ); if(index !== -1) { var owner = this._Owners[index]; owner.dispose(); this._Owners.splice(index, 1); } } /** * Forces a complete rebuild of all of the relationships between existing targets and owners. This should be * called whenever something moves DOM elements in such a way that existing parent/child relationships could be * distrupted. */ rebuildRelationships() { var length; var i; length = this._Owners.length; for(i = 0;i < length;++i) { this._Owners[i].removeAllTargets(); } length = this._Targets.length; for(i = 0;i < length;++i) { var target = this._Targets[i]; var owners = this.buildOwners(target.targetJQ); var ownersLength = owners.length; for(var j = 0;j < ownersLength;++j) { owners[j].addTarget(target); } } } /** * Refreshes all of the targets associated with an owner. */ refreshTargets(ownerJQ: JQuery) { var index = this.getOwnerIndex(ownerJQ); if(index !== -1) this._Owners[index].refreshTargets(); } /** * Returns the VRS.RefreshTarget for the jQuery element passed across or -1 if no such target exists. */ private getTargetIndex(elementJQ: JQuery) : number { var result = -1; var length = this._Targets.length; for(var i = 0;i < length;++i) { var target = this._Targets[i]; if(target.targetJQ.is(elementJQ)) { result = i; break; } } return result; } /** * Returns the VRS.RefreshOwner for the jQuery element passed across or -1 if no such owner exists. */ private getOwnerIndex(elementJQ: JQuery) : number { var result = -1; var length = this._Owners.length; for(var i = 0;i < length;++i) { var owner = this._Owners[i]; if(owner.ownerJQ.is(elementJQ)) { result = i; break; } } return result; } /** * Examines all of the parents of the element passed across to build a list of registered VRS.RefreshOwner objects. * It does not take into account the targets already registered against the owner, the targets held by an owner * object may or may not include the element passed across. */ private buildOwners(elementJQ: JQuery) : RefreshOwner[] { var result: RefreshOwner[] = []; var parents = elementJQ.parents(); var ownerLength = this._Owners.length; for(var i = 0;i < ownerLength;++i) { var owner = this._Owners[i]; parents.each(function(/** number */idx, /** HTMLElement */ parentElement) { if(owner.ownerJQ.is(parentElement)) result.push(owner); }); } return result; } } /* * Prebuilts */ export var refreshManager = new VRS.RefreshManager(); }
the_stack
import * as d3 from "d3"; import { assert } from "chai"; import * as Plottable from "../../src"; import { BarOrientation } from "../../src/plots/barPlot"; import * as TestMethods from "../testMethods"; describe("Plots", () => { describe("Vertical Stacked Bar Plot", () => { describe("rendering using positive data", () => { let div: d3.Selection<HTMLDivElement, any, any, any>; let xScale: Plottable.Scales.Category; let yScale: Plottable.Scales.Linear; let stackedBarPlot: Plottable.Plots.StackedBar<string, number>; beforeEach(() => { div = TestMethods.generateDiv(); xScale = new Plottable.Scales.Category(); yScale = new Plottable.Scales.Linear(); const data1 = [ {x: "A", y: 1}, {x: "B", y: 2}, ]; const data2 = [ {x: "A", y: 2}, {x: "B", y: 1}, ]; const dataset1 = new Plottable.Dataset(data1); const dataset2 = new Plottable.Dataset(data2); stackedBarPlot = new Plottable.Plots.StackedBar<string, number>(); stackedBarPlot.addDataset(dataset1); stackedBarPlot.addDataset(dataset2); stackedBarPlot.x((d) => d.x, xScale); stackedBarPlot.y((d) => d.y, yScale); stackedBarPlot.renderTo(div); }); afterEach(() => { stackedBarPlot.destroy(); div.remove(); }); it("renders rects offset by previous values", () => { const bars = stackedBarPlot.content().selectAll<Element, any>("rect"); const dataLength = stackedBarPlot.datasets()[0].data().length; const dataCount = stackedBarPlot.datasets().length * dataLength; assert.strictEqual(bars.size(), dataCount, "same number of bars as data"); const calculateStackedYs = (yAccessor: Plottable.IAccessor<number>) => { const stackedYDataArray: number[][] = []; stackedBarPlot.datasets().forEach((dataset, datasetIndex) => { const yData = dataset.data().map((d, i) => yAccessor(d, i, dataset)); if (datasetIndex === 0) { stackedYDataArray[datasetIndex] = yData; return; } stackedYDataArray[datasetIndex] = dataset.data().map((d, i) => { return yData[i] + stackedYDataArray[datasetIndex - 1][i]; }); }); return stackedYDataArray; }; const stackedYs = calculateStackedYs((d) => d.y); bars.each(function(d, i) { const bar = d3.select(this); const datasetIndex = Math.floor(i / dataLength); const datumIndex = i % dataLength; assert.closeTo(TestMethods.numAttr(bar, "y"), yScale.scale(stackedYs[datasetIndex][datumIndex]), window.Pixel_CloseTo_Requirement, "y attribute offset set correctly"); }); }); // HACKHACK #2795: correct off-bar label logic to be implemented it("doesn't show any off-bar labels", () => { stackedBarPlot.labelsEnabled(true); yScale.domain([0, 30]); const offBarLabels = stackedBarPlot.content().selectAll<Element, any>(".off-bar-label"); assert.operator(offBarLabels.size(), ">", 0, "some off-bar labels are drawn"); offBarLabels.each(function(d, i) { assert.isTrue(d3.select(this).style("visibility") === "hidden", `off-bar label ${i} is hidden`); }); }); it("shows stacked bar labels", () => { stackedBarPlot.labelsEnabled(true); yScale.domain([0, 30]); const stackedBarLabels = stackedBarPlot.content().selectAll<Element, any>(".stacked-bar-label"); assert.strictEqual(stackedBarLabels.size(), 2); const text: string[] = []; stackedBarLabels.each(function (d) { text.push(d3.select(this).text()); }); assert.deepEqual(["3", "3"], text); }); it("shows stacked bar labels for date axes", () => { // remove existing stacked bar plot stackedBarPlot.destroy(); const dateString1 = "2013-09-02T00:00:00.000Z"; const dateString2 = "2013-09-03T00:00:00.000Z"; const data1 = [ { x: new Date(dateString1) , y: 1 }, { x: new Date(dateString2), y: 2 }, ]; const data2 = [ { x: new Date(dateString1) , y: 2 }, { x: new Date(dateString2), y: 1 }, ]; const dataset1 = new Plottable.Dataset(data1); const dataset2 = new Plottable.Dataset(data2); const stackedBar = new Plottable.Plots.StackedBar<Date, number>(); stackedBar.addDataset(dataset1); stackedBar.addDataset(dataset2); const xScale = new Plottable.Scales.Time(); stackedBar.x((d) => d.x, xScale); stackedBar.y((d) => d.y, yScale); stackedBar.renderTo(div); stackedBar.labelsEnabled(true); yScale.domain([0, 30]); const stackedBarLabels = stackedBar.content().selectAll<Element, any>(".stacked-bar-label"); assert.strictEqual(stackedBarLabels.size(), 2); const text: string[] = []; stackedBarLabels.each(function (d) { text.push(d3.select(this).text()); }); assert.deepEqual(["3", "3"], text); stackedBar.destroy(); }); it("doesn't show stacked bar labels when columns are too narrow", () => { stackedBarPlot.labelsEnabled(true); xScale.range([0, 20]); // HACKHACK send a scale update to update the barPixelThickness xScale.domain(xScale.domain()); // HACKHACK explicitly re-render with the new barPixelThickness stackedBarPlot.render(); const stackedBarLabels = stackedBarPlot.content().selectAll<Element, any>(".stacked-bar-label"); assert.strictEqual(stackedBarLabels.size(), 0); }); it("considers lying within a bar's y-range to mean it is closest", () => { const d0 = stackedBarPlot.datasets()[0].data()[0]; const d1 = stackedBarPlot.datasets()[1].data()[0]; let closestEntity = stackedBarPlot.entityNearest({ x: 0, y: yScale.scale(d0.y) + 1 }); assert.strictEqual(closestEntity.datum, d0, "bottom bar is closest when within its range"); closestEntity = stackedBarPlot.entityNearest({ x: 0, y: yScale.scale(d0.y) - 1 }); assert.strictEqual(closestEntity.datum, d1, "top bar is closest when within its range"); }); }); describe("rendering using negative data", () => { let div: d3.Selection<HTMLDivElement, any, any, any>; let xScale: Plottable.Scales.Category; let yScale: Plottable.Scales.Linear; let stackedBarPlot: Plottable.Plots.StackedBar<string, number>; beforeEach(() => { div = TestMethods.generateDiv(); xScale = new Plottable.Scales.Category(); yScale = new Plottable.Scales.Linear(); const data1 = [ {x: "A", y: -1}, {x: "B", y: -2}, ]; const data2 = [ {x: "A", y: -2}, {x: "B", y: -1}, ]; const dataset1 = new Plottable.Dataset(data1); const dataset2 = new Plottable.Dataset(data2); stackedBarPlot = new Plottable.Plots.StackedBar<string, number>(); stackedBarPlot.addDataset(dataset1); stackedBarPlot.addDataset(dataset2); stackedBarPlot.x((d) => d.x, xScale); stackedBarPlot.y((d) => d.y, yScale); stackedBarPlot.renderTo(div); }); afterEach(() => { stackedBarPlot.destroy(); div.remove(); }); it("shows stacked bar labels", () => { yScale.domain([3, -3]); stackedBarPlot.labelsEnabled(true); const stackedBarLabels = stackedBarPlot.content().selectAll<Element, any>(".stacked-bar-label"); assert.strictEqual(stackedBarLabels.size(), 2); const text: string[] = []; stackedBarLabels.each(function (d) { text.push(d3.select(this).text()); }); assert.deepEqual(["-3", "-3"], text); }); it("doesn't show stacked bar labels when columns are too narrow", () => { stackedBarPlot.labelsEnabled(true); xScale.range([0, 40]); // HACKHACK send a scale update to update the barPixelThickness xScale.domain(xScale.domain()); // HACKHACK explicitly re-render to cause the barPixelThickness stackedBarPlot.render(); const stackedBarLabels = stackedBarPlot.content().selectAll<Element, any>(".stacked-bar-label"); assert.strictEqual(stackedBarLabels.size(), 0); }); it("renders rects offset by previous values", () => { const bars = stackedBarPlot.content().selectAll<Element, any>("rect"); const dataLength = stackedBarPlot.datasets()[0].data().length; const dataCount = stackedBarPlot.datasets().length * dataLength; assert.strictEqual(bars.size(), dataCount, "same number of bars as data"); const calculateStackedYs = (yAccessor: Plottable.IAccessor<number>) => { const stackedYDataArray: number[][] = []; stackedBarPlot.datasets().forEach((dataset, datasetIndex) => { const yData = dataset.data().map((d, i) => yAccessor(d, i, dataset)); if (datasetIndex === 0) { stackedYDataArray[datasetIndex] = dataset.data().map(() => 0); } stackedYDataArray[datasetIndex + 1] = dataset.data().map((d, i) => { return yData[i] + stackedYDataArray[datasetIndex][i]; }); }); return stackedYDataArray; }; const stackedYs = calculateStackedYs((d) => d.y); bars.each(function(d, i) { const bar = d3.select(this); const datasetIndex = Math.floor(i / dataLength); const datumIndex = i % dataLength; assert.closeTo(TestMethods.numAttr(bar, "y"), yScale.scale(stackedYs[datasetIndex][datumIndex]), window.Pixel_CloseTo_Requirement, "y attribute offset set correctly"); }); }); }); describe("non-overlapping datasets", () => { let div: d3.Selection<HTMLDivElement, any, any, any>; let xScale: Plottable.Scales.Category; let stackedBarPlot: Plottable.Plots.StackedBar<string, number>; beforeEach(() => { div = TestMethods.generateDiv(); xScale = new Plottable.Scales.Category(); const yScale = new Plottable.Scales.Linear(); const data1 = [ {x: "A", y: 1}, {x: "B", y: 2}, {x: "C", y: 1}, ]; const data2 = [ {x: "A", y: 2}, {x: "B", y: 3}, ]; const data3 = [ {x: "B", y: 1}, {x: "C", y: 7}, ]; stackedBarPlot = new Plottable.Plots.StackedBar<string, number>(); stackedBarPlot.addDataset(new Plottable.Dataset(data1)); stackedBarPlot.addDataset(new Plottable.Dataset(data2)); stackedBarPlot.addDataset(new Plottable.Dataset(data3)); stackedBarPlot.x((d) => d.x, xScale); stackedBarPlot.y((d) => d.y, yScale); stackedBarPlot.renderTo(div); }); afterEach(() => { stackedBarPlot.destroy(); div.remove(); }); it("draws bars at specified x location and stacks in order of datasets", () => { const bars = stackedBarPlot.content().selectAll<Element, any>("rect"); const datumCount = stackedBarPlot.datasets().reduce((prev, curr) => prev + curr.data().length, 0); assert.strictEqual(bars.size(), datumCount, "draws a bar for each datum"); const domain = xScale.domain(); domain.forEach((value) => { const domainBarPairs = d3.pairs(bars.filter((d) => d.x === value).nodes()); domainBarPairs.forEach((aBarPair) => { assert.closeTo(TestMethods.numAttr(d3.select(aBarPair[0]), "x"), TestMethods.numAttr(d3.select(aBarPair[1]), "x"), window.Pixel_CloseTo_Requirement, "bars at same x position"); assert.operator(TestMethods.numAttr(d3.select(aBarPair[0]), "y"), ">", TestMethods.numAttr(d3.select(aBarPair[1]), "y"), "previous dataset bar under second"); }); }); }); it("can be use reverse stacking order", () => { // change stacking order stackedBarPlot.stackingOrder("topdown"); const bars = stackedBarPlot.content().selectAll<Element, any>("rect"); const datumCount = stackedBarPlot.datasets().reduce((prev, curr) => prev + curr.data().length, 0); assert.strictEqual(bars.size(), datumCount, "draws a bar for each datum"); const domain = xScale.domain(); domain.forEach((value) => { const domainBarPairs = d3.pairs(bars.filter((d) => d.x === value).nodes()); domainBarPairs.forEach((aBarPair) => { assert.closeTo(TestMethods.numAttr(d3.select(aBarPair[0]), "x"), TestMethods.numAttr(d3.select(aBarPair[1]), "x"), window.Pixel_CloseTo_Requirement, "bars at same x position"); assert.operator(TestMethods.numAttr(d3.select(aBarPair[0]), "y"), "<", TestMethods.numAttr(d3.select(aBarPair[1]), "y"), "previous dataset bar above second"); }); }); }); }); describe("fail safe tests", () => { it("should default to 0 when calculating stack offsets with non-numbers", () => { const div = TestMethods.generateDiv(); const stringData = [ { x: "A", y: "s"}, ]; const nullData: {x: string, y: number}[] = [ { x: "A", y: null}, ]; const undefinedData: {x: string, y: number}[] = [ { x: "A", y: undefined}, ]; const naNData = [ { x: "A", y: NaN}, ]; const validData = [ { x: "A", y: 1}, ]; const xScale = new Plottable.Scales.Category(); const yScale = new Plottable.Scales.Linear(); const stackedBarPlot = new Plottable.Plots.StackedBar<string, number>(); const ds1 = new Plottable.Dataset(stringData); const ds2 = new Plottable.Dataset(nullData); const ds3 = new Plottable.Dataset(undefinedData); const ds4 = new Plottable.Dataset(naNData); const ds5 = new Plottable.Dataset(validData); stackedBarPlot.addDataset(ds1); stackedBarPlot.addDataset(ds2); stackedBarPlot.addDataset(ds3); stackedBarPlot.addDataset(ds4); stackedBarPlot.addDataset(ds5); stackedBarPlot.x((d: any) => d.x, xScale).y((d: any) => d.y, yScale); stackedBarPlot.renderTo(div); const validBar = stackedBarPlot.content().selectAll<Element, any>("rect").filter((d) => d.y === 1); assert.closeTo(TestMethods.numAttr(validBar, "y"), yScale.scale(1), window.Pixel_CloseTo_Requirement, "bar stacks from 0"); stackedBarPlot.destroy(); div.remove(); }); }); }); describe("Horizontal Stacked Bar Plot", () => { describe("rendering using positive data", () => { let div: d3.Selection<HTMLDivElement, any, any, any>; let xScale: Plottable.Scales.Linear; let yScale: Plottable.Scales.Category; let stackedBarPlot: Plottable.Plots.StackedBar<number, string>; beforeEach(() => { div = TestMethods.generateDiv(); xScale = new Plottable.Scales.Linear(); yScale = new Plottable.Scales.Category(); const data1 = [ {x: 1, y: "A"}, {x: 2, y: "B"}, ]; const data2 = [ {x: 2, y: "A"}, {x: 1, y: "B"}, ]; const dataset1 = new Plottable.Dataset(data1); const dataset2 = new Plottable.Dataset(data2); stackedBarPlot = new Plottable.Plots.StackedBar<number, string>(BarOrientation.horizontal); stackedBarPlot.addDataset(dataset1); stackedBarPlot.addDataset(dataset2); stackedBarPlot.x((d) => d.x, xScale); stackedBarPlot.y((d) => d.y, yScale); stackedBarPlot.renderTo(div); }); afterEach(() => { stackedBarPlot.destroy(); div.remove(); }); it("shows stacked bar labels", () => { xScale.domain([0, 30]); stackedBarPlot.labelsEnabled(true); const stackedBarLabels = stackedBarPlot.content().selectAll<Element, any>(".stacked-bar-label"); assert.strictEqual(stackedBarLabels.size(), 2); const text: string[] = []; stackedBarLabels.each(function (d) { text.push(d3.select(this).text()); }); assert.deepEqual(["3", "3"], text); }); it("doesn't show stacked bar labels when columns are too narrow", () => { stackedBarPlot.labelsEnabled(true); yScale.range([0, 40]); // HACKHACK send a scale update to update the barPixelThickness yScale.domain(yScale.domain()); // HACKHACK explicitly re-render to cause the barPixelThickness stackedBarPlot.render(); const stackedBarLabels = stackedBarPlot.content().selectAll<Element, any>(".stacked-bar-label"); assert.strictEqual(stackedBarLabels.size(), 0); }); it("renders rects offset by previous values", () => { const bars = stackedBarPlot.content().selectAll<Element, any>("rect"); const dataLength = stackedBarPlot.datasets()[0].data().length; const dataCount = stackedBarPlot.datasets().length * dataLength; assert.strictEqual(bars.size(), dataCount, "same number of bars as data"); const calculateStackedXs = (xAccessor: Plottable.IAccessor<number>) => { const stackedXDataArray: number[][] = []; stackedBarPlot.datasets().forEach((dataset, datasetIndex) => { const xData = dataset.data().map((d, i) => xAccessor(d, i, dataset)); if (datasetIndex === 0) { stackedXDataArray[datasetIndex] = dataset.data().map(() => 0); } stackedXDataArray[datasetIndex + 1] = dataset.data().map((d, i) => { return xData[i] + stackedXDataArray[datasetIndex][i]; }); }); return stackedXDataArray; }; const stackedXs = calculateStackedXs((d) => d.x); bars.each(function(d, i) { const bar = d3.select(this); const datasetIndex = Math.floor(i / dataLength); const datumIndex = i % dataLength; assert.closeTo(TestMethods.numAttr(bar, "x"), xScale.scale(stackedXs[datasetIndex][datumIndex]), window.Pixel_CloseTo_Requirement, "x attribute offset correctly"); }); }); // HACKHACK #2795: correct off-bar label logic to be implemented it("doesn't show any off-bar labels", () => { stackedBarPlot.labelsEnabled(true); xScale.domain([0, 90]); const offBarLabels = stackedBarPlot.content().selectAll<Element, any>(".off-bar-label"); assert.operator(offBarLabels.size(), ">", 0, "some off-bar labels are drawn"); offBarLabels.each(function(d, i) { assert.strictEqual(d3.select(this).style("visibility"), "hidden", `off-bar label ${i} is hidden`); }); }); }); describe("non-overlapping datasets", () => { let div: d3.Selection<HTMLDivElement, any, any, any>; let yScale: Plottable.Scales.Category; let stackedBarPlot: Plottable.Plots.StackedBar<number, string>; beforeEach(() => { div = TestMethods.generateDiv(); const xScale = new Plottable.Scales.Linear(); yScale = new Plottable.Scales.Category(); const data1 = [ {y: "A", x: 1}, {y: "B", x: 2}, {y: "C", x: 1}, ]; const data2 = [ {y: "A", x: 2}, {y: "B", x: 3}, ]; const data3 = [ {y: "B", x: 1}, {y: "C", x: 7}, ]; stackedBarPlot = new Plottable.Plots.StackedBar<number, string>(BarOrientation.horizontal); stackedBarPlot.addDataset(new Plottable.Dataset(data1)); stackedBarPlot.addDataset(new Plottable.Dataset(data2)); stackedBarPlot.addDataset(new Plottable.Dataset(data3)); stackedBarPlot.x((d) => d.x, xScale); stackedBarPlot.y((d) => d.y, yScale); stackedBarPlot.renderTo(div); }); afterEach(() => { stackedBarPlot.destroy(); div.remove(); }); it("draws bars at specified y location and stacks in order of datasets", () => { const bars = stackedBarPlot.content().selectAll<Element, any>("rect"); const datumCount = stackedBarPlot.datasets().reduce((prev, curr) => prev + curr.data().length, 0); assert.strictEqual(bars.size(), datumCount, "draws a bar for each datum"); const domain = yScale.domain(); domain.forEach((value) => { const domainBarPairs = d3.pairs(bars.filter((d) => d.y === value).nodes()); domainBarPairs.forEach((aBarPair) => { assert.closeTo(TestMethods.numAttr(d3.select(aBarPair[0]), "y"), TestMethods.numAttr(d3.select(aBarPair[1]), "y"), window.Pixel_CloseTo_Requirement, "bars at same x position"); assert.operator(TestMethods.numAttr(d3.select(aBarPair[0]), "x"), "<", TestMethods.numAttr(d3.select(aBarPair[1]), "x"), "previous dataset bar under second"); }); }); }); }); describe("fail safe tests", () => { it("should default to 0 when calculating stack offsets with non-numbers", () => { const div = TestMethods.generateDiv(); const stringData = [ { x: "s", y: "A"}, ]; const nullData: {x: number, y: string}[] = [ { x: null, y: "A"}, ]; const undefinedData: {x: number, y: string}[] = [ { x: undefined, y: "A"}, ]; const naNData = [ { x: NaN, y: "A"}, ]; const validData = [ { x: 1, y: "A"}, ]; const xScale = new Plottable.Scales.Linear(); const yScale = new Plottable.Scales.Category(); const stackedBarPlot = new Plottable.Plots.StackedBar<number, string>(BarOrientation.horizontal); const ds1 = new Plottable.Dataset(stringData); const ds2 = new Plottable.Dataset(nullData); const ds3 = new Plottable.Dataset(undefinedData); const ds4 = new Plottable.Dataset(naNData); const ds5 = new Plottable.Dataset(validData); stackedBarPlot.addDataset(ds1); stackedBarPlot.addDataset(ds2); stackedBarPlot.addDataset(ds3); stackedBarPlot.addDataset(ds4); stackedBarPlot.addDataset(ds5); stackedBarPlot.x((d: any) => d.x, xScale).y((d: any) => d.y, yScale); stackedBarPlot.renderTo(div); const validBar = stackedBarPlot.content().selectAll<Element, any>("rect").filter((d) => d.x === 1); assert.closeTo(TestMethods.numAttr(validBar, "x"), xScale.scale(0), window.Pixel_CloseTo_Requirement, "bar stacks from 0"); stackedBarPlot.destroy(); div.remove(); }); }); }); });
the_stack
module Encounters { enum Tok { IF = 0, LPAREN = 1, RPAREN = 2, IDENT = 3, OP = 4, INT = 5 } type Token = [Tok, string /* Matched text */, number /* length (or number value for Tok.INT tokens) */]; interface IfNode { type: "if", cond: Node } interface OpNode { type: "op", op: string, lhs: Node, rhs: Node } interface CallNode { type: "call", name: string, arg: Node } interface VarNode { type: "var", name: string } interface IntNode { type: "int", value: number } export type Node = IfNode | OpNode | CallNode | VarNode | IntNode; function tokenizeCond(data: string): Token[] { var tokensRe: { [re: string]: number } = { "if": Tok.IF, "and": Tok.OP, "[a-z_]+": Tok.IDENT, "-?[0-9]+": Tok.INT, "[><=&]+": Tok.OP, "\\(": Tok.LPAREN, "\\)": Tok.RPAREN, } function match(str: string): Token|null { for(var re in tokensRe) { var m = str.match(new RegExp("^\\s*(" + re + ")\\s*")) if(m !== null) return [tokensRe[re], m[1], m[0].length] } return null } var acc = data var toks: Token[] = [] while(acc.length > 0) { var m = match(acc) if(m === null) throw "error parsing condition: '" + data + "': choked on '" + acc + "'" toks.push(m[0] === Tok.INT ? [Tok.INT, m[1], parseInt(m[1])] : m) acc = acc.slice(m[2]) } return toks } function parseCond(data: string) { data = data.replace("%", "") // percentages don't really matter var tokens = tokenizeCond(data) var curTok = 0 function expect(t: Tok) { if(tokens[curTok++][0] !== t) throw "expect: expected " + t + ", got " + tokens[curTok-1] + ", input: " + data } function next() { return tokens[curTok++] } function peek() { if(curTok >= tokens.length) return null return tokens[curTok] } function call(name: string): Node { expect(Tok.LPAREN) var arg = expr() expect(Tok.RPAREN) return {type: 'call', name, arg} } function checkOp(node: Node): Node { var t = peek() if(t === null || t[0] !== Tok.OP) return node curTok++ var rhs = checkOp(expr()) return {type: 'op', op: t[1], lhs: node, rhs: rhs} } function expr(): Node { var t = next() switch(t[0]) { case Tok.IF: expect(Tok.LPAREN) var cond = expr() expect(Tok.RPAREN) return checkOp({type: 'if', cond: cond}) case Tok.IDENT: if(peek()![0] === Tok.LPAREN) return checkOp(call(t[1])) return checkOp({type: 'var', name: t[1]}) case Tok.INT: return checkOp({type: 'int', value: t[2]}) default: throw "unhandled/unexpected token: " + t + " in: " + data } } return expr() } export function parseConds(data: string) { // conditions are formed by conjunctions, so // x AND y AND z can just be collapsed to [x, y, z] here var cond = parseCond(data) var out: Node[] = [] function visit(node: Node) { if(node.type === "op" && node.op === "and") { visit(node.lhs) visit(node.rhs) } else out.push(node) } visit(cond) return out } function printTree(node: Node, s: string) { switch(node.type) { case "if": console.log(s + "if") printTree(node.cond, s + " ") break case "op": console.log(s + "op " + node.op + "") printTree(node.lhs, s + " ") printTree(node.rhs, s + " ") break case "call": console.log(s + "call " + node.name + "") printTree(node.arg, s + " ") break case "var": console.log(s + "var " + node.name) break case "int": console.log(s + "int " + node.value) break } } // evaluates conditions against game state function evalCond(node: Node): number|boolean { switch(node.type) { case "if": // condition return evalCond(node.cond) case "call": // call (more like a property access) switch(node.name) { case "global": // GVAR if(node.arg.type !== "int") throw "evalCond: GVAR not a number"; return Scripting.getGlobalVar(node.arg.value) case "player": if(node.arg.type !== "var") throw "evalCond: player arg not a var"; if(node.arg.name !== "level") throw "player( " + node.arg.name + ")" return 0 // player level case "rand": // random percentage if(node.arg.type !== "int") throw "evalCond: rand arg not a number"; return getRandomInt(0, 100) <= node.arg.value default: throw "unhandled call: " + node.name } case "var": switch(node.name) { case "time_of_day": return 12 // hour of the day default: throw "unhandled var: " + node.name } case "int": return node.value case "op": var lhs = evalCond(node.lhs) var rhs = evalCond(node.rhs) var op: { [op: string]: (l: boolean|number, r: boolean|number) => boolean|number } = { "<": (l, r) => l < r, ">": (l, r) => l > r, "and": (l, r) => l && r } if(op[node.op] === undefined) throw "unhandled op: " + node.op return op[node.op](lhs, rhs) default: throw "unhandled node: " + node } } function evalConds(conds: Node[]): boolean { // TODO: Array.every for(var i = 0; i < conds.length; i++) { if(evalCond(conds[i]) === false) return false } return true } function evalEncounterCritter(critter: Worldmap.EncounterCritter): Worldmap.EncounterCritter { var items = [] for(var i = 0; i < critter.items.length; i++) { var item = critter.items[i] var amount = 1 if(item.range) { amount = getRandomInt(item.range.start, item.range.end) } if(amount > 0) items.push({pid: item.pid, wielded: item.wielded, amount: amount}) } return {items: items, pid: critter.pid, script: critter.script, dead: critter.dead} } function evalEncounterCritters(count: number, group: Worldmap.EncounterGroup): Worldmap.EncounterCritter[] { var critters: Worldmap.EncounterCritter[] = [] for(var i = 0; i < group.critters.length; i++) { var critter = group.critters[i] if(critter.cond) { if(!evalConds(critter.cond)) { console.log("critter cond false: %o", critter.cond) continue } else console.log("critter cond true: %o", critter.cond) } if(critter.ratio === undefined) critters.push(evalEncounterCritter(critter)) else { var num = Math.ceil(critter.ratio/100 * count) // TODO: better distribution (might be +1 now) console.log("critter nums: %d (%d% of %d)", num, critter.ratio, count) for(var j = 0; j < num; j++) critters.push(evalEncounterCritter(critter)) } } return critters } function pickEncounter(encounters: Worldmap.Encounter[]) { // Pick an encounter from an encounter list based on a roll var succEncounters = encounters.filter(function(enc) { return (enc.cond !== null) ? evalConds(enc.cond) : true }) var numEncounters = succEncounters.length var totalChance = succEncounters.reduce(function(sum, x) { return x.chance + sum }, 0) if(numEncounters === 0) throw "pickEncounter: There were no successfully-conditioned encounters" console.log("pickEncounter: num: %d, chance: %d, encounters: %o", numEncounters, totalChance, succEncounters) var luck = critterGetStat(player, "LUK") var roll = getRandomInt(0, totalChance) + (luck - 5) // TODO: Adjust roll for difficulty (easy +5, hard -5), // perks (Scout +1, Ranger +1, Explorer +2) // Remove chances from roll until either we reach the end of the list or the roll runs out. // If our roll does *not* run out (i.e., its value exceeds totalChance), then // we will choose the last encounter in the list. var acc = roll var idx = 0 for(; idx < succEncounters.length; idx++) { var chance = succEncounters[idx].chance if(acc < chance) break acc -= chance } console.log("idx: %d", idx) return succEncounters[idx] } export function positionCritters(groups: Worldmap.EncounterGroup[], playerPos: Point, map: MapInfo) { // set up critters' positions in their formations groups.forEach(function(group) { var dir = getRandomInt(0, 5) var formation = group.position.type let pos: Point if(formation === "surrounding") pos = {x: playerPos.x, y: playerPos.y} else { // choose a random starting point from the map var randomPoint = map.randomStartPoints[getRandomInt(0, map.randomStartPoints.length - 1)] pos = fromTileNum(randomPoint.tileNum) } console.log("positionCritters: map %o, dir %d, formation %s, pos %o", map, dir, formation, pos) group.critters.forEach(function(critter) { switch(formation) { case "huddle": critter.position = {x: pos.x, y: pos.y} dir = (dir + 1) % 6 pos = hexInDirectionDistance(pos, dir, group.position.spacing) break case "surrounding": var roll = critterGetStat(player, "PER") + getRandomInt(-2, 2) // TODO: if have Cautious Nature perk, roll += 3 if(roll < 0) roll = 0 pos = hexInDirectionDistance(pos, dir, roll) dir++ if(dir >= 6) dir = 0 var rndSpacing = getRandomInt(0, Math.floor(roll / 2)) var rndDir = getRandomInt(0, 5) pos = hexInDirectionDistance(pos, (rndDir + dir) % 6, rndSpacing) critter.position = {x: pos.x, y: pos.y} break case "straight_line": case "double_line": case "wedge": case "cone": default: console.log("UNHANDLED FORMATION %s", formation) // use some arbitrary formation critter.position = {x: pos.x, y: pos.y} pos.x-- break } }) }) } export function evalEncounter(encTable: Worldmap.EncounterTable) { var mapIndex = getRandomInt(0, encTable.maps.length - 1) var mapLookupName = encTable.maps[mapIndex] var mapName = lookupMapNameFromLookup(mapLookupName) var groups: Worldmap.EncounterGroup[] = [] var encounter = pickEncounter(encTable.encounters) if(encounter.special !== null) { // special encounter: use specific map mapLookupName = encounter.special mapName = lookupMapNameFromLookup(mapLookupName) console.log("special encounter: %s", mapName) } console.log("map: %s (from %s)", mapName, mapLookupName) console.log("encounter: %o", encounter) // TODO: maybe unify these and just have a `.groups` in the encounter, along with a target. if(encounter.enc.type === "ambush") { // player ambush console.log("(player ambush)") var party = encounter.enc.party var group = Worldmap.getEncounterGroup(party.name) var position = group.position console.log("party: %d-%d of %s", party.start, party.end, party.name) console.log("encounter group: %o", group) console.log("position:", position) var critterCount = getRandomInt(party.start, party.end) var critters = evalEncounterCritters(critterCount, group) groups.push({critters: critters, position: position, target: "player"}) } else if(encounter.enc.type === "fighting") { // two factions fighting var firstParty = encounter.enc.firstParty var secondParty = encounter.enc.secondParty console.log("two factions: %o vs %o", firstParty, secondParty) if(!firstParty) throw Error(); var firstGroup = Worldmap.getEncounterGroup(firstParty.name) var firstCritterCount = getRandomInt(firstParty.start, firstParty.end) groups.push({critters: evalEncounterCritters(firstCritterCount, firstGroup), target: 1, position: firstGroup.position}) // one-party fighting? TODO: check what all is allowed with `fighting` if(secondParty && secondParty.name !== undefined) { var secondGroup = Worldmap.getEncounterGroup(secondParty.name) var secondCritterCount = getRandomInt(secondParty.start, secondParty.end) groups.push({critters: evalEncounterCritters(secondCritterCount, secondGroup), target: 0, position: secondGroup.position}) } } else if(encounter.enc.type === "special") { //console.log("TODO: special encounter type") } else throw "unknown encounter type: " + encounter.enc.type console.log("groups: %o", groups) return {mapName: mapName, mapLookupName: mapLookupName, encounter: encounter, encounterType: encounter.enc.type, groups: groups} } }
the_stack
import { PluginObject } from './plugin'; import { AleUIComponent, AleUIComponentSize, AleUIHorizontalAlignment } from './component'; import { AlAlert } from './alert'; import { AlAside } from './aside'; import { AlAutocomplete } from './autocomplete'; import { AlBadge } from './badge'; import { AlBreadcrumb } from './breadcrumb'; import { AlBreadcrumbItem } from './breadcrumb-item'; import { AlButton } from './button'; import { AlButtonGroup } from './button-group'; import { AlCard } from './card'; import { AlCarousel } from './carousel'; import { AlCarouselItem } from './carousel-item'; import { AlCascader } from './cascader'; import { AlCheckbox } from './checkbox'; import { AlCheckboxButton } from './checkbox-button'; import { AlCheckboxGroup } from './checkbox-group'; import { AlCol } from './col'; import { AlCollapse } from './collapse'; import { AlCollapseItem } from './collapse-item'; import { AlColorPicker } from './color-picker'; import { AlContainer } from './container'; import { AlDatePicker } from './date-picker'; import { AlDialog } from './dialog'; import { AlDropdown } from './dropdown'; import { AlDropdownItem } from './dropdown-item'; import { AlDropdownMenu } from './dropdown-menu'; import { AlFooter } from './footer'; import { AlForm } from './form'; import { AlFormItem } from './form-item'; import { AlHeader } from './header'; import { AlInput } from './input'; import { AlInputNumber } from './input-number'; import { AlLoading } from './loading'; import { AlMain } from './main'; import { AlMenu } from './menu'; import { AlMenuItem } from './menu-item'; import { AlMenuItemGroup } from './menu-item-group'; import { AlMessage } from './message'; import { AlMessageBox } from './message-box'; import { AlNotification } from './notification'; import { AlOption } from './option'; import { AlOptionGroup } from './option-group'; import { AlPagination } from './pagination'; import { AlPopover } from './popover'; import { AlProgress } from './progress'; import { AlRate } from './rate'; import { AlRadio } from './radio'; import { AlRadioButton } from './radio-button'; import { AlRadioGroup } from './radio-group'; import { AlRow } from './row'; import { AlSelect } from './select'; import { AlSlider } from './slider'; import { AlStep } from './step'; import { AlSteps } from './steps'; import { AlSubmenu } from './submenu'; import { AlSwitch } from './switch'; import { AlTable } from './table'; import { AlTableColumn } from './table-column'; import { AlTag } from './tag'; import { AlTabs } from './tabs'; import { AlTabPane } from './tab-pane'; import { AlTimeline } from './timeline'; import { AlTimelineItem } from './timeline-item'; import { AlTimePicker } from './time-picker'; import { AlTimeSelect } from './time-select'; import { AlTooltip } from './tooltip'; import { AlTransfer } from './transfer'; import { AlTree, TreeData } from './tree'; import { AlUpload } from './upload'; import { AlLink } from './link'; import { AlDivider } from './divider'; import { AlIcon } from './icon'; import { AlCalendar } from './calendar'; import { AlImage } from './image'; import { AlBacktop } from './backtop'; import { AlInfiniteScroll } from './infinite-scroll'; import { AlPageHeader } from './page-header'; import { AlAvatar } from './avatar'; import { AlDrawer } from './drawer'; import { AlPopconfirm } from './popconfirm'; export interface InstallationOptions { locale: any; i18n: any; size: string; } /** The version of ale-ui */ export const version: string; /** * Install all ale-ui components into Vue. * Please do not invoke this method directly. * Call `Vue.use(AleUI)` to install. */ export function install(vue: typeof any, options: InstallationOptions): void; /** AleUI component common definition */ export type Component = AleUIComponent; /** Component size definition for button, input, etc */ export type ComponentSize = AleUIComponentSize; /** Horizontal alignment */ export type HorizontalAlignment = AleUIHorizontalAlignment; /** Show animation while loading data */ export const Loading: AlLoading; /** Used to show feedback after an activity. The difference with Notification is that the latter is often used to show a system level passive notification. */ export const Message: AlMessage; /** A set of modal boxes simulating system message box, mainly for message prompt, success tips, error messages and query information */ export const MessageBox: AlMessageBox; /** Displays a global notification message at the upper right corner of the page */ export const Notification: AlNotification; // TS cannot merge imported class with namespace, so declare subclasses instead /** Alert Component */ export class Alert extends AlAlert {} /** Aside Component */ export class Aside extends AlAside {} /** Autocomplete Component */ export class Autocomplete extends AlAutocomplete {} /** Bagde Component */ export class Badge extends AlBadge {} /** Breadcrumb Component */ export class Breadcrumb extends AlBreadcrumb {} /** Breadcrumb Item Component */ export class BreadcrumbItem extends AlBreadcrumbItem {} /** Button Component */ export class Button extends AlButton {} /** Button Group Component */ export class ButtonGroup extends AlButtonGroup {} /** Card Component */ export class Card extends AlCard {} /** Cascader Component */ export class Cascader extends AlCascader {} /** Carousel Component */ export class Carousel extends AlCarousel {} /** Carousel Item Component */ export class CarouselItem extends AlCarouselItem {} /** Checkbox Component */ export class Checkbox extends AlCheckbox {} /** Checkbox Button Component */ export class CheckboxButton extends AlCheckboxButton {} /** Checkbox Group Component */ export class CheckboxGroup extends AlCheckboxGroup {} /** Colunm Layout Component */ export class Col extends AlCol {} /** Collapse Component */ export class Collapse extends AlCollapse {} /** Collapse Item Component */ export class CollapseItem extends AlCollapseItem {} /** Color Picker Component */ export class ColorPicker extends AlColorPicker {} /** Container Component */ export class Container extends AlContainer {} /** Date Picker Component */ export class DatePicker extends AlDatePicker {} /** Dialog Component */ export class Dialog extends AlDialog {} /** Dropdown Component */ export class Dropdown extends AlDropdown {} /** Dropdown Item Component */ export class DropdownItem extends AlDropdownItem {} /** Dropdown Menu Component */ export class DropdownMenu extends AlDropdownMenu {} /** Footer Component */ export class Footer extends AlFooter {} /** Form Component */ export class Form extends AlForm {} /** Form Item Component */ export class FormItem extends AlFormItem {} /** Header Component */ export class Header extends AlHeader {} /** Input Component */ export class Input extends AlInput {} /** Input Number Component */ export class InputNumber extends AlInputNumber {} /** Main Component */ export class Main extends AlMain {} /** Menu that provides navigation for your website */ export class Menu extends AlMenu {} /** Menu Item Component */ export class MenuItem extends AlMenuItem {} /** Menu Item Group Component */ export class MenuItemGroup extends AlMenuItemGroup {} /** Dropdown Select Option Component */ export class Option extends AlOption {} /** Dropdown Select Option Group Component */ export class OptionGroup extends AlOptionGroup {} /** Pagination Component */ export class Pagination extends AlPagination {} /** Popover Component */ export class Popover extends AlPopover {} /** Progress Component */ export class Progress extends AlProgress {} /** Rate Component */ export class Rate extends AlRate {} /** Radio Component */ export class Radio extends AlRadio {} /** Radio Button Component */ export class RadioButton extends AlRadioButton {} /** Radio Group Component */ export class RadioGroup extends AlRadioGroup {} /** Row Layout Component */ export class Row extends AlRow {} /** Dropdown Select Component */ export class Select extends AlSelect {} /** Slider Component */ export class Slider extends AlSlider {} /** Step Component */ export class Step extends AlStep {} /** Steps Component */ export class Steps extends AlSteps {} /** Submenu Component */ export class Submenu extends AlSubmenu {} /** Switch Component */ export class Switch extends AlSwitch {} /** Table Component */ export class Table extends AlTable {} /** Table Column Component */ export class TableColumn extends AlTableColumn {} /** Tabs Component */ export class Tabs extends AlTabs {} /** Tab Pane Component */ export class TabPane extends AlTabPane {} /** Tag Component */ export class Tag extends AlTag {} /** Timeline Component */ export class Timeline extends AlTimeline {} /** Timeline Item Component */ export class TimelineItem extends AlTimelineItem {} /** TimePicker Component */ export class TimePicker extends AlTimePicker {} /** TimeSelect Component */ export class TimeSelect extends AlTimeSelect {} /** Tooltip Component */ export class Tooltip extends AlTooltip {} /** Transfer Component */ export class Transfer extends AlTransfer {} /** Tree Component */ export class Tree<K = any, D = TreeData> extends AlTree<K, D> {} /** Upload Component */ export class Upload extends AlUpload {} /** Divider Component */ export class Divider extends AlDivider {} /** Link Component */ export class Link extends AlLink {} /** Image Component */ export class Image extends AlImage {} /** Icon Component */ export class Icon extends AlIcon {} /** Calendar Component */ export class Calendar extends AlCalendar {} /** Backtop Component */ export class Backtop extends AlBacktop {} /** InfiniteScroll Directive */ export const InfiniteScroll: PluginObject<AlInfiniteScroll>; /** PageHeader Component */ export class PageHeader extends AlPageHeader {} /** Avatar Component */ export class Avatar extends AlAvatar {} /** Drawer Component */ export class Drawer extends AlDrawer {} /** Popconfirm Component */ export class Popconfirm extends AlPopconfirm {}
the_stack
import { ILayoutManager } from './ILayoutManager'; import { WidgetGroup } from '../WidgetGroup'; import { Widget } from '../Widget'; import { LayoutOptions, ALIGN } from '../layout-options'; import { BorderLayoutOptions } from '../layout-options/BorderLayoutOptions'; import { MeasureMode } from '../IMeasurable'; const { REGION_LEFT, REGION_TOP, REGION_RIGHT, REGION_BOTTOM, REGION_CENTER, } = BorderLayoutOptions; const { FILL_PARENT, } = LayoutOptions; const { EXACTLY, AT_MOST, } = MeasureMode; /** * `PUXI.BorderLayout` is used in conjunction with `PUXI.BorderLayoutOptions`. * * This layout guarantees that the "center" region will always be in the center of * the widget-group. * * WARNING: This layout may have some bugs in edge cases that haven't been reported. * * @memberof PUXI * @class * @implements PUXI.ILayoutManager */ export class BorderLayout implements ILayoutManager { protected host: WidgetGroup; protected leftWidgets: Widget[]; protected topWidgets: Widget[]; protected rightWidgets: Widget[]; protected bottomWidgets: Widget[]; protected centerWidgets: Widget[]; protected measuredLeftWidth: number; protected measuredRightWidth: number; protected measuredCenterWidth: number; protected measuredWidth: number; protected measuredTopHeight: number; protected measuredBottomHeight: number; protected measuredCenterHeight: number; protected measuredHeight: number; constructor() { this.leftWidgets = []; this.topWidgets = []; this.rightWidgets = []; this.bottomWidgets = []; this.centerWidgets = []; } onAttach(host: WidgetGroup): void { this.host = host; } onDetach(): void { this.host = null; this.clearMeasureCache(); this.clearRegions(); } onLayout(): void { this.layoutChildren( this.leftWidgets, 0, this.measuredTopHeight, this.measuredLeftWidth, this.measuredCenterHeight); this.layoutChildren(this.topWidgets, 0, 0, this.measuredWidth, this.measuredTopHeight); this.layoutChildren( this.rightWidgets, this.measuredWidth - this.measuredRightWidth, this.measuredTopHeight, this.measuredRightWidth, this.measuredCenterHeight, ); this.layoutChildren( this.bottomWidgets, 0, this.measuredTopHeight + this.measuredCenterHeight, this.measuredWidth, this.measuredBottomHeight, ); this.layoutChildren( this.centerWidgets, this.measuredLeftWidth, this.measuredTopHeight, this.measuredCenterWidth, this.measuredCenterHeight, ); } layoutChildren( widgets: Widget[], regionX: number, regionY: number, regionWidth: number, regionHeight: number, ): void { for (let i = 0, j = widgets.length; i < j; i++) { const widget = widgets[i]; let x = 0; let y = 0; switch ((widget.layoutOptions as BorderLayoutOptions)?.horizontalAlign) { case ALIGN.CENTER: x = (regionWidth - widget.getMeasuredWidth()) / 2; break; case ALIGN.RIGHT: x = regionWidth - widget.getMeasuredWidth(); break; default: x = 0; break; } switch ((widget.layoutOptions as BorderLayoutOptions)?.verticalAlign) { case ALIGN.CENTER: y = (regionHeight - widget.getMeasuredHeight()) / 2; break; case ALIGN.BOTTOM: y = regionHeight - widget.getMeasuredHeight(); break; default: y = 0; break; } x += regionX; y += regionY; widget.layout(x, y, x + widget.getMeasuredWidth(), y + widget.getMeasuredHeight(), true); } } /** * @param {number} maxWidth * @param {number} maxHeight * @param {PUXI.MeasureMode} widthMode * @param {PUXI.MeasureMode} heightMode * @override */ onMeasure(maxWidth: number, maxHeight: number, widthMode: MeasureMode, heightMode: MeasureMode): void { this.indexRegions(); this.clearMeasureCache(); // Children can be aligned inside region if smaller const childWidthMode = widthMode === MeasureMode.EXACTLY ? MeasureMode.AT_MOST : widthMode; const childHeightMode = heightMode === MeasureMode.EXACTLY ? MeasureMode.AT_MOST : widthMode; // Measure top, bottom, and center. The max. of each row's width will be our "reference". let [tw, th, , thmin] = this.measureChildren(// eslint-disable-line prefer-const this.topWidgets, maxWidth, maxHeight, childWidthMode, childHeightMode, ); let [bw, bh,, bhmin] = this.measureChildren(// eslint-disable-line prefer-const this.bottomWidgets, maxWidth, maxHeight, childWidthMode, childHeightMode, ); let [cw, ch, cwmin, chmin] = this.measureChildren(// eslint-disable-line prefer-const this.centerWidgets, maxWidth, maxHeight, childWidthMode, heightMode); // Measure left & right regions. Their heights will equal center's height. let [lw, , lwmin] = this.measureChildren(// eslint-disable-line prefer-const this.leftWidgets, maxWidth, ch, childWidthMode, MeasureMode.AT_MOST); let [rw, , rwmin] = this.measureChildren(// eslint-disable-line prefer-const this.rightWidgets, maxWidth, ch, childWidthMode, MeasureMode.AT_MOST); // Check if total width/height is greater than our limit. If so, then downscale // each row's height or each column's (in middle row) width. const middleRowWidth = lw + rw + cw; const netWidth = Math.max(tw, bw, middleRowWidth); const netHeight = th + bh + ch; // Resolve our limits. if (widthMode === MeasureMode.EXACTLY) { this.measuredWidth = maxWidth; } else if (widthMode === MeasureMode.AT_MOST) { this.measuredWidth = Math.min(netWidth, maxWidth); } else { this.measuredWidth = netWidth; } if (heightMode === MeasureMode.EXACTLY) { this.measuredHeight = maxHeight; } else if (heightMode === MeasureMode.AT_MOST) { this.measuredHeight = Math.min(netHeight, maxHeight); } else { this.measuredHeight = netHeight; } tw = this.measuredWidth; bw = this.measuredWidth; if (netHeight > this.measuredHeight) { const hmin = (thmin + chmin + bhmin); // Redistribute heights minus min-heights. if (hmin < this.measuredHeight) { const downscale = (this.measuredHeight - hmin) / (netHeight - hmin); th = thmin + ((th - thmin) * downscale); bh = bhmin + ((bh - bhmin) * downscale); ch = chmin + ((ch - chmin) * downscale); } // Redistribute full heights. else { const downscale = this.measuredHeight / netHeight; th *= downscale; bh *= downscale; ch *= downscale; } } if (netWidth > this.measuredWidth) { const wmin = lwmin + cwmin + rwmin; // Redistribute widths minus min. widths if (wmin < this.measuredWidth) { const downscale = (this.measuredWidth - wmin) / (netWidth - wmin); lw = lwmin + ((lw - lwmin) * downscale); cw = cwmin + ((cw - cwmin) * downscale); rw = rwmin + ((rw - rwmin) * downscale); } // Redistribute full widths else { const downscale = this.measuredWidth / netWidth; lw *= downscale; cw *= downscale; rw *= downscale; } } // Useful to know! this.measuredLeftWidth = lw; this.measuredRightWidth = rw; this.measuredCenterWidth = cw; this.measuredTopHeight = th; this.measuredBottomHeight = bh; this.measuredCenterHeight = ch; this.fitChildren(this.leftWidgets, this.measuredLeftWidth, this.measuredCenterHeight); this.fitChildren(this.topWidgets, this.measuredWidth, this.measuredTopHeight); this.fitChildren(this.rightWidgets, this.measuredRightWidth, this.measuredCenterHeight); this.fitChildren(this.bottomWidgets, this.measuredWidth, this.measuredBottomHeight); this.fitChildren(this.centerWidgets, this.measuredCenterWidth, this.measuredCenterHeight); } /** * This measures the list of widgets given the constraints. The max width and * height amongst the children is returned. * * @param {PUXI.Widget[]} list * @param {number} maxWidth * @param {number} maxHeight * @param {PUXI.MeasureMode} widthMode * @param {PUXI.MeasureMode} heightMode * @returns {number[]} - [width, height, widthFixedLowerBound, heightFixedLowerBound] - * the max. width and height amongst children. Also, the minimum required width/height * for the region (as defined in layout-options). */ protected measureChildren( list: Widget[], maxWidth: number, maxHeight: number, widthMode: MeasureMode, heightMode: MeasureMode, ): number[] { let width = 0; let height = 0; let widthFixedLowerBound = 0; let heightFixedLowerBound = 0; for (let i = 0, j = list.length; i < j; i++) { const widget = list[i]; const lopt = widget.layoutOptions || LayoutOptions.DEFAULT; let w = maxWidth; let h = maxHeight; let wmd = widthMode; let hmd = heightMode; if (lopt.width <= LayoutOptions.MAX_DIMEN) { w = lopt.width; wmd = EXACTLY; widthFixedLowerBound = Math.max(widthFixedLowerBound, w); } if (lopt.height <= LayoutOptions.MAX_DIMEN) { h = lopt.height; hmd = EXACTLY; heightFixedLowerBound = Math.max(heightFixedLowerBound, h); } widget.measure(w, h, wmd, hmd); width = Math.max(width, widget.getMeasuredWidth()); height = Math.max(height, widget.getMeasuredHeight()); } return [width, height, widthFixedLowerBound, heightFixedLowerBound]; } /** * Ensures all widgets in the list measured their dimensions below the region * width & height. Widgets that are too large are remeasured in the those * limits (using `MeasureMode.AT_MOST`). * * This will handle widgets that have "FILL_PARENT" width or height. * * @param {PUXI.Widget[]} list * @param {number} measuredRegionWidth * @param {number} measuredRegionHeight */ protected fitChildren( list: Widget[], measuredRegionWidth: number, measuredRegionHeight: number, ): void { for (let i = 0, j = list.length; i < j; i++) { const widget = list[i]; if (widget.getMeasuredWidth() <= measuredRegionWidth && widget.getMeasuredHeight() <= measuredRegionHeight && widget.getMeasuredWidth() > 0 && widget.getMeasuredHeight() > 0 && widget.layoutOptions?.width !== FILL_PARENT && widget.layoutOptions?.height !== FILL_PARENT) { continue; } if (measuredRegionWidth > 0 && measuredRegionHeight > 0) { const wm = widget.layoutOptions?.width === FILL_PARENT ? EXACTLY : AT_MOST; const hm = widget.layoutOptions?.height === FILL_PARENT ? EXACTLY : AT_MOST; widget.measure(measuredRegionWidth, measuredRegionHeight, wm, hm); } } } /** * Indexes the list of left, top, right, bottom, and center widget lists. */ protected indexRegions(): void { this.clearRegions(); const { widgetChildren: children } = this.host; for (let i = 0, j = children.length; i < j; i++) { const widget = children[i]; const lopt = (widget.layoutOptions || LayoutOptions.DEFAULT) as BorderLayoutOptions; const region = lopt.region || REGION_CENTER; switch (region) { case REGION_LEFT: this.leftWidgets.push(widget); break; case REGION_TOP: this.topWidgets.push(widget); break; case REGION_RIGHT: this.rightWidgets.push(widget); break; case REGION_BOTTOM: this.bottomWidgets.push(widget); break; default: this.centerWidgets.push(widget); } } } /** * Clears the left, top, right, bottom, and center widget lists. */ protected clearRegions(): void { this.leftWidgets.length = 0; this.topWidgets.length = 0; this.rightWidgets.length = 0; this.bottomWidgets.length = 0; } /** * Zeros the measured dimensions. */ protected clearMeasureCache(): void { this.measuredLeftWidth = 0; this.measuredRightWidth = 0; this.measuredCenterWidth = 0; this.measuredTopHeight = 0; this.measuredBottomHeight = 0; this.measuredCenterHeight = 0; } getMeasuredWidth(): number { return this.measuredWidth; } getMeasuredHeight(): number { return this.measuredHeight; } }
the_stack
import { AfterContentInit, AfterViewInit, Directive, ElementRef, EventEmitter, forwardRef, HostBinding, HostListener, Inject, Input, OnChanges, OnDestroy, Output, Renderer2, Self, SimpleChange, SimpleChanges } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'; import { MDCSliderFoundation, MDCSliderAdapter } from '@material/slider'; import { events } from '@material/dom'; import { asBoolean } from '../../utils/value.utils'; import { MdcEventRegistry } from '../../utils/mdc.event.registry'; /** * Directive for creating a Material Design slider input. * (Modelled after the <code>&lt;input type="range"/&gt;</code> element). * The slider is fully accessible. The current implementation * will add and manage all DOM child elements that are required for the wrapped * <code>mdc-slider</code> component. * Future implementations will also support supplying (customized) * DOM children. */ @Directive({ selector: '[mdcSlider]' }) export class MdcSliderDirective implements AfterContentInit, AfterViewInit, OnChanges, OnDestroy { /** @internal */ @HostBinding('class.mdc-slider') readonly _cls = true; /** @internal */ @HostBinding('attr.role') _role: string = 'slider'; /** * Event emitted when the value changes. The value may change because of user input, * or as a side affect of setting new min, max, or step values. */ @Output() readonly valueChange: EventEmitter<number> = new EventEmitter(); /** * Event emitted when the min range value changes. This may happen as a side effect * of setting a new max value (when the new max is smaller than the old min). */ @Output() readonly minValueChange: EventEmitter<number> = new EventEmitter(); /** * Event emitted when the max range value changes. This may happen as a side effect * of setting a new min value (when the new min is larger than the old max). */ @Output() readonly maxValueChange: EventEmitter<number> = new EventEmitter(); /** * Event emitted when the step value changes. This may happen as a side effect * of making the slider discrete. */ @Output() readonly stepValueChange: EventEmitter<number> = new EventEmitter(); private trackCntr: HTMLElement | null = null; private _elmThumbCntr: HTMLElement | null = null; private _elmSliderPin: HTMLElement | null = null; private _elmValueMarker: HTMLElement | null = null; private _elmTrack: HTMLElement | null = null; private _elmTrackMarkerCntr: HTMLElement | null = null; private _reinitTabIndex: number | null = null; private _onChange: (value: any) => void = (value) => {}; private _onTouched: () => any = () => {}; private _discrete = false; private _markers = false; private _disabled = false; private _value: number = 0; private _min = 0; private _max = 100; private _step = 0; private _lastWidth: number | null = null; private mdcAdapter: MDCSliderAdapter = { hasClass: (className: string) => { if (className === 'mdc-slider--discrete') return this._discrete; if (className === 'mdc-slider--display-markers') return this._markers; return this._root.nativeElement.classList.contains(className); }, addClass: (className: string) => { this._rndr.addClass(this._root.nativeElement, className); }, removeClass: (className: string) => { this._rndr.removeClass(this._root.nativeElement, className); }, getAttribute: (name: string) => this._root.nativeElement.getAttribute(name), setAttribute: (name: string, value: string) => { // skip attributes that we control with angular if (!/^aria-(value.*|disabled)$/.test(name)) this._rndr.setAttribute(this._root.nativeElement, name, value); }, removeAttribute: (name: string) => {this._rndr.removeAttribute(this._root.nativeElement, name); }, computeBoundingRect: () => this._root.nativeElement.getBoundingClientRect(), getTabIndex: () => this._root.nativeElement.tabIndex, registerInteractionHandler: (evtType, handler) => this._registry.listen(this._rndr, evtType, handler, this._root, events.applyPassive()), deregisterInteractionHandler: (evtType, handler) => this._registry.unlisten(evtType, handler), registerThumbContainerInteractionHandler: (evtType, handler) => this._registry.listenElm(this._rndr, evtType, handler, this._elmThumbCntr!, events.applyPassive()), deregisterThumbContainerInteractionHandler: (evtType, handler) => this._registry.unlisten(evtType, handler), registerBodyInteractionHandler: (evtType, handler) => this._registry.listenElm(this._rndr, evtType, handler, this.document.body), deregisterBodyInteractionHandler: (evtType, handler) => this._registry.unlisten(evtType, handler), registerResizeHandler: (handler) => this._registry.listenElm(this._rndr, 'resize', handler, this.document.defaultView!), deregisterResizeHandler: (handler) => this._registry.unlisten('resize', handler), notifyInput: () => { let newValue = this.asNumber(this.foundation!.getValue()); if (newValue !== this._value) { this._value = newValue!; this.notifyValueChanged(); } }, notifyChange: () => { // currently not handling this event, if there is a usecase for this, please // create a feature request. }, setThumbContainerStyleProperty: (propertyName: string, value: string) => { this._rndr.setStyle(this._elmThumbCntr, propertyName, value); }, setTrackStyleProperty: (propertyName: string, value: string) => { this._rndr.setStyle(this._elmTrack, propertyName, value); }, setMarkerValue: (value: number) => { if (this._elmValueMarker) this._elmValueMarker.innerText = value != null ? value.toLocaleString() : ''; }, setTrackMarkers: (step, max, min) => { if (this._elmTrackMarkerCntr) { // from https://github.com/material-components/material-components-web/blob/v5.1.0/packages/mdc-slider/component.ts#L141 const stepStr = step.toLocaleString(); const maxStr = max.toLocaleString(); const minStr = min.toLocaleString(); const markerAmount = `((${maxStr} - ${minStr}) / ${stepStr})`; const markerWidth = `2px`; const markerBkgdImage = `linear-gradient(to right, currentColor ${markerWidth}, transparent 0)`; const markerBkgdLayout = `0 center / calc((100% - ${markerWidth}) / ${markerAmount}) 100% repeat-x`; const markerBkgdShorthand = `${markerBkgdImage} ${markerBkgdLayout}`; this._rndr.setStyle(this._elmTrackMarkerCntr, 'background', markerBkgdShorthand); } }, isRTL: () => getComputedStyle(this._root.nativeElement).direction === 'rtl' }; private foundation: MDCSliderFoundation | null = null; private document: Document; constructor(private _rndr: Renderer2, private _root: ElementRef, private _registry: MdcEventRegistry, @Inject(DOCUMENT) doc: any) { this.document = doc as Document; // work around ngc issue https://github.com/angular/angular/issues/20351 } ngAfterContentInit() { this.initElements(); this.initDefaultAttributes(); this.foundation = new MDCSliderFoundation(this.mdcAdapter) this.foundation.init(); this._lastWidth = this.mdcAdapter.computeBoundingRect().width; this.updateValues({}); } ngAfterViewInit() { this.updateLayout(); } ngOnDestroy() { this.foundation?.destroy(); } ngOnChanges(changes: SimpleChanges) { this._onChanges(changes); } /** @internal */ _onChanges(changes: SimpleChanges) { if (this.foundation) { if (this.isChanged('discrete', changes) || this.isChanged('markers', changes)) { this.foundation.destroy(); this.initElements(); this.initDefaultAttributes(); this.foundation = new MDCSliderFoundation(this.mdcAdapter); this.foundation.init(); } this.updateValues(changes); this.updateLayout(); } } private isChanged(name: string, changes: SimpleChanges) { return changes[name] && changes[name].currentValue !== changes[name].previousValue; } private initElements() { // initElements is also called when changes dictate a new Foundation initialization, // in which case we create new child elements: if (this.trackCntr) { this._rndr.removeChild(this._root.nativeElement, this.trackCntr); this._rndr.removeChild(this._root.nativeElement, this._elmThumbCntr); } this.trackCntr = this.addElement(this._root.nativeElement, 'div', ['mdc-slider__track-container']); this._elmTrack = this.addElement(this.trackCntr!, 'div', ['mdc-slider__track']); if (this._discrete && this._markers) this._elmTrackMarkerCntr = this.addElement(this.trackCntr!, 'div', ['mdc-slider__track-marker-container']); else this._elmTrackMarkerCntr = null; this._elmThumbCntr = this.addElement(this._root.nativeElement, 'div', ['mdc-slider__thumb-container']); if (this._discrete) { this._elmSliderPin = this.addElement(this._elmThumbCntr!, 'div', ['mdc-slider__pin']); this._elmValueMarker = this.addElement(this._elmSliderPin!, 'div', ['mdc-slider__pin-value-marker']); } else { this._elmSliderPin = null; this._elmValueMarker = null; } const svg = this._rndr.createElement('svg', 'svg'); this._rndr.addClass(svg, 'mdc-slider__thumb'); this._rndr.setAttribute(svg, 'width', '21'); this._rndr.setAttribute(svg, 'height', '21'); this._rndr.appendChild(this._elmThumbCntr, svg); const circle = this._rndr.createElement('circle', 'svg'); this._rndr.setAttribute(circle, 'cx', '10.5'); this._rndr.setAttribute(circle, 'cy', '10.5'); this._rndr.setAttribute(circle, 'r', '7.875'); this._rndr.appendChild(svg, circle); this.addElement(this._elmThumbCntr!, 'div', ['mdc-slider__focus-ring']); } private addElement(parent: HTMLElement, element: string, classNames: string[]) { let child = this._rndr.createElement(element); classNames.forEach(name => { this._rndr.addClass(child, name); }); this._rndr.appendChild(parent, child); return child; } private initDefaultAttributes() { if (this._reinitTabIndex) // value was set the first time we initialized the foundation, // so it should also be set when we reinitialize evrything: this._root.nativeElement.tabIndex = this._reinitTabIndex; else if (!this._root.nativeElement.hasAttribute('tabindex')) { // unless overridden by another tabIndex, we want sliders to // participate in tabbing (the foundation will remove the tabIndex // when the slider is disabled, reset to the initial value when enabled again): this._root.nativeElement.tabIndex = 0; this._reinitTabIndex = 0; } else { this._reinitTabIndex = this._root.nativeElement.tabIndex; } } private updateValues(changes: SimpleChanges) { if (this._discrete && this._step < 1) { // See https://github.com/material-components/material-components-web/issues/1426 // mdc-slider doesn't allow a discrete step value < 1 currently: this._step = 1; Promise.resolve().then(() => {this.stepValueChange.emit(this._step); }); } else if (this._step < 0) { this._step = 0; Promise.resolve().then(() => {this.stepValueChange.emit(this._step); }); } if (this._min > this._max) { if (this.isChanged('maxValue', changes)) { this._min = this._max; Promise.resolve().then(() => {this.minValueChange.emit(this._min); }); } else { this._max = this._min; Promise.resolve().then(() => {this.maxValueChange.emit(this._max); }); } } let currValue = this.asNumber(changes['value'] ? changes['value'].currentValue : this._value); if (this._value < this._min) this._value = this._min; if (this._value > this._max) this._value = this._max; // find an order in which the changed values will be accepted by the foundation // (since the foundation will throw errors for min > max and other conditions): if (this._min < this.foundation!.getMax()) { this.foundation!.setMin(this._min); this.foundation!.setMax(this._max); } else { this.foundation!.setMax(this._max); this.foundation!.setMin(this._min); } this.foundation!.setStep(this._step); if (this.foundation!.isDisabled() !== this._disabled) { // without this check, MDCFoundation may remove the tabIndex incorrectly, // preventing the slider from getting focus on keyboard commands: this.foundation!.setDisabled(this._disabled); } this.foundation!.setValue(this._value); // value may have changed during setValue(), due to step settings: this._value = this.asNumber(this.foundation!.getValue()); // compare with '!=' as null and undefined are considered the same (for initialisation sake): if (currValue !== this._value) Promise.resolve().then(() => {this.notifyValueChanged(); }); } private updateLayout() { let newWidth = this.mdcAdapter.computeBoundingRect().width; if (newWidth !== this._lastWidth) { this._lastWidth = newWidth; this.foundation!.layout(); } } private notifyValueChanged() { this.valueChange.emit(this._value); this._onChange(this._value); } /** @internal */ registerOnChange(onChange: (value: any) => void) { this._onChange = onChange; } /** @internal */ registerOnTouched(onTouched: () => any) { this._onTouched = onTouched; } /** * Make the slider discrete. Note from the wrapped <code>mdc-slider</code> * component: * <blockquote>If a slider contains a step value it does not mean that the slider is a "discrete" slider. * "Discrete slider" is a UX treatment, while having a step value is behavioral.</blockquote> */ @Input() @HostBinding('class.mdc-slider--discrete') get discrete() { return this._discrete; } set discrete(value: boolean) { this._discrete = asBoolean(value); } static ngAcceptInputType_discrete: boolean | ''; /** * Property to enable/disable the display of track markers. Display markers * are only supported for discrete sliders. Thus they are only shown when the values * of both markers and discrete equal true. */ @Input() @HostBinding('class.mdc-slider--display-markers') get markers() { return this._markers; } set markers(value: boolean) { this._markers = asBoolean(value); } static ngAcceptInputType_markers: boolean | ''; /** * The current value of the slider. */ @Input() @HostBinding('attr.aria-valuenow') get value() { return this._value; } set value(value: number) { this._value = this.asNumber(value); } static ngAcceptInputType_value: string | number; /** * The minumum allowed value of the slider. */ @Input() @HostBinding('attr.aria-valuemin') get minValue() { return this._min; } set minValue(value: number) { this._min = this.asNumber(value); } static ngAcceptInputType_minValue: string | number; /** * The maximum allowed value of the slider. */ @Input() @HostBinding('attr.aria-valuemax') get maxValue() { return this._max; } set maxValue(value: number) { this._max = this.asNumber(value); } static ngAcceptInputType_maxValue: string | number; /** * Set the step value (or set to 0 for no step value). * The step value can be a floating point value &gt;= 0. * The slider will quantize all values to match the step value, except for the minimum and * maximum, which can always be set. * Discrete sliders are required to have a step value other than 0. * Note from the wrapped <code>mdc-slider</code> component: * <blockquote>If a slider contains a step value it does not mean that the slider is a "discrete" slider. * "Discrete slider" is a UX treatment, while having a step value is behavioral.</blockquote> */ @Input() get stepValue() { return this._step; } set stepValue(value: number) { this._step = this.asNumber(value); } static ngAcceptInputType_stepValue: string | number; /** * A property to disable the slider. */ @Input() @HostBinding('attr.aria-disabled') get disabled() { return this._disabled; } set disabled(value: boolean) { this._disabled = asBoolean(value); } static ngAcceptInputType_disabled: boolean | ''; /** @internal */ @HostListener('blur') _onBlur() { this._onTouched(); } /** @internal */ asNumber(value: number | string | null): number { if (value == null) return 0; let result = +value; if (isNaN(result)) return 0; return result; } } /** * Directive for adding Angular Forms (<code>ControlValueAccessor</code>) behavior to an * <code>MdcSliderDirective</code>. Allows the use of the Angular Forms API with * icon toggles, e.g. binding to <code>[(ngModel)]</code>, form validation, etc. */ @Directive({ selector: '[mdcSlider][formControlName],[mdcSlider][formControl],[mdcSlider][ngModel]', providers: [ {provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MdcFormsSliderDirective), multi: true} ] }) export class MdcFormsSliderDirective implements ControlValueAccessor { constructor(@Self() private mdcSlider: MdcSliderDirective) { } /** @docs-private */ writeValue(obj: any) { let change = new SimpleChange(this.mdcSlider.value, this.mdcSlider.asNumber(obj), false); this.mdcSlider.value = obj; this.mdcSlider._onChanges({value: change}); } /** @docs-private */ registerOnChange(onChange: (value: any) => void) { this.mdcSlider.registerOnChange(onChange); } /** @docs-private */ registerOnTouched(onTouched: () => any) { this.mdcSlider.registerOnTouched(onTouched); } /** @docs-private */ setDisabledState(disabled: boolean) { this.mdcSlider.disabled = disabled; } } export const SLIDER_DIRECTIVES = [ MdcSliderDirective, MdcFormsSliderDirective ];
the_stack
import { ComponentClass } from 'react' import Taro, { Component, Config } from '@tarojs/taro' import { View, Button, Image, Canvas } from '@tarojs/components' import { connect } from '@tarojs/redux' import globalData from '../../services/global_data' import { getSystemInfo } from '../../model/actions/global' import tool from '../../utils/tool' import {createCache} from '../../services/cache' import './index.less' import Title from '../../components/Title' import CustomIcon from '../../components/Icon' import Sticker from '../../components/Sticker' import SceneList from '../../components/SceneList' import ResultModal from '../../components/ResultModal' import service from '../../services/service' import mock_theme_data from './mock_theme_data.json' const mock_path = 'https://static01.versa-ai.com/upload/783272fc1375/999deac02e85f3ea.png' const mock_segment_url = 'https://static01.versa-ai.com/images/process/segment/2019/01/14/b4cf047a-17a5-11e9-817f-00163e001583.png' const getSceneList = function (sceneList:Array<object> = []) { const result = [] sceneList.forEach(v => { const {bgUrl, sceneId, sceneName, shareContent, thumbnailUrl, sceneConfig, segmentType, segmentZIndex, bgZIndex} = v let supportMusic = false if (sceneConfig) { const {music = {}} = JSON.parse(sceneConfig) supportMusic = music.fileUrl ? true : false } result.push({bgUrl, sceneId, sceneName, shareContent, thumbnailUrl, sceneConfig, segmentType, segmentZIndex, bgZIndex, supportMusic}) }) return result } type PageStateProps = { global: { system: object } } type PageDispatchProps = { getSystemInfo: (data:object) => void } type PageOwnProps = {} type PageState = { foreground: { remoteUrl: string, zIndex: number, width: number, height: number, x: number, y: number, rotate: number, originWidth: number, originHeight: number, autoWidth: number, autoHeight: number, autoScale: number, fixed: boolean, visible: boolean } } type IProps = PageStateProps & PageDispatchProps & PageOwnProps interface Dynamic { props: IProps; } @connect(({ counter, global }) => ({ counter, global }), (dispatch) => ({ getSystemInfo (data) { dispatch(getSystemInfo(data)) } })) class Dynamic extends Component { config: Config = { navigationBarTitleText: '马卡龙玩图-taro', disableScroll: true, } state = { rawImage: { localUrl: '', remoteUrl: '' }, frame: { width: 0, height: 0, left: 0, top: 0, }, foreground: { id: 'foreground', remoteUrl: '', zIndex:2, width:0, height:0, x: 0, y:0, rotate: 0, originWidth: 0, // 原始宽度 originHeight: 0, // 原始高度 autoWidth: 0, // 自适应后的宽度 autoHeight: 0, // 自适应后的高度 autoScale: 0, // 相对画框缩放比例 fixed: false, // 是否固定 isActive: true, // 是否激活 visible: true, // 是否显示 }, coverList: [ // { // id: 'cover-01', // remoteUrl: 'https://static01.versa-ai.com/images/process/segment/2019/01/07/a102310e-122a-11e9-b5ef-00163e023476.png', // originHeight: 2440, // originWidth: 750, // autoHeight: 244, // autoScale: 0.1, // autoWidth: 75, // width: 57.378244033967235, // height:186.6705539238401, // x: 185.1442062300867, // y: 155.66472303807996, // rotate: -25.912119928692746, // zIndex: 3, // fixed: false, // 是否固定 // isActive: false, // 是否激活 // visible: true, // 是否显示 // } ], sceneList: [], currentScene: {}, canvas: { id: 'shareCanvas', ratio: 3 }, result: { show: false, url: '', } } // 全局主题数据 themeData = { sceneList: [], rawCoverList: [], // 原始贴纸数据 } cache = { foreground: createCache('foreground'), cover: createCache('cover'), source: createCache('source'), } componentWillMount () { this.initSystemInfo() } componentDidMount () { this.calFrameRect() this.initRawImage() this.initSceneData(() => { this.initCoverData() }) this.initSegment() } componentWillReceiveProps (nextProps) { // console.log(this.props, nextProps) } componentWillUnmount () { } componentDidShow () { } componentDidHide () { } test = async () => { // try { // const result = await service.core.column() // console.log('result', result) // } catch(err) { // console.log('catch', err) // } // const uploadResult = await service.base.upload(mock_path, 'png') // console.log('uploadResult', uploadResult) } // 公共方法 PageToHome = () => { Taro.redirectTo({ url: '/pages/home/index' }) } setStateTarget = (key, value = {}, callback?:() => void) => { const target = this.state[key] this.setState({ [key]: { ...target, ...value } }, () => { typeof callback === 'function' && callback() }) } getDomRect = (id:string, callback:(rect:object)=>void) => { Taro.createSelectorQuery().select('#' + id).boundingClientRect(function(rect){ // rect.id // 节点的ID // rect.dataset // 节点的dataset // rect.left // 节点的左边界坐标 // rect.right // 节点的右边界坐标 // rect.top // 节点的上边界坐标 // rect.bottom // 节点的下边界坐标 // rect.width // 节点的宽度 // rect.height // 节点的高度 typeof callback === 'function' && callback(rect) }).exec() } calFrameRect = () => { this.getDomRect('crop', rect => { this.setState({ frame: { width: rect.width, height: rect.height, left: rect.left, top: rect.top, } }) }) } getSceneInfoById = (id:string, list:Array<any> = [], key:string) => { return list.filter(v => { return v[key] === id })[0] } getCoverInfoById = (id:string, list:Array<any> = [], key:string) => { return list.filter(v => { return v[key] === id })[0] } formatRawCoverList = (list) => { return list.map(v => { const cover_model = { id: '', remoteUrl: '', originHeight: 0, originWidth: 0, autoHeight: 0, autoScale: 0, autoWidth: 0, width: 0, height: 0, x: 0, y: 0, rotate: 0, zIndex: 0, fixed: false, isActive: false, visible: false } cover_model.remoteUrl = v.imageUrl cover_model.id = v.id cover_model.zIndex = v.zIndex || 0 cover_model.fixed = v.fixed || false cover_model.isActive = v.isActive || false cover_model.visible = true return cover_model }) } // 初始化系统信息 initSystemInfo = () => { const {getSystemInfo, global} = this.props if (!global.system.model) { const systemInfo = Taro.getSystemInfoSync() getSystemInfo(systemInfo) } } initRawImage = () => { const {rawImage} = this.state this.setState({ rawImage: { ...rawImage, localUrl: globalData.choosedImage } }) } // 初始化分割 initSegment = async () => { const {foreground} = this.state let segmentData try { Taro.showLoading({ title: '照片变身中...', mask: true, }) segmentData = await service.core.segmentDemo(globalData.choosedImage, mock_segment_url , 3000) Taro.hideLoading() } catch(err) { console.log('catch', err) } this.setState({ foreground: { ...foreground, remoteUrl: segmentData.result } }) } // 初始化场景信息 initSceneData = (callback) => { // 全局主题数据 const themeData = mock_theme_data.result this.themeData.sceneList = getSceneList(themeData.sceneList || []) // 去除sceneConfig属性 const sceneList = this.themeData.sceneList.map((v:object) => { const {sceneConfig, ...rest} = v return { ...rest } }) const currentScene = sceneList[0] this.setState({ sceneList: sceneList, currentScene: currentScene }, () => { // console.log('state', this.state) typeof callback === 'function' && callback() }) } // 初始化贴纸 initCoverData = () => { const {currentScene} = this.state const sceneInfo = this.getSceneInfoById(currentScene.sceneId, this.themeData.sceneList, 'sceneId') const sceneConfig = JSON.parse(sceneInfo.sceneConfig) const {cover = {}} = sceneConfig this.themeData.rawCoverList = cover.list || [] const coverList = this.formatRawCoverList(this.themeData.rawCoverList) this.setState({ coverList: coverList }) // console.log('initCoverData cover', cover, coverList) } // 背景 handleBackgroundClick = () => { this.setForegroundActiveStatus(false) this.setCoverListActiveStatus({type: 'all'}, false) } // 人物 handleForegroundLoaded = (detail:object, item?:any) => { // console.log('handleForegroundLoaded', detail, item) const {width, height} = detail this.setStateTarget('foreground', { originWidth: width, originHeight: height }, () => { this.foregroundAuto() }) } handleChangeStyle = (data) => { const {foreground} = this.state this.setState({ foreground: { ...foreground, ...data } }, () => { }) } handleForegroundTouchstart = (sticker) => { // console.log('handleForegroundTouchstart', sticker) this.setForegroundActiveStatus(true) this.setCoverListActiveStatus({type: 'all'}, false) } handleForegroundTouchend = () => { this.storeForegroundInfo() } // 贴纸 handleCoverLoaded = (detail:object, item?:any) => { // console.log('handleCoverLoaded', detail, item) const {width, height} = detail const originInfo = { originWidth: width, originHeight: height } this.coverAuto(originInfo, item) } handleChangeCoverStyle = (data) => { const {id} = data const {coverList} = this.state coverList.forEach((v, i) => { if (v.id === id) { coverList[i] = data } }) this.setState({ coverList: coverList }) } handleCoverTouchstart = (sticker) => { // console.log('handleCoverTouchstart', sticker) this.setCoverListActiveStatus({type: 'some', ids:[sticker.id]}, true) this.setForegroundActiveStatus(false) } handleCoverTouchend = (sticker) => { // console.log('handleCoverTouchend', sticker) this.storeCoverInfo(sticker) } // 更换场景 handleChooseScene = (scene) => { const {currentScene} = this.state if (!scene.sceneId || currentScene.sceneId === scene.sceneId ) { return } this.setState({ currentScene: scene }, () => { // console.log('handleChooseScene', this.state.currentScene) this.foregroundAuto() this.initCoverData() }) } // 保存 handleOpenResult = async () => { Taro.showLoading({ title: '照片生成中...', mask: true, }) const canvasImageUrl = await this.createCanvas() console.log('canvasImageUrl', canvasImageUrl) Taro.hideLoading() this.setState({ result: { url: canvasImageUrl, show: true } }) } // 再玩一次 handleResultClick = () => { this.setResultModalStatus(false) } setResultModalStatus = (flag = false) => { const {result} = this.state result.show = flag this.setState({ result: { ...result } }) } createCanvas = async () => { return new Promise(async (resolve, reject) => { const {currentScene, foreground, frame, canvas} = this.state const postfix = '?x-oss-process=image/resize,h_748,w_560' const context = Taro.createCanvasContext(canvas.id, this) const { ratio = 3 } = canvas // 下载远程背景图片 let localBgImagePath = '' try { const bgUrl = currentScene.bgUrl + postfix localBgImagePath = await this.downloadRemoteImage(bgUrl) } catch (err) { console.log('下载背景图片失败', err) return } //防止锯齿,绘的图片是所需图片的3倍 context.drawImage(localBgImagePath, 0, 0, frame.width * ratio, frame.height * ratio) // 绘制元素 await this.canvasDrawElement(context, ratio) //绘制图片 context.draw() //将生成好的图片保存到本地,需要延迟一会,绘制期间耗时 setTimeout(function () { Taro.canvasToTempFilePath({ canvasId: canvas.id, fileType: 'jpg', success: function (res) { let tempFilePath = res.tempFilePath resolve(tempFilePath) }, fail: function (res) { reject(res) }, complete:function(){ } }); }, 400) }) } // 绘制贴纸,文字,覆盖层所有元素 canvasDrawElement = async (context, ratio) => { const {currentScene, foreground, frame, canvas, coverList = []} = this.state // 收集所有元素进行排序 let elements:Array<any> = [] const element_foreground = { type: 'foreground', id: foreground.id, zIndex: foreground.zIndex, remoteUrl: foreground.remoteUrl, width: foreground.width * ratio, height: foreground.height * ratio, x: foreground.x * ratio, y: foreground.y * ratio, rotate: foreground.rotate, } // 收集人物 elements.push(element_foreground) // 收集贴纸 coverList.forEach(v => { const element_cover = { type: 'cover', zIndex: v.zIndex, id: v.id, remoteUrl: v.remoteUrl, width: v.width * ratio, height: v.height * ratio, x: v.x * ratio, y: v.y * ratio, rotate: v.rotate, } elements.push(element_cover) }) // 对元素进行排序 elements.sort((a, b) => { return a.zIndex - b.zIndex }) // 下载成本地图片并绘制 for (let i = 0; i < elements.length; i++ ) { const element = elements[i] try { const localImagePath = await this.downloadRemoteImage(element.remoteUrl) element.localUrl = localImagePath drawElement(element) } catch (err) { console.log('下载贴纸图片失败', err) continue } } // console.log('elements', elements) function drawElement ({localUrl, width, height, x, y, rotate}) { context.save() context.translate(x + 0.5 * width, y + 0.5 * height) context.rotate(rotate * Math.PI / 180) context.drawImage(localUrl, -0.5 * width, -0.5 * height, width, height) context.restore() context.stroke() } } // 下载照片并存储到本地 downloadRemoteImage = async (remoteUrl = '') => { // 判断是否在缓存里 const cacheKey = `${remoteUrl}_localPath` const cache_source = this.cache['source'] let localImagePath = '' if (cache_source.get(cacheKey)) { // console.log('get-cache', cacheKey, cache_source.get(cacheKey)) return cache_source.get(cacheKey) } else { try { const result = await service.base.downloadFile(remoteUrl) localImagePath = result.tempFilePath } catch (err) { console.log('下载图片失败', err) } } return this.cache['source'].set(cacheKey, localImagePath) } // 设置人物状态 setForegroundActiveStatus = (value = false) => { this.setStateTarget('foreground', {isActive: value}) } // 设置贴纸状态 setCoverListActiveStatus = (options = {}, value = false) => { const {type, ids = []} = options const {coverList} = this.state if (type === 'all') { coverList.forEach(v => { v['isActive'] = value }) } else { coverList.forEach(v => { if (ids.indexOf(v.id) > -1) { v['isActive'] = value } else { v['isActive'] = !value } }) } this.setState({ coverList }) } // 人物自适应 foregroundAuto = (callback?:()=>void) => { // 先判断是否有缓存 const {currentScene} = this.state const sceneId = currentScene.sceneId || 'demo_scene' const cache_foreground = this.cache['foreground'] const scene_foreground_params = cache_foreground.get(sceneId) if ( scene_foreground_params ) { this.setStateTarget('foreground', { ...scene_foreground_params }, () => { typeof callback === 'function' && callback() }) return } const size = this.calcForegroundSize() const position = this.calcForegroundPosition(size) this.setStateTarget('foreground', { ...size, ...position }, () => { typeof callback === 'function' && callback() }) } // 计算人物尺寸 calcForegroundSize = () => { const {currentScene, sceneList, foreground, frame} = this.state const {originWidth, originHeight} = foreground const sceneInfo = this.getSceneInfoById(currentScene.sceneId, this.themeData.sceneList, 'sceneId') // console.log('calcForegroundSize', this.themeData.sceneList, currentScene.sceneId, sceneInfo) const imageRatio = originWidth / originHeight const params = JSON.parse(sceneInfo.sceneConfig) const autoScale = parseFloat(params.size.default) const result = { autoScale, autoWidth: 0, autoHeight: 0, width: 0, height: 0 } if (originWidth > originHeight) { // 以最短边计算 result.autoWidth = frame.width * autoScale result.autoHeight = result.autoWidth / imageRatio } else { result.autoHeight = frame.height * autoScale result.autoWidth = result.autoHeight * imageRatio } result.width = result.autoWidth result.height = result.autoHeight return result } // 计算人物位置 calcForegroundPosition = ({width, height} = {}) => { const {currentScene, sceneList, foreground, frame} = this.state const {originWidth, originHeight} = foreground width = width || foreground.width height = height || foreground.height const sceneInfo = this.getSceneInfoById(currentScene.sceneId, this.themeData.sceneList, 'sceneId') const boxWidth = frame.width const boxHeight = frame.height const sceneConfig = JSON.parse(sceneInfo.sceneConfig) const {position} = sceneConfig const type = position.place || '0' const result = { x: 0, y: 0, rotate: 0 } switch (type) { case '0': result.x = (boxWidth - width) * 0.5 result.y = (boxHeight - height) * 0.5 break case '1': result.x = 0 result.y = 0 break case '2': result.x = (boxWidth - width) * 0.5 result.y = 0 break case '3': result.x = boxWidth - width result.y = 0 break case '4': result.x = boxWidth - width result.y = (boxHeight - height) * 0.5 break case '5': result.x = boxWidth - width result.y = boxHeight - height break case '6': result.x = (boxWidth - width) * 0.5 result.y = boxHeight - height break case '7': result.x = 0 result.y = boxHeight - height break case '8': result.x = 0 result.y = (boxHeight - height) * 0.5 break case '9': const result_location = location(position, boxWidth, boxHeight, width, height) result.x = result_location.x result.y = result_location.y break case '10': const result_center = centerLocation(position, boxWidth, boxHeight, width, height) result.x = result_center.x result.y = result_center.y break default: result.x = (boxWidth - width) * 0.5 result.y = (boxHeight - height) * 0.5 } result.rotate = parseInt(sceneConfig.rotate) return result function location (position, boxWidth, boxHeight, width, height) { const result = { x: 0, y: 0 } if (position.xAxis.derection === 'left') { result.x = position.xAxis.offset * boxWidth } if (position.xAxis.derection === 'right') { result.x = boxWidth * (1 - position.xAxis.offset) - width } if (position.yAxis.derection === 'top') { result.y = position.yAxis.offset * boxHeight } if (position.yAxis.derection === 'bottom') { result.y = boxHeight * (1 - position.yAxis.offset) - height } return result } // 中心点设置位置 function centerLocation (position, boxWidth, boxHeight, width, height) { const result = { x: 0, y: 0 } if (position.xAxis.derection === 'left') { result.x = position.xAxis.offset * boxWidth - width * 0.5 } if (position.xAxis.derection === 'right') { result.x = boxWidth * (1 - position.xAxis.offset) - width * 0.5 } if (position.yAxis.derection === 'top') { result.y = position.yAxis.offset * boxHeight - height * 0.5 } if (position.yAxis.derection === 'bottom') { result.y = boxHeight * (1 - position.yAxis.offset) - height * 0.5 } return result } } // 缓存人物尺寸位置 storeForegroundInfo = () => { const {foreground, currentScene} = this.state const clone_foreground = tool.deepClone(foreground) clone_foreground.isActive = false const sceneId = currentScene.sceneId || 'demo_scene' this.cache['foreground'].set(sceneId, clone_foreground) // console.log('this.cache.foreground', this.cache['foreground'].get(sceneId)) } // 贴纸自适应 coverAuto = (originInfo, cover, callback?:()=>void) => { const size = this.calcCoverSize(originInfo, cover) const position = this.calcCoverPosition(size, cover) const {coverList, currentScene} = this.state coverList.forEach((v, i) => { if (v.id === cover.id) { // 判断是否有缓存 const cacheKey = `${currentScene.sceneId}_${v.id}` const cacheRes = this.cache['cover'].get(cacheKey) if (cacheRes) { coverList[i] = cacheRes } else { coverList[i] = {...v, ...size, ...position} } } }) this.setState({ coverList: coverList }, () => { typeof callback === 'function' && callback() }) } calcCoverSize = (originInfo, cover) => { const {originWidth, originHeight} = originInfo const {frame} = this.state const coverInfo = this.getCoverInfoById(cover.id, this.themeData.rawCoverList, 'id') const imageRatio = originWidth / originHeight const autoScale = parseFloat(coverInfo.size.default || 0.5) const result = { autoScale, autoWidth: 0, autoHeight: 0, width: 0, height: 0 } if (originWidth > originHeight) { // 以最短边计算 result.autoWidth = frame.width * autoScale result.autoHeight = result.autoWidth / imageRatio } else { result.autoHeight = frame.height * autoScale result.autoWidth = result.autoHeight * imageRatio } result.width = result.autoWidth result.height = result.autoHeight return result } calcCoverPosition = (size = {}, cover = {}) => { const {width = 0, height = 0} = size const {frame} = this.state const coverInfo = this.getCoverInfoById(cover.id, this.themeData.rawCoverList, 'id') const {position, rotate = 0} = coverInfo const boxWidth = frame.width const boxHeight = frame.height const type = position.place || '0' const result = { x: 0, y: 0, rotate: 0 } switch (type) { case '0': result.x = (boxWidth - width) * 0.5 result.y = (boxHeight - height) * 0.5 break case '1': result.x = 0 result.y = 0 break case '2': result.x = (boxWidth - width) * 0.5 result.y = 0 break case '3': result.x = boxWidth - width result.y = 0 break case '4': result.x = boxWidth - width result.y = (boxHeight - height) * 0.5 break case '5': result.x = boxWidth - width result.y = boxHeight - height break case '6': result.x = (boxWidth - width) * 0.5 result.y = boxHeight - height break case '7': result.x = 0 result.y = boxHeight - height break case '8': result.x = 0 result.y = (boxHeight - height) * 0.5 break case '9': const result_location = location(position, boxWidth, boxHeight, width, height) result.x = result_location.x result.y = result_location.y break case '10': const result_center = centerLocation(position, boxWidth, boxHeight, width, height) result.x = result_center.x result.y = result_center.y break default: result.x = (boxWidth - width) * 0.5 result.y = (boxHeight - height) * 0.5 } result.rotate = parseInt(rotate) return result function location (position, boxWidth, boxHeight, width, height) { const result = { x: 0, y: 0 } if (position.xAxis.derection === 'left') { result.x = position.xAxis.offset * boxWidth } if (position.xAxis.derection === 'right') { result.x = boxWidth * (1 - position.xAxis.offset) - width } if (position.yAxis.derection === 'top') { result.y = position.yAxis.offset * boxHeight } if (position.yAxis.derection === 'bottom') { result.y = boxHeight * (1 - position.yAxis.offset) - height } return result } // 中心点设置位置 function centerLocation (position, boxWidth, boxHeight, width, height) { const result = { x: 0, y: 0 } if (position.xAxis.derection === 'left') { result.x = position.xAxis.offset * boxWidth - width * 0.5 } if (position.xAxis.derection === 'right') { result.x = boxWidth * (1 - position.xAxis.offset) - width * 0.5 } if (position.yAxis.derection === 'top') { result.y = position.yAxis.offset * boxHeight - height * 0.5 } if (position.yAxis.derection === 'bottom') { result.y = boxHeight * (1 - position.yAxis.offset) - height * 0.5 } return result } } // 缓存贴纸信息 storeCoverInfo = (sticker) => { const {currentScene} = this.state const clone_cover = tool.deepClone(sticker) // 贴纸存储不激活状态 clone_cover.isActive = false const sceneId = currentScene.sceneId || 'demo_scene' const cacheKey = `${sceneId}_${sticker.id}` this.cache['cover'].set(cacheKey, clone_cover) } render () { const { global } = this.props const { rawImage, frame, foreground, coverList, sceneList, currentScene, result, canvas } = this.state // console.log('state sceneList', sceneList) return ( <View className='page-dynamic'> <Title top={global.system.statusBarHeight + 10} color="#333" renderLeft={ <CustomIcon type="back" theme="dark" onClick={this.PageToHome}/> } >马卡龙玩图</Title> <View className="main"> <View className="pic-section"> <View className={`raw ${foreground.remoteUrl ? 'hidden' : ''}`}> <Image src={rawImage.localUrl} style="width:100%;height:100%" mode="aspectFit"/> </View> <View className={`crop ${foreground.remoteUrl ? '' : 'hidden'}`} id="crop"> <View className="background-image"> <Image src={currentScene.bgUrl} style="width:100%;height:100%" mode="scaleToFill" onClick={this.handleBackgroundClick} /> </View> <Sticker ref="foreground" url={foreground.remoteUrl} stylePrams={foreground} framePrams={frame} onChangeStyle={this.handleChangeStyle} onImageLoaded={this.handleForegroundLoaded} onTouchstart={this.handleForegroundTouchstart} onTouchend={this.handleForegroundTouchend} /> {coverList.map(item => { return <Sticker key={item.id} url={item.remoteUrl} stylePrams={item} framePrams={frame} onChangeStyle={this.handleChangeCoverStyle} onImageLoaded={this.handleCoverLoaded} onTouchstart={this.handleCoverTouchstart} onTouchend={this.handleCoverTouchend} /> })} </View> </View> <SceneList list={sceneList} currentScene={currentScene} styleObj={{width: '720rpx', paddingTop: '20rpx', marginRight: '-60rpx'}} onClick={this.handleChooseScene} /> <View className="button-section"> <Button className="custom-button pink" hoverClass="btn-hover" onClick={this.handleOpenResult}>保存</Button> </View> </View> <View class="canvas-wrap"> <Canvas style={`width: ${frame.width * canvas.ratio}px; height: ${frame.height * canvas.ratio}px;`} canvasId={canvas.id} /> </View> {result.show && <ResultModal url={result.url} onClick={this.handleResultClick} /> } </View> ) } } export default Dynamic as ComponentClass<PageOwnProps, PageState>
the_stack
import { extender, MessageBuilder, Message, MessageOptions, SplitOptions } from '@klasa/core'; import { Cache } from '@klasa/cache'; import { regExpEsc } from '@klasa/utils'; import { APIMessageData, ChannelType } from '@klasa/dapi-types'; import type { Command } from '../structures/Command'; import type { Language } from '../structures/Language'; import type { CommandPrompt } from '../usage/CommandPrompt'; import type { Gateway } from '../settings/gateway/Gateway'; import type { Settings } from '../settings/Settings'; export interface CachedPrefix { length: number; regex: RegExp | null; } /** * Klasa's Extended Message */ export class KlasaMessage extends extender.get('Message') { /** * The command being ran. */ public command!: Command | null; /** * The name of the command being ran. */ public commandText!: string | null; /** * The prefix used. */ public prefix!: RegExp | null; /** * The length of the prefix used. */ public prefixLength!: number | null; /** * A command prompt/argument handler. */ public prompter!: CommandPrompt | null; /** * The language for this message. */ public language!: Language; /** * The guild level settings for this context (guild || default) */ public guildSettings!: Settings; /** * All of the responses to this message. */ #responses: Message[]; public constructor(...args: any[]) { super(...args); this.command = this.command || null; this.commandText = this.commandText || null; this.prefix = this.prefix || null; this.prefixLength = this.prefixLength || null; this.prompter = this.prompter || null; this.#responses = []; } /** * The previous responses to this message * @since 0.5.0 */ public get responses(): Message[] { return this.#responses.filter(msg => !msg.deleted); } /** * The string arguments derived from the usageDelim of the command * @since 0.0.1 */ public get args(): (string | undefined | null)[] { return this.prompter ? this.prompter.args : []; } /** * The parameters resolved by this class * @since 0.0.1 */ public get params(): unknown[] { return this.prompter ? this.prompter.params : []; } /** * The flags resolved by this class * @since 0.5.0 */ public get flagArgs(): Record<string, string> { return this.prompter ? this.prompter.flags : {}; } /** * If the command reprompted for missing args * @since 0.0.1 */ public get reprompted(): boolean { return this.prompter ? this.prompter.reprompted : false; } /** * The usable commands by the author in this message's context * @since 0.0.1 */ public async usableCommands(): Promise<Cache<string, Command>> { const col = new Cache<string, Command>(); await Promise.all(this.client.commands.map((command) => this.client.inhibitors.run(this, command, true) .then(() => { col.set(command.name, command); }) .catch(() => { // noop }) )); return col; } /** * Checks if the author of this message, has applicable permission in this message's context of at least min * @since 0.0.1 */ public async hasAtLeastPermissionLevel(min: number): Promise<boolean> { const { permission } = await this.client.permissionLevels.run(this, min); return permission; } /** * Sends a message to the channel. * @param data The {@link MessageBuilder builder} to send. * @param options The split options for the message. * @since 0.0.1 * @see https://discord.com/developers/docs/resources/channel#create-message * @example * message.reply(new MessageBuilder() * .setContent('Ping!') * .setEmbed(new Embed().setDescription('From an embed!'))); */ public reply(data: MessageOptions, options?: SplitOptions): Promise<Message[]>; /** * Sends a message to the channel. * @param data A callback with a {@link MessageBuilder builder} as an argument. * @param options The split options for the message. * @since 0.0.1 * @see https://discord.com/developers/docs/resources/channel#create-message * @example * message.reply(builder => builder * .setContent('Ping!') * .setEmbed(embed => embed.setDescription('From an embed!'))); */ public reply(data: (message: MessageBuilder) => MessageBuilder | Promise<MessageBuilder>, options?: SplitOptions): Promise<Message[]>; public async reply(data: MessageOptions | ((message: MessageBuilder) => MessageBuilder | Promise<MessageBuilder>), options: SplitOptions = {}): Promise<Message[]> { const split = (typeof data === 'function' ? await data(new MessageBuilder()) : new MessageBuilder(data)).split(options); const { responses } = this; const promises = []; const deletes = []; const max = Math.max(split.length, responses.length); for (let i = 0; i < max; i++) { if (i >= split.length) deletes.push(responses[i].delete()); else if (responses.length > i) promises.push(responses[i].edit(split[i])); else promises.push(this.channel.send(split[i]).then(([message]: Message[]): Message => message)); } this.#responses = await Promise.all(promises) as Message[]; await Promise.all(deletes); return this.#responses.slice(0); } /** * Sends a message that will be editable via command editing (if nothing is attached) * @since 0.5.0 * @param key The Language key to send * @param options The split options */ public replyLocale(key: string, options?: SplitOptions): Promise<Message[]>; /** * Sends a message that will be editable via command editing (if nothing is attached) * @since 0.5.0 * @param key The Language key to send * @param localeArgs The language arguments to pass * @param options The split options */ public replyLocale(key: string, localeArgs?: unknown[], options?: SplitOptions): Promise<Message[]>; public replyLocale(key: string, localeArgs: unknown[] | SplitOptions = [], options?: SplitOptions): Promise<Message[]> { if (!Array.isArray(localeArgs)) [options, localeArgs] = [localeArgs, []]; return this.reply(mb => mb.setContent(this.language.get(key, ...localeArgs as unknown[])), options); } public toJSON(): Record<string, unknown> { return { ...super.toJSON(), prompter: undefined }; } /** * Extends the patch method from Message to attach and update the language to this instance * @since 0.5.0 */ protected _patch(data: Partial<APIMessageData>): this { super._patch(data); this.language = this.guild ? this.guild.language : this.client.languages.default; if (!this.guildSettings) { this.guildSettings = this.guild ? this.guild.settings : (this.client.gateways.get('guilds') as Gateway).schema.defaults as Settings; } this._parseCommand(); return this; } /** * Parses this message as a command * @since 0.5.0 */ private _parseCommand(): void { // Clear existing command state so edits to non-commands do not re-run commands this.prefix = null; this.prefixLength = null; this.commandText = null; this.command = null; this.prompter = null; try { const prefix = this._mentionPrefix() || this._customPrefix() || this._prefixLess(); if (!prefix) return; this.prefix = prefix.regex; this.prefixLength = prefix.length; this.commandText = this.content.slice(prefix.length).trim().split(' ')[0].toLowerCase(); this.command = this.client.commands.get(this.commandText) || null; if (!this.command) return; this.prompter = this.command.usage.createPrompt(this, { flagSupport: this.command.flagSupport, quotedStringSupport: this.command.quotedStringSupport, time: this.command.promptTime, limit: this.command.promptLimit }); } catch (error) { return; } } /** * Checks if the per-guild or default prefix is used * @since 0.5.0 */ private _customPrefix(): CachedPrefix | null { const prefix = this.guildSettings.get('prefix'); if (!prefix) return null; for (const prf of Array.isArray(prefix) ? prefix : [prefix]) { const testingPrefix = KlasaMessage.prefixes.get(prf) || KlasaMessage.generateNewPrefix(prf, this.client.options.commands.prefixCaseInsensitive ? 'i' : ''); if (testingPrefix.regex.test(this.content)) return testingPrefix; } return null; } /** * Checks if the mention was used as a prefix * @since 0.5.0 */ private _mentionPrefix(): CachedPrefix | null { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const mentionPrefix = this.client.mentionPrefix!.exec(this.content); return mentionPrefix ? { length: mentionPrefix[0].length, regex: this.client.mentionPrefix } : null; } /** * Checks if a prefixless scenario is possible * @since 0.5.0 */ private _prefixLess(): CachedPrefix | null { return this.client.options.commands.noPrefixDM && this.channel.type === ChannelType.DM ? { length: 0, regex: null } : null; } /** * Caches a new prefix regexp * @since 0.5.0 */ private static generateNewPrefix(prefix: string, flags: string): CachedPrefix { const prefixObject = { length: prefix.length, regex: new RegExp(`^${regExpEsc(prefix)}`, flags) }; this.prefixes.set(prefix, prefixObject); return prefixObject; } /** * Cache of RegExp prefixes * @since 0.5.0 */ private static prefixes = new Map(); } extender.extend('Message', () => KlasaMessage); declare module '@klasa/core/dist/src/lib/caching/structures/messages/Message' { export interface Message { command: Command | null; commandText: string | null; prefix: RegExp | null; prefixLength: number | null; prompter: CommandPrompt | null; language: Language; guildSettings: Settings; readonly responses: Message[]; readonly args: (string | undefined | null)[]; readonly params: unknown[]; readonly flagArgs: Record <string, string>; readonly reprompted: boolean; usableCommands(): Promise <Cache <string, Command>>; hasAtLeastPermissionLevel(min: number): Promise<boolean>; reply(data: MessageOptions, options?: SplitOptions): Promise<Message[]>; reply(data: (message: MessageBuilder) => MessageBuilder | Promise <MessageBuilder>, options?: SplitOptions): Promise<Message[]>; replyLocale(key: string, options?: SplitOptions): Promise<Message[]>; replyLocale(key: string, localeArgs?: unknown[], options?: SplitOptions): Promise<Message[]>; } }
the_stack
import request from 'supertest'; import { Ethereum } from '../../../src/chains/ethereum/ethereum'; import { patch, unpatch } from '../../services/patch'; import { gatewayApp } from '../../../src/app'; import { NETWORK_ERROR_CODE, RATE_LIMIT_ERROR_CODE, OUT_OF_GAS_ERROR_CODE, UNKNOWN_ERROR_ERROR_CODE, NETWORK_ERROR_MESSAGE, RATE_LIMIT_ERROR_MESSAGE, OUT_OF_GAS_ERROR_MESSAGE, UNKNOWN_ERROR_MESSAGE, } from '../../../src/services/error-handler'; import * as transactionSuccesful from './fixtures/transaction-succesful.json'; import * as transactionSuccesfulReceipt from './fixtures/transaction-succesful-receipt.json'; import * as transactionOutOfGas from './fixtures/transaction-out-of-gas.json'; import * as transactionOutOfGasReceipt from './fixtures/transaction-out-of-gas-receipt.json'; let eth: Ethereum; beforeAll(async () => { eth = Ethereum.getInstance('kovan'); await eth.init(); }); afterEach(() => unpatch()); const patchGetWallet = () => { patch(eth, 'getWallet', () => { return { address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', }; }); }; const patchGetNonce = () => { patch(eth.nonceManager, 'getNonce', () => 2); }; const patchGetERC20Balance = () => { patch(eth, 'getERC20Balance', () => ({ value: 1, decimals: 3 })); }; const patchGetNativeBalance = () => { patch(eth, 'getNativeBalance', () => ({ value: 1, decimals: 3 })); }; const patchGetERC20Allowance = () => { patch(eth, 'getERC20Allowance', () => ({ value: 1, decimals: 3 })); }; const patchGetTokenBySymbol = () => { patch(eth, 'getTokenBySymbol', (symbol: string) => { let result; switch (symbol) { case 'WETH': result = { chainId: 42, name: 'WETH', symbol: 'WETH', address: '0xd0A1E359811322d97991E03f863a0C30C2cF029C', decimals: 18, }; break; case 'DAI': result = { chainId: 42, name: 'DAI', symbol: 'DAI', address: '0xd0A1E359811322d97991E03f863a0C30C2cFFFFF', decimals: 18, }; break; } return result; }); }; const patchApproveERC20 = (tx_type?: string) => { const default_tx = { type: 2, chainId: 42, nonce: 115, maxPriorityFeePerGas: { toString: () => '106000000000' }, maxFeePerGas: { toString: () => '106000000000' }, gasPrice: { toString: () => null }, gasLimit: { toString: () => '100000' }, to: '0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa', value: { toString: () => '0' }, data: '0x095ea7b30000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', // noqa: mock accessList: [], hash: '0x75f98675a8f64dcf14927ccde9a1d59b67fa09b72cc2642ad055dae4074853d9', // noqa: mock v: 0, r: '0xbeb9aa40028d79b9fdab108fcef5de635457a05f3a254410414c095b02c64643', // noqa: mock s: '0x5a1506fa4b7f8b4f3826d8648f27ebaa9c0ee4bd67f569414b8cd8884c073100', // noqa: mock from: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', confirmations: 0, }; if (tx_type === 'overwritten_tx') { default_tx.hash = '0x5a1ed682d0d7a58fbd7828bbf5994cd024feb8895d4da82c741ec4a191b9e849'; // noqa: mock } patch(eth, 'approveERC20', () => { return default_tx; }); }; describe('POST /evm/allowances', () => { it('should return 200 asking for allowances', async () => { patchGetWallet(); patchGetTokenBySymbol(); const theSpender = '0xFaA12FD102FE8623C9299c72B03E45107F2772B5'; eth.getSpender = jest.fn().mockReturnValue(theSpender); eth.getContract = jest.fn().mockReturnValue({ address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', }); patchGetERC20Allowance(); await request(gatewayApp) .post(`/evm/allowances`) .send({ chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', spender: theSpender, tokenSymbols: ['WETH', 'DAI'], }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .expect((res) => expect(res.body.spender).toEqual(theSpender)) .expect((res) => expect(res.body.approvals.WETH).toEqual('0.001')) .expect((res) => expect(res.body.approvals.DAI).toEqual('0.001')); }); it('should return 404 when parameters are invalid', async () => { await request(gatewayApp) .post(`/evm/allowances`) .send({ chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', spender: '0xSpender', tokenSymbols: ['WETH', 'DAI'], }) .expect(404); }); }); describe('POST /network/balances', () => { it('should return 200 asking for supported tokens', async () => { patchGetWallet(); patchGetTokenBySymbol(); patchGetNativeBalance(); patchGetERC20Balance(); eth.getContract = jest.fn().mockReturnValue({ address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', }); await request(gatewayApp) .post(`/network/balances`) .send({ chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', tokenSymbols: ['WETH', 'DAI'], }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .expect((res) => expect(res.body.balances.WETH).toBeDefined()) .expect((res) => expect(res.body.balances.DAI).toBeDefined()); }); it('should return 200 asking for native token', async () => { patchGetWallet(); patchGetTokenBySymbol(); patchGetNativeBalance(); patchGetERC20Balance(); eth.getContract = jest.fn().mockReturnValue({ address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', }); await request(gatewayApp) .post(`/network/balances`) .send({ chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', tokenSymbols: ['ETH'], }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .expect((res) => expect(res.body.balances.ETH).toBeDefined()) .expect((res) => console.log(res.body)); }); it('should return 500 for unsupported tokens', async () => { patchGetWallet(); patchGetTokenBySymbol(); patchGetNativeBalance(); patchGetERC20Balance(); eth.getContract = jest.fn().mockReturnValue({ address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', }); await request(gatewayApp) .post(`/network/balances`) .send({ chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', tokenSymbols: ['XXX', 'YYY'], }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(500); }); it('should return 404 when parameters are invalid', async () => { await request(gatewayApp) .post(`/network/balances`) .send({ chain: 'ethereum', network: 'kovan', address: 'da857cbda0ba96757fed842617a4', }) .expect(404); }); }); describe('POST /evm/nonce', () => { it('should return 200', async () => { patchGetWallet(); patchGetNonce(); await request(gatewayApp) .post(`/evm/nonce`) .send({ chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .expect((res) => expect(res.body.nonce).toBe(2)); }); it('should return 404 when parameters are invalid', async () => { await request(gatewayApp) .post(`/evm/nonce`) .send({ chain: 'ethereum', network: 'kovan', address: 'da857cbda0ba96757fed842617a4', }) .expect(404); }); }); describe('POST /evm/approve', () => { it('approve without nonce parameter should return 200', async () => { patchGetWallet(); eth.getContract = jest.fn().mockReturnValue({ address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', }); patch(eth.nonceManager, 'getNonce', () => 115); patchGetTokenBySymbol(); patchApproveERC20(); await request(gatewayApp) .post(`/evm/approve`) .send({ chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', spender: 'uniswap', token: 'WETH', }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200); }); it('approve with nonce parameter should return 200', async () => { patchGetWallet(); patch(eth.nonceManager, 'getNonce', () => 115); patchGetTokenBySymbol(); patchApproveERC20(); await request(gatewayApp) .post(`/evm/approve`) .send({ chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', spender: 'uniswap', token: 'WETH', nonce: 115, }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((res: any) => { expect(res.body.nonce).toEqual(115); }); }); it('approve with maxFeePerGas and maxPriorityFeePerGas should return 200', async () => { patchGetWallet(); patch(eth.nonceManager, 'getNonce', () => 115); patchGetTokenBySymbol(); patchApproveERC20(); await request(gatewayApp) .post(`/evm/approve`) .send({ chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', spender: 'uniswap', token: 'WETH', nonce: 115, maxFeePerGas: '5000000000', maxPriorityFeePerGas: '5000000000', }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200); }); it('should return 404 when parameters are invalid', async () => { await request(gatewayApp) .post(`/evm/approve`) .send({ chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', spender: 'uniswap', token: 123, nonce: '23', }) .expect(404); }); }); describe('POST /evm/cancel', () => { it('should return 200', async () => { // override getWallet (network call) eth.getWallet = jest.fn().mockReturnValue({ address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', }); eth.cancelTx = jest.fn().mockReturnValue({ hash: '0xf6b9e7cec507cb3763a1179ff7e2a88c6008372e3a6f297d9027a0b39b0fff77', // noqa: mock }); await request(gatewayApp) .post(`/evm/cancel`) .send({ chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', nonce: 23, }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((res: any) => { expect(res.body.txHash).toEqual( '0xf6b9e7cec507cb3763a1179ff7e2a88c6008372e3a6f297d9027a0b39b0fff77' // noqa: mock ); }); }); it('should return 404 when parameters are invalid', async () => { await request(gatewayApp) .post(`/evm/cancel`) .send({ chain: 'ethereum', network: 'kovan', address: '', nonce: '23', }) .expect(404); }); }); describe('POST /network/poll', () => { it('should get a NETWORK_ERROR_CODE when the network is unavailable', async () => { patch(eth, 'getCurrentBlockNumber', () => { const error: any = new Error('something went wrong'); error.code = 'NETWORK_ERROR'; throw error; }); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'ethereum', network: 'kovan', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(503); expect(res.body.errorCode).toEqual(NETWORK_ERROR_CODE); expect(res.body.message).toEqual(NETWORK_ERROR_MESSAGE); }); it('should get a UNKNOWN_ERROR_ERROR_CODE when an unknown error is thrown', async () => { patch(eth, 'getCurrentBlockNumber', () => { throw new Error(); }); const res = await request(gatewayApp).post('/network/poll').send({ txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(503); expect(res.body.errorCode).toEqual(UNKNOWN_ERROR_ERROR_CODE); }); it('should get an OUT of GAS error for failed out of gas transactions', async () => { patch(eth, 'getCurrentBlockNumber', () => 1); patch(eth, 'getTransaction', () => transactionOutOfGas); patch(eth, 'getTransactionReceipt', () => transactionOutOfGasReceipt); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'ethereum', network: 'kovan', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(503); expect(res.body.errorCode).toEqual(OUT_OF_GAS_ERROR_CODE); expect(res.body.message).toEqual(OUT_OF_GAS_ERROR_MESSAGE); }); it('should get a null in txReceipt for Tx in the mempool', async () => { patch(eth, 'getCurrentBlockNumber', () => 1); patch(eth, 'getTransaction', () => transactionOutOfGas); patch(eth, 'getTransactionReceipt', () => null); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'ethereum', network: 'kovan', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(200); expect(res.body.txReceipt).toEqual(null); expect(res.body.txData).toBeDefined(); }); it('should get a null in txReceipt and txData for Tx that didnt reach the mempool and TxReceipt is null', async () => { patch(eth, 'getCurrentBlockNumber', () => 1); patch(eth, 'getTransaction', () => null); patch(eth, 'getTransactionReceipt', () => null); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'ethereum', network: 'kovan', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(200); expect(res.body.txReceipt).toEqual(null); expect(res.body.txData).toEqual(null); }); it('should get txStatus = 1 for a succesful query', async () => { patch(eth, 'getCurrentBlockNumber', () => 1); patch(eth, 'getTransaction', () => transactionSuccesful); patch(eth, 'getTransactionReceipt', () => transactionSuccesfulReceipt); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'ethereum', network: 'kovan', txHash: '0x6d068067a5e5a0f08c6395b31938893d1cdad81f54a54456221ecd8c1941294d', // noqa: mock }); expect(res.statusCode).toEqual(200); expect(res.body.txReceipt).toBeDefined(); expect(res.body.txData).toBeDefined(); }); it('should get an RATE_LIMIT_ERROR_CODE when the blockchain API is rate limited', async () => { patch(eth, 'getCurrentBlockNumber', () => { const error: any = new Error( 'daily request count exceeded, request rate limited' ); error.code = -32005; error.data = { see: 'https://infura.io/docs/ethereum/jsonrpc/ratelimits', current_rps: 13.333, allowed_rps: 10.0, backoff_seconds: 30.0, }; throw error; }); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'ethereum', network: 'kovan', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(503); expect(res.body.errorCode).toEqual(RATE_LIMIT_ERROR_CODE); expect(res.body.message).toEqual(RATE_LIMIT_ERROR_MESSAGE); }); it('should get unknown error', async () => { patch(eth, 'getCurrentBlockNumber', () => { const error: any = new Error('something went wrong'); error.code = -32006; throw error; }); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'ethereum', network: 'kovan', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(503); expect(res.body.errorCode).toEqual(UNKNOWN_ERROR_ERROR_CODE); expect(res.body.message).toEqual(UNKNOWN_ERROR_MESSAGE); }); }); describe('overwrite existing transaction', () => { it('overwritten transaction is dropped', async () => { patchGetWallet(); patch(eth.nonceManager, 'getNonce', () => 115); patchGetTokenBySymbol(); const requestParam = { chain: 'ethereum', network: 'kovan', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', spender: 'uniswap', token: 'WETH', nonce: 115, maxFeePerGas: '5000000000', maxPriorityFeePerGas: '5000000000', }; patchApproveERC20('overwritten_tx'); const tx_1 = await request(gatewayApp) .post(`/evm/approve`) .send(requestParam) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200); patchApproveERC20(); // patch to return different tx_hash requestParam.maxPriorityFeePerGas = '8000000000'; // we only increase maxPriorityFeePerGas const tx_2 = await request(gatewayApp) .post(`/evm/approve`) .send(requestParam) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200); // once tx_2 is confirmed, tx_1 will be dropped patch(eth, 'getCurrentBlockNumber', () => 1); patch(eth, 'getTransaction', () => null); patch(eth, 'getTransactionReceipt', () => null); const res_1 = await request(gatewayApp).post('/network/poll').send({ chain: 'ethereum', network: 'kovan', txHash: tx_1.body.approval.hash, }); expect(res_1.statusCode).toEqual(200); expect(res_1.body.txReceipt).toEqual(null); expect(res_1.body.txData).toEqual(null); patch(eth, 'getCurrentBlockNumber', () => 1); patch(eth, 'getTransaction', () => transactionSuccesful); patch(eth, 'getTransactionReceipt', () => transactionSuccesfulReceipt); const res_2 = await request(gatewayApp).post('/network/poll').send({ chain: 'ethereum', network: 'kovan', txHash: tx_2.body.approval.hash, }); expect(res_2.statusCode).toEqual(200); expect(res_2.body.txReceipt).toBeDefined(); expect(res_2.body.txData).toBeDefined(); }); });
the_stack
import colors from 'colors/safe'; import fs from 'fs'; import open from 'open'; import path from 'path'; import { Transform, TransformCallback } from 'stream'; import { FullConfig, Suite, Reporter } from '../../types/testReporter'; import { HttpServer } from 'playwright-core/lib/utils/httpServer'; import { calculateSha1, removeFolders } from 'playwright-core/lib/utils/utils'; import RawReporter, { JsonReport, JsonSuite, JsonTestCase, JsonTestResult, JsonTestStep } from './raw'; import assert from 'assert'; import yazl from 'yazl'; import { stripAnsiEscapes } from './base'; export type Stats = { total: number; expected: number; unexpected: number; flaky: number; skipped: number; ok: boolean; duration: number; }; export type Location = { file: string; line: number; column: number; }; export type HTMLReport = { files: TestFileSummary[]; stats: Stats; projectNames: string[]; }; export type TestFile = { fileId: string; fileName: string; tests: TestCase[]; hooks: TestCase[]; }; export type TestFileSummary = { fileId: string; fileName: string; tests: TestCaseSummary[]; hooks: TestCaseSummary[]; stats: Stats; }; export type TestCaseSummary = { testId: string, title: string; path: string[]; projectName: string; location: Location; annotations: { type: string, description?: string }[]; outcome: 'skipped' | 'expected' | 'unexpected' | 'flaky'; duration: number; ok: boolean; }; export type TestCase = TestCaseSummary & { results: TestResult[]; }; export type TestAttachment = { name: string; body?: string; path?: string; contentType: string; }; export type TestResult = { retry: number; startTime: string; duration: number; steps: TestStep[]; error?: string; attachments: TestAttachment[]; status: 'passed' | 'failed' | 'timedOut' | 'skipped'; }; export type TestStep = { title: string; startTime: string; duration: number; location?: Location; snippet?: string; error?: string; steps: TestStep[]; }; type TestEntry = { testCase: TestCase; testCaseSummary: TestCaseSummary }; const kMissingContentType = 'x-playwright/missing'; class HtmlReporter implements Reporter { private config!: FullConfig; private suite!: Suite; private _outputFolder: string | undefined; private _open: 'always' | 'never' | 'on-failure'; constructor(options: { outputFolder?: string, open?: 'always' | 'never' | 'on-failure' } = {}) { // TODO: resolve relative to config. this._outputFolder = options.outputFolder; this._open = options.open || 'on-failure'; } printsToStdio() { return false; } onBegin(config: FullConfig, suite: Suite) { this.config = config; this.suite = suite; } async onEnd() { const projectSuites = this.suite.suites; const reports = projectSuites.map(suite => { const rawReporter = new RawReporter(); const report = rawReporter.generateProjectReport(this.config, suite); return report; }); const reportFolder = htmlReportFolder(this._outputFolder); await removeFolders([reportFolder]); const builder = new HtmlBuilder(reportFolder); const { ok, singleTestId } = await builder.build(reports); if (process.env.PWTEST_SKIP_TEST_OUTPUT || process.env.CI) return; const shouldOpen = this._open === 'always' || (!ok && this._open === 'on-failure'); if (shouldOpen) { await showHTMLReport(reportFolder, singleTestId); } else { const outputFolderPath = htmlReportFolder(this._outputFolder) === defaultReportFolder() ? '' : ' ' + path.relative(process.cwd(), htmlReportFolder(this._outputFolder)); console.log(''); console.log('To open last HTML report run:'); console.log(colors.cyan(` npx playwright show-report${outputFolderPath} `)); } } } export function htmlReportFolder(outputFolder?: string): string { if (process.env[`PLAYWRIGHT_HTML_REPORT`]) return path.resolve(process.cwd(), process.env[`PLAYWRIGHT_HTML_REPORT`]); if (outputFolder) return outputFolder; return defaultReportFolder(); } function defaultReportFolder(): string { return path.resolve(process.cwd(), 'playwright-report'); } export async function showHTMLReport(reportFolder: string | undefined, testId?: string) { const folder = reportFolder || htmlReportFolder(); try { assert(fs.statSync(folder).isDirectory()); } catch (e) { console.log(colors.red(`No report found at "${folder}"`)); process.exit(1); return; } const server = startHtmlReportServer(folder); let url = await server.start(9323); console.log(''); console.log(colors.cyan(` Serving HTML report at ${url}. Press Ctrl+C to quit.`)); if (testId) url += `#?testId=${testId}`; open(url); await new Promise(() => {}); } export function startHtmlReportServer(folder: string): HttpServer { const server = new HttpServer(); server.routePrefix('/', (request, response) => { let relativePath = new URL('http://localhost' + request.url).pathname; if (relativePath.startsWith('/trace/file')) { const url = new URL('http://localhost' + request.url!); try { return server.serveFile(request, response, url.searchParams.get('path')!); } catch (e) { return false; } } if (relativePath === '/') relativePath = '/index.html'; const absolutePath = path.join(folder, ...relativePath.split('/')); return server.serveFile(request, response, absolutePath); }); return server; } class HtmlBuilder { private _reportFolder: string; private _tests = new Map<string, JsonTestCase>(); private _testPath = new Map<string, string[]>(); private _dataZipFile: yazl.ZipFile; private _hasTraces = false; constructor(outputDir: string) { this._reportFolder = path.resolve(process.cwd(), outputDir); fs.mkdirSync(this._reportFolder, { recursive: true }); this._dataZipFile = new yazl.ZipFile(); } async build(rawReports: JsonReport[]): Promise<{ ok: boolean, singleTestId: string | undefined }> { const data = new Map<string, { testFile: TestFile, testFileSummary: TestFileSummary }>(); for (const projectJson of rawReports) { for (const file of projectJson.suites) { const fileName = file.location!.file; const fileId = file.fileId; let fileEntry = data.get(fileId); if (!fileEntry) { fileEntry = { testFile: { fileId, fileName, tests: [], hooks: [] }, testFileSummary: { fileId, fileName, tests: [], hooks: [], stats: emptyStats() }, }; data.set(fileId, fileEntry); } const { testFile, testFileSummary } = fileEntry; const testEntries: TestEntry[] = []; const hookEntries: TestEntry[] = []; this._processJsonSuite(file, fileId, projectJson.project.name, [], testEntries, hookEntries); for (const test of testEntries) { testFile.tests.push(test.testCase); testFileSummary.tests.push(test.testCaseSummary); } for (const hook of hookEntries) { testFile.hooks.push(hook.testCase); testFileSummary.hooks.push(hook.testCaseSummary); } } } let ok = true; for (const [fileId, { testFile, testFileSummary }] of data) { const stats = testFileSummary.stats; for (const test of testFileSummary.tests) { if (test.outcome === 'expected') ++stats.expected; if (test.outcome === 'skipped') ++stats.skipped; if (test.outcome === 'unexpected') ++stats.unexpected; if (test.outcome === 'flaky') ++stats.flaky; ++stats.total; stats.duration += test.duration; } stats.ok = stats.unexpected + stats.flaky === 0; if (!stats.ok) ok = false; const testCaseSummaryComparator = (t1: TestCaseSummary, t2: TestCaseSummary) => { const w1 = (t1.outcome === 'unexpected' ? 1000 : 0) + (t1.outcome === 'flaky' ? 1 : 0); const w2 = (t2.outcome === 'unexpected' ? 1000 : 0) + (t2.outcome === 'flaky' ? 1 : 0); if (w2 - w1) return w2 - w1; return t1.location.line - t2.location.line; }; testFileSummary.tests.sort(testCaseSummaryComparator); testFileSummary.hooks.sort(testCaseSummaryComparator); this._addDataFile(fileId + '.json', testFile); } const htmlReport: HTMLReport = { files: [...data.values()].map(e => e.testFileSummary), projectNames: rawReports.map(r => r.project.name), stats: [...data.values()].reduce((a, e) => addStats(a, e.testFileSummary.stats), emptyStats()) }; htmlReport.files.sort((f1, f2) => { const w1 = f1.stats.unexpected * 1000 + f1.stats.flaky; const w2 = f2.stats.unexpected * 1000 + f2.stats.flaky; return w2 - w1; }); this._addDataFile('report.json', htmlReport); // Copy app. const appFolder = path.join(require.resolve('playwright-core'), '..', 'lib', 'webpack', 'htmlReport'); fs.copyFileSync(path.join(appFolder, 'index.html'), path.join(this._reportFolder, 'index.html')); // Copy trace viewer. if (this._hasTraces) { const traceViewerFolder = path.join(require.resolve('playwright-core'), '..', 'lib', 'webpack', 'traceViewer'); const traceViewerTargetFolder = path.join(this._reportFolder, 'trace'); fs.mkdirSync(traceViewerTargetFolder, { recursive: true }); for (const file of fs.readdirSync(traceViewerFolder)) { if (file.endsWith('.map')) continue; fs.copyFileSync(path.join(traceViewerFolder, file), path.join(traceViewerTargetFolder, file)); } } // Inline report data. const indexFile = path.join(this._reportFolder, 'index.html'); fs.appendFileSync(indexFile, '<script>\nwindow.playwrightReportBase64 = "data:application/zip;base64,'); await new Promise(f => { this._dataZipFile!.end(undefined, () => { this._dataZipFile!.outputStream .pipe(new Base64Encoder()) .pipe(fs.createWriteStream(indexFile, { flags: 'a' })).on('close', f); }); }); fs.appendFileSync(indexFile, '";</script>'); let singleTestId: string | undefined; if (htmlReport.stats.total === 1) { const testFile: TestFile = data.values().next().value.testFile; singleTestId = testFile.tests[0].testId; } return { ok, singleTestId }; } private _addDataFile(fileName: string, data: any) { this._dataZipFile.addBuffer(Buffer.from(JSON.stringify(data)), fileName); } private _processJsonSuite(suite: JsonSuite, fileId: string, projectName: string, path: string[], outTests: TestEntry[], outHooks: TestEntry[]) { const newPath = [...path, suite.title]; suite.suites.map(s => this._processJsonSuite(s, fileId, projectName, newPath, outTests, outHooks)); suite.tests.forEach(t => outTests.push(this._createTestEntry(t, projectName, newPath))); suite.hooks.forEach(t => outHooks.push(this._createTestEntry(t, projectName, newPath))); } private _createTestEntry(test: JsonTestCase, projectName: string, path: string[]): TestEntry { const duration = test.results.reduce((a, r) => a + r.duration, 0); this._tests.set(test.testId, test); const location = test.location; path = [...path.slice(1)]; this._testPath.set(test.testId, path); return { testCase: { testId: test.testId, title: test.title, projectName, location, duration, annotations: test.annotations, outcome: test.outcome, path, results: test.results.map(r => this._createTestResult(r)), ok: test.outcome === 'expected' || test.outcome === 'flaky', }, testCaseSummary: { testId: test.testId, title: test.title, projectName, location, duration, annotations: test.annotations, outcome: test.outcome, path, ok: test.outcome === 'expected' || test.outcome === 'flaky', }, }; } private _createTestResult(result: JsonTestResult): TestResult { let lastAttachment: TestAttachment | undefined; return { duration: result.duration, startTime: result.startTime, retry: result.retry, steps: result.steps.map(s => this._createTestStep(s)), error: result.error, status: result.status, attachments: result.attachments.map(a => { if (a.name === 'trace') this._hasTraces = true; if ((a.name === 'stdout' || a.name === 'stderr') && a.contentType === 'text/plain') { if (lastAttachment && lastAttachment.name === a.name && lastAttachment.contentType === a.contentType) { lastAttachment.body += stripAnsiEscapes(a.body as string); return null; } a.body = stripAnsiEscapes(a.body as string); lastAttachment = a as TestAttachment; return a; } if (a.path) { let fileName = a.path; try { const buffer = fs.readFileSync(a.path); const sha1 = calculateSha1(buffer) + path.extname(a.path); fileName = 'data/' + sha1; fs.mkdirSync(path.join(this._reportFolder, 'data'), { recursive: true }); fs.writeFileSync(path.join(this._reportFolder, 'data', sha1), buffer); } catch (e) { return { name: `Missing attachment "${a.name}"`, contentType: kMissingContentType, body: `Attachment file ${fileName} is missing`, }; } return { name: a.name, contentType: a.contentType, path: fileName, body: a.body, }; } if (a.body instanceof Buffer) { if (isTextContentType(a.contentType)) { // Content type is like this: "text/html; charset=UTF-8" const charset = a.contentType.match(/charset=(.*)/)?.[1]; try { const body = a.body.toString(charset as any || 'utf-8'); return { name: a.name, contentType: a.contentType, body, }; } catch (e) { // Invalid encoding, fall through and save to file. } } fs.mkdirSync(path.join(this._reportFolder, 'data'), { recursive: true }); const sha1 = calculateSha1(a.body) + '.dat'; fs.writeFileSync(path.join(this._reportFolder, 'data', sha1), a.body); return { name: a.name, contentType: a.contentType, path: 'data/' + sha1, body: a.body, }; } // string return { name: a.name, contentType: a.contentType, body: a.body, }; }).filter(Boolean) as TestAttachment[] }; } private _createTestStep(step: JsonTestStep): TestStep { return { title: step.title, startTime: step.startTime, duration: step.duration, snippet: step.snippet, steps: step.steps.map(s => this._createTestStep(s)), location: step.location, error: step.error }; } } const emptyStats = (): Stats => { return { total: 0, expected: 0, unexpected: 0, flaky: 0, skipped: 0, ok: true, duration: 0, }; }; const addStats = (stats: Stats, delta: Stats): Stats => { stats.total += delta.total; stats.skipped += delta.skipped; stats.expected += delta.expected; stats.unexpected += delta.unexpected; stats.flaky += delta.flaky; stats.ok = stats.ok && delta.ok; stats.duration += delta.duration; return stats; }; class Base64Encoder extends Transform { private _remainder: Buffer | undefined; override _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void { if (this._remainder) { chunk = Buffer.concat([this._remainder, chunk]); this._remainder = undefined; } const remaining = chunk.length % 3; if (remaining) { this._remainder = chunk.slice(chunk.length - remaining); chunk = chunk.slice(0, chunk.length - remaining); } chunk = chunk.toString('base64'); this.push(Buffer.from(chunk)); callback(); } override _flush(callback: TransformCallback): void { if (this._remainder) this.push(Buffer.from(this._remainder.toString('base64'))); callback(); } } function isTextContentType(contentType: string) { return contentType.startsWith('text/') || contentType.startsWith('application/json'); } export default HtmlReporter;
the_stack
import { Dataset } from "../core/dataset"; import { IAccessor, IRangeProjector, Point } from "../core/interfaces"; import * as Scales from "../scales"; import { IScaleCallback, Scale } from "../scales/scale"; import * as Utils from "../utils"; import { ITransformableAccessorScaleBinding } from "./commons"; import { DeferredRenderer } from "./deferredRenderer"; import { Plot } from "./plot"; export class XYPlot<X, Y> extends Plot { protected static _X_KEY = "x"; protected static _Y_KEY = "y"; private _autoAdjustXScaleDomain = false; private _autoAdjustYScaleDomain = false; private _adjustYDomainOnChangeFromXCallback: IScaleCallback<Scale<any, any>>; private _adjustXDomainOnChangeFromYCallback: IScaleCallback<Scale<any, any>>; private _deferredRendering = false; private _deferredRenderer: DeferredRenderer<X, Y>; /** * An XYPlot is a Plot that displays data along two primary directions, X and Y. * * @constructor * @param {Scale} xScale The x scale to use. * @param {Scale} yScale The y scale to use. */ constructor() { super(); this.addClass("xy-plot"); this._adjustYDomainOnChangeFromXCallback = (scale) => this._adjustYDomainOnChangeFromX(); this._adjustXDomainOnChangeFromYCallback = (scale) => this._adjustXDomainOnChangeFromY(); this._renderCallback = () => { if (this.deferredRendering()) { const scaleX = this.x() && this.x().scale; const scaleY = this.y() && this.y().scale; this._deferredRenderer.updateDomains(scaleX, scaleY); } else { this.render(); } }; this._deferredRenderer = new DeferredRenderer<X, Y>(() => this.render(), this._applyDeferredRenderingTransform); } public render() { if (this.deferredRendering()) { this._deferredRenderer.resetTransforms(); } return super.render(); } /** * Returns the whether or not the rendering is deferred for performance boost. * * @return {boolean} The deferred rendering option */ public deferredRendering(): boolean; /** * Sets / unsets the deferred rendering option Activating this option improves * the performance of plot interaction (pan / zoom) by performing lazy * renders, only after the interaction has stopped. Because re-rendering is no * longer performed during the interaction, the zooming might experience a * small resolution degradation, before the lazy re-render is performed. * * This option is intended for cases where performance is an issue. */ public deferredRendering(deferredRendering: boolean): this; public deferredRendering(deferredRendering?: boolean): any { if (deferredRendering == null) { return this._deferredRendering; } if (deferredRendering) { const scaleX = this.x() && this.x().scale; const scaleY = this.y() && this.y().scale; this._deferredRenderer.setDomains(scaleX, scaleY); } this._deferredRendering = deferredRendering; return this; } /** * Gets the TransformableAccessorScaleBinding for X. */ public x(): ITransformableAccessorScaleBinding<X, number>; /** * Sets X to a constant number or the result of an Accessor<number>. * * @param {number|Accessor<number>} x * @returns {XYPlot} The calling XYPlot. */ public x(x: number | IAccessor<number>): this; /** * Sets X to a scaled constant value or scaled result of an Accessor. * The provided Scale will account for the values when autoDomain()-ing. * * @param {X|Accessor<X>} x * @param {Scale<X, number>} xScale * @returns {XYPlot} The calling XYPlot. */ public x(x: X | IAccessor<X>, xScale: Scale<X, number>, postScale?: IRangeProjector<number>): this; public x(x?: number | IAccessor<number> | X | IAccessor<X>, xScale?: Scale<X, number>, postScale?: IRangeProjector<number>): any { if (x == null) { return this._propertyBindings.get(XYPlot._X_KEY); } this._bindProperty(XYPlot._X_KEY, x, xScale, postScale); const width = this.width(); if (xScale != null && width != null) { xScale.range([0, width]); } if (this._autoAdjustYScaleDomain) { this._updateYExtentsAndAutodomain(); } this.render(); return this; } /** * Gets the AccessorScaleBinding for Y. */ public y(): ITransformableAccessorScaleBinding<Y, number>; /** * Sets Y to a constant number or the result of an Accessor<number>. * * @param {number|Accessor<number>} y * @returns {XYPlot} The calling XYPlot. */ public y(y: number | IAccessor<number>): this; /** * Sets Y to a scaled constant value or scaled result of an Accessor. * The provided Scale will account for the values when autoDomain()-ing. * * @param {Y|Accessor<Y>} y * @param {Scale<Y, number>} yScale * @returns {XYPlot} The calling XYPlot. */ public y(y: Y | IAccessor<Y>, yScale: Scale<Y, number>, postScale?: IRangeProjector<number>): this; public y(y?: number | IAccessor<number> | Y | IAccessor<Y>, yScale?: Scale<Y, number>, postScale?: IRangeProjector<number>): any { if (y == null) { return this._propertyBindings.get(XYPlot._Y_KEY); } this._bindProperty(XYPlot._Y_KEY, y, yScale, postScale); const height = this.height(); if (yScale != null && height != null) { if (yScale instanceof Scales.Category) { yScale.range([0, height]); } else { yScale.range([height, 0]); } } if (this._autoAdjustXScaleDomain) { this._updateXExtentsAndAutodomain(); } this.render(); return this; } protected _filterForProperty(property: string): IAccessor<boolean> { if (property === "x" && this._autoAdjustXScaleDomain) { return this._makeFilterByProperty("y"); } else if ((property === "y" || property === "y0") && this._autoAdjustYScaleDomain) { return this._makeFilterByProperty("x"); } return null; } private _makeFilterByProperty(property: string) { const binding = this._propertyBindings.get(property); if (binding != null) { const accessor = binding.accessor; const scale = binding.scale; if (scale != null) { return (datum: any, index: number, dataset: Dataset) => { const range = scale.range(); return Utils.Math.inRange(scale.scale(accessor(datum, index, dataset)), range[0], range[1]); }; } } return null; } private _applyDeferredRenderingTransform = (tx: number, ty: number, sx: number, sy: number) => { if (!this._isAnchored) { return; } if (this._renderArea != null) { this._renderArea.attr("transform", `translate(${tx}, ${ty}) scale(${sx}, ${sy})`); } if (this._canvas != null) { this._canvas.style("transform", `translate(${tx}px, ${ty}px) scale(${sx}, ${sy})`); } } protected _uninstallScaleForKey(scale: Scale<any, any>, key: string) { super._uninstallScaleForKey(scale, key); const adjustCallback = key === XYPlot._X_KEY ? this._adjustYDomainOnChangeFromXCallback : this._adjustXDomainOnChangeFromYCallback; scale.offUpdate(adjustCallback); } protected _installScaleForKey(scale: Scale<any, any>, key: string) { super._installScaleForKey(scale, key); const adjustCallback = key === XYPlot._X_KEY ? this._adjustYDomainOnChangeFromXCallback : this._adjustXDomainOnChangeFromYCallback; scale.onUpdate(adjustCallback); } public destroy() { super.destroy(); if (this.x().scale) { this.x().scale.offUpdate(this._adjustYDomainOnChangeFromXCallback); } if (this.y().scale) { this.y().scale.offUpdate(this._adjustXDomainOnChangeFromYCallback); } return this; } /** * Gets the automatic domain adjustment mode for visible points. */ public autorangeMode(): string; /** * Sets the automatic domain adjustment mode for visible points to operate against the X Scale, Y Scale, or neither. * If "x" or "y" is specified the adjustment is immediately performed. * * @param {string} autorangeMode One of "x"/"y"/"none". * "x" will adjust the x Scale in relation to changes in the y domain. * "y" will adjust the y Scale in relation to changes in the x domain. * "none" means neither Scale will change automatically. * @returns {XYPlot} The calling XYPlot. */ public autorangeMode(autorangeMode: string): this; public autorangeMode(autorangeMode?: string): any { if (autorangeMode == null) { if (this._autoAdjustXScaleDomain) { return "x"; } if (this._autoAdjustYScaleDomain) { return "y"; } return "none"; } switch (autorangeMode) { case "x": this._autoAdjustXScaleDomain = true; this._autoAdjustYScaleDomain = false; this._adjustXDomainOnChangeFromY(); break; case "y": this._autoAdjustXScaleDomain = false; this._autoAdjustYScaleDomain = true; this._adjustYDomainOnChangeFromX(); break; case "none": this._autoAdjustXScaleDomain = false; this._autoAdjustYScaleDomain = false; break; default: throw new Error("Invalid scale name '" + autorangeMode + "', must be 'x', 'y' or 'none'"); } return this; } public computeLayout(origin?: Point, availableWidth?: number, availableHeight?: number) { super.computeLayout(origin, availableWidth, availableHeight); const xBinding = this.x(); const xScale = xBinding && xBinding.scale; if (xScale != null) { xScale.range([0, this.width()]); } const yBinding = this.y(); const yScale = yBinding && yBinding.scale; if (yScale != null) { if (yScale instanceof Scales.Category) { yScale.range([0, this.height()]); } else { yScale.range([this.height(), 0]); } } return this; } private _updateXExtentsAndAutodomain() { const xScale = this.x().scale; if (xScale != null) { xScale.autoDomain(); } } private _updateYExtentsAndAutodomain() { const yScale = this.y().scale; if (yScale != null) { yScale.autoDomain(); } } /** * Adjusts the domains of both X and Y scales to show all data. * This call does not override the autorange() behavior. * * @returns {XYPlot} The calling XYPlot. */ public showAllData() { this._updateXExtentsAndAutodomain(); this._updateYExtentsAndAutodomain(); return this; } private _adjustYDomainOnChangeFromX() { if (!this._projectorsReady()) { return; } if (this._autoAdjustYScaleDomain) { this._updateYExtentsAndAutodomain(); } } private _adjustXDomainOnChangeFromY() { if (!this._projectorsReady()) { return; } if (this._autoAdjustXScaleDomain) { this._updateXExtentsAndAutodomain(); } } protected _projectorsReady() { const xBinding = this.x(); const yBinding = this.y(); return xBinding != null && xBinding.accessor != null && yBinding != null && yBinding.accessor != null; } protected _pixelPoint(datum: any, index: number, dataset: Dataset): Point { const xProjector = Plot._scaledAccessor(this.x()); const yProjector = Plot._scaledAccessor(this.y()); return { x: xProjector(datum, index, dataset), y: yProjector(datum, index, dataset) }; } protected _getDataToDraw(): Utils.Map<Dataset, any[]> { const dataToDraw: Utils.Map<Dataset, any[]> = super._getDataToDraw(); const definedAttr = this.attr("defined"); const definedFunction = (d: any, i: number, dataset: Dataset) => { const positionX = Plot._scaledAccessor(this.x())(d, i, dataset); const positionY = Plot._scaledAccessor(this.y())(d, i, dataset); if (definedAttr && definedAttr.accessor(d, i, dataset) === false) { return false; } return Utils.Math.isValidNumber(positionX) && Utils.Math.isValidNumber(positionY); }; this.datasets().forEach((dataset) => { dataToDraw.set(dataset, dataToDraw.get(dataset).filter((d, i) => definedFunction(d, i, dataset))); }); return dataToDraw; } }
the_stack
import { ChainId, ContractAddresses } from '@0x/contract-addresses'; import { IZeroExContract } from '@0x/contract-wrappers'; import { encodeAffiliateFeeTransformerData, encodeCurveLiquidityProviderData, encodeFillQuoteTransformerData, encodePayTakerTransformerData, encodePositiveSlippageFeeTransformerData, encodeWethTransformerData, ETH_TOKEN_ADDRESS, FillQuoteTransformerOrderType, FillQuoteTransformerSide, findTransformerNonce, } from '@0x/protocol-utils'; import { BigNumber } from '@0x/utils'; import * as _ from 'lodash'; import { constants, POSITIVE_SLIPPAGE_FEE_TRANSFORMER_GAS } from '../constants'; import { AffiliateFeeType, CalldataInfo, ExchangeProxyContractOpts, MarketBuySwapQuote, MarketOperation, MarketSellSwapQuote, SwapQuote, SwapQuoteConsumerBase, SwapQuoteConsumerOpts, SwapQuoteExecutionOpts, SwapQuoteGetOutputOpts, } from '../types'; import { assert } from '../utils/assert'; import { CURVE_LIQUIDITY_PROVIDER_BY_CHAIN_ID, MOONISWAP_LIQUIDITY_PROVIDER_BY_CHAIN_ID, NATIVE_FEE_TOKEN_BY_CHAIN_ID, } from '../utils/market_operation_utils/constants'; import { poolEncoder } from '../utils/market_operation_utils/orders'; import { CurveFillData, ERC20BridgeSource, FinalUniswapV3FillData, LiquidityProviderFillData, MooniswapFillData, OptimizedMarketBridgeOrder, OptimizedMarketOrder, UniswapV2FillData, } from '../utils/market_operation_utils/types'; import { multiplexPlpEncoder, multiplexRfqEncoder, MultiplexSubcall, multiplexTransformERC20Encoder, multiplexUniswapEncoder, } from './multiplex_encoders'; import { getFQTTransformerDataFromOptimizedOrders, isBuyQuote, isDirectSwapCompatible, isMultiplexBatchFillCompatible, isMultiplexMultiHopFillCompatible, } from './quote_consumer_utils'; // tslint:disable-next-line:custom-no-magic-numbers const MAX_UINT256 = new BigNumber(2).pow(256).minus(1); const { NULL_ADDRESS, NULL_BYTES, ZERO_AMOUNT } = constants; // use the same order in IPancakeSwapFeature.sol const PANCAKE_SWAP_FORKS = [ ERC20BridgeSource.PancakeSwap, ERC20BridgeSource.PancakeSwapV2, ERC20BridgeSource.BakerySwap, ERC20BridgeSource.SushiSwap, ERC20BridgeSource.ApeSwap, ERC20BridgeSource.CafeSwap, ERC20BridgeSource.CheeseSwap, ERC20BridgeSource.JulSwap, ]; const FAKE_PROVIDER: any = { sendAsync(): void { return; }, }; export class ExchangeProxySwapQuoteConsumer implements SwapQuoteConsumerBase { public readonly chainId: ChainId; public readonly transformerNonces: { wethTransformer: number; payTakerTransformer: number; fillQuoteTransformer: number; affiliateFeeTransformer: number; positiveSlippageFeeTransformer: number; }; private readonly _exchangeProxy: IZeroExContract; constructor(public readonly contractAddresses: ContractAddresses, options: Partial<SwapQuoteConsumerOpts> = {}) { const { chainId } = _.merge({}, constants.DEFAULT_SWAP_QUOTER_OPTS, options); assert.isNumber('chainId', chainId); this.chainId = chainId; this.contractAddresses = contractAddresses; this._exchangeProxy = new IZeroExContract(contractAddresses.exchangeProxy, FAKE_PROVIDER); this.transformerNonces = { wethTransformer: findTransformerNonce( contractAddresses.transformers.wethTransformer, contractAddresses.exchangeProxyTransformerDeployer, ), payTakerTransformer: findTransformerNonce( contractAddresses.transformers.payTakerTransformer, contractAddresses.exchangeProxyTransformerDeployer, ), fillQuoteTransformer: findTransformerNonce( contractAddresses.transformers.fillQuoteTransformer, contractAddresses.exchangeProxyTransformerDeployer, ), affiliateFeeTransformer: findTransformerNonce( contractAddresses.transformers.affiliateFeeTransformer, contractAddresses.exchangeProxyTransformerDeployer, ), positiveSlippageFeeTransformer: findTransformerNonce( contractAddresses.transformers.positiveSlippageFeeTransformer, contractAddresses.exchangeProxyTransformerDeployer, ), }; } public async getCalldataOrThrowAsync( quote: MarketBuySwapQuote | MarketSellSwapQuote, opts: Partial<SwapQuoteGetOutputOpts> = {}, ): Promise<CalldataInfo> { const optsWithDefaults: ExchangeProxyContractOpts = { ...constants.DEFAULT_EXCHANGE_PROXY_EXTENSION_CONTRACT_OPTS, ...opts.extensionContractOpts, }; // tslint:disable-next-line:no-object-literal-type-assertion const { refundReceiver, affiliateFee, isFromETH, isToETH, shouldSellEntireBalance } = optsWithDefaults; const sellToken = quote.takerToken; const buyToken = quote.makerToken; // Take the bounds from the worst case const sellAmount = BigNumber.max( quote.bestCaseQuoteInfo.totalTakerAmount, quote.worstCaseQuoteInfo.totalTakerAmount, ); let minBuyAmount = quote.worstCaseQuoteInfo.makerAmount; let ethAmount = quote.worstCaseQuoteInfo.protocolFeeInWeiAmount; if (isFromETH) { ethAmount = ethAmount.plus(sellAmount); } const slippedOrders = slipNonNativeOrders(quote); // VIP routes. if ( this.chainId === ChainId.Mainnet && isDirectSwapCompatible(quote, optsWithDefaults, [ERC20BridgeSource.UniswapV2, ERC20BridgeSource.SushiSwap]) ) { const source = slippedOrders[0].source; const fillData = (slippedOrders[0] as OptimizedMarketBridgeOrder<UniswapV2FillData>).fillData; return { calldataHexString: this._exchangeProxy .sellToUniswap( fillData.tokenAddressPath.map((a, i) => { if (i === 0 && isFromETH) { return ETH_TOKEN_ADDRESS; } if (i === fillData.tokenAddressPath.length - 1 && isToETH) { return ETH_TOKEN_ADDRESS; } return a; }), sellAmount, minBuyAmount, source === ERC20BridgeSource.SushiSwap, ) .getABIEncodedTransactionData(), ethAmount: isFromETH ? sellAmount : ZERO_AMOUNT, toAddress: this._exchangeProxy.address, allowanceTarget: this._exchangeProxy.address, gasOverhead: ZERO_AMOUNT, }; } if ( this.chainId === ChainId.Mainnet && isDirectSwapCompatible(quote, optsWithDefaults, [ERC20BridgeSource.UniswapV3]) ) { const fillData = (slippedOrders[0] as OptimizedMarketBridgeOrder<FinalUniswapV3FillData>).fillData; let _calldataHexString; if (isFromETH) { _calldataHexString = this._exchangeProxy .sellEthForTokenToUniswapV3(fillData.uniswapPath, minBuyAmount, NULL_ADDRESS) .getABIEncodedTransactionData(); } else if (isToETH) { _calldataHexString = this._exchangeProxy .sellTokenForEthToUniswapV3(fillData.uniswapPath, sellAmount, minBuyAmount, NULL_ADDRESS) .getABIEncodedTransactionData(); } else { _calldataHexString = this._exchangeProxy .sellTokenForTokenToUniswapV3(fillData.uniswapPath, sellAmount, minBuyAmount, NULL_ADDRESS) .getABIEncodedTransactionData(); } return { calldataHexString: _calldataHexString, ethAmount: isFromETH ? sellAmount : ZERO_AMOUNT, toAddress: this._exchangeProxy.address, allowanceTarget: this._exchangeProxy.address, gasOverhead: ZERO_AMOUNT, }; } if ( this.chainId === ChainId.BSC && isDirectSwapCompatible(quote, optsWithDefaults, [ ERC20BridgeSource.PancakeSwap, ERC20BridgeSource.PancakeSwapV2, ERC20BridgeSource.BakerySwap, ERC20BridgeSource.SushiSwap, ERC20BridgeSource.ApeSwap, ERC20BridgeSource.CafeSwap, ERC20BridgeSource.CheeseSwap, ERC20BridgeSource.JulSwap, ]) ) { const source = slippedOrders[0].source; const fillData = (slippedOrders[0] as OptimizedMarketBridgeOrder<UniswapV2FillData>).fillData; return { calldataHexString: this._exchangeProxy .sellToPancakeSwap( fillData.tokenAddressPath.map((a, i) => { if (i === 0 && isFromETH) { return ETH_TOKEN_ADDRESS; } if (i === fillData.tokenAddressPath.length - 1 && isToETH) { return ETH_TOKEN_ADDRESS; } return a; }), sellAmount, minBuyAmount, PANCAKE_SWAP_FORKS.indexOf(source), ) .getABIEncodedTransactionData(), ethAmount: isFromETH ? sellAmount : ZERO_AMOUNT, toAddress: this._exchangeProxy.address, allowanceTarget: this._exchangeProxy.address, gasOverhead: ZERO_AMOUNT, }; } if ( [ChainId.Mainnet, ChainId.BSC].includes(this.chainId) && isDirectSwapCompatible(quote, optsWithDefaults, [ERC20BridgeSource.LiquidityProvider]) ) { const fillData = (slippedOrders[0] as OptimizedMarketBridgeOrder<LiquidityProviderFillData>).fillData; const target = fillData.poolAddress; return { calldataHexString: this._exchangeProxy .sellToLiquidityProvider( isFromETH ? ETH_TOKEN_ADDRESS : sellToken, isToETH ? ETH_TOKEN_ADDRESS : buyToken, target, NULL_ADDRESS, sellAmount, minBuyAmount, NULL_BYTES, ) .getABIEncodedTransactionData(), ethAmount: isFromETH ? sellAmount : ZERO_AMOUNT, toAddress: this._exchangeProxy.address, allowanceTarget: this._exchangeProxy.address, gasOverhead: ZERO_AMOUNT, }; } if ( this.chainId === ChainId.Mainnet && isDirectSwapCompatible(quote, optsWithDefaults, [ERC20BridgeSource.Curve, ERC20BridgeSource.Swerve]) && // Curve VIP cannot currently support WETH buy/sell as the functionality needs to WITHDRAW or DEPOSIT // into WETH prior/post the trade. // ETH buy/sell is supported ![sellToken, buyToken].includes(NATIVE_FEE_TOKEN_BY_CHAIN_ID[ChainId.Mainnet]) ) { const fillData = slippedOrders[0].fills[0].fillData as CurveFillData; return { calldataHexString: this._exchangeProxy .sellToLiquidityProvider( isFromETH ? ETH_TOKEN_ADDRESS : sellToken, isToETH ? ETH_TOKEN_ADDRESS : buyToken, CURVE_LIQUIDITY_PROVIDER_BY_CHAIN_ID[this.chainId], NULL_ADDRESS, sellAmount, minBuyAmount, encodeCurveLiquidityProviderData({ curveAddress: fillData.pool.poolAddress, exchangeFunctionSelector: fillData.pool.exchangeFunctionSelector, fromCoinIdx: new BigNumber(fillData.fromTokenIdx), toCoinIdx: new BigNumber(fillData.toTokenIdx), }), ) .getABIEncodedTransactionData(), ethAmount: isFromETH ? sellAmount : ZERO_AMOUNT, toAddress: this._exchangeProxy.address, allowanceTarget: this._exchangeProxy.address, gasOverhead: ZERO_AMOUNT, }; } if ( this.chainId === ChainId.Mainnet && isDirectSwapCompatible(quote, optsWithDefaults, [ERC20BridgeSource.Mooniswap]) ) { const fillData = slippedOrders[0].fills[0].fillData as MooniswapFillData; return { calldataHexString: this._exchangeProxy .sellToLiquidityProvider( isFromETH ? ETH_TOKEN_ADDRESS : sellToken, isToETH ? ETH_TOKEN_ADDRESS : buyToken, MOONISWAP_LIQUIDITY_PROVIDER_BY_CHAIN_ID[this.chainId], NULL_ADDRESS, sellAmount, minBuyAmount, poolEncoder.encode([fillData.poolAddress]), ) .getABIEncodedTransactionData(), ethAmount: isFromETH ? sellAmount : ZERO_AMOUNT, toAddress: this._exchangeProxy.address, allowanceTarget: this.contractAddresses.exchangeProxy, gasOverhead: ZERO_AMOUNT, }; } if (this.chainId === ChainId.Mainnet && isMultiplexBatchFillCompatible(quote, optsWithDefaults)) { return { calldataHexString: this._encodeMultiplexBatchFillCalldata( { ...quote, orders: slippedOrders }, optsWithDefaults, ), ethAmount, toAddress: this._exchangeProxy.address, allowanceTarget: this._exchangeProxy.address, gasOverhead: ZERO_AMOUNT, }; } if (this.chainId === ChainId.Mainnet && isMultiplexMultiHopFillCompatible(quote, optsWithDefaults)) { return { calldataHexString: this._encodeMultiplexMultiHopFillCalldata( { ...quote, orders: slippedOrders }, optsWithDefaults, ), ethAmount, toAddress: this._exchangeProxy.address, allowanceTarget: this._exchangeProxy.address, gasOverhead: ZERO_AMOUNT, }; } // Build up the transforms. const transforms = []; // Create a WETH wrapper if coming from ETH. // Dont add the wethTransformer to CELO. There is no wrap/unwrap logic for CELO. if (isFromETH && this.chainId !== ChainId.Celo) { transforms.push({ deploymentNonce: this.transformerNonces.wethTransformer, data: encodeWethTransformerData({ token: ETH_TOKEN_ADDRESS, amount: shouldSellEntireBalance ? MAX_UINT256 : sellAmount, }), }); } // If it's two hop we have an intermediate token this is needed to encode the individual FQT // and we also want to ensure no dust amount is left in the flash wallet const intermediateToken = quote.isTwoHop ? slippedOrders[0].makerToken : NULL_ADDRESS; // This transformer will fill the quote. if (quote.isTwoHop) { const [firstHopOrder, secondHopOrder] = slippedOrders; transforms.push({ deploymentNonce: this.transformerNonces.fillQuoteTransformer, data: encodeFillQuoteTransformerData({ side: FillQuoteTransformerSide.Sell, sellToken, buyToken: intermediateToken, ...getFQTTransformerDataFromOptimizedOrders([firstHopOrder]), refundReceiver: refundReceiver || NULL_ADDRESS, fillAmount: shouldSellEntireBalance ? MAX_UINT256 : firstHopOrder.takerAmount, }), }); transforms.push({ deploymentNonce: this.transformerNonces.fillQuoteTransformer, data: encodeFillQuoteTransformerData({ side: FillQuoteTransformerSide.Sell, buyToken, sellToken: intermediateToken, ...getFQTTransformerDataFromOptimizedOrders([secondHopOrder]), refundReceiver: refundReceiver || NULL_ADDRESS, fillAmount: MAX_UINT256, }), }); } else { const fillAmount = isBuyQuote(quote) ? quote.makerTokenFillAmount : quote.takerTokenFillAmount; transforms.push({ deploymentNonce: this.transformerNonces.fillQuoteTransformer, data: encodeFillQuoteTransformerData({ side: isBuyQuote(quote) ? FillQuoteTransformerSide.Buy : FillQuoteTransformerSide.Sell, sellToken, buyToken, ...getFQTTransformerDataFromOptimizedOrders(slippedOrders), refundReceiver: refundReceiver || NULL_ADDRESS, fillAmount: !isBuyQuote(quote) && shouldSellEntireBalance ? MAX_UINT256 : fillAmount, }), }); } // Create a WETH unwrapper if going to ETH. // Dont add the wethTransformer on CELO. There is no wrap/unwrap logic for CELO. if (isToETH && this.chainId !== ChainId.Celo) { transforms.push({ deploymentNonce: this.transformerNonces.wethTransformer, data: encodeWethTransformerData({ token: NATIVE_FEE_TOKEN_BY_CHAIN_ID[this.chainId], amount: MAX_UINT256, }), }); } const { feeType, buyTokenFeeAmount, sellTokenFeeAmount, recipient: feeRecipient } = affiliateFee; let gasOverhead = ZERO_AMOUNT; if (feeType === AffiliateFeeType.PositiveSlippageFee && feeRecipient !== NULL_ADDRESS) { // bestCaseAmountWithSurplus is used to cover gas cost of sending positive slipapge fee to fee recipient // this helps avoid sending dust amounts which are not worth the gas cost to transfer let bestCaseAmountWithSurplus = quote.bestCaseQuoteInfo.makerAmount .plus( POSITIVE_SLIPPAGE_FEE_TRANSFORMER_GAS.multipliedBy(quote.gasPrice).multipliedBy( quote.makerAmountPerEth, ), ) .integerValue(); // In the event makerAmountPerEth is unknown, we only allow for positive slippage which is greater than // the best case amount bestCaseAmountWithSurplus = BigNumber.max(bestCaseAmountWithSurplus, quote.bestCaseQuoteInfo.makerAmount); transforms.push({ deploymentNonce: this.transformerNonces.positiveSlippageFeeTransformer, data: encodePositiveSlippageFeeTransformerData({ token: isToETH ? ETH_TOKEN_ADDRESS : buyToken, bestCaseAmount: BigNumber.max(bestCaseAmountWithSurplus, quote.bestCaseQuoteInfo.makerAmount), recipient: feeRecipient, }), }); // This may not be visible at eth_estimateGas time, so we explicitly add overhead gasOverhead = POSITIVE_SLIPPAGE_FEE_TRANSFORMER_GAS; } else if (feeType === AffiliateFeeType.PercentageFee && feeRecipient !== NULL_ADDRESS) { // This transformer pays affiliate fees. if (buyTokenFeeAmount.isGreaterThan(0)) { transforms.push({ deploymentNonce: this.transformerNonces.affiliateFeeTransformer, data: encodeAffiliateFeeTransformerData({ fees: [ { token: isToETH ? ETH_TOKEN_ADDRESS : buyToken, amount: buyTokenFeeAmount, recipient: feeRecipient, }, ], }), }); // Adjust the minimum buy amount by the fee. minBuyAmount = BigNumber.max(0, minBuyAmount.minus(buyTokenFeeAmount)); } if (sellTokenFeeAmount.isGreaterThan(0)) { throw new Error('Affiliate fees denominated in sell token are not yet supported'); } } // Return any unspent sell tokens. const payTakerTokens = [sellToken]; // Return any unspent intermediate tokens for two-hop swaps. if (quote.isTwoHop) { payTakerTokens.push(intermediateToken); } // Return any unspent ETH. If ETH is the buy token, it will // be returned in TransformERC20Feature rather than PayTakerTransformer. if (!isToETH) { payTakerTokens.push(ETH_TOKEN_ADDRESS); } // The final transformer will send all funds to the taker. transforms.push({ deploymentNonce: this.transformerNonces.payTakerTransformer, data: encodePayTakerTransformerData({ tokens: payTakerTokens, amounts: [], }), }); const TO_ETH_ADDRESS = this.chainId === ChainId.Celo ? this.contractAddresses.etherToken : ETH_TOKEN_ADDRESS; const calldataHexString = this._exchangeProxy .transformERC20( isFromETH ? ETH_TOKEN_ADDRESS : sellToken, isToETH ? TO_ETH_ADDRESS : buyToken, shouldSellEntireBalance ? MAX_UINT256 : sellAmount, minBuyAmount, transforms, ) .getABIEncodedTransactionData(); return { calldataHexString, ethAmount, toAddress: this._exchangeProxy.address, allowanceTarget: this._exchangeProxy.address, gasOverhead, }; } // tslint:disable-next-line:prefer-function-over-method public async executeSwapQuoteOrThrowAsync( _quote: SwapQuote, _opts: Partial<SwapQuoteExecutionOpts>, ): Promise<string> { throw new Error('Execution not supported for Exchange Proxy quotes'); } private _encodeMultiplexBatchFillCalldata(quote: SwapQuote, opts: ExchangeProxyContractOpts): string { const subcalls = []; for_loop: for (const [i, order] of quote.orders.entries()) { switch_statement: switch (order.source) { case ERC20BridgeSource.Native: if (order.type !== FillQuoteTransformerOrderType.Rfq) { // Should never happen because we check `isMultiplexBatchFillCompatible` // before calling this function. throw new Error('Multiplex batch fill only supported for RFQ native orders'); } subcalls.push({ id: MultiplexSubcall.Rfq, sellAmount: order.takerAmount, data: multiplexRfqEncoder.encode({ order: order.fillData.order, signature: order.fillData.signature, }), }); break switch_statement; case ERC20BridgeSource.UniswapV2: case ERC20BridgeSource.SushiSwap: subcalls.push({ id: MultiplexSubcall.UniswapV2, sellAmount: order.takerAmount, data: multiplexUniswapEncoder.encode({ tokens: (order.fillData as UniswapV2FillData).tokenAddressPath, isSushi: order.source === ERC20BridgeSource.SushiSwap, }), }); break switch_statement; case ERC20BridgeSource.LiquidityProvider: subcalls.push({ id: MultiplexSubcall.LiquidityProvider, sellAmount: order.takerAmount, data: multiplexPlpEncoder.encode({ provider: (order.fillData as LiquidityProviderFillData).poolAddress, auxiliaryData: NULL_BYTES, }), }); break switch_statement; case ERC20BridgeSource.UniswapV3: const fillData = (order as OptimizedMarketBridgeOrder<FinalUniswapV3FillData>).fillData; subcalls.push({ id: MultiplexSubcall.UniswapV3, sellAmount: order.takerAmount, data: fillData.uniswapPath, }); break switch_statement; default: const fqtData = encodeFillQuoteTransformerData({ side: FillQuoteTransformerSide.Sell, sellToken: quote.takerToken, buyToken: quote.makerToken, ...getFQTTransformerDataFromOptimizedOrders(quote.orders.slice(i)), refundReceiver: NULL_ADDRESS, fillAmount: MAX_UINT256, }); const transformations = [ { deploymentNonce: this.transformerNonces.fillQuoteTransformer, data: fqtData }, { deploymentNonce: this.transformerNonces.payTakerTransformer, data: encodePayTakerTransformerData({ tokens: [quote.takerToken], amounts: [], }), }, ]; subcalls.push({ id: MultiplexSubcall.TransformERC20, sellAmount: BigNumber.sum(...quote.orders.slice(i).map(o => o.takerAmount)), data: multiplexTransformERC20Encoder.encode({ transformations, }), }); break for_loop; } } if (opts.isFromETH) { return this._exchangeProxy .multiplexBatchSellEthForToken(quote.makerToken, subcalls, quote.worstCaseQuoteInfo.makerAmount) .getABIEncodedTransactionData(); } else if (opts.isToETH) { return this._exchangeProxy .multiplexBatchSellTokenForEth( quote.takerToken, subcalls, quote.worstCaseQuoteInfo.totalTakerAmount, quote.worstCaseQuoteInfo.makerAmount, ) .getABIEncodedTransactionData(); } else { return this._exchangeProxy .multiplexBatchSellTokenForToken( quote.takerToken, quote.makerToken, subcalls, quote.worstCaseQuoteInfo.totalTakerAmount, quote.worstCaseQuoteInfo.makerAmount, ) .getABIEncodedTransactionData(); } } private _encodeMultiplexMultiHopFillCalldata(quote: SwapQuote, opts: ExchangeProxyContractOpts): string { const subcalls = []; const [firstHopOrder, secondHopOrder] = quote.orders; const intermediateToken = firstHopOrder.makerToken; const tokens = [quote.takerToken, intermediateToken, quote.makerToken]; for (const order of [firstHopOrder, secondHopOrder]) { switch (order.source) { case ERC20BridgeSource.UniswapV2: case ERC20BridgeSource.SushiSwap: subcalls.push({ id: MultiplexSubcall.UniswapV2, data: multiplexUniswapEncoder.encode({ tokens: (order.fillData as UniswapV2FillData).tokenAddressPath, isSushi: order.source === ERC20BridgeSource.SushiSwap, }), }); break; case ERC20BridgeSource.LiquidityProvider: subcalls.push({ id: MultiplexSubcall.LiquidityProvider, data: multiplexPlpEncoder.encode({ provider: (order.fillData as LiquidityProviderFillData).poolAddress, auxiliaryData: NULL_BYTES, }), }); break; case ERC20BridgeSource.UniswapV3: subcalls.push({ id: MultiplexSubcall.UniswapV3, data: (order.fillData as FinalUniswapV3FillData).uniswapPath, }); break; default: // Should never happen because we check `isMultiplexMultiHopFillCompatible` // before calling this function. throw new Error(`Multiplex multi-hop unsupported source: ${order.source}`); } } if (opts.isFromETH) { return this._exchangeProxy .multiplexMultiHopSellEthForToken(tokens, subcalls, quote.worstCaseQuoteInfo.makerAmount) .getABIEncodedTransactionData(); } else if (opts.isToETH) { return this._exchangeProxy .multiplexMultiHopSellTokenForEth( tokens, subcalls, quote.worstCaseQuoteInfo.totalTakerAmount, quote.worstCaseQuoteInfo.makerAmount, ) .getABIEncodedTransactionData(); } else { return this._exchangeProxy .multiplexMultiHopSellTokenForToken( tokens, subcalls, quote.worstCaseQuoteInfo.totalTakerAmount, quote.worstCaseQuoteInfo.makerAmount, ) .getABIEncodedTransactionData(); } } } function slipNonNativeOrders(quote: MarketSellSwapQuote | MarketBuySwapQuote): OptimizedMarketOrder[] { const slippage = getMaxQuoteSlippageRate(quote); if (!slippage) { return quote.orders; } return quote.orders.map(o => { if (o.source === ERC20BridgeSource.Native) { return o; } return { ...o, ...(quote.type === MarketOperation.Sell ? { makerAmount: o.makerAmount.times(1 - slippage).integerValue(BigNumber.ROUND_DOWN) } : { takerAmount: o.takerAmount.times(1 + slippage).integerValue(BigNumber.ROUND_UP) }), }; }); } function getMaxQuoteSlippageRate(quote: MarketBuySwapQuote | MarketSellSwapQuote): number { if (quote.type === MarketOperation.Buy) { // (worstCaseTaker - bestCaseTaker) / bestCaseTaker // where worstCaseTaker >= bestCaseTaker return quote.worstCaseQuoteInfo.takerAmount .minus(quote.bestCaseQuoteInfo.takerAmount) .div(quote.bestCaseQuoteInfo.takerAmount) .toNumber(); } // (bestCaseMaker - worstCaseMaker) / bestCaseMaker // where bestCaseMaker >= worstCaseMaker return quote.bestCaseQuoteInfo.makerAmount .minus(quote.worstCaseQuoteInfo.makerAmount) .div(quote.bestCaseQuoteInfo.makerAmount) .toNumber(); }
the_stack
import { ChildProperty, Property, Complex } from '@syncfusion/ej2-base'; import { PointModel, DecoratorShapes } from '@syncfusion/ej2-drawings'; import { Point } from '@syncfusion/ej2-drawings'; import { Size } from '@syncfusion/ej2-drawings'; import { PdfBoundsModel, PdfAnnotationBaseModel, PdfFontModel } from './pdf-annotation-model'; import { Container } from '@syncfusion/ej2-drawings'; import { PdfAnnotationType, FormFieldAnnotationType } from './enum'; import { ICommentsCollection, IReviewCollection, AnnotationSelectorSettingsModel, AllowedInteraction, ItemModel, SignatureIndicatorSettingsModel } from '../index'; /** * The `PdfBounds` is base for annotation bounds. * * @hidden */ export abstract class PdfBounds extends ChildProperty<PdfBounds> { /** * Represents the the x value of the annotation. * * @default 0 */ @Property(0) public x: number; /** * Represents the the y value of the annotation. * * @default 0 */ @Property(0) public y: number; /** * Represents the the width value of the annotation. * * @default 0 */ @Property(0) public width: number; /** * Represents the the height value of the annotation. * * @default 0 */ @Property(0) public height: number; /** * Represents the the left value of the annotation. * * @default 0 */ @Property(0) public left: number; /** * Represents the the top value of the annotation. * * @default 0 */ @Property(0) public top: number; /** * Represents the the right value of the annotation. * * @default 0 */ @Property(0) public right: number; /** * Represents the the bottom value of the annotation. * * @default 0 */ @Property(0) public bottom: number; /** * Sets the reference point, that will act as the offset values(offsetX, offsetY) of a node * * @default new Point(0,0) */ @Complex<PointModel>({ x: 0, y: 0 }, Point) public location: PointModel; /** * Sets the size of the annotation * * @default new Size(0, 0) */ @Complex<Size>(new Size(0, 0), Size) public size: Size; } /** * The `PdfFont` is base for annotation Text styles. * * @hidden */ export abstract class PdfFont extends ChildProperty<PdfFont> { /** * Represents the the font Bold style of annotation text content. * * @default 'false' */ @Property(false) public isBold: boolean; /** * Represents the the font Italic style of annotation text content. * * @default 'false' */ @Property(false) public isItalic: boolean; /** * Represents the the font Underline style of annotation text content. * * @default 'false' */ @Property(false) public isUnderline: boolean; /** * Represents the the font Strikeout style of annotation text content. * * @default 'false' */ @Property(false) public isStrikeout: boolean; } /** * Defines the common behavior of PdfAnnotationBase * * @hidden */ export class PdfAnnotationBase extends ChildProperty<PdfAnnotationBase> { /** * Represents the unique id of annotation * * @default '' */ @Property('') public id: string; /** * Represents the annotation type of the pdf * * @default 'Rectangle' */ @Property('Rectangle') public shapeAnnotationType: PdfAnnotationType; /** * Represents the annotation type of the form field * * @default '' */ @Property(null) public formFieldAnnotationType: FormFieldAnnotationType; /** * Represents the measure type of the annotation * * @default '' */ @Property('') public measureType: string; /** * Represents the auther value of the annotation * * @default '' */ @Property('') public author: string; /** * Represents the modified date of the annotation * * @default '' */ @Property('') public modifiedDate: string; /** * Represents the subject of the annotation * * @default '' */ @Property('') public subject: string; /** * Represents the notes of the annotation * * @default '' */ @Property('') public notes: string; /** * specifies the locked action of the comment * * @default 'false' */ @Property(false) public isCommentLock: boolean; /** * Represents the stroke color of the annotation * * @default 'black' */ @Property('black') public strokeColor: string; /** * Represents the fill color of the annotation * * @default 'tranparent' */ @Property('#ffffff00') public fillColor: string; /** * Represents the fill color of the annotation * * @default 'tranparent' */ @Property('#ffffff00') public stampFillColor: string; /** * Represents the stroke color of the annotation * * @default 'black' */ @Property('black') public stampStrokeColor: string; /** * Represents the path data of the annotation * * @default '' */ @Property('') public data: string; /** * Represents the opecity value of the annotation * * @default 1 */ @Property(1) public opacity: number; /** * Represents the thickness value of annotation * * @default 1 */ @Property(1) public thickness: number; /** * Represents the border style of annotation * * @default '' */ @Property('') public borderStyle: string; /** * Represents the border dash array of annotation * * @default '' */ @Property('') public borderDashArray: string; /** * Represents the rotate angle of annotation * * @default 0 */ @Property(0) public rotateAngle: number; /** * Represents the annotation as cloud shape * * @default false */ @Property(false) public isCloudShape: boolean; /** * Represents the cloud intensity * * @default 0 */ @Property(0) public cloudIntensity: number; /** * Represents the height of the leader of distance shapes * * @default 40 */ @Property(40) public leaderHeight: number; /** * Represents the line start shape style * * @default null */ @Property(null) public lineHeadStart: string; /** * Represents the line end shape style * * @default null */ @Property(null) public lineHeadEnd: string; /** * Represents vertex points in the line annotation or shape annotation. * * @default [] */ @Property([]) public vertexPoints: PointModel[]; /** * Represents vertex points in the line annotation or shape annotation. * * @default null */ @Property(null) public sourcePoint: PointModel; /** * Represents vertex points in the line annotation or shape annotation. * * @default None */ @Property('None') public sourceDecoraterShapes: DecoratorShapes; /** * Represents vertex points in the line annotation or shape annotation. * * @default None */ @Property('None') public taregetDecoraterShapes: DecoratorShapes; /** * Represents vertex points in the line annotation or shape annotation. * * @default null */ @Property(null) public targetPoint: PointModel; /** * Represents vertex points in the line annotation or shape annotation. * * @default [] */ @Property([]) public segments: PointModel[]; /** * Represents bounds of the annotation * * @default new Point(0,0) */ @Complex<PdfBoundsModel>({ x: 0, y: 0 }, PdfBounds) public bounds: PdfBoundsModel; /** * Represents the cloud intensity * * @default 0 */ @Property(0) public pageIndex: number; /** * Represents the cloud intensity * * @default -1 */ @Property(-1) public zIndex: number; /** * Represents the cloud intensity * * @default null */ @Property(null) public wrapper: Container; /** * Represents the dynamic stamp * * @default false */ @Property(false) public isDynamicStamp: boolean; /** * Represents the dynamic text. * * @default '' */ @Property('') public dynamicText: string; /** * Represents the unique annotName of the annotation * * @default '' */ @Property('') public annotName: string; /** * Represents the review collection of the annotation * * @default '' */ @Property({}) public review: IReviewCollection; /** * Represents the comments collection of the annotation * * @default [] */ @Property([]) public comments: ICommentsCollection[]; /** * Represents the comments collection of the annotation * * @default '#000' */ @Property('#000') public fontColor: string; /** * Represents the font size of the annotation content * * @default '16' */ @Property(16) public fontSize: number; /** * Represents the font family of the annotation content * * @default 'Helvetica' */ @Property('Helvetica') public fontFamily: string; /** * Represents the font style of the annotation content * * @default 'None' */ @Property('None') public fontStyle: string; /** * Represents the shape annotation label add flag * * @default 'false' */ @Property(false) public enableShapeLabel: boolean; /** * Represents the shape annotation label content * * @default 'label' */ @Property('label') public labelContent: string; /** * Represents the shape annotation label content fill color * * @default '#ffffff00' */ @Property('#ffffff00') public labelFillColor: string; /** * Represents the shape annotation label content max-length * * @default '15' */ @Property(15) public labelMaxLength: number; /** * Represents the opecity value of the annotation * * @default 1 */ @Property(1) public labelOpacity: number; /** * Represents the selection settings of the annotation * * @default '' */ @Property('') public annotationSelectorSettings: AnnotationSelectorSettingsModel; /** * Represents the shape annotation label content border color * * @default '#ffffff00' */ @Property('#ffffff00') public labelBorderColor: string; /** * Represents the text anlignment style of annotation * * @default 'left' */ @Property('left') public textAlign: string; /** * Represents the unique Name of the annotation * * @default '' */ @Property('') public signatureName: string; /** * specifies the minHeight of the annotation. * * @default 0 */ @Property(0) public minHeight: number; /** * specifies the minWidth of the annotation. * * @default 0 */ @Property(0) public minWidth: number; /** * specifies the minHeight of the annotation. * * @default 0 */ @Property(0) public maxHeight: number; /** * specifies the maxWidth of the annotation. * * @default 0 */ @Property(0) public maxWidth: number; /** * specifies the locked action of the annotation. * * @default 'false' */ @Property(false) public isLock: boolean; /** * specifies the particular annotation mode. * * @default 'UI Drawn Annotation' */ @Property('UI Drawn Annotation') public annotationAddMode: string; /** * specifies the default settings of the annotation. * * @default '' */ @Property('') public annotationSettings: object; /** * specifies the previous font size of the annotation. * * @default '16' */ @Property(16) public previousFontSize: number; /** * Represents the text style of annotation * * @default '' */ @Complex<PdfFontModel>({ isBold: false, isItalic: false, isStrikeout: false, isUnderline: false }, PdfFont) public font: PdfFontModel; /** * Represents the shape annotation label content bounds * * @default '' */ @Complex<PdfBoundsModel>({ x: 0, y: 0 }, PdfBounds) public labelBounds: PdfBoundsModel; /** * specifies the custom data of the annotation. */ @Property(null) public customData: object; /** * specifies the allowed interactions of the locked annotation. */ @Property(['None']) public allowedInteractions: AllowedInteraction; /** * specifies whether the annotations are included or not in print actions. */ @Property(true) public isPrint: boolean; /** * Allows to edit the free text annotation */ @Property(false) public isReadonly: boolean; // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(parent: any, propName: string, defaultValue: Object, isArray?: boolean) { super(parent, propName, defaultValue, isArray); } } /** * Defines the common behavior of PdfFormFieldBase * * @hidden */ export class PdfFormFieldBase extends ChildProperty<PdfFormFieldBase> { /** * Represents the unique id of formField * * @default '' */ @Property('') public id: string; /** * specifies the type of the signature. */ @Property('') public signatureType: string; /** * Represents the name of the formField * * @default '' */ @Property('') public name: string; /** * Represents the value of the formField * * @default '' */ @Property('') public value: string; /** * Represents the annotation type of the form field * * @default '' */ @Property(null) public formFieldAnnotationType: FormFieldAnnotationType; /** * Represents the fill color of the form field * * @default '#daeaf7ff' */ @Property('#daeaf7ff') public backgroundColor: string; /** * Represents the text color of the form field * * @default 'black' */ @Property('black') public color: string; /** * Represents the border color of the form field * * @default '#303030' */ @Property('#303030') public borderColor: string; /** * Represents the tooltip of the form field * * @default '' */ @Property('') public tooltip: string; /** * Represents the opecity value of the formField * * @default 1 */ @Property(1) public opacity: number; /** * Represents the thickness value of FormField * * @default 1 */ @Property(1) public thickness: number; /** * Represents the rotate angle of formField * * @default 0 */ @Property(0) public rotateAngle: number; /** * Represents bounds of the formField * * @default new Point(0,0) */ @Complex<PdfBoundsModel>({ x: 0, y: 0 }, PdfBounds) public bounds: PdfBoundsModel; /** * Represents the cloud intensity * * @default 0 */ @Property(0) public pageIndex: number; /** * Represents the page number * * @default 1 */ @Property(1) public pageNumber: number; /** * Represents the cloud intensity * * @default -1 */ @Property(-1) public zIndex: number; /** * Represents the cloud intensity * * @default null */ @Property(null) public wrapper: Container; /** * Represents the font size of the formField content * * @default 16 */ @Property(16) public fontSize: number; /** * Represents the font family of the formField content * * @default 'Helvetica' */ @Property('Helvetica') public fontFamily: string; /** * Represents the font style of the formField content * * @default 'None' */ @Property('None') public fontStyle: string; /** * Represents the text anlignment style of formField * * @default 'left' */ @Property('left') public alignment: string; /** * specifies the minHeight of the formField. * * @default 0 */ @Property(0) public minHeight: number; /** * specifies the minWidth of the formField. * * @default 0 */ @Property(0) public minWidth: number; /** * specifies the minHeight of the formField. * * @default 0 */ @Property(0) public maxHeight: number; /** * specifies the maxWidth of the formField. * * @default 0 */ @Property(0) public maxWidth: number; /** * specifies the maxLength of the textbox/password. * * @default 0 */ @Property(0) public maxLength: number; /** * If it is set as Hidden, Html element will be hide in the UI. By default it is visible. */ @Property('visible') public visibility: VisibilityState; /** * specifies whether the form field are included or not in print actions. */ @Property(true) public isPrint: boolean; /** * Allows to edit the form Field text. */ @Property(false) public isReadonly: boolean; /** * Enable or disable the checkbox state. */ @Property(false) public isChecked: boolean; /** * Enable or disable the RadioButton state. */ @Property(false) public isSelected: boolean; /** * Specified whether an form field element is mandatory. */ @Property(false) public isRequired: boolean; /** * Enable or disable the Multiline Textbox. */ @Property(false) public isMultiline: boolean; /** * Gets or sets the items to be displayed for drop down/ listbox. */ @Property('') public options: ItemModel[]; /** * Specifies the properties of the signature indicator in the signature field. */ @Property() public signatureIndicatorSettings: SignatureIndicatorSettingsModel; /** * Represents the text style of annotation * * @default '' */ @Complex<PdfFontModel>({ isBold: false, isItalic: false, isStrikeout: false, isUnderline: false }, PdfFont) public font: PdfFontModel; /** * Gets or sets the items selected in the drop down/ listbox. */ @Property() public selectedIndex: number[]; // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(parent: any, propName: string, defaultValue: Object, isArray?: boolean) { super(parent, propName, defaultValue, isArray); } } /** * @hidden */ export class ZOrderPageTable { private pageIdTemp: number = 0; /** * @private * @returns {number} - Returns the page Id. */ public get pageId(): number { return this.pageIdTemp; } /** * @private * @param {number} offset - The page offset value. */ public set pageId(offset: number) { this.pageIdTemp = offset; } private zIndexTemp: number = -1; /** * @private * @returns {number} - Returns the z-index value. */ public get zIndex(): number { return this.zIndexTemp; } /** * @private * @param {number} offset - The page offset value. */ public set zIndex(offset: number) { this.zIndexTemp = offset; } private childNodesTemp: PdfAnnotationBaseModel[] = []; /** * @private * @returns {PdfAnnotationBaseModel[]} - Returns the annotation childNodes. */ public get objects(): PdfAnnotationBaseModel[] { return this.childNodesTemp; } /** * @private * @param {PdfAnnotationBaseModel[]} childNodes - Specified the annotation child nodes. */ public set objects(childNodes: PdfAnnotationBaseModel[]) { this.childNodesTemp = childNodes; } constructor() { this.objects = []; this.zIndexTemp = -1; this.pageIdTemp = 0; } }
the_stack
import * as React from "react"; import { BeDuration } from "@itwin/core-bentley"; import { ActivityMessageDetails, ActivityMessageEndReason, IModelApp, NotifyMessageDetails, OutputMessagePriority, OutputMessageType, ScreenViewport, ViewState, } from "@itwin/core-frontend"; import { MapLayersWidgetControl } from "@itwin/map-layers"; // used to test map-layers widget control import { NodeKey } from "@itwin/presentation-common"; import { BadgeType, CommonToolbarItem, ConditionalBooleanValue, ContentLayoutProps, RelativePosition, SpecialKey, StageUsage, ToolbarItemUtilities, WidgetState, } from "@itwin/appui-abstract"; import { CustomToolbarItem, SelectionMode, useToolbarPopupContext } from "@itwin/components-react"; import { Point, ScrollView } from "@itwin/core-react"; import { BasicNavigationWidget, BasicToolWidget, CommandItemDef, ConfigurableUiManager, ContentGroup, ContentGroupProps, ContentGroupProvider, ContentProps, ContentViewManager, CoreTools, CursorInformation, CursorPopupContent, CursorPopupManager, CursorUpdatedEventArgs, CustomItemDef, EmphasizeElementsChangedArgs, Frontstage, FrontstageDef, FrontstageManager, FrontstageProps, FrontstageProvider, GroupItemDef, HideIsolateEmphasizeAction, HideIsolateEmphasizeActionHandler, HideIsolateEmphasizeManager, IModelConnectedViewSelector, MessageManager, ModalDialogManager, ModelessDialogManager, ModelsTreeNodeType, StagePanel, SyncUiEventId, ToolbarHelper, UiFramework, Widget, WIDGET_OPACITY_DEFAULT, Zone, ZoneLocation, ZoneState, } from "@itwin/appui-react"; import { Button, Slider } from "@itwin/itwinui-react"; import { SampleAppIModelApp, SampleAppUiActionId } from "../../../frontend/index"; // SVG Support - SvgPath or SvgSprite // import { SvgPath } from "@itwin/core-react"; import { AccuDrawPopupTools } from "../../tools/AccuDrawPopupTools"; import { AppTools } from "../../tools/ToolSpecifications"; import { ToolWithDynamicSettings } from "../../tools/ToolWithDynamicSettings"; import { getSavedViewLayoutProps, OpenComponentExamplesPopoutTool, OpenCustomPopoutTool, OpenViewPopoutTool } from "../../tools/UiProviderTool"; import { AppUi } from "../AppUi"; // cSpell:Ignore contentviews statusbars uitestapp import { IModelViewportControl } from "../contentviews/IModelViewport"; import { CalculatorDialog } from "../dialogs/CalculatorDialog"; import { SpinnerTestDialog } from "../dialogs/SpinnerTestDialog"; import { TestRadialMenu } from "../dialogs/TestRadialMenu"; import { ViewportDialog } from "../dialogs/ViewportDialog"; import { ExampleForm } from "../forms/ExampleForm"; import { AppStatusBarWidgetControl } from "../statusbars/AppStatusBar"; import { VerticalPropertyGridWidgetControl } from "../widgets/PropertyGridDemoWidget"; import { UnifiedSelectionPropertyGridWidgetControl } from "../widgets/UnifiedSelectionPropertyGridWidget"; import { UnifiedSelectionTableWidgetControl } from "../widgets/UnifiedSelectionTableWidget"; import { ViewportWidget } from "../widgets/ViewportWidget"; import { VisibilityWidgetControl } from "../widgets/VisibilityWidget"; import { NestedAnimationStage } from "./NestedAnimationStage"; /* eslint-disable react/jsx-key, deprecation/deprecation */ function MySliderPanel() { const [sliderValues, setSliderValues] = React.useState([50]); React.useEffect(() => { // eslint-disable-next-line no-console console.log("mounting my panel"); return () => { // eslint-disable-next-line no-console console.log("unmounting my panel"); }; }, []); const { closePanel } = useToolbarPopupContext(); const handleApply = React.useCallback(() => { closePanel(); }, [closePanel]); const handleChange = React.useCallback((values) => { setSliderValues(values); }, []); return ( <div style={{ display: "flex", flexDirection: "column", gap: "4px", alignItems: "center", width: "300px", height: "68px", padding: "6px", boxSizing: "border-box" }}> <Slider style={{ width: "100%" }} min={0} max={100} values={sliderValues} step={1} onChange={handleChange} /> <Button onClick={handleApply}>Apply</Button> </div> ); } export class InitialIModelContentStageProvider extends ContentGroupProvider { public override prepareToSaveProps(contentGroupProps: ContentGroupProps) { const newContentsArray = contentGroupProps.contents.map((content: ContentProps) => { const newContent = { ...content }; if (newContent.applicationData) delete newContent.applicationData; return newContent; }); return { ...contentGroupProps, contents: newContentsArray }; } public override applyUpdatesToSavedProps(contentGroupProps: ContentGroupProps) { const newContentsArray = contentGroupProps.contents.map((content: ContentProps) => { const newContent = { ...content }; if (newContent.classId === IModelViewportControl.id) { newContent.applicationData = { ...newContent.applicationData, featureOptions: { defaultViewOverlay: { enableScheduleAnimationViewOverlay: true, enableAnalysisTimelineViewOverlay: true, enableSolarTimelineViewOverlay: true, }, }, }; } return newContent; }); return { ...contentGroupProps, contents: newContentsArray }; } public async provideContentGroup(props: FrontstageProps): Promise<ContentGroup> { const viewIdsSelected = SampleAppIModelApp.getInitialViewIds(); const iModelConnection = UiFramework.getIModelConnection(); if (!iModelConnection) throw new Error(`Unable to generate content group if not iModelConnection is available`); if (0 === viewIdsSelected.length) { const savedViewLayoutProps = await getSavedViewLayoutProps(props.id, iModelConnection); if (savedViewLayoutProps) { const viewState = savedViewLayoutProps.contentGroupProps.contents[0].applicationData?.viewState; if (viewState) { UiFramework.setDefaultViewState(viewState); } return new ContentGroup(savedViewLayoutProps.contentGroupProps); } throw (Error(`Could not load saved layout ContentLayoutProps`)); } // first find an appropriate layout const contentLayoutProps: ContentLayoutProps | undefined = AppUi.findLayoutFromContentCount(viewIdsSelected.length); if (!contentLayoutProps) { throw (Error(`Could not find layout ContentLayoutProps when number of viewStates=${viewIdsSelected.length}`)); } let viewStates: ViewState[] = []; const promises = new Array<Promise<ViewState>>(); viewIdsSelected.forEach((viewId: string) => { promises.push(iModelConnection.views.load(viewId)); }); try { viewStates = await Promise.all(promises); } catch { } // create the content props that specifies an iModelConnection and a viewState entry in the application data. const contentProps: ContentProps[] = []; viewStates.forEach((viewState, index) => { if (0 === index) { UiFramework.setDefaultViewState(viewState); } const thisContentProps: ContentProps = { id: `imodel-view-${index}`, classId: IModelViewportControl, applicationData: { viewState, iModelConnection, featureOptions: { defaultViewOverlay: { enableScheduleAnimationViewOverlay: true, enableAnalysisTimelineViewOverlay: true, enableSolarTimelineViewOverlay: true, }, }, }, }; contentProps.push(thisContentProps); }); const myContentGroup: ContentGroup = new ContentGroup( { id: "views-frontstage-default-content-group", layout: contentLayoutProps, contents: contentProps, }); return myContentGroup; } } export class ViewsFrontstage extends FrontstageProvider { private _contentGroupProvider = new InitialIModelContentStageProvider(); public static stageId = "ViewsFrontstage"; public get id(): string { return ViewsFrontstage.stageId; } public static unifiedSelectionPropertyGridId = "UnifiedSelectionPropertyGrid"; private _additionalTools = new AdditionalTools(); public static savedViewLayoutProps: string; private _rightPanel = { allowedZones: [2, 6, 9], }; private _bottomPanel = { allowedZones: [2, 7], }; private async applyVisibilityOverrideToSpatialViewports(frontstageDef: FrontstageDef, processedViewport: ScreenViewport, action: HideIsolateEmphasizeAction) { frontstageDef?.contentControls?.forEach(async (cc) => { const vp = cc.viewport; if (vp !== processedViewport && vp?.view?.isSpatialView() && vp.iModel === processedViewport.iModel) { switch (action) { case HideIsolateEmphasizeAction.ClearHiddenIsolatedEmphasized: HideIsolateEmphasizeManager.clearEmphasize(vp); break; case HideIsolateEmphasizeAction.EmphasizeSelectedElements: await HideIsolateEmphasizeManager.emphasizeSelected(vp); break; case HideIsolateEmphasizeAction.HideSelectedCategories: await HideIsolateEmphasizeManager.hideSelectedElementsCategory(vp); break; case HideIsolateEmphasizeAction.HideSelectedElements: HideIsolateEmphasizeManager.hideSelected(vp); break; case HideIsolateEmphasizeAction.HideSelectedModels: await HideIsolateEmphasizeManager.hideSelectedElementsModel(vp); break; case HideIsolateEmphasizeAction.IsolateSelectedCategories: await HideIsolateEmphasizeManager.isolateSelectedElementsCategory(vp); break; case HideIsolateEmphasizeAction.IsolateSelectedElements: HideIsolateEmphasizeManager.isolateSelected(vp); break; case HideIsolateEmphasizeAction.IsolateSelectedModels: await HideIsolateEmphasizeManager.isolateSelectedElementsModel(vp); break; case HideIsolateEmphasizeAction.ClearOverrideModels: HideIsolateEmphasizeManager.clearOverrideModels(vp); break; case HideIsolateEmphasizeAction.ClearOverrideCategories: HideIsolateEmphasizeManager.clearOverrideCategories(vp); break; default: break; } } }); } private _onEmphasizeElementsChangedHandler = (args: EmphasizeElementsChangedArgs) => { if (FrontstageManager.activeFrontstageDef && FrontstageManager.activeFrontstageId === ViewsFrontstage.stageId) this.applyVisibilityOverrideToSpatialViewports(FrontstageManager.activeFrontstageDef, args.viewport, args.action); // eslint-disable-line @typescript-eslint/no-floating-promises }; constructor() { super(); HideIsolateEmphasizeActionHandler.emphasizeElementsChanged.addListener(this._onEmphasizeElementsChangedHandler); } /** Get the CustomItemDef for ViewSelector */ private get _viewSelectorItemDef() { return new CustomItemDef({ customId: "sampleApp:viewSelector", reactElement: ( <IModelConnectedViewSelector listenForShowUpdates={false} // Demo for showing only the same type of view in ViewSelector - See IModelViewport.tsx, onActivated /> ), }); } /** Commands that opens switches the content layout */ private get _additionalNavigationVerticalToolbarItems() { const customPopupButton: CustomToolbarItem = { isCustom: true, id: "test.custom-popup-with-slider", itemPriority: 220, icon: "icon-arrow-left", label: "Slider Test", panelContentNode: <MySliderPanel />, groupPriority: 20, }; return [ ToolbarHelper.createToolbarItemFromItemDef(200, this._viewSelectorItemDef), ToolbarHelper.createToolbarItemFromItemDef(210, new GroupItemDef({ label: "Layout Demos", panelLabel: "Layout Demos", iconSpec: "icon-placeholder", items: [AppTools.switchLayout1, AppTools.switchLayout2], }), ), customPopupButton, ]; } public get frontstage() { const iModelConnection = UiFramework.getIModelConnection(); return ( <Frontstage id={ViewsFrontstage.stageId} defaultTool={CoreTools.selectElementCommand} contentGroup={this._contentGroupProvider} isInFooterMode={true} applicationData={{ key: "value" }} usage={StageUsage.General} version={3.1} // Defaults to 0. Increment this when Frontstage changes are meaningful enough to reinitialize saved user layout settings. contentManipulationTools={ <Zone widgets={ [ <Widget isFreeform={true} element={<BasicToolWidget additionalHorizontalItems={this._additionalTools.additionalHorizontalToolbarItems} additionalVerticalItems={this._additionalTools.additionalVerticalToolbarItems} showCategoryAndModelsContextTools={true} />} />, ]} /> } toolSettings={ <Zone allowsMerging widgets={ [ <Widget iconSpec="icon-placeholder" isToolSettings={true} preferredPanelSize="fit-content" />, ]} /> } viewNavigationTools={ <Zone widgets={ [ <Widget isFreeform={true} element={ <BasicNavigationWidget additionalVerticalItems={this._additionalNavigationVerticalToolbarItems} /> } />, ]} /> } centerRight={ <Zone allowsMerging defaultState={ZoneState.Minimized} initialWidth={400} widgets={[ // Used when using map-layers as a package and not using UiItemsProvider (compatible with V1 of framework) <Widget id={MapLayersWidgetControl.id} label={MapLayersWidgetControl.label} control={MapLayersWidgetControl} iconSpec={MapLayersWidgetControl.iconSpec} applicationData={{ hideExternalMapLayers: false, mapTypeOptions: { supportTileUrl: true, supportWmsAuthentication: true }, fetchPublicMapLayerSources: true }} />, // <Widget iconSpec="icon-placeholder" labelKey="SampleApp:widgets.NavigationTree" control={NavigationTreeWidgetControl} // applicationData={{ iModelConnection: this.iModelConnection }} fillZone={true} />, <Widget iconSpec="icon-visibility" label="Searchable Tree" control={VisibilityWidgetControl} applicationData={{ iModelConnection, config: { modelsTree: { selectionMode: SelectionMode.Extended, selectionPredicate: (_key: NodeKey, type: ModelsTreeNodeType) => type === ModelsTreeNodeType.Element, }, }, }} fillZone={true} />, ]} /> } bottomLeft={ <Zone allowsMerging defaultState={ZoneState.Minimized} initialWidth={400} widgets={ [ <Widget iconSpec="icon-placeholder" labelKey="SampleApp:widgets.UnifiedSelectionTable" control={UnifiedSelectionTableWidgetControl} applicationData={{ iModelConnection }} fillZone={true} badgeType={BadgeType.New} />, /* <Widget iconSpec="icon-placeholder" label="External iModel View" control={ViewportWidgetControl} fillZone={true} badgeType={BadgeType.TechnicalPreview} applicationData={{ iTwinName: "iModelHubTest", imodelName: "GrandCanyonTerrain" }} />, */ ]} /> } statusBar={ <Zone widgets={ [ <Widget isStatusBar={true} control={AppStatusBarWidgetControl} />, ]} /> } bottomRight={ <Zone defaultState={ZoneState.Minimized} allowsMerging={true} mergeWithZone={ZoneLocation.CenterRight} initialWidth={450} widgets={ [ <Widget defaultState={WidgetState.Closed} iconSpec="icon-placeholder" labelKey="SampleApp:widgets.UnifiedSelectPropertyGrid" id={ViewsFrontstage.unifiedSelectionPropertyGridId} control={UnifiedSelectionPropertyGridWidgetControl} fillZone={true} applicationData={{ iModelConnection }} />, <Widget id="VerticalPropertyGrid" defaultState={WidgetState.Hidden} iconSpec="icon-placeholder" labelKey="SampleApp:widgets.VerticalPropertyGrid" control={VerticalPropertyGridWidgetControl} />, ]} /> } rightPanel={ <StagePanel allowedZones={this._rightPanel.allowedZones} maxSize={{ percentage: 50 }} /> } bottomPanel={ <StagePanel allowedZones={this._bottomPanel.allowedZones} /> } /> ); } } /** Define a ToolWidget with Buttons to display in the TopLeft zone. */ class AdditionalTools { private _nestedGroup = new GroupItemDef({ groupId: "nested-group", labelKey: "SampleApp:buttons.toolGroup", panelLabelKey: "SampleApp:buttons.toolGroup", iconSpec: "icon-placeholder", items: [AppTools.item1, AppTools.item2, AppTools.item3, AppTools.item4, AppTools.item5, AppTools.item6, AppTools.item7, AppTools.item8], // direction: Direction.Bottom, itemsInColumn: 7, }); private _openNestedAnimationStageDef = new CommandItemDef({ iconSpec: "icon-camera-animation", labelKey: "SampleApp:buttons.openNestedAnimationStage", execute: async () => { const activeContentControl = ContentViewManager.getActiveContentControl(); if (activeContentControl && activeContentControl.viewport && (undefined !== activeContentControl.viewport.view.analysisStyle || undefined !== activeContentControl.viewport.view.scheduleScript)) { const frontstageProvider = new NestedAnimationStage(); const frontstageDef = await FrontstageDef.create(frontstageProvider); if (frontstageDef) { SampleAppIModelApp.saveAnimationViewId(activeContentControl.viewport.view.id); await FrontstageManager.openNestedFrontstage(frontstageDef); } } }, isHidden: new ConditionalBooleanValue(() => { const activeContentControl = ContentViewManager.getActiveContentControl(); if (activeContentControl && activeContentControl.viewport && (undefined !== activeContentControl.viewport.view.analysisStyle || undefined !== activeContentControl.viewport.view.scheduleScript)) return false; return true; }, [SyncUiEventId.ActiveContentChanged]), }); /** Command that opens a nested Frontstage */ private get _openNestedAnimationStage() { return this._openNestedAnimationStageDef; } /** Tool that will start a sample activity and display ActivityMessage. */ private _tool3 = async () => { let isCancelled = false; let progress = 0; const details = new ActivityMessageDetails(true, true, true, true); details.onActivityCancelled = () => { isCancelled = true; }; IModelApp.notifications.setupActivityMessage(details); while (!isCancelled && progress <= 100) { IModelApp.notifications.outputActivityMessage("This is a sample activity message", progress); await BeDuration.wait(100); progress++; } const endReason = isCancelled ? ActivityMessageEndReason.Cancelled : ActivityMessageEndReason.Completed; IModelApp.notifications.endActivityMessage(endReason); }; /** Tool that will display a pointer message on keyboard presses. */ private _tool4Priority = OutputMessagePriority.Info; private _tool4Message = "Move the mouse or press an arrow key."; private _tool4Detailed = "Press an arrow key to change position or Escape to dismiss."; private _toolRelativePosition = RelativePosition.BottomRight; private _tool4 = () => { const details = new NotifyMessageDetails(this._tool4Priority, this._tool4Message, this._tool4Detailed, OutputMessageType.Pointer); const wrapper = ConfigurableUiManager.getWrapperElement(); details.setPointerTypeDetails(wrapper, { x: CursorInformation.cursorX, y: CursorInformation.cursorY }, this._toolRelativePosition); IModelApp.notifications.outputMessage(details); document.addEventListener("keyup", this._handleTool4Keypress); document.addEventListener("mousemove", this._handleTool4MouseMove); }; private _handleTool4Keypress = (event: KeyboardEvent) => { const details = new NotifyMessageDetails(OutputMessagePriority.Info, "", this._tool4Detailed); let changed = false; switch (event.key) { case SpecialKey.ArrowLeft: details.briefMessage = "Left pressed"; this._toolRelativePosition = RelativePosition.Left; changed = true; break; case SpecialKey.ArrowUp: details.briefMessage = "Up pressed"; this._toolRelativePosition = RelativePosition.Top; changed = true; break; case SpecialKey.ArrowRight: details.briefMessage = "Right pressed"; this._toolRelativePosition = RelativePosition.Right; changed = true; break; case SpecialKey.ArrowDown: details.briefMessage = "Down pressed"; this._toolRelativePosition = RelativePosition.Bottom; changed = true; break; case SpecialKey.Escape: this._handleTool4Dismiss(); break; } if (changed) { IModelApp.notifications.outputMessage(details); IModelApp.notifications.updatePointerMessage({ x: CursorInformation.cursorX, y: CursorInformation.cursorY }, this._toolRelativePosition); } }; private _handleTool4MouseMove = () => { IModelApp.notifications.updatePointerMessage({ x: CursorInformation.cursorX, y: CursorInformation.cursorY }, this._toolRelativePosition); }; private _handleTool4Dismiss = () => { IModelApp.notifications.closePointerMessage(); document.removeEventListener("keyup", this._handleTool4Keypress); document.removeEventListener("mousemove", this._handleTool4Dismiss); }; private get _activityMessageItem() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.activityMessage", execute: async () => { await this._tool3(); }, }); } private get _pointerMessageItem() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.pointerMessage", execute: () => { this._tool4(); }, }); } private get _outputMessageItem() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.outputMessage", execute: () => { IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, "Test", undefined, OutputMessageType.Sticky)); }, }); } private get _exampleFormItem() { return new CommandItemDef({ iconSpec: "icon-annotation", label: "Open Example Form", execute: () => { ExampleForm.open(); }, }); } private get _radialMenuItem() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.openRadial", execute: () => { ModalDialogManager.openDialog(this.radialMenu()); }, }); } private radialMenu(): React.ReactNode { return ( <TestRadialMenu opened={true} onClose={this._closeModal} /> ); } private _closeModal = () => { ModalDialogManager.closeDialog(); }; private get _openCalculatorItem() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.openCalculator", execute: () => { ModalDialogManager.openDialog(<CalculatorDialog opened={true} />); }, }); } private get _viewportDialogItem() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.viewportDialog", execute: () => { this.openViewportDialog(); }, }); } private get _spinnerTestDialogItem() { const id = "spinners"; return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.spinnerTestDialog", execute: () => { ModelessDialogManager.openDialog(<SpinnerTestDialog opened={true} onClose={() => ModelessDialogManager.closeDialog(id)} />, id); }, }); } private _viewportDialogCnt: number = 0; private openViewportDialog(): void { this._viewportDialogCnt++; const id = `ViewportDialog_${this._viewportDialogCnt.toString()}`; const dialog = <ViewportDialog opened={true} iTwinName="iModelHubTest" imodelName="GrandCanyonTerrain" dialogId={id} />; ModelessDialogManager.openDialog(dialog, id); } private get _reduceWidgetOpacity() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.reduceWidgetOpacity", execute: () => { UiFramework.setWidgetOpacity(0.50); }, }); } private get _defaultWidgetOpacity() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.defaultWidgetOpacity", execute: () => { UiFramework.setWidgetOpacity(WIDGET_OPACITY_DEFAULT); }, }); } private get _startCursorPopup() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.startCursorPopup", execute: async () => { // const relativePosition = CursorInformation.getRelativePositionFromCursorDirection(CursorInformation.cursorDirection); const content = ( <CursorPopupContent> {FrontstageManager.activeToolSettingsProvider?.toolSettingsNode} </CursorPopupContent> ); // CursorPopupManager.open("test1", content, CursorInformation.cursorPosition, new Point(20, 20), RelativePosition.TopRight, 10); CursorPopupManager.open("test1", content, CursorInformation.cursorPosition, new Point(20, 20), RelativePosition.TopRight, 10); CursorInformation.onCursorUpdatedEvent.addListener(this._handleCursorUpdated); document.addEventListener("keyup", this._handleCursorPopupKeypress); }, }); } private get _addCursorPopups() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.addCursorPopups", execute: async () => { CursorPopupManager.open("testR1", <CursorPopupContent>Hello World!</CursorPopupContent>, CursorInformation.cursorPosition, new Point(40, 20), RelativePosition.Right, 10); CursorPopupManager.open("testBR1", <CursorPopupContent>Hello World!</CursorPopupContent>, CursorInformation.cursorPosition, new Point(20, 20), RelativePosition.BottomRight, 10); CursorPopupManager.open("testB1", <CursorPopupContent>Hello World!</CursorPopupContent>, CursorInformation.cursorPosition, new Point(20, 85), RelativePosition.Bottom, 10); CursorPopupManager.open("testBL1", <CursorPopupContent>Hello World!</CursorPopupContent>, CursorInformation.cursorPosition, new Point(20, 20), RelativePosition.BottomLeft, 10); CursorPopupManager.open("testL1", <CursorPopupContent>Hello World!</CursorPopupContent>, CursorInformation.cursorPosition, new Point(40, 20), RelativePosition.Left, 10); CursorPopupManager.open("testTL1", <CursorPopupContent>Hello World!</CursorPopupContent>, CursorInformation.cursorPosition, new Point(20, 20), RelativePosition.TopLeft, 10); CursorPopupManager.open("testT1", <CursorPopupContent>Hello World!</CursorPopupContent>, CursorInformation.cursorPosition, new Point(20, 100), RelativePosition.Top, 10); }, }); } private get _endCursorPopup() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.stopCursorPopup", execute: async () => { this._closeCursorPopup(); }, }); } private _handleCursorUpdated(args: CursorUpdatedEventArgs) { // const relativePosition = CursorInformation.getRelativePositionFromCursorDirection(args.direction); CursorPopupManager.updatePosition(args.newPt); } private _handleCursorPopupKeypress = (event: KeyboardEvent) => { switch (event.key) { case SpecialKey.Escape: this._closeCursorPopup(); break; } }; private get _clearMessages() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.clearMessages", execute: () => { MessageManager.clearMessages(); }, }); } private _closeCursorPopup() { CursorPopupManager.close("test1", false); CursorPopupManager.close("testR1", false); CursorPopupManager.close("testBR1", false); CursorPopupManager.close("testB1", false); CursorPopupManager.close("testBL1", false); CursorPopupManager.close("testL1", false); CursorPopupManager.close("testTL1", false); CursorPopupManager.close("testT1", false); CursorInformation.onCursorUpdatedEvent.removeListener(this._handleCursorUpdated); document.removeEventListener("keyup", this._handleCursorPopupKeypress); } // cSpell:disable /** Get the CustomItemDef for PopupButton */ private get _viewportPopupButtonItemDef() { return new CustomItemDef({ customId: "test.custom-popup", iconSpec: "icon-arrow-down", label: "Popup Test", badgeType: BadgeType.New, popupPanelNode: <div style={{ width: "400px", height: "300px", padding: "6px 0px 6px 6px" }}> <ScrollView> <div> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div> {false && <ViewportWidget iTwinName="iModelHubTest" imodelName="GrandCanyonTerrain" />} <div> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div> </ScrollView> </div>, }); } public formatGroupItemsItem = (): CommonToolbarItem => { const children = ToolbarHelper.constructChildToolbarItems([ AppTools.openUnitsFormatDialogCommand, AppTools.setLengthFormatMetricCommand, AppTools.setLengthFormatImperialCommand, AppTools.toggleLengthFormatOverrideCommand, ]); const item = ToolbarItemUtilities.createGroupButton("tool-formatting-setting", 135, "icon-placeholder", "set formatting units", children, { badgeType: BadgeType.New, groupPriority: 40 }); return item; }; // cSpell:enable public additionalHorizontalToolbarItems: CommonToolbarItem[] = [ // ToolbarHelper.createToolbarItemFromItemDef(0, CoreTools.keyinBrowserButtonItemDef, {groupPriority: -10 }), ToolbarHelper.createToolbarItemFromItemDef(0, CoreTools.keyinPaletteButtonItemDef, { groupPriority: -10 }), // ToolbarHelper.createToolbarItemFromItemDef(5, this._openNestedAnimationStage, {groupPriority: -10 }), ToolbarHelper.createToolbarItemFromItemDef(115, AppTools.tool1, { groupPriority: 20 }), ToolbarHelper.createToolbarItemFromItemDef(120, AppTools.tool2, { groupPriority: 20 }), ToolbarHelper.createToolbarItemFromItemDef(125, this._viewportPopupButtonItemDef, { groupPriority: 20 }), ToolbarHelper.createToolbarItemFromItemDef(130, AppTools.toolWithSettings, { groupPriority: 30 }), ToolbarHelper.createToolbarItemFromItemDef(132, AppTools.analysisAnimationCommand, { groupPriority: 30 }), ToolbarHelper.createToolbarItemFromItemDef(135, ToolWithDynamicSettings.toolItemDef, { groupPriority: 30 }), ToolbarHelper.createToolbarItemFromItemDef(140, AppTools.toggleHideShowItemsCommand, { groupPriority: 30 }), ToolbarHelper.createToolbarItemFromItemDef(145, new CommandItemDef({ commandId: "Show widget", iconSpec: "icon-placeholder", label: "Show widget", execute: () => { const frontstageDef = FrontstageManager.activeFrontstageDef; if (!frontstageDef) return; const widgetDef = frontstageDef.findWidgetDef("uitestapp-test-wd3"); if (!widgetDef) return; widgetDef.show(); }, }), { groupPriority: 30 }), ToolbarHelper.createToolbarItemFromItemDef(140, CoreTools.restoreFrontstageLayoutCommandItemDef, { groupPriority: 40 }), this.formatGroupItemsItem(), ]; public getMiscGroupItem = (): CommonToolbarItem => { const children = ToolbarHelper.constructChildToolbarItems([ this._nestedGroup, AppTools.saveContentLayout, AppTools.restoreSavedContentLayout, this._startCursorPopup, this._addCursorPopups, this._endCursorPopup, AccuDrawPopupTools.addMenuButton, AccuDrawPopupTools.hideMenuButton, AccuDrawPopupTools.showCalculator, AccuDrawPopupTools.showAngleEditor, AccuDrawPopupTools.showLengthEditor, AccuDrawPopupTools.showHeightEditor, AccuDrawPopupTools.showInputEditor, ]); const groupHiddenCondition = new ConditionalBooleanValue(() => SampleAppIModelApp.getTestProperty() === "HIDE", [SampleAppUiActionId.setTestProperty]); const item = ToolbarItemUtilities.createGroupButton("SampleApp:buttons.anotherGroup", 130, "icon-placeholder", IModelApp.localization.getLocalizedString("SampleApp:buttons.anotherGroup"), children, { badgeType: BadgeType.New, isHidden: groupHiddenCondition, groupPriority: 30 }); return item; }; // test ToolbarHelper.createToolbarItemsFromItemDefs public additionalVerticalToolbarItems: CommonToolbarItem[] = [...ToolbarHelper.createToolbarItemsFromItemDefs([ new GroupItemDef({ labelKey: "SampleApp:buttons.openCloseProperties", panelLabel: "Open Close Properties", iconSpec: "icon-placeholder", items: [AppTools.verticalPropertyGridOpenCommand, AppTools.verticalPropertyGridOffCommand], }), new GroupItemDef({ labelKey: "SampleApp:buttons.messageDemos", panelLabel: "Message Demos", iconSpec: "icon-placeholder", items: [this._activityMessageItem, this._pointerMessageItem, this._outputMessageItem, this._clearMessages], }), new GroupItemDef({ labelKey: "SampleApp:buttons.dialogDemos", panelLabel: "Dialog Demos", iconSpec: "icon-placeholder", items: [ this._radialMenuItem, this._exampleFormItem, this._viewportDialogItem, this._spinnerTestDialogItem, this._reduceWidgetOpacity, this._defaultWidgetOpacity, this._openCalculatorItem, ], badgeType: BadgeType.TechnicalPreview, }), ], 100, { groupPriority: 20 }), this.getMiscGroupItem(), OpenComponentExamplesPopoutTool.getActionButtonDef(400, 40), OpenCustomPopoutTool.getActionButtonDef(410, 40), OpenViewPopoutTool.getActionButtonDef(420, 40)]; }
the_stack
import { Task, RuntimeContext } from '../mol-task'; import { unzip, ungzip } from './zip/zip'; import { utf8Read } from '../mol-io/common/utf8'; import { AssetManager, Asset } from './assets'; // polyfill XMLHttpRequest in node.js const XHR = typeof document === 'undefined' ? require('xhr2') as { prototype: XMLHttpRequest; new(): XMLHttpRequest; readonly DONE: number; readonly HEADERS_RECEIVED: number; readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; } : XMLHttpRequest; export enum DataCompressionMethod { None, Gzip, Zip, } export type DataType = 'json' | 'xml' | 'string' | 'binary' | 'zip' export type DataValue = 'string' | any | XMLDocument | Uint8Array export type DataResponse<T extends DataType> = T extends 'json' ? any : T extends 'xml' ? XMLDocument : T extends 'string' ? string : T extends 'binary' ? Uint8Array : T extends 'zip' ? { [k: string]: Uint8Array } : never export interface AjaxGetParams<T extends DataType = 'string'> { url: string, type?: T, title?: string, headers?: [string, string][], body?: string } export function readStringFromFile(file: File) { return readFromFileInternal(file, 'string'); } export function readUint8ArrayFromFile(file: File) { return readFromFileInternal(file, 'binary'); } export function readFromFile<T extends DataType>(file: File, type: T) { return readFromFileInternal(file, type); } export function ajaxGet(url: string): Task<DataValue> export function ajaxGet<T extends DataType>(params: AjaxGetParams<T>): Task<DataResponse<T>> export function ajaxGet<T extends DataType>(params: AjaxGetParams<T> | string) { if (typeof params === 'string') return ajaxGetInternal(params, params, 'string'); return ajaxGetInternal(params.title, params.url, params.type || 'string', params.body, params.headers); } export type AjaxTask = typeof ajaxGet function isDone(data: XMLHttpRequest | FileReader) { if (data instanceof FileReader) { return data.readyState === FileReader.DONE; } else if (data instanceof XMLHttpRequest) { return data.readyState === XMLHttpRequest.DONE; } throw new Error('unknown data type'); } function genericError(isDownload: boolean) { if (isDownload) return 'Failed to download data. Possible reasons: Resource is not available, or CORS is not allowed on the server.'; return 'Failed to open file.'; } function readData<T extends XMLHttpRequest | FileReader>(ctx: RuntimeContext, action: string, data: T): Promise<T> { return new Promise<T>((resolve, reject) => { // first check if data reading is already done if (isDone(data)) { const { error } = data as FileReader; if (error !== null && error !== undefined) { reject(error ?? genericError(data instanceof XMLHttpRequest)); } else { resolve(data); } return; } let hasError = false; data.onerror = (e: ProgressEvent) => { if (hasError) return; const { error } = e.target as FileReader; reject(error ?? genericError(data instanceof XMLHttpRequest)); }; data.onprogress = (e: ProgressEvent) => { if (!ctx.shouldUpdate || hasError) return; try { if (e.lengthComputable) { ctx.update({ message: action, isIndeterminate: false, current: e.loaded, max: e.total }); } else { ctx.update({ message: `${action} ${(e.loaded / 1024 / 1024).toFixed(2)} MB`, isIndeterminate: true }); } } catch (e) { hasError = true; reject(e); } }; data.onload = (e: ProgressEvent) => { resolve(data); }; }); } function getCompression(name: string) { return /\.gz$/i.test(name) ? DataCompressionMethod.Gzip : /\.zip$/i.test(name) ? DataCompressionMethod.Zip : DataCompressionMethod.None; } async function decompress(ctx: RuntimeContext, data: Uint8Array, compression: DataCompressionMethod): Promise<Uint8Array> { switch (compression) { case DataCompressionMethod.None: return data; case DataCompressionMethod.Gzip: return ungzip(ctx, data); case DataCompressionMethod.Zip: const parsed = await unzip(ctx, data.buffer); const names = Object.keys(parsed); if (names.length !== 1) throw new Error('can only decompress zip files with a single entry'); return parsed[names[0]] as Uint8Array; } } async function processFile<T extends DataType>(ctx: RuntimeContext, reader: FileReader, type: T, compression: DataCompressionMethod): Promise<DataResponse<T>> { const { result } = reader; let data = result instanceof ArrayBuffer ? new Uint8Array(result) : result; if (data === null) throw new Error('no data given'); if (compression !== DataCompressionMethod.None) { if (!(data instanceof Uint8Array)) throw new Error('need Uint8Array for decompression'); const decompressed = await decompress(ctx, data, compression); if (type === 'string') { await ctx.update({ message: 'Decoding text...' }); data = utf8Read(decompressed, 0, decompressed.length); } else { data = decompressed; } } if (type === 'binary' && data instanceof Uint8Array) { return data as DataResponse<T>; } else if (type === 'zip' && data instanceof Uint8Array) { return await unzip(ctx, data.buffer) as DataResponse<T>; } else if (type === 'string' && typeof data === 'string') { return data as DataResponse<T>; } else if (type === 'xml' && typeof data === 'string') { const parser = new DOMParser(); return parser.parseFromString(data, 'application/xml') as DataResponse<T>; } else if (type === 'json' && typeof data === 'string') { return JSON.parse(data) as DataResponse<T>; } throw new Error(`could not get requested response data '${type}'`); } function readFromFileInternal<T extends DataType>(file: File, type: T): Task<DataResponse<T>> { let reader: FileReader | undefined = void 0; return Task.create('Read File', async ctx => { try { reader = new FileReader(); // unzipping for type 'zip' handled explicitly in `processFile` const compression = type === 'zip' ? DataCompressionMethod.None : getCompression(file.name); if (type === 'binary' || type === 'zip' || compression !== DataCompressionMethod.None) { reader.readAsArrayBuffer(file); } else { reader.readAsText(file); } await ctx.update({ message: 'Opening file...', canAbort: true }); const fileReader = await readData(ctx, 'Reading...', reader); await ctx.update({ message: 'Processing file...', canAbort: false }); return await processFile(ctx, fileReader, type, compression); } finally { reader = void 0; } }, () => { if (reader) reader.abort(); }); } class RequestPool { private static pool: XMLHttpRequest[] = []; private static poolSize = 15; static get() { if (this.pool.length) { return this.pool.pop()!; } return new XHR(); } static emptyFunc() { } static deposit(req: XMLHttpRequest) { if (this.pool.length < this.poolSize) { req.onabort = RequestPool.emptyFunc; req.onerror = RequestPool.emptyFunc; req.onload = RequestPool.emptyFunc; req.onprogress = RequestPool.emptyFunc; this.pool.push(req); } } } function processAjax<T extends DataType>(req: XMLHttpRequest, type: T): DataResponse<T> { if (req.status >= 200 && req.status < 400) { const { response } = req; RequestPool.deposit(req); if ((type === 'binary' || type === 'zip') && response instanceof ArrayBuffer) { return new Uint8Array(response) as DataResponse<T>; } else if (type === 'string' && typeof response === 'string') { return response as DataResponse<T>; } else if (type === 'xml' && response instanceof XMLDocument) { return response as DataResponse<T>; } else if (type === 'json' && typeof response === 'object') { return response as DataResponse<T>; } throw new Error(`could not get requested response data '${type}'`); } else { RequestPool.deposit(req); throw new Error(`Download failed with status code ${req.status}`); } } function getRequestResponseType(type: DataType): XMLHttpRequestResponseType { switch (type) { case 'json': return 'json'; case 'xml': return 'document'; case 'string': return 'text'; case 'binary': return 'arraybuffer'; case 'zip': return 'arraybuffer'; } } function ajaxGetInternal<T extends DataType>(title: string | undefined, url: string, type: T, body?: string, headers?: [string, string][]): Task<DataResponse<T>> { let xhttp: XMLHttpRequest | undefined = void 0; return Task.create(title ? title : 'Download', async ctx => { xhttp = RequestPool.get(); xhttp.open(body ? 'post' : 'get', url, true); if (headers) { for (const [name, value] of headers) { xhttp.setRequestHeader(name, value); } } xhttp.responseType = getRequestResponseType(type); xhttp.send(body); await ctx.update({ message: 'Waiting for server...', canAbort: true }); const req = await readData(ctx, 'Downloading...', xhttp); xhttp = void 0; // guard against reuse, help garbage collector await ctx.update({ message: 'Parsing response...', canAbort: false }); const result = processAjax(req, type); return result; }, () => { if (xhttp) { xhttp.abort(); xhttp = void 0; // guard against reuse, help garbage collector } }); } export type AjaxGetManyEntry = { kind: 'ok', id: string, result: Asset.Wrapper<'string' | 'binary'> } | { kind: 'error', id: string, error: any } export async function ajaxGetMany(ctx: RuntimeContext, assetManager: AssetManager, sources: { id: string, url: Asset.Url | string, isBinary?: boolean, canFail?: boolean }[], maxConcurrency: number) { const len = sources.length; const slots: AjaxGetManyEntry[] = new Array(sources.length); await ctx.update({ message: 'Downloading...', current: 0, max: len }); let promises: Promise<AjaxGetManyEntry & { index: number }>[] = [], promiseKeys: number[] = []; let currentSrc = 0; for (let _i = Math.min(len, maxConcurrency); currentSrc < _i; currentSrc++) { const current = sources[currentSrc]; promises.push(wrapPromise(currentSrc, current.id, assetManager.resolve(Asset.getUrlAsset(assetManager, current.url), current.isBinary ? 'binary' : 'string').runAsChild(ctx))); promiseKeys.push(currentSrc); } let done = 0; while (promises.length > 0) { const r = await Promise.race(promises); const src = sources[r.index]; const idx = promiseKeys.indexOf(r.index); done++; if (r.kind === 'error' && !src.canFail) { // TODO: cancel other downloads throw new Error(`${src.url}: ${r.error}`); } if (ctx.shouldUpdate) { await ctx.update({ message: 'Downloading...', current: done, max: len }); } slots[r.index] = r; promises = promises.filter(_filterRemoveIndex, idx); promiseKeys = promiseKeys.filter(_filterRemoveIndex, idx); if (currentSrc < len) { const current = sources[currentSrc]; const asset = assetManager.resolve(Asset.getUrlAsset(assetManager, current.url), current.isBinary ? 'binary' : 'string').runAsChild(ctx); promises.push(wrapPromise(currentSrc, current.id, asset)); promiseKeys.push(currentSrc); currentSrc++; } } return slots; } function _filterRemoveIndex(this: number, _: any, i: number) { return this !== i; } async function wrapPromise(index: number, id: string, p: Promise<Asset.Wrapper<'string' | 'binary'>>): Promise<AjaxGetManyEntry & { index: number }> { try { const result = await p; return { kind: 'ok', result, index, id }; } catch (error) { return { kind: 'error', error, index, id }; } }
the_stack
import { PersistentUnorderedMap, storage, Context, logging, u128, ContractPromiseBatch, PersistentSet, PersistentVector, } from "near-sdk-core"; type NearAccount = string; // example: user.near, user.testnet type ExternalAccount = string; // example: twitter/user //// MODELS // Common const OWNER_ACCOUNT_KEY = "a"; const INIT_CONTRACT_KEY = "l"; const ACTIVE_CONTRACT_KEY = "m"; // Identity const externalByNear = new PersistentUnorderedMap<NearAccount, ExternalAccount>("b"); const nearByExternal = new PersistentUnorderedMap<ExternalAccount, NearAccount>("c"); const ORACLE_ACCOUNT_KEY = "d"; const MIN_STAKE_AMOUNT_KEY = "e"; // Requests @nearBindgen export class VerificationRequest { constructor( public nearAccount: NearAccount, public externalAccount: ExternalAccount, public isUnlink: boolean, public proofUrl: string ) {} } const verificationRequests = new PersistentVector<VerificationRequest>("f"); const pendingRequests = new PersistentSet<u32>("g"); const approvedRequests = new PersistentSet<u32>("k"); // Tipping const totalTipsByItem = new PersistentUnorderedMap<string, u128>("h"); const totalTipsByExternal = new PersistentUnorderedMap<ExternalAccount, u128>("i"); const availableTipsByExternal = new PersistentUnorderedMap<ExternalAccount, u128>("j"); const MAX_AMOUNT_PER_ITEM_KEY = "n"; const MAX_AMOUNT_PER_TIP_KEY = "o"; // INITIALIZATION export function initialize( ownerAccountId: NearAccount, oracleAccountId: NearAccount, minStakeAmount: u128, maxAmountPerItem: u128, maxAmountPerTip: u128 ): void { assert(storage.getPrimitive<bool>(INIT_CONTRACT_KEY, false) == false, "Contract already initialized"); storage.set<NearAccount>(OWNER_ACCOUNT_KEY, ownerAccountId); storage.set<NearAccount>(ORACLE_ACCOUNT_KEY, oracleAccountId); storage.set<u128>(MIN_STAKE_AMOUNT_KEY, minStakeAmount); storage.set<u128>(MAX_AMOUNT_PER_ITEM_KEY, maxAmountPerItem); storage.set<u128>(MAX_AMOUNT_PER_TIP_KEY, maxAmountPerTip); storage.set<bool>(INIT_CONTRACT_KEY, true); storage.set<bool>(ACTIVE_CONTRACT_KEY, true); logging.log( "Init contract with owner: " + ownerAccountId + ", oracle: " + oracleAccountId + " and min stake: " + minStakeAmount.toString() ); } //// READ // Identity export function getExternalAccount(nearAccount: NearAccount): ExternalAccount | null { _active(); return externalByNear.get(nearAccount); } export function getNearAccount(externalAccount: ExternalAccount): NearAccount | null { _active(); return nearByExternal.get(externalAccount); } export function getOwnerAccount(): NearAccount | null { _active(); return storage.get<NearAccount>(OWNER_ACCOUNT_KEY); } export function getOracleAccount(): NearAccount | null { _active(); return storage.get<NearAccount>(ORACLE_ACCOUNT_KEY); } export function getMinStakeAmount(): u128 { _active(); return storage.get<u128>(MIN_STAKE_AMOUNT_KEY, u128.Zero)!; } export function getMaxAmountPerItem(): u128 { _active(); return storage.get<u128>(MAX_AMOUNT_PER_ITEM_KEY, u128.Zero)!; } export function getMaxAmountPerTip(): u128 { _active(); return storage.get<u128>(MAX_AMOUNT_PER_TIP_KEY, u128.Zero)!; } // Requests export function getPendingRequests(): u32[] { _active(); return pendingRequests.values(); } export function getVerificationRequest(id: u32): VerificationRequest | null { _active(); if (!verificationRequests.containsIndex(id)) return null; return verificationRequests[id]; } export function getRequestStatus(id: u32): u8 { _active(); if (!verificationRequests.containsIndex(id)) { return u8(0); // not found } else if (pendingRequests.has(id)) { return u8(1); // pending } else if (approvedRequests.has(id)) { return u8(2); // approved } else { return u8(3); // rejected } } // Tipping export function getTotalTipsByItemId(itemId: string): u128 { _active(); return totalTipsByItem.get(itemId, u128.Zero)!; } export function getTotalTipsByExternalAccount(externalAccount: ExternalAccount): u128 { _active(); return totalTipsByExternal.get(externalAccount, u128.Zero)!; } export function getAvailableTipsByExternalAccount(externalAccount: ExternalAccount): u128 { _active(); return availableTipsByExternal.get(externalAccount, u128.Zero)!; } export function calculateFee(donationAmount: u128): u128 { _active(); return u128.muldiv(donationAmount, u128.from(3), u128.from(100)); // 3% } // WRITE // Identity export function approveRequest(requestId: u32): void { _active(); _onlyOracle(); assert(verificationRequests.containsIndex(requestId), "Non-existent request ID"); assert(pendingRequests.has(requestId), "The request has already been processed"); const req = verificationRequests[requestId]; if (req.isUnlink) { externalByNear.delete(req.nearAccount); nearByExternal.delete(req.externalAccount); logging.log("Accounts " + req.nearAccount + " and " + req.externalAccount + " are unlinked"); } else { externalByNear.set(req.nearAccount, req.externalAccount); nearByExternal.set(req.externalAccount, req.nearAccount); logging.log("Accounts " + req.nearAccount + " and " + req.externalAccount + " are linked"); } pendingRequests.delete(requestId); approvedRequests.add(requestId); } export function rejectRequest(requestId: u32): void { _active(); _onlyOracle(); assert(verificationRequests.containsIndex(requestId), "Non-existent request ID"); assert(pendingRequests.has(requestId), "The request has already been processed"); pendingRequests.delete(requestId); } export function changeOwnerAccount(newAccountId: NearAccount): void { _active(); _onlyOwner(); storage.set(OWNER_ACCOUNT_KEY, newAccountId); logging.log("Changed owner: " + newAccountId); } export function changeOracleAccount(newAccountId: NearAccount): void { _active(); _onlyOwner(); storage.set(ORACLE_ACCOUNT_KEY, newAccountId); logging.log("Changed oracle: " + newAccountId); } export function changeMinStake(minStakeAmount: u128): void { _active(); _onlyOwner(); storage.set<u128>(MIN_STAKE_AMOUNT_KEY, minStakeAmount); logging.log("Changed min stake: " + minStakeAmount.toString()); } export function changeMaxAmountPerItem(maxAmountPerItem: u128): void { _active(); _onlyOwner(); storage.set<u128>(MAX_AMOUNT_PER_ITEM_KEY, maxAmountPerItem); logging.log("Changed max amount of item tips: " + maxAmountPerItem.toString()); } export function changeMaxAmountPerTip(maxAmountPerTip: u128): void { _active(); _onlyOwner(); storage.set<u128>(MAX_AMOUNT_PER_TIP_KEY, maxAmountPerTip); logging.log("Changed max amount of one tip: " + maxAmountPerTip.toString()); } export function unlinkAll(): void { _active(); _onlyOwner(); externalByNear.clear(); nearByExternal.clear(); } // Requests export function requestVerification(externalAccount: ExternalAccount, isUnlink: boolean, url: string): u32 { _active(); assert(Context.sender == Context.predecessor, "Cross-contract calls is not allowed"); assert( u128.ge(Context.attachedDeposit, storage.get<u128>(MIN_STAKE_AMOUNT_KEY, u128.Zero)!), "Insufficient stake amount" ); // ToDo: audit it if (isUnlink) { assert(externalByNear.contains(Context.sender), "The NEAR account doesn't have a linked account"); assert(nearByExternal.contains(externalAccount), "The external account doesn't have a linked account"); // ToDo: // assert(nearByExternal.get(externalAccount) == Context.sender, ""); // assert(nearByExternal.get(Context.sender) == externalAccount, ""); } else { assert(!externalByNear.contains(Context.sender), "The NEAR account already has a linked account"); assert(!nearByExternal.contains(externalAccount), "The external account already has a linked account"); } const id = verificationRequests.push(new VerificationRequest(Context.sender, externalAccount, isUnlink, url)); pendingRequests.add(id); const oracleAccount = storage.get<NearAccount>(ORACLE_ACCOUNT_KEY)!; ContractPromiseBatch.create(oracleAccount).transfer(Context.attachedDeposit); logging.log( Context.sender + " requests to link " + externalAccount + " account. Proof ID: " + id.toString() + " URL: " + url ); return id; } // Tipping export function sendTips(recipientExternalAccount: ExternalAccount, itemId: string): void { _active(); assert(u128.gt(Context.attachedDeposit, u128.Zero), "Tips amounts must be greater than zero"); assert( u128.le( u128.add(totalTipsByItem.get(itemId, u128.Zero)!, Context.attachedDeposit), storage.get<u128>(MAX_AMOUNT_PER_ITEM_KEY, u128.Zero)! ), "New total tips amount exceeds allowance" ); const donationAmount = u128.muldiv(Context.attachedDeposit, u128.from(100), u128.from(103)); const feeAmount = u128.sub(Context.attachedDeposit, donationAmount); assert( u128.le(donationAmount, storage.get<u128>(MAX_AMOUNT_PER_TIP_KEY, u128.Zero)!), "Tips amount exceeds allowance" ); assert(!u128.eq(feeAmount, u128.Zero), "Donation cannot be free"); const nearAccount = nearByExternal.get(recipientExternalAccount); if (nearAccount) { ContractPromiseBatch.create(nearAccount).transfer(donationAmount); logging.log( Context.sender + " tips " + donationAmount.toString() + " NEAR to " + recipientExternalAccount + " <=> " + nearAccount ); } else { const availableTips = availableTipsByExternal.get(recipientExternalAccount, u128.Zero)!; const newAvailableTips = u128.add(availableTips, donationAmount); availableTipsByExternal.set(recipientExternalAccount, newAvailableTips); logging.log(Context.sender + " tips " + donationAmount.toString() + " NEAR to " + recipientExternalAccount); } // update item stat const oldTotalTipsByItem = totalTipsByItem.get(itemId, u128.Zero)!; const newTotalTipsByItem = u128.add(oldTotalTipsByItem, donationAmount); totalTipsByItem.set(itemId, newTotalTipsByItem); // update user stat const oldTotalTipsByExternal = totalTipsByExternal.get(recipientExternalAccount, u128.Zero)!; const newTotalTipsByExternal = u128.add(oldTotalTipsByExternal, donationAmount); totalTipsByExternal.set(recipientExternalAccount, newTotalTipsByExternal); // transfer donation fee to owner const owner = storage.get<NearAccount>(OWNER_ACCOUNT_KEY)!; ContractPromiseBatch.create(owner).transfer(feeAmount); } export function claimTokens(): void { _active(); const externalAccount = externalByNear.get(Context.sender); assert(externalAccount != null, "You don't have any linked account."); const availableTips = availableTipsByExternal.get(externalAccount!, u128.Zero)!; assert(u128.gt(availableTips, u128.Zero), "No tips to withdraw."); ContractPromiseBatch.create(Context.sender).transfer(availableTips); availableTipsByExternal.set(externalAccount!, u128.Zero); logging.log(Context.sender + " claimed " + availableTips.toString() + " NEAR from " + externalAccount!); } export function shutdown(): void { _onlyOwner(); storage.set<bool>(ACTIVE_CONTRACT_KEY, false); logging.log("Shutdown occured"); } // HELPERS function _onlyOracle(): void { assert(storage.get<NearAccount>(ORACLE_ACCOUNT_KEY) == Context.sender, "Only oracle account can write"); } function _onlyOwner(): void { assert(storage.get<NearAccount>(OWNER_ACCOUNT_KEY) == Context.sender, "Only owner account can write"); } function _active(): void { assert(storage.getPrimitive<bool>(ACTIVE_CONTRACT_KEY, false) == true, "Contract inactive"); }
the_stack
import ws from 'ws' import fs from 'fs' import http from 'http' import crypto from 'crypto' import { EventEmitter } from 'events' import tools from './lib/tools' import User from './online' import Options from './options' /** * 程序设置 * * @class WebAPI * @extends {EventEmitter} */ class WebAPI extends EventEmitter { constructor() { super() } protected _wsClients: Map<string, Map<ws, wsOptions>> = new Map() /** * 启动HTTP以及WebSocket服务 * * @memberof WebAPI */ public Start() { // Websockets服务 const wsserver = new ws.Server({ noServer: true }) .on('error', error => tools.ErrorLog('websocket', error)) .on('connection', (client: ws, req: http.IncomingMessage) => { // 限制同时只能连接一个客户端 const protocol = client.protocol if (this._wsClients.has(protocol)) { const clients = <Map<ws, wsOptions>>this._wsClients.get(protocol) clients.forEach((_option, client) => client.close(1001, JSON.stringify({ cmd: 'close', msg: 'too many connections' }))) clients.set(client, { protocol, encrypt: false }) } else { const clients = new Map([[client, { protocol, encrypt: false }]]) this._wsClients.set(protocol, clients) } // 使用Nginx可能需要 const remoteAddress = req.headers['x-real-ip'] === undefined ? `${req.connection.remoteAddress}:${req.connection.remotePort}` : `${req.headers['x-real-ip']}:${req.headers['x-real-port']}` tools.Log(`${remoteAddress} 已连接`) // 使用function可能出现一些问题, 此处无妨 const onLog = (data: string) => this._Broadcast({ message: { cmd: 'log', ts: 'log', msg: data }, protocol }) const destroy = () => { const clients = this._wsClients.get(protocol) if (clients !== undefined) { clients.delete(client) if (clients.size === 0) this._wsClients.delete(protocol) } tools.removeListener('log', onLog) client.close() client.terminate() client.removeAllListeners() } client .on('error', (error) => { destroy() tools.ErrorLog('client', error) }) .on('close', (code, reason) => { destroy() tools.Log(`${remoteAddress} 已断开`, code, reason) }) .on('message', async msg => { const clients = this._wsClients.get(protocol) if (clients !== undefined) { const option = clients.get(client) if (option !== undefined) { let message: message | undefined if (typeof msg === 'string') message = await tools.JSONparse<message>(msg) else { const aesData = Buffer.from(<Buffer>msg) if (option.encrypt && option.sharedSecret !== undefined) message = await this._Decipher(aesData, option) else message = await tools.JSONparse<message>(aesData.toString()) } if (message !== undefined && message.cmd !== undefined && message.ts !== undefined) this._onCMD({ message, client, option }) else this._Send({ message: { cmd: 'error', ts: 'error', msg: '消息格式错误' }, client, option }) } } }) // 一般推荐客户端发送心跳, 不过放在服务端的话可以有一些限制 (目前没有) const ping = setInterval(() => { if (client.readyState === ws.OPEN) client.ping() else clearInterval(ping) }, 60 * 1000) // 60s为Nginx默认的超时时间 // 日志 tools.on('log', onLog) }) // HTTP服务 // 直接跳转到github.io, 为防以后变更使用302 const server = http.createServer((req, res) => { req.on('error', error => tools.ErrorLog('req', error)) res.on('error', error => tools.ErrorLog('res', error)) res.writeHead(302, { 'Location': '//github.halaal.win/bilive_client/' }) res.end() }) .on('error', error => tools.ErrorLog('http', error)) .on('upgrade', (request: http.IncomingMessage, socket, head) => { const protocolraw = request.headers['sec-websocket-protocol'] let protocols: string[] if (protocolraw === undefined) protocols = [] else if (typeof protocolraw === 'string') protocols = protocolraw.split(/, ?/) else protocols = protocolraw const adminProtocol = Options._.server.protocol if (protocols[0] === adminProtocol) wsserver.handleUpgrade(request, socket, head, ws => { wsserver.emit('connection', ws, request) }) else socket.destroy() }) // 监听地址优先支持Unix Domain Socket const listen = Options._.server if (listen.path === '') { const host = process.env.HOST === undefined ? listen.hostname : process.env.HOST const port = process.env.PORT === undefined ? listen.port : Number.parseInt(process.env.PORT) server.listen(port, host, () => { tools.Log(`已监听 ${host}:${port}`) }) } else { if (fs.existsSync(listen.path)) fs.unlinkSync(listen.path) server.listen(listen.path, () => { fs.chmodSync(listen.path, '666') tools.Log(`已监听 ${listen.path}`) }) } } /** * 监听客户端发来的消息, CMD为关键字 * * @private * @param {sendData} { message, client, option } * @memberof WebAPI */ private async _onCMD({ message, client, option }: sendData) { const cmd = message.cmd const ts = message.ts switch (cmd) { // 协议握手 case 'hello': { const algorithm = message.msg switch (algorithm) { case 'ECDH-AES-256-GCM': case 'ECDH-AES-256-CBC': { const clientPublicKeyHex = <string>message.data const computeSecret = await this._ComputeSecret(clientPublicKeyHex) if (computeSecret !== undefined) { const { serverPublicKey, sharedSecret } = computeSecret const serverPublicKeyHex = serverPublicKey.toString('hex') this._Send({ message: { cmd, ts, msg: algorithm, data: serverPublicKeyHex }, client, option }) const clients = this._wsClients.get(option.protocol) if (clients !== undefined) { option.encrypt = true option.algorithm = algorithm option.sharedSecret = sharedSecret.slice(0, 32) clients.set(client, option) } } else this._Send({ message: { cmd, ts, msg: '获取密钥失败' }, client, option }) } break default: this._Send({ message: { cmd, ts, msg: '未知加密格式' }, client, option }) break } } break // 获取log case 'getLog': { const data = tools.logs this._Send({ message: { cmd, ts, data }, client, option }) } break // 获取设置 case 'getConfig': { const config = Options._.config const configInfo = Options._.info const data = Object.assign({}, config) // 判断password类型 for (const i in config) if (configInfo[i]?.password) data[i] = '' this._Send({ message: { cmd, ts, data }, client, option }) } break // 保存设置 case 'setConfig': { const config = Options._.config const configInfo = Options._.info const serverURL = config.serverURL const setConfig = <config>message.data || {} let msg = '' for (const i in config) { if (typeof config[i] !== typeof setConfig[i]) { // 一般都是自用, 做一个简单的验证就够了 msg = i + '参数错误' break } } if (msg === '') { // 防止setConfig里有未定义属性, 不使用Object.assign for (const i in config) { // 判断password类型 if (configInfo[i]?.password && setConfig[i] === '') continue config[i] = setConfig[i] } Options.save() // 更新可能的设置 for (const i in config) { // 判断password类型 if (configInfo[i]?.password) setConfig[i] = '' else setConfig[i] = config[i] } this._Send({ message: { cmd, ts, data: setConfig }, client, option }) if (serverURL !== config.serverURL) Options.emit('clientUpdate') } else this._Send({ message: { cmd, ts, msg, data: config }, client, option }) } break // 获取参数描述 case 'getInfo': { const data = Options._.info this._Send({ message: { cmd, ts, data }, client, option }) } break // 获取uid case 'getAllUID': { const data = Object.keys(Options._.user) this._Send({ message: { cmd, ts, data }, client, option }) } break // 获取用户设置 case 'getUserData': { const user = Options._.user const getUID = message.uid if (typeof getUID === 'string' && user[getUID] !== undefined) { const userData = user[getUID] const configInfo = Options._.info const data = Object.assign({}, userData) // 判断password类型 for (const i in userData) if (configInfo[i]?.password) data[i] = '' this._Send({ message: { cmd, ts, uid: getUID, data }, client, option }) } else this._Send({ message: { cmd, ts, msg: '未知用户' }, client, option }) } break // 保存用户设置 case 'setUserData': { const user = Options._.user const setUID = message.uid if (setUID !== undefined && user[setUID] !== undefined) { const userData = user[setUID] const configInfo = Options._.info const setUserData = <userData>message.data || {} let msg = '' let validate = '' let validatecode = '' // let authcode = '' for (const i in userData) { if (typeof userData[i] !== typeof setUserData[i]) { msg = i + '参数错误' break } } if (msg === '') { for (const i in userData) { // 判断password类型 if (configInfo[i]?.password && setUserData[i] === '') continue userData[i] = setUserData[i] } if (userData.status && !Options.user.has(setUID)) { // 因为使用了Map保存已激活的用户, 所以需要添加一次 const newUser = new User(setUID, userData) const status = await newUser.Start() // 账号会尝试登录, 如果需要极验验证码status会返回'validate', 并且链接会以Url字符串形式保存在validateURL if (status === 'validate') validate = newUser.validateURL // 账号会尝试登录, 如果需要手机验证码status会返回'validatecode', 并且链接会以Url字符串形式保存在validatecodeURL else if (status === 'validatecode') validatecode = newUser.validatecodeURL // 账号会尝试登录, 如果需要扫描登录status会返回'authcode', 并且链接会以Url字符串形式保存在authCodeURL // else if (status === 'authcode') authcode = newUser.authcodeURL else if (Options.user.has(setUID)) Options.emit('newUser', newUser) } else if (userData.status && Options.user.has(setUID)) { // 对于已经存在的用户, 可能处在验证码待输入阶段 const validateUser = <User>Options.user.get(setUID) if (validateUser.validateURL !== '' && message.validate !== undefined) { validateUser.validate = message.validate const status = await validateUser.Start() if (status === 'validate') validate = validateUser.validateURL else if (Options.user.has(setUID)) Options.emit('newUser', validateUser) } else if (validateUser.validatecodeURL !== '' && message.validatecode !== undefined) { const status = await validateUser.Start() if (status === 'validatecode') validatecode = validateUser.validatecodeURL else if (Options.user.has(setUID)) Options.emit('newUser', validateUser) } // else if (captchaUser.authcodeURL !== '' && message.authcode !== undefined) { // const status = await captchaUser.Start() // if (status === 'authcode') authcode = captchaUser.authcodeURL // else if (Options.user.has(setUID)) Options.emit('newUser', captchaUser) // } } else if (!userData.status && Options.user.has(setUID)) (<User>Options.user.get(setUID)).Stop() Options.save() // 更新可能的设置 for (const i in userData) { // 判断password类型 if (configInfo[i]?.password) setUserData[i] = '' else setUserData[i] = userData[i] } if (validate !== '') this._Send({ message: { cmd, ts, uid: setUID, msg: 'validate', data: setUserData, validate }, client, option }) else if (validatecode !== '') this._Send({ message: { cmd, ts, uid: setUID, msg: 'validatecode', data: setUserData, validatecode }, client, option }) // else if (authcode !== '') this._Send({ message: { cmd, ts, uid: setUID, msg: 'authcode', data: setUserData, authcode }, client, option }) else this._Send({ message: { cmd, ts, uid: setUID, data: setUserData }, client, option }) } else this._Send({ message: { cmd, ts, uid: setUID, msg, data: setUserData }, client, option }) } else this._Send({ message: { cmd, ts, uid: setUID, msg: '未知用户' }, client, option }) } break // 删除用户设置 case 'delUserData': { const user = Options._.user const delUID = message.uid if (delUID !== undefined && user[delUID] !== undefined) { const userData = user[delUID] delete Options._.user[delUID] if (Options.user.has(delUID)) (<User>Options.user.get(delUID)).Stop() Options.save() this._Send({ message: { cmd, ts, uid: delUID, data: userData }, client, option }) } else this._Send({ message: { cmd, ts, uid: delUID, msg: '未知用户' }, client, option }) } break // 新建用户设置 case 'newUserData': { // 虽然不能保证唯一性, 但是这都能重复的话可以去买彩票 const uid = crypto.randomBytes(16).toString('hex') const newData = Object.assign({}, Options._.newUserData) const data = Object.assign({}, newData) const configInfo = Options._.info Options.whiteList.add(uid) Options._.user[uid] = data Options.save() for (const i in newData) { // 判断password类型 if (configInfo[i]?.password) data[i] = '' else data[i] = newData[i] } this._Send({ message: { cmd, ts, uid, data }, client, option }) } break // 未知命令 default: this._Send({ message: { cmd, ts, msg: '未知命令' }, client, option }) break } } /** * 广播消息 * * @private * @param {broadcastData} { message, protocol } * @memberof WebAPI */ private _Broadcast({ message, protocol }: broadcastData) { const clients = this._wsClients.get(protocol) if (clients !== undefined) clients.forEach((option, client) => this._Send({ message, client, option })) } /** * 向客户端发送消息 * * @private * @param {sendData} { message, client, option } * @memberof WebAPI */ private async _Send({ message, client, option }: sendData) { const msg = JSON.stringify(message) if (client.readyState === ws.OPEN) { if (option.encrypt && option.sharedSecret !== undefined) { const crypted = await this._Cipher(msg, option) if (crypted !== undefined) client.send(crypted) } else client.send(Buffer.from(msg)) } } /** * 交换密钥 * * @private * @param {string} clientPublicKeyHex * @returns {(Promise<{ serverPublicKey: Buffer, sharedSecret: Buffer } | undefined>)} * @memberof WebAPI */ private _ComputeSecret(clientPublicKeyHex: string): Promise<{ serverPublicKey: Buffer, sharedSecret: Buffer } | undefined> { return new Promise<{ serverPublicKey: Buffer, sharedSecret: Buffer } | undefined>(resolve => { const server = crypto.createECDH('secp521r1') server.generateKeys() const serverPublicKey = server.getPublicKey() try { const sharedSecret = server.computeSecret(clientPublicKeyHex, 'hex') resolve({ serverPublicKey, sharedSecret }) } catch (error) { resolve(undefined) } }) } /** * 加密数据 * * @private * @param {string} data * @param {wsOptions} option * @returns {(Promise<Buffer | undefined>)} * @memberof WebAPI */ private _Cipher(data: string, option: wsOptions): Promise<Buffer | undefined> { return new Promise<Buffer | undefined>(resolve => { switch (option.algorithm) { case 'ECDH-AES-256-GCM': { const iv = crypto.randomBytes(12) try { const cipher = crypto.createCipheriv('aes-256-gcm', <Buffer>option.sharedSecret, iv) const crypted = Buffer.concat([iv, cipher.update(data), cipher.final(), cipher.getAuthTag()]) resolve(crypted) } catch (error) { resolve(undefined) } } break case 'ECDH-AES-256-CBC': { const iv = crypto.randomBytes(16) try { const cipher = crypto.createCipheriv('aes-256-cbc', <Buffer>option.sharedSecret, iv) const crypted = Buffer.concat([iv, cipher.update(data), cipher.final()]) resolve(crypted) } catch (error) { resolve(undefined) } } break default: resolve(undefined) break } }) } /** * 解密数据 * * @private * @param {Buffer} data * @param {wsOptions} option * @returns {(Promise<message | undefined>)} * @memberof WebAPI */ private _Decipher(data: Buffer, option: wsOptions): Promise<message | undefined> { return new Promise<message | undefined>(resolve => { if (data.length < 28) resolve(undefined) else { switch (option.algorithm) { case 'ECDH-AES-256-GCM': { const iv = data.slice(0, 12) const auth = data.slice(data.length - 16) const encrypted = data.slice(12, data.length - 16) try { const decipher = crypto.createDecipheriv('aes-256-gcm', <Buffer>option.sharedSecret, iv) decipher.setAuthTag(auth) const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]) const message: message = JSON.parse(decrypted.toString()) resolve(message) } catch (error) { resolve(undefined) } } break case 'ECDH-AES-256-CBC': { const iv = data.slice(0, 16) const encrypted = data.slice(16) try { const decipher = crypto.createDecipheriv('aes-256-cbc', <Buffer>option.sharedSecret, iv) const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]) const message: message = JSON.parse(decrypted.toString()) resolve(message) } catch (error) { resolve(undefined) } } break default: resolve(undefined) break } } }) } } // WebSocket消息 interface message { cmd: string ts: string msg?: string uid?: string data?: config | optionsInfo | string | string[] | userData validate?: string validatecode?: string authcode?: string } interface wsOptions { protocol: string encrypt: boolean algorithm?: string sharedSecret?: Buffer } interface broadcastData { message: message protocol: string } interface sendData { message: message client: ws option: wsOptions } export default WebAPI export { message }
the_stack
import {Observable, Subject} from 'rxjs'; import {Configuration} from './configuration'; import {Base} from './abstract-base'; import {UnitBase} from './abstract-unit-base'; import {NonPrimitiveUnitBase} from './abstract-non-primitive-unit-base'; import { EventListUnitCopyWithin, EventListUnitDelete, EventListUnitFill, EventListUnitPop, EventListUnitPush, EventListUnitRemove, EventListUnitReverse, EventListUnitSet, EventListUnitShift, EventListUnitSort, EventListUnitSplice, EventListUnitUnshift, KOf, ListUnitEvents, UnitConfig, } from '../models'; import { isFunction, isObject, isValidIndex, IteratorSymbol, makeNonEnumerable, normalizeIndex, sanitizeIndices, } from '../utils/funcs'; // tslint:disable-next-line:no-empty-interface export interface ListUnit<Item> extends Array<Item> {} /** * ListUnit is a reactive storage Unit that emulates `array`. * * ListUnit only accepts `array` data type as its value. * It ensures that at any point of time the value would always be an `array`. * * ListUnit is based on `array`, it implements all the `Array.prototype` methods that are available * in the environment/browser its running, including polyfills. * e.g.: `find`, `filter`, `includes`, etc. * * Learn more about Units [here](https://docs.activejs.dev/fundamentals/units). \ * Learn more about ListUnit [here](https://docs.activejs.dev/fundamentals/units/listunit). * * Just like every other Non-Primitive ActiveJS Unit: * - ListUnit extends {@link NonPrimitiveUnitBase} * - Which further extends {@link UnitBase}, {@link Base} and `Observable` * * @category 1. Units */ export class ListUnit<Item> extends NonPrimitiveUnitBase<Item[]> { /** * @internal please do not use. */ protected readonly eventsSubject: Subject<ListUnitEvents<Item>>; /** * On-demand observable events. */ readonly events$: Observable<ListUnitEvents<Item>>; /** * The length of the list-{@link value}. */ get length(): number { return this.rawValue().length; } /** * Indicates whether the length of the list-{@link value} is `0` or not. */ get isEmpty(): boolean { return this.length === 0; } /** * @internal please do not use. */ protected defaultValue(): Item[] { return []; } constructor(config?: UnitConfig<Item[]>) { super({ ...Configuration.LIST_UNIT, ...config, }); makeNonEnumerable(this); } /** * Extends {@link UnitBase.wouldDispatch} and adds additional check for type `array` {@see {@link Array.isArray}}, \ * which cannot be bypassed even by using {@link force}. * * @param value The value to be dispatched. * @param force Whether dispatch-checks should be bypassed or not. * @returns A boolean indicating whether the param `value` would pass the dispatch-checks if dispatched. * * @category Common Units */ wouldDispatch(value: Item[], force?: boolean): boolean { return this.isValidValue(value) && super.wouldDispatch(value, force); } /** * Sets the item on the given index in the list-{@link value}. \ * Dispatches a new copy of the value, without mutating the current-value. * * It only works if the Unit is not frozen, and the index is valid-numeric. * * @param index The index of the item. \ * A negative index is normalized as following: \ * - If the index is less than negative of list-{@link length} it's treated as 0. * - Otherwise, it's subtracted from the list-{@link length}. * eg: If list length is `5`, negative index `-5` will be normalized to `0`, \ * negative index `-6` will be normalized to `0`, and so on. * @param item The item. * * @triggers {@link EventListUnitSet} * @category Custom ListUnit */ set(index: number, item: Item): void { if (this.isFrozen || !isValidIndex(index)) { return; } this.checkSerializabilityMaybe(item); const listShallowCopy = [...this.rawValue()]; listShallowCopy[normalizeIndex(index, this.length)] = this.deepCopyMaybe(item); this.updateValueAndCache(listShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitSet(index, item)); } } /** * Inserts items to the list-{@link value}. \ * Dispatches a new copy of the value, without mutating the current-value. * * It only works if the Unit is not frozen and there's at least 1 item to be inserted. * * @param start The zero-based index in the list from which to start adding items. \ * A negative index is normalized as following: \ * - If the index is less than negative of list-{@link length} it's treated as 0. * - Otherwise, it's subtracted from the list-{@link length}. * eg: If list length is `5`, negative index `-5` will be normalized to `0`, \ * negative index `-6` will be normalized to `0`, and so on. * @param items The items to be insert. * @returns The new length of the list. * * @triggers {@link EventListUnitSplice} * @category Custom ListUnit */ insert(start: number, ...items: Item[]): number { if (this.isFrozen || !items.length) { return this.length; } this.checkSerializabilityMaybe(items); this.splice(start, 0, ...items); // splice also takes care of empty spaces return this.length; } /** * Removes items at given indices from the list-{@link value}. \ * Dispatches a new copy of the value, without mutating the current-value. \ * It modifies the length of the list as these indices are not deleted, * rather removed using `Array.prototype.splice`. * * It only works if the Unit is not frozen, and * the list is not empty, and at least 1 valid-numeric index is provided. * * Notes: * - The indices are removed in descending order. * - The indices are deduplicated. * - Negative indices are normalized before starting the removal. \ * A negative index is normalized as following: \ * - If the index is less than negative of list-{@link length}, it's treated as 0. * - Otherwise, it's subtracted from the list-{@link length}. * eg: If list length is `5`, negative index `-5` will be normalized to `0`, \ * negative index `-6` will be normalized to `0`, and so on. * * @param indices The indices of the items to be removed. * @returns The removed items or an empty `array`. * * @triggers {@link EventListUnitRemove} * @category Custom ListUnit */ remove(...indices: number[]): Item[] { const listLength = this.length; indices = sanitizeIndices(indices, listLength).filter(i => this.hasOwnProperty(i)); if (this.isFrozen || !indices.length || this.isEmpty) { return []; } indices.sort().reverse(); const removedItems = []; const listShallowCopy = [...this.rawValue()]; indices.forEach(index => { removedItems.push(...this.deepCopyMaybe(listShallowCopy.splice(index, 1))); }); this.updateValueAndCache(listShallowCopy); removedItems.reverse(); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitRemove(indices, removedItems)); } return removedItems; } /** * Removes items from the list-{@link value} where the predicate returns `truthy` value. \ * Dispatches a new copy of the value, without mutating the current-value. \ * It modifies the length of the list as these indices are not deleted, * rather removed using `Array.prototype.splice`. * * It only works if the Unit is not frozen, and * the predicate is a function, and the list is not empty. \ * It uses {@link remove} internally, for actual removal. * * @param predicate A callback function that gets called for every item in the list with the item and index as arguments. * @returns The removed items or an empty `array`. * * @triggers {@link EventListUnitRemove} * @category Custom ListUnit */ removeIf(predicate: (item: Item, index: number) => boolean): Item[] { if (this.isFrozen || typeof predicate !== 'function' || this.isEmpty) { return []; } const indicesToBeRemoved = []; this.value().forEach((item, index) => { if (predicate(item, index)) { indicesToBeRemoved.push(index); } }); return this.remove(...(indicesToBeRemoved as [number, ...number[]])); } /** * Deletes items at given indices in the list-{@link value}. \ * Dispatches a new copy of the value, without mutating the current-value. \ * It doesn't modify the length of the list as these indices are only deleted, not removed. * * It only works if the Unit is not frozen, and * the list is not empty, and at least 1 valid-numeric index is provided. * * @param indices The indices of the items to be deleted. \ * A negative index is normalized as following: \ * - If the index is less than negative of list-{@link length} it's treated as 0. * - Otherwise, it's subtracted from the list-{@link length}. * eg: If list length is `5`, negative index `-5` will be normalized to `0`, \ * negative index `-6` will be normalized to `0`, and so on. * @returns The removed items or an empty `array`. * * @triggers {@link EventListUnitDelete} * @category Custom ListUnit */ delete(...indices: number[]): Item[] { indices = sanitizeIndices(indices, this.length).filter(i => this.hasOwnProperty(i)); if (this.isFrozen || indices.length === 0 || this.isEmpty) { return []; } const deletedItems = []; const listShallowCopy = [...this.rawValue()]; indices.forEach(index => { deletedItems.push(this.deepCopyMaybe(listShallowCopy[index])); delete listShallowCopy[index]; }); this.updateValueAndCache(listShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitDelete(indices, deletedItems)); } return deletedItems; } /** * Deletes items from the list-{@link value} where the predicate returns `true`. \ * Dispatches a new copy of the value, without mutating the current-value. \ * It doesn't modify the length of the list as these indices are only deleted, not removed. * * It only works if the Unit is not frozen, and * the predicate is a function, and the list is not empty. * * @param predicate A callback function that gets called for every item in the list with the item and index as arguments. * @returns The removed items or an empty `array`. * * @triggers {@link EventListUnitDelete} * @category Custom ListUnit */ deleteIf(predicate: (item: Item, index: number) => boolean): Item[] { if (this.isFrozen || typeof predicate !== 'function' || this.isEmpty) { return []; } const indicesToBeDeleted = []; this.value().forEach((item, index) => { if (predicate(item, index)) { indicesToBeDeleted.push(index); } }); return this.delete(...(indicesToBeDeleted as [number, ...number[]])); } /** * Finds items of the list that have a direct child property * that matches with `key` and `value` passed as params. * * @example * ```ts * const initialValue = [{b: 1}, {b: 1, b2: 2}, {c: 1}, {b: null}]; * const list = new ListUnit({initialValue}); * const itemsFound = list.findByProp('b', 1); * console.log(itemsFound); // logs [[0, {b: 1}], [1, {b: 1, b2: 2}]] * ``` * * @param key The key of the property whose value needs to be matched against param `value`. * @param value A value that will be matched against every item's prop-value using equality operator. * @param strictEquality A flag governing whether the value be matched using `===` or `==` operator. * Default is `true`, ie: strict equality `===`. Pass `false` to use `==` instead. * @returns An `array` of key/values of the matched properties, an empty `array` otherwise. * * @category Custom ListUnit */ findByProp<k extends KOf<Item>>( key: k, value: string | number | boolean, strictEquality = true ): [number, Item][] { if (this.isEmpty) { return []; } return this.rawValue().reduce((res: [number, Item][], item, index) => { const aMatch = isObject(item) && (strictEquality === false ? // tslint:disable-next-line:triple-equals item[key as string | number] == value : item[key as string | number] === value); if (aMatch) { res.push([index, this.deepCopyMaybe(item)]); } return res; }, []); } /** * Returns the item at the given index in the list-{@link value}. \ * Negative index returns items from the end of the list. * * @param index The index of the item. \ * A negative index is normalized as following: \ * - If the index is less than negative of list-{@link length} it's treated as 0. * - Otherwise, it's subtracted from the list-{@link length}. * eg: If list length is `5`, negative index `-5` will be normalized to `0`, \ * negative index `-6` will be normalized to `0`, and so on. * @returns The item at the given index. * * @category Custom ListUnit */ get(index: number): Item | undefined { index = normalizeIndex(index, this.length); return this.hasOwnProperty(index) ? this.deepCopyMaybe(this.rawValue()[index]) : undefined; } /** * Returns the first item in the list-{@link value}. * * @returns The first item in the list. * * @category Custom ListUnit */ first(): Item | undefined { return this.get(0); } /** * Returns the last item in the list-{@link value}. * * @returns The last item in the list. * * @category Custom ListUnit */ last(): Item | undefined { return this.get(-1); } /** * Adds all the items of the list separated by the specified separator string, and * all the items are converted into string first using JSON.stringify * * @param separator A string used to separate one item of the list from the next in the resulting String. * If omitted, the list items are separated with a comma. * @returns Concatenated `JSON.stringify`d list items. * * @category Custom ListUnit */ jsonJoin(separator?: string): string { return this.rawValue() .map(item => JSON.stringify(item)) .join(separator); } /** * Appends new items to the list-{@link value}. \ * Dispatches a new copy of the value, without mutating the current-value. * * It only works if the Unit is not frozen, and at least 1 item is provided. * * @param items The items to be appended to the list. * @returns The new length of the list. * * @triggers {@link EventListUnitPush} * @category Customised Array.prototype */ push(...items: Item[]): number { if (this.isFrozen || !items.length) { return this.length; } this.checkSerializabilityMaybe(items); const listShallowCopy = [...this.rawValue()]; const newLength = listShallowCopy.push(...this.deepCopyMaybe(items)); this.updateValueAndCache(listShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitPush(items)); } return newLength; } /** * Removes the last item from the list-{@link value} and returns it. \ * Dispatches a new copy of the value, without mutating the current-value. * * It only works if the Unit is not frozen, and the list is not empty {@link isEmpty}. * * @returns The popped item. * * @triggers {@link EventListUnitPop} * @category Customised Array.prototype */ pop(): Item | undefined { if (this.isFrozen || this.isEmpty) { return; } const listShallowCopy = [...this.rawValue()]; const poppedItem = this.deepCopyMaybe(listShallowCopy.pop()); this.updateValueAndCache(listShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitPop(poppedItem)); } return poppedItem; } /** * Removes the first item from the list-{@link value} and returns it. \ * Dispatches a new copy of the value, without mutating the current-value. * * It only works if the Unit is not frozen, and the list is not empty {@link isEmpty}. * * @returns The shifted item. * * @triggers {@link EventListUnitShift} * @category Customised Array.prototype */ shift(): Item | undefined { if (this.isFrozen || this.isEmpty) { return; } const listShallowCopy = [...this.rawValue()]; const shiftedItem = this.deepCopyMaybe(listShallowCopy.shift()); this.updateValueAndCache(listShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitShift(shiftedItem)); } return shiftedItem; } /** * Inserts new items at the start of the list-{@link value}. \ * Dispatches a new copy of the value, without mutating the current-value. * * It only works if the Unit is not frozen, and at least 1 item is provided. * * @param items The items to be insert at the start of the list * @returns The new length of the list. * * @triggers {@link EventListUnitUnshift} * @category Customised Array.prototype */ unshift(...items: Item[]): number { if (this.isFrozen || !items.length) { return this.length; } this.checkSerializabilityMaybe(items); const listShallowCopy = [...this.rawValue()]; const newLength = listShallowCopy.unshift(...this.deepCopyMaybe(items)); this.updateValueAndCache(listShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitUnshift(items)); } return newLength; } /** * Removes items from the list-{@link value} and, if necessary, * inserts new items in their place, returning the deleted items. \ * Dispatches a new copy of the value, without mutating the current-value. * * It only works if the Unit is not frozen, and \ * either deleteCount is not 0 (loose comparison) and the list is not empty {@link isEmpty}, or \ * there's at least 1 item to be added. * * @param start The zero-based location in the list from which to start removing items. * @param deleteCount The number of items to remove. * @param items Items to insert into the list in place of the deleted items. * @returns The deleted Items or an empty `array`. * * @triggers {@link EventListUnitSplice} * @category Customised Array.prototype */ splice(start: number, deleteCount: number, ...items: Item[]): Item[] { // tslint:disable-next-line:triple-equals if (this.isFrozen || ((deleteCount == 0 || this.isEmpty) && !items.length)) { return []; } this.checkSerializabilityMaybe(items); const listShallowCopy = [...this.rawValue()]; const removedItems = this.deepCopyMaybe( listShallowCopy.splice(start, deleteCount, ...items.map(item => this.deepCopyMaybe(item))) ); this.updateValueAndCache(listShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitSplice(start, deleteCount, removedItems, items)); } return removedItems; } /** * Fills a section of the list-{@link value} with provided param `item`. \ * Dispatches a new copy of the value, without mutating the current-value. * * It only works if the Unit is not frozen, and the list is not empty {@link isEmpty}. * * @param item The item to fill the section of ListUnit's value with. * @param start The index to start filling the list at. If start is negative, it is treated as * length+start where length is the length of the list. * @param end The index to stop filling the list at. If end is negative, it is treated as * length+end. * @returns Nothing, unlike `Array.prototype.fill` * * @triggers {@link EventListUnitFill} * @category Customised Array.prototype */ fill(item: Item, start?: number, end?: number): any { if (this.isFrozen || this.isEmpty) { return; } this.checkSerializabilityMaybe(item); const listShallowCopy = [...this.rawValue()]; listShallowCopy.fill(this.deepCopyMaybe(item), start, end); this.updateValueAndCache(listShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitFill(item, start, end)); } } /** * Copies a section of the current-value identified by param `start` and param `end` * to the ListUnit's value starting at position {@link target}. \ * Dispatches a new copy of the value, without mutating the current-value. * * It only works if the Unit is not frozen, and the list is not empty {@link isEmpty}. * * @param target If target is negative, it is treated as length+target where length is the * length of the list. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If end is not specified, length of the list is used as its default value. * @returns Nothing, unlike `Array.prototype.copyWithin` * * @triggers {@link EventListUnitCopyWithin} * @category Customised Array.prototype */ copyWithin(target: number, start: number, end?: number): any { if (this.isFrozen || this.isEmpty) { return; } const listShallowCopy = [...this.rawValue()]; listShallowCopy.copyWithin(target, start, end); this.updateValueAndCache(listShallowCopy); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitCopyWithin(target, start, end)); } } /** * Reverses the items in the list-{@link value}. \ * Dispatches a new copy of the value, without mutating the current-value. * * It only works if the Unit is not frozen, and the list is not empty {@link isEmpty}. * * @returns Nothing, unlike `Array.prototype.reverse` * * @triggers {@link EventListUnitReverse} * @category Customised Array.prototype */ reverse(): any { if (this.isFrozen || this.isEmpty) { return; } const listShallowCopyReversed = [...this.rawValue()].reverse(); this.updateValueAndCache(listShallowCopyReversed); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitReverse()); } } /** * Sorts the list-{@link value}. \ * Dispatches a new copy of the value, without mutating the current-value. * * It only works if the Unit is not frozen, and the list is not empty {@link isEmpty}. * * @param compareFn The name of the function used to determine the order of the items. * If omitted, the items are sorted in ascending, ASCII character order. * @returns Nothing, unlike `Array.prototype.sort` * * @triggers {@link EventListUnitSort} * @category Customised Array.prototype */ sort(compareFn?: (a: Item, b: Item) => number): any { if (this.isFrozen || this.isEmpty) { return; } const listShallowCopySorted = typeof compareFn === 'function' ? [...this.value()].sort(compareFn) : [...this.rawValue()].sort(); this.updateValueAndCache(listShallowCopySorted); if (this.eventsSubject?.observers.length && !this.isMuted) { this.eventsSubject.next(new EventListUnitSort()); } } /** * Returns a section of the list-{@link value}. * * @param start The beginning of the specified portion of the list. * @param end The end of the specified portion of the list. * @returns A section of the list. * * @category Customised Array.prototype */ slice(start?: number, end?: number): Item[] { return this.deepCopyMaybe(this.rawValue().slice(start, end)); } /** * Performs the specified action for each item in the list-{@link value}. \ * It's a drop-in replacement for the `Array.prototype.forEach` method. * * @param callbackFn A function that accepts up to three arguments. * forEvery calls the callbackFn function one time for each element in the list. * @param thisArg An object to which this keyword can refer in the callbackFn function. * If thisArg is omitted, undefined is used as this value. * * @category Customised Array.prototype */ forEvery(callbackFn: (item: Item, index: number, array: Item[]) => void, thisArg?: any): void { Array.prototype.forEach.apply(this.value(), [callbackFn, thisArg]); } /** * @internal please do not use. */ [IteratorSymbol](): IterableIterator<Item> { return Array.prototype[IteratorSymbol].call(this.value()); } /** * @internal please do not use. */ protected isValidValue(value: any): boolean { return Array.isArray(value); } /** * @alias forEvery * @deprecated Use {@link forEvery} instead. * This `forEach` is not the usual `Array.forEach`. * This `forEach` is an RxJS feature, which got inherited due to extending the Observable class, * But this is not what you want, most probably you just want to iterate over the items, for that * we've implemented the normal `forEach` functionality into `forEvery` method. * * This `forEach` is marked deprecated to prevent accidental usage, and avoid confusion. * You can still use it though, if you want the RxJS feature, * see {@link Observable.forEach} for usage. * @hidden */ forEach: any; /** * @deprecated * @ignore * @internal please do not use. */ [Symbol.unscopables]: any; /** * @deprecated * @ignore * @internal please do not use. */ static Array: any; } /** * @internal please do not use. */ const MethodsWithNoRiskOfMutation = [ 'includes', 'indexOf', 'lastIndexOf', 'join', 'keys', 'toLocaleString', ]; MethodsWithNoRiskOfMutation.forEach(methodName => { Object.defineProperty(ListUnit.prototype, methodName, { value(...args) { return Array.prototype[methodName].apply(this.rawValue(), args); }, }); }); /** * @internal please do not use. */ const MethodsNotToImplement = [ ...Object.getOwnPropertyNames(Observable.prototype), ...Object.getOwnPropertyNames(Base.prototype), ...Object.getOwnPropertyNames(UnitBase.prototype), ...Object.getOwnPropertyNames(ListUnit.prototype), ...MethodsWithNoRiskOfMutation, ]; Object.getOwnPropertyNames(Array.prototype).forEach(method => { if (!isFunction(Array.prototype[method]) || MethodsNotToImplement.includes(method)) { return; } Object.defineProperty(ListUnit.prototype, method, { value(...args) { return Array.prototype[method].apply(this.value(), args); }, }); });
the_stack
module Supler { export class CreateFormFromJson { private idCounter:number = 0; constructor(private renderOptionsGetter:RenderOptionsGetter, private i18n:I18n, private validatorFnFactories:any, private fieldsOptions:FieldsOptions, private fieldOrder: string[][]) { } renderForm(meta, formJson, formElementDictionary:FormElementDictionary = new FormElementDictionary()):RenderFormResult { var fieldsByName = {}; formJson.fields.forEach((f: any) => { fieldsByName[f.name] = f; }); function getField(fieldName: string) { var result = fieldsByName[fieldName]; if (!result) Log.warn('Trying to access field not found in JSON: '+fieldName); return result; } var fieldOrder = this.fieldOrder || formJson.fieldOrder; var rowsHtml = ''; fieldOrder.forEach(row => { rowsHtml += this.row((<string[]>row).map(getField), formElementDictionary, this.renderOptionsGetter.defaultRenderOptions()) }); this.verifyAllFieldsDisplayed(fieldOrder, formJson.fields.map(f => f.name)); return new RenderFormResult( this.generateMeta(meta) + this.renderOptionsGetter.defaultRenderOptions().renderForm(rowsHtml), formElementDictionary); } private verifyAllFieldsDisplayed(fieldOrder: string[][], fieldNames: string[]) { var fieldsInFieldOrder = []; fieldOrder.forEach(row => row.forEach(fieldName => fieldsInFieldOrder.push(fieldName))); var missingFields = Util.arrayDifference(fieldNames, fieldsInFieldOrder); if (missingFields.length > 0) { Log.warn("There are fields sent from the server that were not shown on the form: ["+missingFields+"]"); } } private generateMeta(meta:any) { if (meta) { var html = '<span class="supler_meta" style="display: none; visibility: hidden">\n'; Util.foreach(meta, (metaKey, metaValue) => { var attributes = {'type': 'hidden', 'value': metaValue}; attributes[SuplerAttributes.FIELD_TYPE] = FieldTypes.META; attributes[SuplerAttributes.FIELD_NAME] = metaKey; html += HtmlUtil.renderTag('input', attributes) + '\n'; }); return html + '</span>\n'; } else { return ''; } } private row(fields: Object[], formElementDictionary:FormElementDictionary, renderOptions: RenderOptions) { var fieldsHtml = ''; fields.forEach(field => { fieldsHtml += this.fieldFromJson(field, formElementDictionary, false, fields.length) }); return renderOptions.renderRow(fieldsHtml); } private fieldFromJson(fieldJson:any, formElementDictionary:FormElementDictionary, compact:boolean, fieldsPerRow: number):string { var id = this.nextId(); var validationId = this.nextId(); var fieldData = new FieldData(id, validationId, fieldJson, this.labelFor(fieldJson.label), fieldsPerRow); var fieldOptions = this.fieldsOptions.forFieldData(fieldData); if (fieldOptions && fieldOptions.renderHint) { fieldData = fieldData.withRenderHintOverride(fieldOptions.renderHint); } var html = this.fieldHtmlFromJson(fieldData, formElementDictionary, compact); if (html) { formElementDictionary.getElement(id).validator = new ElementValidator( this.fieldValidatorFns(fieldData), fieldData.validate.required, fieldJson.empty_value); return html; } else { return null; } } private fieldValidatorFns(fieldData:FieldData):ValidatorFn[] { var validators = []; var typeValidator = this.validatorFnFactories['type_' + fieldData.type]; if (typeValidator) validators.push(typeValidator.apply(this)); var validatorsJson = fieldData.validate; Util.foreach(validatorsJson, (validatorName, validatorJson) => { if (this.validatorFnFactories[validatorName]) { validators.push(this.validatorFnFactories[validatorName](validatorJson, fieldData.json)); } }); return validators; } private fieldHtmlFromJson(fieldData:FieldData, formElementDictionary:FormElementDictionary, compact:boolean):string { var renderOptions = this.renderOptionsGetter.forField(fieldData.path, fieldData.type, fieldData.getRenderHintName()); var fieldOptions = Util.copyProperties({ 'id': fieldData.id, // the field name must be unique for a value, so that e.g. radio button groups in multiple subforms work // correctly, hence we cannot use the field's name. 'name': fieldData.path, 'supler:fieldName': fieldData.name, 'supler:fieldType': fieldData.type, 'supler:multiple': fieldData.multiple, 'supler:validationId': fieldData.validationId, 'supler:path': fieldData.path }, renderOptions.additionalFieldOptions()); if (!fieldData.enabled) { fieldOptions['disabled'] = true; } switch (fieldData.type) { case FieldTypes.BOOLEAN: return this.booleanFieldFromJson(renderOptions, fieldData, fieldOptions, compact); case FieldTypes.SELECT: return this.selectFieldFromJson(renderOptions, fieldData, fieldOptions, compact); case FieldTypes.SUBFORM: return this.subformFieldFromJson(renderOptions, fieldData, formElementDictionary); case FieldTypes.STATIC: return this.staticFieldFromJson(renderOptions, fieldData, compact); case FieldTypes.ACTION: return this.actionFieldFromJson(renderOptions, fieldData, fieldOptions, formElementDictionary, compact); default: // STRING, INTEGER, FLOAT, custom return this.textFieldFromJson(renderOptions, fieldData, fieldOptions, compact); } } private textFieldFromJson(renderOptions, fieldData:FieldData, fieldOptions, compact) { if (fieldData.getRenderHintName() === 'textarea') { var renderHint = fieldData.getRenderHint(); var fieldOptionsWithDim = Util.copyProperties( {rows: renderHint.rows, cols: renderHint.cols}, fieldOptions); return renderOptions.renderTextareaField(fieldData, fieldOptionsWithDim, compact); } else if (fieldData.getRenderHintName() === 'hidden') { return renderOptions.renderHiddenField(fieldData, fieldOptions, compact); } else if (fieldData.getRenderHintName() === 'date') { return renderOptions.renderDateField(fieldData, fieldOptions, compact); } else { return renderOptions.renderTextField(fieldData, fieldOptions, compact); } } private booleanFieldFromJson(renderOptions, fieldData:FieldData, fieldOptions, compact) { var possibleSelectValues = [ new SelectValue("0", this.i18n.label_boolean_false()), new SelectValue("1", this.i18n.label_boolean_true()) ]; fieldData.value = fieldData.value ? "1" : "0"; return renderOptions.renderSingleChoiceRadioField(fieldData, possibleSelectValues, this.checkableContainerOptions(fieldData.id, fieldOptions), fieldOptions, compact); } private selectFieldFromJson(renderOptions, fieldData:FieldData, fieldOptions, compact) { var possibleSelectValues = fieldData.json.possible_values.map(v => new SelectValue(v.id, this.labelFor(v.label))); var containerOptions = this.checkableContainerOptions(fieldData.id, fieldOptions); if (fieldData.multiple) { return renderOptions.renderMultiChoiceCheckboxField(fieldData, possibleSelectValues, containerOptions, fieldOptions, compact); } else { var isRequired = fieldData.json.validate && fieldData.json.validate.required; var noValueSelected = fieldData.value === fieldData.json.empty_value; var isRadio = fieldData.getRenderHintName() === 'radio'; if (!isRadio && (!isRequired || noValueSelected)) { possibleSelectValues = [new SelectValue(null, "")].concat(possibleSelectValues); } if (isRadio) { return renderOptions.renderSingleChoiceRadioField(fieldData, possibleSelectValues, containerOptions, fieldOptions, compact); } else { return renderOptions.renderSingleChoiceSelectField(fieldData, possibleSelectValues, containerOptions, fieldOptions, compact); } } } /** * When using the container options, which include the id, the ids of the elements should be changed. */ private checkableContainerOptions(id:string, elementOptions) { // radio buttons and checkboxes need to be grouped inside an element with the form field's id and validation // id, so that it could be found e.g. during validation. return { 'id': id, 'supler:validationId': elementOptions[SuplerAttributes.VALIDATION_ID], 'supler:path': elementOptions[SuplerAttributes.PATH] }; } private subformFieldFromJson(renderOptions, fieldData:FieldData, formElementDictionary:FormElementDictionary) { var subformHtml = ''; var options = { 'supler:fieldType': FieldTypes.SUBFORM, 'supler:fieldName': fieldData.name, 'supler:multiple': fieldData.multiple }; var values; // value can be undefined for an optional subform if (typeof fieldData.value !== 'undefined') { values = fieldData.multiple ? fieldData.value : [fieldData.value]; } else values = []; this.propagateDisabled(fieldData, values); if (fieldData.getRenderHintName() === 'list') { for (var k in values) { var subformResult = this.renderForm(null, values[k], formElementDictionary); subformHtml += renderOptions.renderSubformListElement(subformResult.html, options); } } else { // table var headers = this.getTableHeaderLabels(fieldData.json); var cells:string[][] = []; for (var i = 0; i < values.length; i++) { var j = 0; cells[i] = []; var subfieldsJson = values[i].fields; Util.foreach(subfieldsJson, (subfield, subfieldJson) => { cells[i][j] = this.fieldFromJson(subfieldJson, formElementDictionary, true, -1); j += 1; }); } subformHtml += renderOptions.renderSubformTable(headers, cells, options); } return renderOptions.renderSubformDecoration(subformHtml, fieldData.label, fieldData.id, fieldData.name); } private propagateDisabled(fromFieldData:FieldData, toSubforms:any) { if (!fromFieldData.enabled) { for (var k in toSubforms) { Util.foreach(toSubforms[k].fields, (k, v) => v.enabled = false); } } } private staticFieldFromJson(renderOptions, fieldData:FieldData, compact) { var value = this.i18n.fromKeyAndParams(fieldData.value.key, fieldData.value.params); if (!value) value = '-'; fieldData.value = value; return renderOptions.renderStaticField(fieldData, compact); } private actionFieldFromJson(renderOptions, fieldData:FieldData, fieldOptions, formElementDictionary:FormElementDictionary, compact) { formElementDictionary.getElement(fieldData.id).validationScope = ValidationScopeParser.fromJson(fieldData.json.validation_scope); return renderOptions.renderActionField(fieldData, fieldOptions, compact); } private getTableHeaderLabels(fieldJson:any):string[] { if (fieldJson.value.length > 0) { var firstRow = fieldJson.value[0]; var result = []; Util.foreach(firstRow.fields, (fieldName, fieldValue) => { if (fieldValue.type === FieldTypes.ACTION) result.push(''); else result.push(this.labelFor(fieldValue.label)); }); return result; } else { return []; } } private labelFor(rawLabel:any):string { return this.i18n.fromKeyAndParams(rawLabel, []); } private nextId() { this.idCounter += 1; return 'id' + this.idCounter; } } export class RenderFormResult { constructor(public html:string, public formElementDictionary:FormElementDictionary) { } } }
the_stack
import type * as ts from "typescript"; import { ParameterType } from "./declaration"; import type { NeverIfInternal } from ".."; import type { Application } from "../../.."; import { insertPrioritySorted, unique } from "../array"; import type { Logger } from "../loggers"; import { convert, DeclarationOption, getDefaultValue, KeyToDeclaration, TypeDocOptionMap, TypeDocOptions, TypeDocOptionValues, } from "./declaration"; import { addTypeDocOptions } from "./sources"; /** * Describes an option reader that discovers user configuration and converts it to the * TypeDoc format. */ export interface OptionsReader { /** * Readers will be processed according to their priority. * A higher priority indicates that the reader should be called *later* so that * it can override options set by lower priority readers. * * Note that to preserve expected behavior, the argv reader must have both the lowest * priority so that it may set the location of config files used by other readers and * the highest priority so that it can override settings from lower priority readers. */ priority: number; /** * The name of this reader so that it may be removed by plugins without the plugin * accessing the instance performing the read. Multiple readers may have the same * name. */ name: string; /** * Read options from the reader's source and place them in the options parameter. * Options without a declared name may be treated as if they were declared with type * {@link ParameterType.Mixed}. Options which have been declared must be converted to the * correct type. As an alternative to doing this conversion in the reader, * the reader may use {@link Options.setValue}, which will correctly convert values. * @param options * @param compilerOptions * @param container the options container that provides declarations * @param logger */ read(container: Options, logger: Logger): void; } /** * Maintains a collection of option declarations split into TypeDoc options * and TypeScript options. Ensures options are of the correct type for calling * code. * * ### Option Discovery * * Since plugins commonly add custom options, and TypeDoc does not permit options which have * not been declared to be set, options must be read twice. The first time options are read, * a noop logger is passed so that any errors are ignored. Then, after loading plugins, options * are read again, this time with the logger specified by the application. * * Options are read in a specific order. * 1. argv (0) - Must be read first since it should change the files read when * passing --options or --tsconfig. * 2. typedoc-json (100) - Read next so that it can specify the tsconfig.json file to read. * 3. tsconfig-json (200) - Last config file reader, cannot specify the typedoc.json file to read. * 4. argv (300) - Read argv again since any options set there should override those set in config * files. */ export class Options { private _readers: OptionsReader[] = []; private _declarations = new Map<string, Readonly<DeclarationOption>>(); private _values: Record<string, unknown> = {}; private _setOptions = new Set<string>(); private _compilerOptions: ts.CompilerOptions = {}; private _fileNames: readonly string[] = []; private _projectReferences: readonly ts.ProjectReference[] = []; private _logger: Logger; constructor(logger: Logger) { this._logger = logger; } /** * Marks the options as readonly, enables caching when fetching options, which improves performance. */ freeze() { Object.freeze(this._values); } /** * Checks if the options object has been frozen, preventing future changes to option values. */ isFrozen() { return Object.isFrozen(this._values); } /** * Sets the logger used when an option declaration fails to be added. * @param logger */ setLogger(logger: Logger) { this._logger = logger; } /** * Adds the option declarations declared by the TypeDoc and all supported TypeScript declarations. */ addDefaultDeclarations() { addTypeDocOptions(this); } /** * Resets the option bag to all default values. * If a name is provided, will only reset that name. */ reset(name?: keyof TypeDocOptions): void; reset(name?: NeverIfInternal<string>): void; reset(name?: string): void { if (name != null) { const declaration = this.getDeclaration(name); if (!declaration) { throw new Error( "Cannot reset an option which has not been declared." ); } this._values[declaration.name] = getDefaultValue(declaration); this._setOptions.delete(declaration.name); } else { for (const declaration of this.getDeclarations()) { this._values[declaration.name] = getDefaultValue(declaration); } this._setOptions.clear(); this._compilerOptions = {}; this._fileNames = []; } } /** * Adds an option reader that will be used to read configuration values * from the command line, configuration files, or other locations. * @param reader */ addReader(reader: OptionsReader): void { insertPrioritySorted(this._readers, reader); } /** * Removes all readers of a given name. * @param name * @deprecated should not be used, will be removed in 0.23 */ removeReaderByName(name: string): void { this._readers = this._readers.filter((reader) => reader.name !== name); } read(logger: Logger) { for (const reader of this._readers) { reader.read(this, logger); } } /** * Adds an option declaration to the container with extra type checking to ensure that * the runtime type is consistent with the declared type. * @param declaration The option declaration that should be added. */ addDeclaration<K extends keyof TypeDocOptions>( declaration: { name: K } & KeyToDeclaration<K> ): void; /** * Adds an option declaration to the container. * @param declaration The option declaration that should be added. */ addDeclaration( declaration: NeverIfInternal<Readonly<DeclarationOption>> ): void; addDeclaration(declaration: Readonly<DeclarationOption>): void { const decl = this.getDeclaration(declaration.name); if (decl) { this._logger.error( `The option ${declaration.name} has already been registered` ); } else { this._declarations.set(declaration.name, declaration); } this._values[declaration.name] = getDefaultValue(declaration); } /** * Adds the given declarations to the container * @param declarations * @deprecated will be removed in 0.23. */ addDeclarations(declarations: readonly DeclarationOption[]): void { for (const decl of declarations) { this.addDeclaration(decl as any); } } /** * Removes a declared option. * WARNING: This is probably a bad idea. If you do this you will probably cause a crash * when code assumes that an option that it declared still exists. * @param name * @deprecated will be removed in 0.23. */ removeDeclarationByName(name: string): void { const declaration = this.getDeclaration(name); if (declaration) { this._declarations.delete(declaration.name); delete this._values[declaration.name]; } } /** * Gets a declaration by one of its names. * @param name */ getDeclaration(name: string): Readonly<DeclarationOption> | undefined { return this._declarations.get(name); } /** * Gets all declared options. */ getDeclarations(): Readonly<DeclarationOption>[] { return unique(this._declarations.values()); } /** * Checks if the given option's value is deeply strict equal to the default. * @param name */ isSet(name: keyof TypeDocOptions): boolean; isSet(name: NeverIfInternal<string>): boolean; isSet(name: string): boolean { if (!this._declarations.has(name)) { throw new Error("Tried to check if an undefined option was set"); } return this._setOptions.has(name); } /** * Gets all of the TypeDoc option values defined in this option container. */ getRawValues(): Readonly<Partial<TypeDocOptions>> { return this._values; } /** * Gets a value for the given option key, throwing if the option has not been declared. * @param name */ getValue<K extends keyof TypeDocOptions>(name: K): TypeDocOptionValues[K]; getValue(name: NeverIfInternal<string>): unknown; getValue(name: string): unknown { const declaration = this.getDeclaration(name); if (!declaration) { throw new Error(`Unknown option '${name}'`); } return this._values[declaration.name]; } /** * Sets the given declared option. Throws if setting the option fails. * @param name * @param value * @param configPath the directory to resolve Path type values against */ setValue<K extends keyof TypeDocOptions>( name: K, value: TypeDocOptions[K], configPath?: string ): void; setValue( name: NeverIfInternal<string>, value: NeverIfInternal<unknown>, configPath?: NeverIfInternal<string> ): void; setValue(name: string, value: unknown, configPath?: string): void { if (this.isFrozen()) { throw new Error( "Tried to modify an option value after options have been sealed." ); } const declaration = this.getDeclaration(name); if (!declaration) { throw new Error( `Tried to set an option (${name}) that was not declared.` ); } const converted = convert( value, declaration, configPath ?? process.cwd() ); if (declaration.type === ParameterType.Flags) { Object.assign(this._values[declaration.name], converted); } else { this._values[declaration.name] = converted; } this._setOptions.add(name); } /** * Gets the set compiler options. */ getCompilerOptions(): ts.CompilerOptions { return this.fixCompilerOptions(this._compilerOptions); } /** @internal */ fixCompilerOptions( options: Readonly<ts.CompilerOptions> ): ts.CompilerOptions { const result = { ...options }; if ( this.getValue("emit") !== "both" && this.getValue("emit") !== true ) { result.noEmit = true; delete result.emitDeclarationOnly; } return result; } /** * Gets the file names discovered through reading a tsconfig file. */ getFileNames(): readonly string[] { return this._fileNames; } /** * Gets the project references - used in solution style tsconfig setups. */ getProjectReferences(): readonly ts.ProjectReference[] { return this._projectReferences; } /** * Sets the compiler options that will be used to get a TS program. */ setCompilerOptions( fileNames: readonly string[], options: ts.CompilerOptions, projectReferences: readonly ts.ProjectReference[] | undefined ) { if (this.isFrozen()) { throw new Error( "Tried to modify an option value after options have been sealed." ); } // We do this here instead of in the tsconfig reader so that API consumers which // supply a program to `Converter.convert` instead of letting TypeDoc create one // can just set the compiler options, and not need to know about this mapping. // It feels a bit like a hack... but it's better to have it here than to put it // in Application or Converter. if (options.stripInternal && !this.isSet("excludeInternal")) { this.setValue("excludeInternal", true); } this._fileNames = fileNames; this._compilerOptions = { ...options }; this._projectReferences = projectReferences ?? []; } } /** * Binds an option to the given property. Does not register the option. * * @since v0.16.3 */ export function BindOption<K extends keyof TypeDocOptionMap>( name: K ): <IK extends PropertyKey>( target: ({ application: Application } | { options: Options }) & { [K2 in IK]: TypeDocOptionValues[K]; }, key: IK ) => void; /** * Binds an option to the given property. Does not register the option. * @since v0.16.3 * * @privateRemarks * This overload is intended for plugin use only with looser type checks. Do not use internally. */ export function BindOption( name: NeverIfInternal<string> ): ( target: { application: Application } | { options: Options }, key: PropertyKey ) => void; export function BindOption(name: string) { return function ( target: { application: Application } | { options: Options }, key: PropertyKey ) { Object.defineProperty(target, key, { get(this: { application: Application } | { options: Options }) { const options = "options" in this ? this.options : this.application.options; const value = options.getValue(name as keyof TypeDocOptions); if (options.isFrozen()) { Object.defineProperty(this, key, { value }); } return value; }, enumerable: true, configurable: true, }); }; }
the_stack
import { Matrix4, JulianDate, Cartesian3, Cartographic, Quaternion, CesiumMath } from './cesium/cesium-imports' /** * Default distance from a user's eyes to the floor */ export const AVERAGE_EYE_HEIGHT = 1.6; /** * Default near plane */ export const DEFAULT_NEAR_PLANE = 0.01; /** * Default far plane */ export const DEFAULT_FAR_PLANE = 10000; /** * Describes the role of an [[ArgonSystem]] */ export enum Role { /** * A system with this role is responsible for augmenting an arbitrary view of reality, * generally by overlaying computer generated graphics. A reality augmentor may also, * if appropriate, be elevated to the role of a [[REALITY_MANAGER]]. */ REALITY_AUGMENTER = "RealityAugmenter" as any, /** * A system with this role is responsible for (at minimum) describing (and providing, * if necessary) a visual representation of the world and the 3D eye pose of the viewer. */ REALITY_VIEWER = "RealityViewer" as any, /** * A system with this role is responsible for mediating access to sensors/trackers * and pose data for known entities in the world, selecting/configuring/loading * [[REALITY_VIEWER]]s, and providing the mechanism by which any given [[REALITY_AUGMENTER]] * can augment any given [[REALITY_VIEWER]]. */ REALITY_MANAGER = "RealityManager" as any, /** * Deprecated. Use [[REALITY_AUGMENTER]]. * @private */ APPLICATION = "Application" as any, /** * Deprecated. Use [[REALITY_MANAGER]]. * @private */ MANAGER = "Manager" as any, /** * Deprecated. Use [[REALITY_VIEWER]] * @private */ REALITY_VIEW = "RealityView" as any, } export namespace Role { export function isRealityViewer(r?:Role) { return r === Role.REALITY_VIEWER || r === Role.REALITY_VIEW; } export function isRealityAugmenter(r?:Role) { return r === Role.REALITY_AUGMENTER || r === Role.APPLICATION; } export function isRealityManager(r?:Role) { return r === Role.REALITY_MANAGER || r === Role.MANAGER; } } /** * Configuration options for an [[ArgonSystem]] */ export abstract class Configuration { version?: number[]; uri?: string; title?: string; role?: Role; protocols?: string[]; userData?: any; // other options / hints defaultUI?: { disable?: boolean }; 'supportsCustomProtocols'?: boolean; } export class Viewport { x: number = 0; y: number = 0; width: number = 0; height: number = 0; static clone(viewport?:Viewport, result:Viewport=new Viewport) { if (!viewport) return undefined; result.x = viewport.x; result.y = viewport.y; result.width = viewport.width; result.height = viewport.height; return result; } static equals(viewportA?:Viewport, viewportB?:Viewport) { return viewportA && viewportB && CesiumMath.equalsEpsilon(viewportA.x, viewportB.x, CesiumMath.EPSILON7) && CesiumMath.equalsEpsilon(viewportA.y, viewportB.y, CesiumMath.EPSILON7) && CesiumMath.equalsEpsilon(viewportA.width, viewportB.width, CesiumMath.EPSILON7) && CesiumMath.equalsEpsilon(viewportA.height, viewportB.height, CesiumMath.EPSILON7); } } /** * Viewport values are expressed using a right-handed coordinate system with the origin * at the bottom left corner. */ export class CanvasViewport extends Viewport { pixelRatio: number = 1; renderWidthScaleFactor: number = 1; renderHeightScaleFactor: number = 1; static clone(viewport?:CanvasViewport, result:CanvasViewport=<any>new CanvasViewport) { if (!viewport) return undefined; Viewport.clone(viewport, result); result.renderWidthScaleFactor = viewport.renderWidthScaleFactor; result.renderHeightScaleFactor = viewport.renderHeightScaleFactor; return result; } static equals(viewportA?:CanvasViewport, viewportB?:CanvasViewport) { return viewportA && viewportB && Viewport.equals(viewportA, viewportB) && CesiumMath.equalsEpsilon(viewportA.renderWidthScaleFactor, viewportB.renderWidthScaleFactor, CesiumMath.EPSILON7) && CesiumMath.equalsEpsilon(viewportA.renderHeightScaleFactor, viewportB.renderHeightScaleFactor, CesiumMath.EPSILON7); } } /** * Identifies a subview in a [[SerializedSubview]] */ export enum SubviewType { /* * Identities a subview for a handheld display. */ SINGULAR = "Singular" as any, /* * Identifies a subview for the left eye (when the user is wearing an HMD or Viewer) */ LEFTEYE = "LeftEye" as any, /* * Identifies a subview for the right eye (when the user is wearing an HMD or Viewer) */ RIGHTEYE = "RightEye" as any, /* * Identifies a subview for a custom view configuration */ OTHER = "Other" as any, } /** * A serialized notation for the position, orientation, and referenceFrame of an entity. */ export interface SerializedEntityState { p: Cartesian3, // position o: Quaternion, // orientation r: number | string, // reference frame meta?: any // meta data } export namespace SerializedEntityState { export function clone(state?:SerializedEntityState, result?:SerializedEntityState|null) { if (!state) return null; result = result || <SerializedEntityState><any>{}; result.p = Cartesian3.clone(state.p, result.p); result.o = Quaternion.clone(state.o, result.o); result.r = state.r; result.meta = state.meta; return result; } } /** * A map of entity ids and their associated poses. */ export interface SerializedEntityStateMap { [id: string]: SerializedEntityState | null } /** * The serialized rendering parameters for a particular subview */ export interface SerializedSubview { type: SubviewType, /** * The projection matrix for this subview */ projectionMatrix: Matrix4, /** * The viewport for this subview (relative to the primary viewport) */ viewport: Viewport /** * The pose for this subview (relative to the primary pose) */ // pose: SerializedEntityState|null|undefined, // if undefined, identity is assumed } /** * The serialized rendering parameters for a particular subview */ export interface ReadonlySerializedSubview { readonly type: SubviewType, /** * The projection matrix for this subview */ readonly projectionMatrix: Readonly<Matrix4>, /** * The viewport for this subview (relative to the primary viewport) */ readonly viewport: Readonly<CanvasViewport> // /** // * The pose for this subview (relative to the primary pose) // */ // readonly pose?: Readonly<SerializedEntityState>, // if undefined, identity is assumed } export namespace SerializedSubview { export function clone(subview:SerializedSubview, result?:SerializedSubview) { result = result || <SerializedSubview>{}; result.type = subview.type; result.projectionMatrix = Matrix4.clone(subview.projectionMatrix, result.projectionMatrix); result.viewport = Viewport.clone(subview.viewport, result.viewport)!; // result.pose = subview.pose ? SerializedEntityState.clone(subview.pose, result.pose) : undefined; return result; } export function equals(left?:SerializedSubview, right?:SerializedSubview) { return left && right && left.type === right.type && Viewport.equals(left.viewport, right.viewport) && Matrix4.equals(left.projectionMatrix, right.projectionMatrix); } } export interface SerializedDeviceState { currentFov: number; eyeCartographicPosition: Cartographic|undefined; eyeHorizontalAccuracy: number|undefined; eyeVerticalAccuracy: number|undefined; viewport: CanvasViewport; subviews: SerializedSubview[]; strictSubviews: boolean; isPresentingHMD: boolean; } // export interface PhysicalViewState { // time: JulianDate, // stagePose: SerializedEntityPose|undefined, // stageHorizontalAccuracy: number|undefined, // stageVerticalAccuracy: number|undefined, // eyePose: SerializedEntityPose|undefined, // eyeCompassAccuracy: number|undefined, // subviews: SerializedSubviewList, // strict:boolean; // } // export interface ViewState { // /** // * The viewing pose. // */ // pose: SerializedEntityState|undefined, // /** // * The viewport to render into. In a DOM environment, // * the bottom left corner of the document element (document.documentElement) // * is the origin. // */ // viewport: Viewport, // /** // * The list of subviews to render. // */ // subviews:SerializedSubviewList, // /** // * The current field of view (of each subview) // */ // fovs: number[] // } export class SerializedSubviewList extends Array<SerializedSubview> { constructor() { super(); } static clone(subviews?:SerializedSubviewList, result?:SerializedSubviewList) { if (!subviews) return undefined; result = result || new SerializedSubviewList; result.length = subviews.length; for (let i=0; i < subviews.length; i++) { const s = subviews[i]; result![i] = SerializedSubview.clone(s, result![i]); } return result; } } // export namespace ViewState { // export function clone(viewState:ViewState, result?:ViewState) { // result = result || <ViewState>{}; // result.time = JulianDate.clone(viewState.time, result.time); // result.stagePose = viewState.stagePose ? SerializedEntityState.clone(viewState.stagePose, result.stagePose) : undefined; // result.pose = viewState.pose ? SerializedEntityState.clone(viewState.pose, result.pose) : undefined; // result.viewport = Viewport.clone(viewState.viewport, result.viewport); // result.subviews = result.subviews || []; // result.fovs = result.fovs || []; // viewState.subviews.forEach((s, i)=>{ // result!.subviews[i] = SerializedSubview.clone(s, result!.subviews[i]); // }); // viewState.fovs.forEach((f, i)=>{ // result!.fovs[i] = f // }); // return result; // } // } /** * Describes the pose of a reality view and how it is able to render */ export interface DeprecatedEyeParameters { viewport?: CanvasViewport; // default: maximum pose?: SerializedEntityState; stereoMultiplier?: number; // default: 1 fov?: number; // default: defer to manager aspect?: number; // default: matches viewport } /** * Deprecated. See [[ViewSpec]] * Describes the partial frame state reported by reality viewers before v1.1 * @deprecated */ export interface DeprecatedPartialFrameState { index: number, time: { dayNumber: number, secondsOfDay: number }, // JulianDate, view?: any, eye?: DeprecatedEyeParameters, entities?: SerializedEntityStateMap } /** * Describes a complete frame state which is sent to child sessions */ export interface ContextFrameState { time: JulianDate, viewport: CanvasViewport, subviews: SerializedSubviewList, reality?: string, index?: number, entities: SerializedEntityStateMap, sendTime?: JulianDate, // the time this state was sent } export interface GeolocationOptions { enableHighAccuracy?: boolean; }
the_stack
import { ColorUtils, Expr, getPropertyValue, TEXTURE_PROPERTY_KEYS, Value } from "@here/harp-datasource-protocol"; import { disableBlending, enableBlending, RawShaderMaterial } from "@here/harp-materials"; import * as THREE from "three"; import { evaluateColorProperty } from "./DecodedTileHelpers"; import { MapView } from "./MapView"; /** * @hidden * * Pick of {@link MapView} properties required to update materials used [[MapMaterialAdapter]]. */ export type MapAdapterUpdateEnv = Pick<MapView, "env" | "frameNumber">; /** * @hidden * * Custom, callback based property evaluator used by [[MapObjectAdapter]] to evaluate dynamic * properties of object/material. */ export type StylePropertyEvaluator = (context: MapAdapterUpdateEnv) => Value; /** * @hidden * * Styled properties of material managed by [[MapMaterialAdapter]]. */ export interface StyledProperties { [name: string]: Expr | StylePropertyEvaluator | Value | undefined; } function isTextureProperty(propertyName: string): boolean { return TEXTURE_PROPERTY_KEYS.includes(propertyName); } /** * @hidden * * {@link MapView} specific data assigned to `THREE.Material` instance in installed in `userData`. * * [[MapMaterialAdapter]] is registered in `usedData.mapAdapter` property of `THREE.Material`. */ export class MapMaterialAdapter { /** * Resolve `MapMaterialAdapter` associated with `material`. */ static get(material: THREE.Material): MapMaterialAdapter | undefined { const mapAdapter = material.userData?.mapAdapter; if (mapAdapter instanceof MapMaterialAdapter) { return mapAdapter; } else if (mapAdapter !== undefined) { // NOTE: we can rebuild MapMaterialAdapter here if userData.mapAdapter contains // stylesed etc, this can be done to rebuild previously saved scene return undefined; } else { return undefined; } } static install(objData: MapMaterialAdapter): MapMaterialAdapter { if (!objData.material.userData) { objData.material.userData = {}; } return (objData.material.userData.mapAdapter = objData); } static create( material: THREE.Material, styledProperties: StyledProperties ): MapMaterialAdapter { return MapMaterialAdapter.install(new MapMaterialAdapter(material, styledProperties)); } static ensureUpdated(material: THREE.Material, context: MapAdapterUpdateEnv): boolean { return MapMaterialAdapter.get(material)?.ensureUpdated(context) ?? false; } /** * Associated material object. */ readonly material: THREE.Material; /** * Styled material properties. * * Usually pick from [[Technique]] attributes that constitute material properties managed * by this adapter. */ readonly styledProperties: StyledProperties; /** * Current values of styled material properties. * * Actual values valid for scope of one frame updated in [[ensureUpdated]]. */ readonly currentStyledProperties: { [name: string]: Value | undefined }; private m_lastUpdateFrameNumber = -1; private readonly m_dynamicProperties: Array<[string, Expr | StylePropertyEvaluator]>; private readonly tmpColor = new THREE.Color(); constructor(material: THREE.Material, styledProperties: StyledProperties) { this.material = material; this.styledProperties = styledProperties; this.currentStyledProperties = {}; this.m_dynamicProperties = []; for (const propName in styledProperties) { if (!styledProperties.hasOwnProperty(propName)) { continue; } const propDefinition = styledProperties![propName]; if (Expr.isExpr(propDefinition) || typeof propDefinition === "function") { this.m_dynamicProperties.push([propName, propDefinition as any]); } else { this.currentStyledProperties[propName] = propDefinition; } } this.setupStaticProperties(); } /** * Serialize contents. * * `THREE.Material.userData` is serialized during `clone`/`toJSON`, so we need to ensure that * we emit only "data" set of this object. */ toJSON() { return { styledProperties: this.styledProperties }; } /** * Ensure that underlying object is updated to current state of {@link MapView}. * * Updates dynamically styled properties of material by evaluating scene dependent expressions. * * Executes updates only once per frame basing on [[MapView.frameNumber]]. * * @returns `true` if object performed some kind of update, `false` if no update was needed. */ ensureUpdated(context: MapAdapterUpdateEnv) { if (this.m_lastUpdateFrameNumber === context.frameNumber) { return false; } this.m_lastUpdateFrameNumber = context.frameNumber; return this.updateDynamicProperties(context); } /** * Applies static properties to target material. */ private setupStaticProperties() { let updateBaseColor = false; for (const propName in this.styledProperties) { if (!this.styledProperties.hasOwnProperty(propName)) { continue; } const currentValue = this.currentStyledProperties[propName]; if (currentValue === undefined || currentValue === null) { continue; } if (propName === "color" || propName === "opacity") { updateBaseColor = true; } else if (!isTextureProperty(propName)) { // Static textures are already set in the material during tile construction. this.applyMaterialGenericProp(propName, currentValue); } } if (updateBaseColor) { const color = (this.currentStyledProperties.color as number) ?? 0xff0000; const opacity = (this.currentStyledProperties.opacity as number) ?? 1; this.applyMaterialBaseColor(color, opacity); } } /** * Applies static properties to target material. */ private updateDynamicProperties(context: MapAdapterUpdateEnv) { let somethingChanged = false; if (this.m_dynamicProperties.length > 0) { let updateBaseColor = false; for (const [propName, propDefinition] of this.m_dynamicProperties) { const newValue = Expr.isExpr(propDefinition) ? getPropertyValue(propDefinition, context.env) : propDefinition(context); if (newValue === this.currentStyledProperties[propName]) { continue; } this.currentStyledProperties[propName] = newValue; // `color` and `opacity` are special properties to support RGBA if (propName === "color" || propName === "opacity") { updateBaseColor = true; } else if (isTextureProperty(propName)) { this.applyMaterialTextureProp(propName, newValue); somethingChanged = true; } else { this.applyMaterialGenericProp(propName, newValue); somethingChanged = true; } } if (updateBaseColor) { const color = this.currentStyledProperties.color ?? 0xff0000; const opacity = (this.currentStyledProperties.opacity as number) ?? 1; this.applyMaterialBaseColor(color, opacity); somethingChanged = true; } } return somethingChanged; } private applyMaterialTextureProp(propName: string, value: Value) { const m = this.material as any; // Wait until the texture is loaded for the first time on tile creation, that way, // the old texture properties can be copied to the new texture. if (!m[propName] || value === null) { return; } const oldTexture = m[propName]; let newTexture: THREE.Texture | undefined; if (typeof value === "string") { newTexture = new THREE.TextureLoader().load(value, (texture: THREE.Texture) => { m[propName] = texture; }); } else if (typeof value === "object") { const element = value as any; const isImage = element.nodeName === "IMG"; const isCanvas = element.nodeName === "CANVAS"; if (isImage || isCanvas) { newTexture = new THREE.CanvasTexture(element); if (isImage && !element.complete) { const onLoad = () => { m[propName] = newTexture; element.removeEventListener("load", onLoad); }; element.addEventListener("load", onLoad); } else { m[propName] = newTexture; } } } if (newTexture) { newTexture.wrapS = oldTexture.wrapS; newTexture.wrapT = oldTexture.wrapT; newTexture.magFilter = oldTexture.magFilter; newTexture.minFilter = oldTexture.minFilter; newTexture.flipY = oldTexture.flipY; newTexture.repeat = oldTexture.repeat; } } private applyMaterialGenericProp(propName: string, value: Value) { const m = this.material as any; if (m[propName] instanceof THREE.Color) { let colorValue = value; if (typeof colorValue !== "number") { const parsed = evaluateColorProperty(colorValue); if (parsed === undefined) { return; } colorValue = parsed; } const rgbValue = ColorUtils.removeAlphaFromHex(colorValue); this.tmpColor.set(rgbValue); // We set the value, i.e. using =, as opposed to setting the color directly using set // because the material may be a custom material with a setter. value = this.tmpColor; } m[propName] = value; } private applyMaterialBaseColor(color: Value, opacity: number | undefined) { if (typeof color !== "number") { const parsed = evaluateColorProperty(color); if (parsed === undefined) { return; } color = parsed; } const { r, g, b, a } = ColorUtils.getRgbaFromHex(color ?? 0xff0000); const actualOpacity = a * THREE.MathUtils.clamp(opacity ?? 1, 0, 1); if (this.material instanceof RawShaderMaterial) { this.material.setOpacity(actualOpacity); } else { this.material.opacity = actualOpacity; } (this.material as any).color.setRGB(r, g, b); const opaque = actualOpacity >= 1.0; if (!opaque) { enableBlending(this.material); } else { disableBlending(this.material); } } }
the_stack
import { App, WebhookInterface } from './app'; import axios from 'axios'; import { Utils } from './utils'; import { Lambda } from 'aws-sdk'; import { Log } from './log'; import { Server } from './server'; import { createHmac } from "crypto"; export interface ClientEventData { name: string; channel: string; event?: string, data?: { [key: string]: any; }; socket_id?: string; user_id?: string; time_ms?: number; } export interface JobData { appKey: string; payload: { time_ms: number; events: ClientEventData[]; }, pusherSignature: string; } /** * Create the HMAC for the given data. */ export function createWebhookHmac(data: string, secret: string): string { return createHmac('sha256', secret) .update(data) .digest('hex'); } export class WebhookSender { /** * Batch of ClientEventData, to be sent as one webhook. */ public batch: ClientEventData[] = []; /** * Whether current process has nominated batch handler. */ public batchHasLeader = false; /** * Initialize the Webhook sender. */ constructor(protected server: Server) { let queueProcessor = (job, done) => { let rawData: JobData = job.data; const { appKey, payload, pusherSignature } = rawData; server.appManager.findByKey(appKey).then(app => { app.webhooks.forEach((webhook: WebhookInterface) => { // Apply filters only if batching is disabled. if (!server.options.webhooks.batching.enabled) { if (!webhook.event_types.includes(payload.events[0].name)) { return; } if (webhook.filter) { if (webhook.filter.channel_name_starts_with && !payload.events[0].channel.startsWith(webhook.filter.channel_name_starts_with)) { return; } if (webhook.filter.channel_name_ends_with && !payload.events[0].channel.endsWith(webhook.filter.channel_name_ends_with)) { return; } } } // TODO: For batches, you can filter the messages, but recalculate the pusherSignature value. /* payload.events = payload.events.filter(event => { if (!webhook.event_types.includes(event.name)) { return false; } if (webhook.filter) { if (webhook.filter.channel_name_starts_with && !event.channel.startsWith(webhook.filter.channel_name_starts_with)) { return false; } if (webhook.filter.channel_name_ends_with && !event.channel.endsWith(webhook.filter.channel_name_ends_with)) { return false; } } return true; }); */ if (this.server.options.debug) { Log.webhookSenderTitle('🚀 Processing webhook from queue.'); Log.webhookSender({ appKey, payload, pusherSignature }); } const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': `SoketiWebhooksAxiosClient/1.0 (Process: ${this.server.options.instance.process_id})`, // We specifically merge in the custom headers here so the headers below cannot be overwritten ...webhook.headers ?? {}, 'X-Pusher-Key': appKey, 'X-Pusher-Signature': pusherSignature, }; // Send HTTP POST to the target URL if (webhook.url) { axios.post(webhook.url, payload, { headers }).then((res) => { if (this.server.options.debug) { Log.webhookSenderTitle('✅ Webhook sent.'); Log.webhookSender({ webhook, payload }); } }).catch(err => { // TODO: Maybe retry exponentially? if (this.server.options.debug) { Log.webhookSenderTitle('❎ Webhook could not be sent.'); Log.webhookSender({ err, webhook, payload }); } }).then(() => { if (typeof done === 'function') { done(); } }); } else if (webhook.lambda_function) { // Invoke a Lambda function const params = { FunctionName: webhook.lambda_function, InvocationType: webhook.lambda.async ? 'Event' : 'RequestResponse', Payload: Buffer.from(JSON.stringify({ payload, headers })), }; let lambda = new Lambda({ apiVersion: '2015-03-31', region: webhook.lambda.region || 'us-east-1', ...(webhook.lambda.client_options || {}), }); lambda.invoke(params, (err, data) => { if (err) { if (this.server.options.debug) { Log.webhookSenderTitle('❎ Lambda trigger failed.'); Log.webhookSender({ webhook, err, data }); } } else { if (this.server.options.debug) { Log.webhookSenderTitle('✅ Lambda triggered.'); Log.webhookSender({ webhook, payload }); } } if (typeof done === 'function') { // TODO: Maybe retry exponentially? done(); } }); } }); }); }; // TODO: Maybe have one queue per app to reserve queue thresholds? server.queueManager.processQueue('client_event_webhooks', queueProcessor); server.queueManager.processQueue('member_added_webhooks', queueProcessor); server.queueManager.processQueue('member_removed_webhooks', queueProcessor); server.queueManager.processQueue('channel_vacated_webhooks', queueProcessor); server.queueManager.processQueue('channel_occupied_webhooks', queueProcessor); } /** * Send a webhook for the client event. */ public sendClientEvent(app: App, channel: string, event: string, data: any, socketId?: string, userId?: string) { let formattedData: ClientEventData = { name: App.CLIENT_EVENT_WEBHOOK, channel, event, data, }; if (socketId) { formattedData.socket_id = socketId; } if (userId && Utils.isPresenceChannel(channel)) { formattedData.user_id = userId; } this.send(app, formattedData, 'client_event_webhooks'); } /** * Send a member_added event. */ public sendMemberAdded(app: App, channel: string, userId: string): void { this.send(app, { name: App.MEMBER_ADDED_WEBHOOK, channel, user_id: userId, }, 'member_added_webhooks'); } /** * Send a member_removed event. */ public sendMemberRemoved(app: App, channel: string, userId: string): void { this.send(app, { name: App.MEMBER_REMOVED_WEBHOOK, channel, user_id: userId, }, 'member_removed_webhooks'); } /** * Send a channel_vacated event. */ public sendChannelVacated(app: App, channel: string): void { this.send(app, { name: App.CHANNEL_VACATED_WEBHOOK, channel, }, 'channel_vacated_webhooks'); } /** * Send a channel_occupied event. */ public sendChannelOccupied(app: App, channel: string): void { this.send(app, { name: App.CHANNEL_OCCUPIED_WEBHOOK, channel, }, 'channel_occupied_webhooks'); } /** * Send a webhook for the app with the given data. */ protected send(app: App, data: ClientEventData, queueName: string): void { if (this.server.options.webhooks.batching.enabled) { this.sendWebhookByBatching(app, data, queueName); } else { this.sendWebhook(app, data, queueName) } } /** * Send a webhook for the app with the given data, without batching. */ protected sendWebhook(app: App, data: ClientEventData|ClientEventData[], queueName: string): void { let events = data instanceof Array ? data : [data]; if (events.length === 0) { return; } // According to the Pusher docs: The time_ms key provides the unix timestamp in milliseconds when the webhook was created. // So we set the time here instead of creating a new one in the queue handler so you can detect delayed webhooks when the queue is busy. let time = (new Date).getTime(); let payload = { time_ms: time, events, }; let pusherSignature = createWebhookHmac(JSON.stringify(payload), app.secret); this.server.queueManager.addToQueue(queueName, { appKey: app.key, payload, pusherSignature, }); } /** * Send a webhook for the app with the given data, with batching enabled. */ protected sendWebhookByBatching(app: App, data: ClientEventData, queueName: string): void { this.batch.push(data); // If there's no batch leader, elect itself as the batch leader, then wait an arbitrary time using // setTimeout to build up a batch, before firing off the full batch of events in one webhook. if (!this.batchHasLeader) { this.batchHasLeader = true; setTimeout(() => { if (this.batch.length > 0) { this.sendWebhook(app, this.batch.splice(0, this.batch.length), queueName); } this.batchHasLeader = false; }, this.server.options.webhooks.batching.duration); } } }
the_stack
import { Box, Text, Section, Container, Grid, Code, Heading, Flex, Paragraph, } from '@modulz/design-system'; export function ColorScale01() { return ( <Box> <Grid css={{ gridTemplateColumns: 'repeat(12, minmax(0, 1fr))', gap: 2, ai: 'center', my: '$5', }} > <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet1' }}> <Text css={{ fontSize: '$2' }}>1</Text> </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet2' }}> <Text css={{ fontSize: '$2' }}>2</Text> </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet4', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>3</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet5', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>4</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet6', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>5</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet7', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>6</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet8', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>7</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet9', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>8</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet10', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>9</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet11', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>10</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet12', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>11</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet12', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>12</Text> */} </Flex> </Grid> </Box> ); } export function ColorScale02() { return ( <Box> <Grid css={{ gridTemplateColumns: 'repeat(12, minmax(0, 1fr))', gap: 2, ai: 'center', my: '$5', }} > <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet1', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>1</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet2', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>2</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet3' }}> <Text css={{ fontSize: '$2' }}>3</Text> </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet4' }}> <Text css={{ fontSize: '$2' }}>4</Text> </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet5' }}> <Text css={{ fontSize: '$2' }}>5</Text> </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet6', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>6</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet7', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>7</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet8', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>8</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet9', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>9</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet10', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>10</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet11', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>11</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet12', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>12</Text> */} </Flex> </Grid> </Box> ); } export function ColorScale03() { return ( <Box> <Grid css={{ gridTemplateColumns: 'repeat(12, minmax(0, 1fr))', gap: 2, ai: 'center', my: '$5', }} > <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet1', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>1</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet2', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>2</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet3', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>3</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet4', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>4</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet5', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>5</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet6' }}> <Text css={{ fontSize: '$2' }}>6</Text> </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet7' }}> <Text css={{ fontSize: '$2' }}>7</Text> </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet8' }}> <Text css={{ fontSize: '$2' }}>8</Text> </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet9', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>9</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet10', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>10</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet11', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>11</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet12', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>12</Text> */} </Flex> </Grid> </Box> ); } export function ColorScale04() { return ( <Box> <Grid css={{ gridTemplateColumns: 'repeat(12, minmax(0, 1fr))', gap: 2, ai: 'center', my: '$5', }} > <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet1', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>1</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet2', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>2</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet3', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>3</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet4', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>4</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet5', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>5</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet6', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>6</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet7', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>7</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet8', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>8</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet9' }}> <Text css={{ fontSize: '$2', color: '$loContrast' }}>9</Text> </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet10' }}> <Text css={{ fontSize: '$2', color: '$loContrast' }}>10</Text> </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet11', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>11</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet12', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>12</Text> */} </Flex> </Grid> </Box> ); } export function ColorScale05() { return ( <Box> <Grid css={{ gridTemplateColumns: 'repeat(12, minmax(0, 1fr))', gap: 2, ai: 'center', my: '$5', }} > <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet1', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>1</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet2', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>2</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet3', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>3</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet4', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>4</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet5', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>5</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet6', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>6</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet7', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>7</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet8', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2' }}>8</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet9', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>9</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet10', filter: 'grayscale(1)' }} > {/* <Text css={{ fontSize: '$2', color: '$loContrast' }}>10</Text> */} </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet11' }}> <Text css={{ fontSize: '$2', color: '$loContrast' }}>11</Text> </Flex> <Flex align="center" justify="center" css={{ height: 35, backgroundColor: '$violet12' }}> <Text css={{ fontSize: '$2', color: '$loContrast' }}>12</Text> </Flex> </Grid> </Box> ); } export function ColorExample04() { return ( <Box> <Grid gap="5" css={{ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', ai: 'center', my: '$5', }} > <Flex align="center" gap="7"> <Box css={{ display: 'inline-flex', ai: 'center', cursor: 'default', px: '$3', height: 35, backgroundColor: '$violet10', borderRadius: '$2', '&:hover': { backgroundColor: '$violet11' }, }} > <Text css={{ fontSize: '$3', color: 'white', fontWeight: 500 }}>Button</Text> </Box> <Box css={{ display: 'inline-flex', ai: 'center', jc: 'flex-end', p: 2, width: 50, backgroundColor: '$violet10', borderRadius: '9999px', }} > <Box css={{ height: 21, width: 21, backgroundColor: 'white', borderRadius: '50%' }} ></Box> </Box> <Box css={{ position: 'relative', width: 125, height: 2, backgroundColor: '$mauve300', borderRadius: '9999px', }} > <Box css={{ width: '50%', height: '100%', backgroundColor: '$violet10', borderRadius: '9999px 0 0 9999px', }} > <Box css={{ position: 'absolute', left: '50%', height: 16, width: 16, backgroundColor: 'white', mt: -8, ml: -8, borderRadius: '50%', boxShadow: '0 2px 5px rgba(0,0,0,.1)', }} ></Box> </Box> </Box> </Flex> </Grid> </Box> ); }
the_stack
export interface paths { '/': { get: { responses: { /** OK */ 200: unknown } } } '/admin_search': { get: { parameters: { query: { user_id?: parameters['rowFilter.admin_search.user_id'] email?: parameters['rowFilter.admin_search.email'] token?: parameters['rowFilter.admin_search.token'] token_id?: parameters['rowFilter.admin_search.token_id'] deleted_at?: parameters['rowFilter.admin_search.deleted_at'] reason_inserted_at?: parameters['rowFilter.admin_search.reason_inserted_at'] reason?: parameters['rowFilter.admin_search.reason'] status?: parameters['rowFilter.admin_search.status'] /** Filtering Columns */ select?: parameters['select'] /** Ordering */ order?: parameters['order'] /** Limiting and Pagination */ offset?: parameters['offset'] /** Limiting and Pagination */ limit?: parameters['limit'] } header: { /** Limiting and Pagination */ Range?: parameters['range'] /** Limiting and Pagination */ 'Range-Unit'?: parameters['rangeUnit'] /** Preference */ Prefer?: parameters['preferCount'] } } responses: { /** OK */ 200: { schema: definitions['admin_search'][] } /** Partial Content */ 206: unknown } } } '/auth_key': { get: { parameters: { query: { id?: parameters['rowFilter.auth_key.id'] name?: parameters['rowFilter.auth_key.name'] secret?: parameters['rowFilter.auth_key.secret'] user_id?: parameters['rowFilter.auth_key.user_id'] inserted_at?: parameters['rowFilter.auth_key.inserted_at'] updated_at?: parameters['rowFilter.auth_key.updated_at'] deleted_at?: parameters['rowFilter.auth_key.deleted_at'] /** Filtering Columns */ select?: parameters['select'] /** Ordering */ order?: parameters['order'] /** Limiting and Pagination */ offset?: parameters['offset'] /** Limiting and Pagination */ limit?: parameters['limit'] } header: { /** Limiting and Pagination */ Range?: parameters['range'] /** Limiting and Pagination */ 'Range-Unit'?: parameters['rangeUnit'] /** Preference */ Prefer?: parameters['preferCount'] } } responses: { /** OK */ 200: { schema: definitions['auth_key'][] } /** Partial Content */ 206: unknown } } post: { parameters: { body: { /** auth_key */ auth_key?: definitions['auth_key'] } query: { /** Filtering Columns */ select?: parameters['select'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** Created */ 201: unknown } } delete: { parameters: { query: { id?: parameters['rowFilter.auth_key.id'] name?: parameters['rowFilter.auth_key.name'] secret?: parameters['rowFilter.auth_key.secret'] user_id?: parameters['rowFilter.auth_key.user_id'] inserted_at?: parameters['rowFilter.auth_key.inserted_at'] updated_at?: parameters['rowFilter.auth_key.updated_at'] deleted_at?: parameters['rowFilter.auth_key.deleted_at'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } patch: { parameters: { query: { id?: parameters['rowFilter.auth_key.id'] name?: parameters['rowFilter.auth_key.name'] secret?: parameters['rowFilter.auth_key.secret'] user_id?: parameters['rowFilter.auth_key.user_id'] inserted_at?: parameters['rowFilter.auth_key.inserted_at'] updated_at?: parameters['rowFilter.auth_key.updated_at'] deleted_at?: parameters['rowFilter.auth_key.deleted_at'] } body: { /** auth_key */ auth_key?: definitions['auth_key'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } } '/auth_key_history': { get: { parameters: { query: { id?: parameters['rowFilter.auth_key_history.id'] status?: parameters['rowFilter.auth_key_history.status'] reason?: parameters['rowFilter.auth_key_history.reason'] auth_key_id?: parameters['rowFilter.auth_key_history.auth_key_id'] inserted_at?: parameters['rowFilter.auth_key_history.inserted_at'] deleted_at?: parameters['rowFilter.auth_key_history.deleted_at'] /** Filtering Columns */ select?: parameters['select'] /** Ordering */ order?: parameters['order'] /** Limiting and Pagination */ offset?: parameters['offset'] /** Limiting and Pagination */ limit?: parameters['limit'] } header: { /** Limiting and Pagination */ Range?: parameters['range'] /** Limiting and Pagination */ 'Range-Unit'?: parameters['rangeUnit'] /** Preference */ Prefer?: parameters['preferCount'] } } responses: { /** OK */ 200: { schema: definitions['auth_key_history'][] } /** Partial Content */ 206: unknown } } post: { parameters: { body: { /** auth_key_history */ auth_key_history?: definitions['auth_key_history'] } query: { /** Filtering Columns */ select?: parameters['select'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** Created */ 201: unknown } } delete: { parameters: { query: { id?: parameters['rowFilter.auth_key_history.id'] status?: parameters['rowFilter.auth_key_history.status'] reason?: parameters['rowFilter.auth_key_history.reason'] auth_key_id?: parameters['rowFilter.auth_key_history.auth_key_id'] inserted_at?: parameters['rowFilter.auth_key_history.inserted_at'] deleted_at?: parameters['rowFilter.auth_key_history.deleted_at'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } patch: { parameters: { query: { id?: parameters['rowFilter.auth_key_history.id'] status?: parameters['rowFilter.auth_key_history.status'] reason?: parameters['rowFilter.auth_key_history.reason'] auth_key_id?: parameters['rowFilter.auth_key_history.auth_key_id'] inserted_at?: parameters['rowFilter.auth_key_history.inserted_at'] deleted_at?: parameters['rowFilter.auth_key_history.deleted_at'] } body: { /** auth_key_history */ auth_key_history?: definitions['auth_key_history'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } } '/content': { get: { parameters: { query: { cid?: parameters['rowFilter.content.cid'] dag_size?: parameters['rowFilter.content.dag_size'] inserted_at?: parameters['rowFilter.content.inserted_at'] updated_at?: parameters['rowFilter.content.updated_at'] /** Filtering Columns */ select?: parameters['select'] /** Ordering */ order?: parameters['order'] /** Limiting and Pagination */ offset?: parameters['offset'] /** Limiting and Pagination */ limit?: parameters['limit'] } header: { /** Limiting and Pagination */ Range?: parameters['range'] /** Limiting and Pagination */ 'Range-Unit'?: parameters['rangeUnit'] /** Preference */ Prefer?: parameters['preferCount'] } } responses: { /** OK */ 200: { schema: definitions['content'][] } /** Partial Content */ 206: unknown } } post: { parameters: { body: { /** content */ content?: definitions['content'] } query: { /** Filtering Columns */ select?: parameters['select'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** Created */ 201: unknown } } delete: { parameters: { query: { cid?: parameters['rowFilter.content.cid'] dag_size?: parameters['rowFilter.content.dag_size'] inserted_at?: parameters['rowFilter.content.inserted_at'] updated_at?: parameters['rowFilter.content.updated_at'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } patch: { parameters: { query: { cid?: parameters['rowFilter.content.cid'] dag_size?: parameters['rowFilter.content.dag_size'] inserted_at?: parameters['rowFilter.content.inserted_at'] updated_at?: parameters['rowFilter.content.updated_at'] } body: { /** content */ content?: definitions['content'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } } '/metric': { get: { parameters: { query: { name?: parameters['rowFilter.metric.name'] value?: parameters['rowFilter.metric.value'] inserted_at?: parameters['rowFilter.metric.inserted_at'] updated_at?: parameters['rowFilter.metric.updated_at'] /** Filtering Columns */ select?: parameters['select'] /** Ordering */ order?: parameters['order'] /** Limiting and Pagination */ offset?: parameters['offset'] /** Limiting and Pagination */ limit?: parameters['limit'] } header: { /** Limiting and Pagination */ Range?: parameters['range'] /** Limiting and Pagination */ 'Range-Unit'?: parameters['rangeUnit'] /** Preference */ Prefer?: parameters['preferCount'] } } responses: { /** OK */ 200: { schema: definitions['metric'][] } /** Partial Content */ 206: unknown } } post: { parameters: { body: { /** metric */ metric?: definitions['metric'] } query: { /** Filtering Columns */ select?: parameters['select'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** Created */ 201: unknown } } delete: { parameters: { query: { name?: parameters['rowFilter.metric.name'] value?: parameters['rowFilter.metric.value'] inserted_at?: parameters['rowFilter.metric.inserted_at'] updated_at?: parameters['rowFilter.metric.updated_at'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } patch: { parameters: { query: { name?: parameters['rowFilter.metric.name'] value?: parameters['rowFilter.metric.value'] inserted_at?: parameters['rowFilter.metric.inserted_at'] updated_at?: parameters['rowFilter.metric.updated_at'] } body: { /** metric */ metric?: definitions['metric'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } } '/pin': { get: { parameters: { query: { id?: parameters['rowFilter.pin.id'] status?: parameters['rowFilter.pin.status'] content_cid?: parameters['rowFilter.pin.content_cid'] service?: parameters['rowFilter.pin.service'] inserted_at?: parameters['rowFilter.pin.inserted_at'] updated_at?: parameters['rowFilter.pin.updated_at'] /** Filtering Columns */ select?: parameters['select'] /** Ordering */ order?: parameters['order'] /** Limiting and Pagination */ offset?: parameters['offset'] /** Limiting and Pagination */ limit?: parameters['limit'] } header: { /** Limiting and Pagination */ Range?: parameters['range'] /** Limiting and Pagination */ 'Range-Unit'?: parameters['rangeUnit'] /** Preference */ Prefer?: parameters['preferCount'] } } responses: { /** OK */ 200: { schema: definitions['pin'][] } /** Partial Content */ 206: unknown } } post: { parameters: { body: { /** pin */ pin?: definitions['pin'] } query: { /** Filtering Columns */ select?: parameters['select'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** Created */ 201: unknown } } delete: { parameters: { query: { id?: parameters['rowFilter.pin.id'] status?: parameters['rowFilter.pin.status'] content_cid?: parameters['rowFilter.pin.content_cid'] service?: parameters['rowFilter.pin.service'] inserted_at?: parameters['rowFilter.pin.inserted_at'] updated_at?: parameters['rowFilter.pin.updated_at'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } patch: { parameters: { query: { id?: parameters['rowFilter.pin.id'] status?: parameters['rowFilter.pin.status'] content_cid?: parameters['rowFilter.pin.content_cid'] service?: parameters['rowFilter.pin.service'] inserted_at?: parameters['rowFilter.pin.inserted_at'] updated_at?: parameters['rowFilter.pin.updated_at'] } body: { /** pin */ pin?: definitions['pin'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } } '/upload': { get: { parameters: { query: { id?: parameters['rowFilter.upload.id'] user_id?: parameters['rowFilter.upload.user_id'] key_id?: parameters['rowFilter.upload.key_id'] content_cid?: parameters['rowFilter.upload.content_cid'] source_cid?: parameters['rowFilter.upload.source_cid'] mime_type?: parameters['rowFilter.upload.mime_type'] type?: parameters['rowFilter.upload.type'] name?: parameters['rowFilter.upload.name'] files?: parameters['rowFilter.upload.files'] origins?: parameters['rowFilter.upload.origins'] meta?: parameters['rowFilter.upload.meta'] backup_urls?: parameters['rowFilter.upload.backup_urls'] inserted_at?: parameters['rowFilter.upload.inserted_at'] updated_at?: parameters['rowFilter.upload.updated_at'] deleted_at?: parameters['rowFilter.upload.deleted_at'] /** Filtering Columns */ select?: parameters['select'] /** Ordering */ order?: parameters['order'] /** Limiting and Pagination */ offset?: parameters['offset'] /** Limiting and Pagination */ limit?: parameters['limit'] } header: { /** Limiting and Pagination */ Range?: parameters['range'] /** Limiting and Pagination */ 'Range-Unit'?: parameters['rangeUnit'] /** Preference */ Prefer?: parameters['preferCount'] } } responses: { /** OK */ 200: { schema: definitions['upload'][] } /** Partial Content */ 206: unknown } } post: { parameters: { body: { /** upload */ upload?: definitions['upload'] } query: { /** Filtering Columns */ select?: parameters['select'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** Created */ 201: unknown } } delete: { parameters: { query: { id?: parameters['rowFilter.upload.id'] user_id?: parameters['rowFilter.upload.user_id'] key_id?: parameters['rowFilter.upload.key_id'] content_cid?: parameters['rowFilter.upload.content_cid'] source_cid?: parameters['rowFilter.upload.source_cid'] mime_type?: parameters['rowFilter.upload.mime_type'] type?: parameters['rowFilter.upload.type'] name?: parameters['rowFilter.upload.name'] files?: parameters['rowFilter.upload.files'] origins?: parameters['rowFilter.upload.origins'] meta?: parameters['rowFilter.upload.meta'] backup_urls?: parameters['rowFilter.upload.backup_urls'] inserted_at?: parameters['rowFilter.upload.inserted_at'] updated_at?: parameters['rowFilter.upload.updated_at'] deleted_at?: parameters['rowFilter.upload.deleted_at'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } patch: { parameters: { query: { id?: parameters['rowFilter.upload.id'] user_id?: parameters['rowFilter.upload.user_id'] key_id?: parameters['rowFilter.upload.key_id'] content_cid?: parameters['rowFilter.upload.content_cid'] source_cid?: parameters['rowFilter.upload.source_cid'] mime_type?: parameters['rowFilter.upload.mime_type'] type?: parameters['rowFilter.upload.type'] name?: parameters['rowFilter.upload.name'] files?: parameters['rowFilter.upload.files'] origins?: parameters['rowFilter.upload.origins'] meta?: parameters['rowFilter.upload.meta'] backup_urls?: parameters['rowFilter.upload.backup_urls'] inserted_at?: parameters['rowFilter.upload.inserted_at'] updated_at?: parameters['rowFilter.upload.updated_at'] deleted_at?: parameters['rowFilter.upload.deleted_at'] } body: { /** upload */ upload?: definitions['upload'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } } '/user': { get: { parameters: { query: { id?: parameters['rowFilter.user.id'] magic_link_id?: parameters['rowFilter.user.magic_link_id'] github_id?: parameters['rowFilter.user.github_id'] name?: parameters['rowFilter.user.name'] picture?: parameters['rowFilter.user.picture'] email?: parameters['rowFilter.user.email'] public_address?: parameters['rowFilter.user.public_address'] did?: parameters['rowFilter.user.did'] github?: parameters['rowFilter.user.github'] inserted_at?: parameters['rowFilter.user.inserted_at'] updated_at?: parameters['rowFilter.user.updated_at'] /** Filtering Columns */ select?: parameters['select'] /** Ordering */ order?: parameters['order'] /** Limiting and Pagination */ offset?: parameters['offset'] /** Limiting and Pagination */ limit?: parameters['limit'] } header: { /** Limiting and Pagination */ Range?: parameters['range'] /** Limiting and Pagination */ 'Range-Unit'?: parameters['rangeUnit'] /** Preference */ Prefer?: parameters['preferCount'] } } responses: { /** OK */ 200: { schema: definitions['user'][] } /** Partial Content */ 206: unknown } } post: { parameters: { body: { /** user */ user?: definitions['user'] } query: { /** Filtering Columns */ select?: parameters['select'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** Created */ 201: unknown } } delete: { parameters: { query: { id?: parameters['rowFilter.user.id'] magic_link_id?: parameters['rowFilter.user.magic_link_id'] github_id?: parameters['rowFilter.user.github_id'] name?: parameters['rowFilter.user.name'] picture?: parameters['rowFilter.user.picture'] email?: parameters['rowFilter.user.email'] public_address?: parameters['rowFilter.user.public_address'] did?: parameters['rowFilter.user.did'] github?: parameters['rowFilter.user.github'] inserted_at?: parameters['rowFilter.user.inserted_at'] updated_at?: parameters['rowFilter.user.updated_at'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } patch: { parameters: { query: { id?: parameters['rowFilter.user.id'] magic_link_id?: parameters['rowFilter.user.magic_link_id'] github_id?: parameters['rowFilter.user.github_id'] name?: parameters['rowFilter.user.name'] picture?: parameters['rowFilter.user.picture'] email?: parameters['rowFilter.user.email'] public_address?: parameters['rowFilter.user.public_address'] did?: parameters['rowFilter.user.did'] github?: parameters['rowFilter.user.github'] inserted_at?: parameters['rowFilter.user.inserted_at'] updated_at?: parameters['rowFilter.user.updated_at'] } body: { /** user */ user?: definitions['user'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } } '/user_tag': { get: { parameters: { query: { id?: parameters['rowFilter.user_tag.id'] user_id?: parameters['rowFilter.user_tag.user_id'] tag?: parameters['rowFilter.user_tag.tag'] value?: parameters['rowFilter.user_tag.value'] reason?: parameters['rowFilter.user_tag.reason'] inserted_at?: parameters['rowFilter.user_tag.inserted_at'] deleted_at?: parameters['rowFilter.user_tag.deleted_at'] /** Filtering Columns */ select?: parameters['select'] /** Ordering */ order?: parameters['order'] /** Limiting and Pagination */ offset?: parameters['offset'] /** Limiting and Pagination */ limit?: parameters['limit'] } header: { /** Limiting and Pagination */ Range?: parameters['range'] /** Limiting and Pagination */ 'Range-Unit'?: parameters['rangeUnit'] /** Preference */ Prefer?: parameters['preferCount'] } } responses: { /** OK */ 200: { schema: definitions['user_tag'][] } /** Partial Content */ 206: unknown } } post: { parameters: { body: { /** user_tag */ user_tag?: definitions['user_tag'] } query: { /** Filtering Columns */ select?: parameters['select'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** Created */ 201: unknown } } delete: { parameters: { query: { id?: parameters['rowFilter.user_tag.id'] user_id?: parameters['rowFilter.user_tag.user_id'] tag?: parameters['rowFilter.user_tag.tag'] value?: parameters['rowFilter.user_tag.value'] reason?: parameters['rowFilter.user_tag.reason'] inserted_at?: parameters['rowFilter.user_tag.inserted_at'] deleted_at?: parameters['rowFilter.user_tag.deleted_at'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } patch: { parameters: { query: { id?: parameters['rowFilter.user_tag.id'] user_id?: parameters['rowFilter.user_tag.user_id'] tag?: parameters['rowFilter.user_tag.tag'] value?: parameters['rowFilter.user_tag.value'] reason?: parameters['rowFilter.user_tag.reason'] inserted_at?: parameters['rowFilter.user_tag.inserted_at'] deleted_at?: parameters['rowFilter.user_tag.deleted_at'] } body: { /** user_tag */ user_tag?: definitions['user_tag'] } header: { /** Preference */ Prefer?: parameters['preferReturn'] } } responses: { /** No Content */ 204: never } } } '/rpc/pgrst_watch': { post: { parameters: { body: { args: { [key: string]: unknown } } header: { /** Preference */ Prefer?: parameters['preferParams'] } } responses: { /** OK */ 200: unknown } } } '/rpc/find_deals_by_content_cids': { post: { parameters: { body: { args: { /** Format: text[] */ cids: string } } header: { /** Preference */ Prefer?: parameters['preferParams'] } } responses: { /** OK */ 200: unknown } } } '/rpc/json_arr_to_text_arr': { post: { parameters: { body: { args: { /** Format: json */ _json: string } } header: { /** Preference */ Prefer?: parameters['preferParams'] } } responses: { /** OK */ 200: unknown } } } '/rpc/create_upload': { post: { parameters: { body: { args: { /** Format: json */ data: string } } header: { /** Preference */ Prefer?: parameters['preferParams'] } } responses: { /** OK */ 200: unknown } } } } export interface definitions { admin_search: { /** Format: text */ user_id?: string /** Format: text */ email?: string /** Format: text */ token?: string /** Format: text */ token_id?: string /** Format: timestamp with time zone */ deleted_at?: string /** Format: timestamp with time zone */ reason_inserted_at?: string /** Format: text */ reason?: string /** Format: public.auth_key_blocked_status_type */ status?: 'Blocked' | 'Unblocked' } auth_key: { /** * Format: bigint * @description Note: * This is a Primary Key.<pk/> */ id: number /** Format: text */ name: string /** Format: text */ secret: string /** * Format: bigint * @description Note: * This is a Foreign Key to `user.id`.<fk table='user' column='id'/> */ user_id: number /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ inserted_at: string /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ updated_at: string /** Format: timestamp with time zone */ deleted_at?: string } auth_key_history: { /** * Format: bigint * @description Note: * This is a Primary Key.<pk/> */ id: number /** Format: public.auth_key_blocked_status_type */ status: 'Blocked' | 'Unblocked' /** Format: text */ reason: string /** * Format: bigint * @description Note: * This is a Foreign Key to `auth_key.id`.<fk table='auth_key' column='id'/> */ auth_key_id: number /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ inserted_at: string /** Format: timestamp with time zone */ deleted_at?: string } content: { /** * Format: text * @description Note: * This is a Primary Key.<pk/> */ cid: string /** Format: bigint */ dag_size?: number /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ inserted_at: string /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ updated_at: string } metric: { /** * Format: text * @description Note: * This is a Primary Key.<pk/> */ name: string /** Format: bigint */ value: number /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ inserted_at: string /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ updated_at: string } pin: { /** * Format: bigint * @description Note: * This is a Primary Key.<pk/> */ id: number /** Format: public.pin_status_type */ status: 'PinError' | 'PinQueued' | 'Pinned' | 'Pinning' /** * Format: text * @description Note: * This is a Foreign Key to `content.cid`.<fk table='content' column='cid'/> */ content_cid: string /** Format: public.service_type */ service: 'Pinata' | 'IpfsCluster' | 'IpfsCluster2' | 'IpfsCluster3' /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ inserted_at: string /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ updated_at: string } upload: { /** * Format: bigint * @description Note: * This is a Primary Key.<pk/> */ id: number /** * Format: bigint * @description Note: * This is a Foreign Key to `user.id`.<fk table='user' column='id'/> */ user_id: number /** * Format: bigint * @description Note: * This is a Foreign Key to `auth_key.id`.<fk table='auth_key' column='id'/> */ key_id?: number /** * Format: text * @description Note: * This is a Foreign Key to `content.cid`.<fk table='content' column='cid'/> */ content_cid: string /** Format: text */ source_cid: string /** Format: text */ mime_type?: string /** Format: public.upload_type */ type: 'Car' | 'Blob' | 'Multipart' | 'Remote' | 'Nft' /** Format: text */ name?: string /** Format: jsonb */ files?: string /** Format: jsonb */ origins?: string /** Format: jsonb */ meta?: string /** Format: ARRAY */ backup_urls?: unknown[] /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ inserted_at: string /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ updated_at: string /** Format: timestamp with time zone */ deleted_at?: string } user: { /** * Format: bigint * @description Note: * This is a Primary Key.<pk/> */ id: number /** Format: text */ magic_link_id?: string /** Format: text */ github_id: string /** Format: text */ name: string /** Format: text */ picture?: string /** Format: text */ email: string /** Format: text */ public_address?: string /** Format: text */ did?: string /** Format: jsonb */ github?: string /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ inserted_at: string /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ updated_at: string } user_tag: { /** * Format: bigint * @description Note: * This is a Primary Key.<pk/> */ id: number /** * Format: bigint * @description Note: * This is a Foreign Key to `user.id`.<fk table='user' column='id'/> */ user_id: number /** Format: public.user_tag_type */ tag: | 'HasAccountRestriction' | 'HasPsaAccess' | 'HasSuperHotAccess' | 'StorageLimitBytes' /** Format: text */ value: string /** Format: text */ reason: string /** * Format: timestamp with time zone * @default timezone('utc'::text, now()) */ inserted_at: string /** Format: timestamp with time zone */ deleted_at?: string } } export interface parameters { /** @description Preference */ preferParams: 'params=single-object' /** @description Preference */ preferReturn: 'return=representation' | 'return=minimal' | 'return=none' /** @description Preference */ preferCount: 'count=none' /** @description Filtering Columns */ select: string /** @description On Conflict */ on_conflict: string /** @description Ordering */ order: string /** @description Limiting and Pagination */ range: string /** * @description Limiting and Pagination * @default items */ rangeUnit: string /** @description Limiting and Pagination */ offset: string /** @description Limiting and Pagination */ limit: string /** @description admin_search */ 'body.admin_search': definitions['admin_search'] /** Format: text */ 'rowFilter.admin_search.user_id': string /** Format: text */ 'rowFilter.admin_search.email': string /** Format: text */ 'rowFilter.admin_search.token': string /** Format: text */ 'rowFilter.admin_search.token_id': string /** Format: timestamp with time zone */ 'rowFilter.admin_search.deleted_at': string /** Format: timestamp with time zone */ 'rowFilter.admin_search.reason_inserted_at': string /** Format: text */ 'rowFilter.admin_search.reason': string /** Format: public.auth_key_blocked_status_type */ 'rowFilter.admin_search.status': string /** @description auth_key */ 'body.auth_key': definitions['auth_key'] /** Format: bigint */ 'rowFilter.auth_key.id': string /** Format: text */ 'rowFilter.auth_key.name': string /** Format: text */ 'rowFilter.auth_key.secret': string /** Format: bigint */ 'rowFilter.auth_key.user_id': string /** Format: timestamp with time zone */ 'rowFilter.auth_key.inserted_at': string /** Format: timestamp with time zone */ 'rowFilter.auth_key.updated_at': string /** Format: timestamp with time zone */ 'rowFilter.auth_key.deleted_at': string /** @description auth_key_history */ 'body.auth_key_history': definitions['auth_key_history'] /** Format: bigint */ 'rowFilter.auth_key_history.id': string /** Format: public.auth_key_blocked_status_type */ 'rowFilter.auth_key_history.status': string /** Format: text */ 'rowFilter.auth_key_history.reason': string /** Format: bigint */ 'rowFilter.auth_key_history.auth_key_id': string /** Format: timestamp with time zone */ 'rowFilter.auth_key_history.inserted_at': string /** Format: timestamp with time zone */ 'rowFilter.auth_key_history.deleted_at': string /** @description content */ 'body.content': definitions['content'] /** Format: text */ 'rowFilter.content.cid': string /** Format: bigint */ 'rowFilter.content.dag_size': string /** Format: timestamp with time zone */ 'rowFilter.content.inserted_at': string /** Format: timestamp with time zone */ 'rowFilter.content.updated_at': string /** @description metric */ 'body.metric': definitions['metric'] /** Format: text */ 'rowFilter.metric.name': string /** Format: bigint */ 'rowFilter.metric.value': string /** Format: timestamp with time zone */ 'rowFilter.metric.inserted_at': string /** Format: timestamp with time zone */ 'rowFilter.metric.updated_at': string /** @description pin */ 'body.pin': definitions['pin'] /** Format: bigint */ 'rowFilter.pin.id': string /** Format: public.pin_status_type */ 'rowFilter.pin.status': string /** Format: text */ 'rowFilter.pin.content_cid': string /** Format: public.service_type */ 'rowFilter.pin.service': string /** Format: timestamp with time zone */ 'rowFilter.pin.inserted_at': string /** Format: timestamp with time zone */ 'rowFilter.pin.updated_at': string /** @description upload */ 'body.upload': definitions['upload'] /** Format: bigint */ 'rowFilter.upload.id': string /** Format: bigint */ 'rowFilter.upload.user_id': string /** Format: bigint */ 'rowFilter.upload.key_id': string /** Format: text */ 'rowFilter.upload.content_cid': string /** Format: text */ 'rowFilter.upload.source_cid': string /** Format: text */ 'rowFilter.upload.mime_type': string /** Format: public.upload_type */ 'rowFilter.upload.type': string /** Format: text */ 'rowFilter.upload.name': string /** Format: jsonb */ 'rowFilter.upload.files': string /** Format: jsonb */ 'rowFilter.upload.origins': string /** Format: jsonb */ 'rowFilter.upload.meta': string /** Format: ARRAY */ 'rowFilter.upload.backup_urls': string /** Format: timestamp with time zone */ 'rowFilter.upload.inserted_at': string /** Format: timestamp with time zone */ 'rowFilter.upload.updated_at': string /** Format: timestamp with time zone */ 'rowFilter.upload.deleted_at': string /** @description user */ 'body.user': definitions['user'] /** Format: bigint */ 'rowFilter.user.id': string /** Format: text */ 'rowFilter.user.magic_link_id': string /** Format: text */ 'rowFilter.user.github_id': string /** Format: text */ 'rowFilter.user.name': string /** Format: text */ 'rowFilter.user.picture': string /** Format: text */ 'rowFilter.user.email': string /** Format: text */ 'rowFilter.user.public_address': string /** Format: text */ 'rowFilter.user.did': string /** Format: jsonb */ 'rowFilter.user.github': string /** Format: timestamp with time zone */ 'rowFilter.user.inserted_at': string /** Format: timestamp with time zone */ 'rowFilter.user.updated_at': string /** @description user_tag */ 'body.user_tag': definitions['user_tag'] /** Format: bigint */ 'rowFilter.user_tag.id': string /** Format: bigint */ 'rowFilter.user_tag.user_id': string /** Format: public.user_tag_type */ 'rowFilter.user_tag.tag': string /** Format: text */ 'rowFilter.user_tag.value': string /** Format: text */ 'rowFilter.user_tag.reason': string /** Format: timestamp with time zone */ 'rowFilter.user_tag.inserted_at': string /** Format: timestamp with time zone */ 'rowFilter.user_tag.deleted_at': string } export interface operations {} export interface external {}
the_stack
import { locStub, generate, NodeTypes, RootNode, createSimpleExpression, createObjectExpression, createObjectProperty, createArrayExpression, createCompoundExpression, createInterpolation, createSequenceExpression, createCallExpression, createConditionalExpression, IfCodegenNode, ForCodegenNode, createCacheExpression } from '../src' import { CREATE_VNODE, COMMENT, TO_STRING, RESOLVE_DIRECTIVE, helperNameMap, RESOLVE_COMPONENT } from '../src/runtimeHelpers' import { createElementWithCodegen } from './testUtils' import { PatchFlags } from '@vue/shared' function createRoot(options: Partial<RootNode> = {}): RootNode { return { type: NodeTypes.ROOT, children: [], helpers: [], components: [], directives: [], hoists: [], cached: 0, codegenNode: createSimpleExpression(`null`, false), loc: locStub, ...options } } describe('compiler: codegen', () => { test('module mode preamble', () => { const root = createRoot({ helpers: [CREATE_VNODE, RESOLVE_DIRECTIVE] }) const { code } = generate(root, { mode: 'module' }) expect(code).toMatch( `import { ${helperNameMap[CREATE_VNODE]}, ${ helperNameMap[RESOLVE_DIRECTIVE] } } from "vue"` ) expect(code).toMatchSnapshot() }) test('function mode preamble', () => { const root = createRoot({ helpers: [CREATE_VNODE, RESOLVE_DIRECTIVE] }) const { code } = generate(root, { mode: 'function' }) expect(code).toMatch(`const _Vue = Vue`) expect(code).toMatch( `const { ${helperNameMap[CREATE_VNODE]}: _${ helperNameMap[CREATE_VNODE] }, ${helperNameMap[RESOLVE_DIRECTIVE]}: _${ helperNameMap[RESOLVE_DIRECTIVE] } } = _Vue` ) expect(code).toMatchSnapshot() }) test('function mode preamble w/ prefixIdentifiers: true', () => { const root = createRoot({ helpers: [CREATE_VNODE, RESOLVE_DIRECTIVE] }) const { code } = generate(root, { mode: 'function', prefixIdentifiers: true }) expect(code).not.toMatch(`const _Vue = Vue`) expect(code).toMatch( `const { ${helperNameMap[CREATE_VNODE]}, ${ helperNameMap[RESOLVE_DIRECTIVE] } } = Vue` ) expect(code).toMatchSnapshot() }) test('assets', () => { const root = createRoot({ components: [`Foo`, `bar-baz`, `barbaz`], directives: [`my_dir`] }) const { code } = generate(root, { mode: 'function' }) expect(code).toMatch( `const _component_Foo = _${helperNameMap[RESOLVE_COMPONENT]}("Foo")\n` ) expect(code).toMatch( `const _component_bar_baz = _${ helperNameMap[RESOLVE_COMPONENT] }("bar-baz")\n` ) expect(code).toMatch( `const _component_barbaz = _${ helperNameMap[RESOLVE_COMPONENT] }("barbaz")\n` ) expect(code).toMatch( `const _directive_my_dir = _${ helperNameMap[RESOLVE_DIRECTIVE] }("my_dir")\n` ) expect(code).toMatchSnapshot() }) test('hoists', () => { const root = createRoot({ hoists: [ createSimpleExpression(`hello`, false, locStub), createObjectExpression( [ createObjectProperty( createSimpleExpression(`id`, true, locStub), createSimpleExpression(`foo`, true, locStub) ) ], locStub ) ] }) const { code } = generate(root) expect(code).toMatch(`const _hoisted_1 = hello`) expect(code).toMatch(`const _hoisted_2 = { id: "foo" }`) expect(code).toMatchSnapshot() }) test('prefixIdentifiers: true should inject _ctx statement', () => { const { code } = generate(createRoot(), { prefixIdentifiers: true }) expect(code).toMatch(`const _ctx = this\n`) expect(code).toMatchSnapshot() }) test('static text', () => { const { code } = generate( createRoot({ codegenNode: { type: NodeTypes.TEXT, content: 'hello', isEmpty: false, loc: locStub } }) ) expect(code).toMatch(`return "hello"`) expect(code).toMatchSnapshot() }) test('interpolation', () => { const { code } = generate( createRoot({ codegenNode: createInterpolation(`hello`, locStub) }) ) expect(code).toMatch(`return _${helperNameMap[TO_STRING]}(hello)`) expect(code).toMatchSnapshot() }) test('comment', () => { const { code } = generate( createRoot({ codegenNode: { type: NodeTypes.COMMENT, content: 'foo', loc: locStub } }) ) expect(code).toMatch( `return _${helperNameMap[CREATE_VNODE]}(_${ helperNameMap[COMMENT] }, null, "foo")` ) expect(code).toMatchSnapshot() }) test('compound expression', () => { const { code } = generate( createRoot({ codegenNode: createCompoundExpression([ `_ctx.`, createSimpleExpression(`foo`, false, locStub), ` + `, { type: NodeTypes.INTERPOLATION, loc: locStub, content: createSimpleExpression(`bar`, false, locStub) } ]) }) ) expect(code).toMatch(`return _ctx.foo + _${helperNameMap[TO_STRING]}(bar)`) expect(code).toMatchSnapshot() }) test('ifNode', () => { const { code } = generate( createRoot({ codegenNode: { type: NodeTypes.IF, loc: locStub, branches: [], codegenNode: createSequenceExpression([ createSimpleExpression('foo', false), createSimpleExpression('bar', false) ]) as IfCodegenNode } }) ) expect(code).toMatch(`return (foo, bar)`) expect(code).toMatchSnapshot() }) test('forNode', () => { const { code } = generate( createRoot({ codegenNode: { type: NodeTypes.FOR, loc: locStub, source: createSimpleExpression('foo', false), valueAlias: undefined, keyAlias: undefined, objectIndexAlias: undefined, children: [], codegenNode: createSequenceExpression([ createSimpleExpression('foo', false), createSimpleExpression('bar', false) ]) as ForCodegenNode } }) ) expect(code).toMatch(`return (foo, bar)`) expect(code).toMatchSnapshot() }) test('Element (callExpression + objectExpression + TemplateChildNode[])', () => { const { code } = generate( createRoot({ codegenNode: createElementWithCodegen([ // string `"div"`, // ObjectExpression createObjectExpression( [ createObjectProperty( createSimpleExpression(`id`, true, locStub), createSimpleExpression(`foo`, true, locStub) ), createObjectProperty( createSimpleExpression(`prop`, false, locStub), createSimpleExpression(`bar`, false, locStub) ), // compound expression as computed key createObjectProperty( { type: NodeTypes.COMPOUND_EXPRESSION, loc: locStub, children: [ `foo + `, createSimpleExpression(`bar`, false, locStub) ] }, createSimpleExpression(`bar`, false, locStub) ) ], locStub ), // ChildNode[] [ createElementWithCodegen([ `"p"`, createObjectExpression( [ createObjectProperty( // should quote the key! createSimpleExpression(`some-key`, true, locStub), createSimpleExpression(`foo`, true, locStub) ) ], locStub ) ]) ], // flag PatchFlags.FULL_PROPS + '' ]) }) ) expect(code).toMatch(` return _${helperNameMap[CREATE_VNODE]}("div", { id: "foo", [prop]: bar, [foo + bar]: bar }, [ _${helperNameMap[CREATE_VNODE]}("p", { "some-key": "foo" }) ], ${PatchFlags.FULL_PROPS})`) expect(code).toMatchSnapshot() }) test('ArrayExpression', () => { const { code } = generate( createRoot({ codegenNode: createArrayExpression([ createSimpleExpression(`foo`, false), createCallExpression(`bar`, [`baz`]) ]) }) ) expect(code).toMatch(`return [ foo, bar(baz) ]`) expect(code).toMatchSnapshot() }) test('SequenceExpression', () => { const { code } = generate( createRoot({ codegenNode: createSequenceExpression([ createSimpleExpression(`foo`, false), createCallExpression(`bar`, [`baz`]) ]) }) ) expect(code).toMatch(`return (foo, bar(baz))`) expect(code).toMatchSnapshot() }) test('ConditionalExpression', () => { const { code } = generate( createRoot({ codegenNode: createConditionalExpression( createSimpleExpression(`ok`, false), createCallExpression(`foo`), createConditionalExpression( createSimpleExpression(`orNot`, false), createCallExpression(`bar`), createCallExpression(`baz`) ) ) }) ) expect(code).toMatch( `return ok ? foo() : orNot ? bar() : baz()` ) expect(code).toMatchSnapshot() }) test('CacheExpression', () => { const { code } = generate( createRoot({ cached: 1, codegenNode: createCacheExpression( 1, createSimpleExpression(`foo`, false) ) }), { mode: 'module', prefixIdentifiers: true } ) expect(code).toMatch(`const _cache = _ctx.$cache`) expect(code).toMatch(`_cache[1] || (_cache[1] = foo)`) expect(code).toMatchSnapshot() }) })
the_stack
import * as assert from 'assert'; import { CharCode } from 'vs/base/common/charCode'; import * as platform from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { createStringBuilder } from 'vs/editor/common/core/stringBuilder'; import { DefaultEndOfLine, ITextModel } from 'vs/editor/common/model'; import { createTextBuffer } from 'vs/editor/common/model/textModel'; import { ModelSemanticColoring, ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { TestColorTheme, TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; import { NullLogService } from 'vs/platform/log/common/log'; import { UndoRedoService } from 'vs/platform/undoRedo/common/undoRedoService'; import { TestDialogService } from 'vs/platform/dialogs/test/common/testDialogService'; import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService'; import { createTextModel } from 'vs/editor/test/common/editorTestUtils'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { DocumentSemanticTokensProvider, DocumentSemanticTokensProviderRegistry, SemanticTokens, SemanticTokensEdits, SemanticTokensLegend } from 'vs/editor/common/modes'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Barrier, timeout } from 'vs/base/common/async'; import { ModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl'; import { ColorScheme } from 'vs/platform/theme/common/theme'; import { ModesRegistry } from 'vs/editor/common/modes/modesRegistry'; import { IModelService } from 'vs/editor/common/services/modelService'; import { IModeService } from 'vs/editor/common/services/modeService'; import { TestTextResourcePropertiesService } from 'vs/editor/test/common/services/testTextResourcePropertiesService'; const GENERATE_TESTS = false; suite('ModelService', () => { let modelService: ModelServiceImpl; setup(() => { const configService = new TestConfigurationService(); configService.setUserConfiguration('files', { 'eol': '\n' }); configService.setUserConfiguration('files', { 'eol': '\r\n' }, URI.file(platform.isWindows ? 'c:\\myroot' : '/myroot')); const dialogService = new TestDialogService(); modelService = new ModelServiceImpl(configService, new TestTextResourcePropertiesService(configService), new TestThemeService(), new NullLogService(), new UndoRedoService(dialogService, new TestNotificationService())); }); teardown(() => { modelService.dispose(); }); test('EOL setting respected depending on root', () => { const model1 = modelService.createModel('farboo', null); const model2 = modelService.createModel('farboo', null, URI.file(platform.isWindows ? 'c:\\myroot\\myfile.txt' : '/myroot/myfile.txt')); const model3 = modelService.createModel('farboo', null, URI.file(platform.isWindows ? 'c:\\other\\myfile.txt' : '/other/myfile.txt')); assert.strictEqual(model1.getOptions().defaultEOL, DefaultEndOfLine.LF); assert.strictEqual(model2.getOptions().defaultEOL, DefaultEndOfLine.CRLF); assert.strictEqual(model3.getOptions().defaultEOL, DefaultEndOfLine.LF); }); test('_computeEdits no change', function () { const model = createTextModel( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n') ); const textBuffer = createTextBuffer( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n'), DefaultEndOfLine.LF ).textBuffer; const actual = ModelServiceImpl._computeEdits(model, textBuffer); assert.deepStrictEqual(actual, []); }); test('_computeEdits first line changed', function () { const model = createTextModel( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n') ); const textBuffer = createTextBuffer( [ 'This is line One', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n'), DefaultEndOfLine.LF ).textBuffer; const actual = ModelServiceImpl._computeEdits(model, textBuffer); assert.deepStrictEqual(actual, [ EditOperation.replaceMove(new Range(1, 1, 2, 1), 'This is line One\n') ]); }); test('_computeEdits EOL changed', function () { const model = createTextModel( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n') ); const textBuffer = createTextBuffer( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\r\n'), DefaultEndOfLine.LF ).textBuffer; const actual = ModelServiceImpl._computeEdits(model, textBuffer); assert.deepStrictEqual(actual, []); }); test('_computeEdits EOL and other change 1', function () { const model = createTextModel( [ 'This is line one', //16 'and this is line number two', //27 'it is followed by #3', //20 'and finished with the fourth.', //29 ].join('\n') ); const textBuffer = createTextBuffer( [ 'This is line One', //16 'and this is line number two', //27 'It is followed by #3', //20 'and finished with the fourth.', //29 ].join('\r\n'), DefaultEndOfLine.LF ).textBuffer; const actual = ModelServiceImpl._computeEdits(model, textBuffer); assert.deepStrictEqual(actual, [ EditOperation.replaceMove( new Range(1, 1, 4, 1), [ 'This is line One', 'and this is line number two', 'It is followed by #3', '' ].join('\r\n') ) ]); }); test('_computeEdits EOL and other change 2', function () { const model = createTextModel( [ 'package main', // 1 'func foo() {', // 2 '}' // 3 ].join('\n') ); const textBuffer = createTextBuffer( [ 'package main', // 1 'func foo() {', // 2 '}', // 3 '' ].join('\r\n'), DefaultEndOfLine.LF ).textBuffer; const actual = ModelServiceImpl._computeEdits(model, textBuffer); assert.deepStrictEqual(actual, [ EditOperation.replaceMove(new Range(3, 2, 3, 2), '\r\n') ]); }); test('generated1', () => { const file1 = ['pram', 'okctibad', 'pjuwtemued', 'knnnm', 'u', '']; const file2 = ['tcnr', 'rxwlicro', 'vnzy', '', '', 'pjzcogzur', 'ptmxyp', 'dfyshia', 'pee', 'ygg']; assertComputeEdits(file1, file2); }); test('generated2', () => { const file1 = ['', 'itls', 'hrilyhesv', '']; const file2 = ['vdl', '', 'tchgz', 'bhx', 'nyl']; assertComputeEdits(file1, file2); }); test('generated3', () => { const file1 = ['ubrbrcv', 'wv', 'xodspybszt', 's', 'wednjxm', 'fklajt', 'fyfc', 'lvejgge', 'rtpjlodmmk', 'arivtgmjdm']; const file2 = ['s', 'qj', 'tu', 'ur', 'qerhjjhyvx', 't']; assertComputeEdits(file1, file2); }); test('generated4', () => { const file1 = ['ig', 'kh', 'hxegci', 'smvker', 'pkdmjjdqnv', 'vgkkqqx', '', 'jrzeb']; const file2 = ['yk', '']; assertComputeEdits(file1, file2); }); test('does insertions in the middle of the document', () => { const file1 = [ 'line 1', 'line 2', 'line 3' ]; const file2 = [ 'line 1', 'line 2', 'line 5', 'line 3' ]; assertComputeEdits(file1, file2); }); test('does insertions at the end of the document', () => { const file1 = [ 'line 1', 'line 2', 'line 3' ]; const file2 = [ 'line 1', 'line 2', 'line 3', 'line 4' ]; assertComputeEdits(file1, file2); }); test('does insertions at the beginning of the document', () => { const file1 = [ 'line 1', 'line 2', 'line 3' ]; const file2 = [ 'line 0', 'line 1', 'line 2', 'line 3' ]; assertComputeEdits(file1, file2); }); test('does replacements', () => { const file1 = [ 'line 1', 'line 2', 'line 3' ]; const file2 = [ 'line 1', 'line 7', 'line 3' ]; assertComputeEdits(file1, file2); }); test('does deletions', () => { const file1 = [ 'line 1', 'line 2', 'line 3' ]; const file2 = [ 'line 1', 'line 3' ]; assertComputeEdits(file1, file2); }); test('does insert, replace, and delete', () => { const file1 = [ 'line 1', 'line 2', 'line 3', 'line 4', 'line 5', ]; const file2 = [ 'line 0', // insert line 0 'line 1', 'replace line 2', // replace line 2 'line 3', // delete line 4 'line 5', ]; assertComputeEdits(file1, file2); }); test('maintains undo for same resource and same content', () => { const resource = URI.parse('file://test.txt'); // create a model const model1 = modelService.createModel('text', null, resource); // make an edit model1.pushEditOperations(null, [{ range: new Range(1, 5, 1, 5), text: '1' }], () => [new Selection(1, 5, 1, 5)]); assert.strictEqual(model1.getValue(), 'text1'); // dispose it modelService.destroyModel(resource); // create a new model with the same content const model2 = modelService.createModel('text1', null, resource); // undo model2.undo(); assert.strictEqual(model2.getValue(), 'text'); }); test('maintains version id and alternative version id for same resource and same content', () => { const resource = URI.parse('file://test.txt'); // create a model const model1 = modelService.createModel('text', null, resource); // make an edit model1.pushEditOperations(null, [{ range: new Range(1, 5, 1, 5), text: '1' }], () => [new Selection(1, 5, 1, 5)]); assert.strictEqual(model1.getValue(), 'text1'); const versionId = model1.getVersionId(); const alternativeVersionId = model1.getAlternativeVersionId(); // dispose it modelService.destroyModel(resource); // create a new model with the same content const model2 = modelService.createModel('text1', null, resource); assert.strictEqual(model2.getVersionId(), versionId); assert.strictEqual(model2.getAlternativeVersionId(), alternativeVersionId); }); test('does not maintain undo for same resource and different content', () => { const resource = URI.parse('file://test.txt'); // create a model const model1 = modelService.createModel('text', null, resource); // make an edit model1.pushEditOperations(null, [{ range: new Range(1, 5, 1, 5), text: '1' }], () => [new Selection(1, 5, 1, 5)]); assert.strictEqual(model1.getValue(), 'text1'); // dispose it modelService.destroyModel(resource); // create a new model with the same content const model2 = modelService.createModel('text2', null, resource); // undo model2.undo(); assert.strictEqual(model2.getValue(), 'text2'); }); test('setValue should clear undo stack', () => { const resource = URI.parse('file://test.txt'); const model = modelService.createModel('text', null, resource); model.pushEditOperations(null, [{ range: new Range(1, 5, 1, 5), text: '1' }], () => [new Selection(1, 5, 1, 5)]); assert.strictEqual(model.getValue(), 'text1'); model.setValue('text2'); model.undo(); assert.strictEqual(model.getValue(), 'text2'); }); }); suite('ModelSemanticColoring', () => { const disposables = new DisposableStore(); const ORIGINAL_FETCH_DOCUMENT_SEMANTIC_TOKENS_DELAY = ModelSemanticColoring.FETCH_DOCUMENT_SEMANTIC_TOKENS_DELAY; let modelService: IModelService; let modeService: IModeService; setup(() => { ModelSemanticColoring.FETCH_DOCUMENT_SEMANTIC_TOKENS_DELAY = 0; const configService = new TestConfigurationService({ editor: { semanticHighlighting: true } }); const themeService = new TestThemeService(); themeService.setTheme(new TestColorTheme({}, ColorScheme.DARK, true)); modelService = disposables.add(new ModelServiceImpl( configService, new TestTextResourcePropertiesService(configService), themeService, new NullLogService(), new UndoRedoService(new TestDialogService(), new TestNotificationService()) )); modeService = disposables.add(new ModeServiceImpl(false)); }); teardown(() => { disposables.clear(); ModelSemanticColoring.FETCH_DOCUMENT_SEMANTIC_TOKENS_DELAY = ORIGINAL_FETCH_DOCUMENT_SEMANTIC_TOKENS_DELAY; }); test('DocumentSemanticTokens should be fetched when the result is empty if there are pending changes', async () => { disposables.add(ModesRegistry.registerLanguage({ id: 'testMode' })); const inFirstCall = new Barrier(); const delayFirstResult = new Barrier(); const secondResultProvided = new Barrier(); let callCount = 0; disposables.add(DocumentSemanticTokensProviderRegistry.register('testMode', new class implements DocumentSemanticTokensProvider { getLegend(): SemanticTokensLegend { return { tokenTypes: ['class'], tokenModifiers: [] }; } async provideDocumentSemanticTokens(model: ITextModel, lastResultId: string | null, token: CancellationToken): Promise<SemanticTokens | SemanticTokensEdits | null> { callCount++; if (callCount === 1) { assert.ok('called once'); inFirstCall.open(); await delayFirstResult.wait(); await timeout(0); // wait for the simple scheduler to fire to check that we do actually get rescheduled return null; } if (callCount === 2) { assert.ok('called twice'); secondResultProvided.open(); return null; } assert.fail('Unexpected call'); } releaseDocumentSemanticTokens(resultId: string | undefined): void { } })); const textModel = disposables.add(modelService.createModel('Hello world', modeService.create('testMode'))); // wait for the provider to be called await inFirstCall.wait(); // the provider is now in the provide call // change the text buffer while the provider is running textModel.applyEdits([{ range: new Range(1, 1, 1, 1), text: 'x' }]); // let the provider finish its first result delayFirstResult.open(); // we need to check that the provider is called again, even if it returns null await secondResultProvided.wait(); // assert that it got called twice assert.strictEqual(callCount, 2); }); }); function assertComputeEdits(lines1: string[], lines2: string[]): void { const model = createTextModel(lines1.join('\n')); const textBuffer = createTextBuffer(lines2.join('\n'), DefaultEndOfLine.LF).textBuffer; // compute required edits // let start = Date.now(); const edits = ModelServiceImpl._computeEdits(model, textBuffer); // console.log(`took ${Date.now() - start} ms.`); // apply edits model.pushEditOperations([], edits, null); assert.strictEqual(model.getValue(), lines2.join('\n')); } function getRandomInt(min: number, max: number): number { return Math.floor(Math.random() * (max - min + 1)) + min; } function getRandomString(minLength: number, maxLength: number): string { let length = getRandomInt(minLength, maxLength); let t = createStringBuilder(length); for (let i = 0; i < length; i++) { t.appendASCII(getRandomInt(CharCode.a, CharCode.z)); } return t.build(); } function generateFile(small: boolean): string[] { let lineCount = getRandomInt(1, small ? 3 : 10000); let lines: string[] = []; for (let i = 0; i < lineCount; i++) { lines.push(getRandomString(0, small ? 3 : 10000)); } return lines; } if (GENERATE_TESTS) { let number = 1; while (true) { console.log('------TEST: ' + number++); const file1 = generateFile(true); const file2 = generateFile(true); console.log('------TEST GENERATED'); try { assertComputeEdits(file1, file2); } catch (err) { console.log(err); console.log(` const file1 = ${JSON.stringify(file1).replace(/"/g, '\'')}; const file2 = ${JSON.stringify(file2).replace(/"/g, '\'')}; assertComputeEdits(file1, file2); `); break; } } }
the_stack
module CorsicaTests { var AppBar = <typeof WinJS.UI.PrivateAppBar> WinJS.UI.AppBar; var Command = <typeof WinJS.UI.PrivateCommand> WinJS.UI.AppBarCommand; var _LightDismissService = <typeof WinJS.UI._LightDismissService>Helper.require("WinJS/_LightDismissService"); var Util = WinJS.Utilities; var _Constants = Helper.require("WinJS/Controls/AppBar/_Constants"); // Taking the registration mechanism as a parameter allows us to use this code to test both // DOM level 0 (e.g. onbeforeopen) and DOM level 2 (e.g. addEventListener) events. function testEvents(testElement, registerForEvent: (appBar: WinJS.UI.PrivateAppBar, eventName: string, handler: Function) => void) { var appBar = new AppBar(testElement); Helper.AppBar.useSynchronousAnimations(appBar); var counter = 0; registerForEvent(appBar, _Constants.EventNames.beforeOpen, () => { LiveUnit.Assert.areEqual(1, counter, _Constants.EventNames.beforeOpen + " fired out of order"); counter++; LiveUnit.Assert.isFalse(appBar.opened, _Constants.EventNames.beforeOpen + ": AppBar should not be in opened state"); }); registerForEvent(appBar, _Constants.EventNames.afterOpen, () => { LiveUnit.Assert.areEqual(2, counter, _Constants.EventNames.afterOpen + " fired out of order"); counter++; LiveUnit.Assert.isTrue(appBar.opened, _Constants.EventNames.afterOpen + ": AppBar should be in opened state"); }); registerForEvent(appBar, _Constants.EventNames.beforeClose, () => { LiveUnit.Assert.areEqual(4, counter, _Constants.EventNames.beforeClose + " fired out of order"); counter++; LiveUnit.Assert.isTrue(appBar.opened, _Constants.EventNames.beforeClose + ": AppBar should be in opened state"); }); registerForEvent(appBar, _Constants.EventNames.afterClose, () => { LiveUnit.Assert.areEqual(5, counter, _Constants.EventNames.afterClose + " fired out of order"); counter++; LiveUnit.Assert.isFalse(appBar.opened, _Constants.EventNames.afterClose + ": AppBar should not be in opened state"); }); LiveUnit.Assert.areEqual(0, counter, "before open: wrong number of events fired"); counter++; LiveUnit.Assert.isFalse(appBar.opened, "before open: AppBar should not be in opened state"); appBar.open(); LiveUnit.Assert.areEqual(3, counter, "after open: wrong number of events fired"); counter++; LiveUnit.Assert.isTrue(appBar.opened, "after open: AppBar should be in opened state"); appBar.close(); LiveUnit.Assert.areEqual(6, counter, "after close: wrong number of events fired"); LiveUnit.Assert.isFalse(appBar.opened, "after close: AppBar should not be in opened state"); } function failEventHandler(eventName: string, msg?: string) { return function () { LiveUnit.Assert.fail("Failure, " + eventName + " dectected: " + msg); }; } function disposeAndRemoveElement(element: HTMLElement) { if (element.winControl) { element.winControl.dispose(); } WinJS.Utilities.disposeSubTree(element); if (element.parentElement) { element.parentElement.removeChild(element); } } export class AppBarTests { "use strict"; _element: HTMLElement; setUp() { LiveUnit.LoggingCore.logComment("In setup"); var newNode = document.createElement("div"); newNode.id = "host"; document.body.appendChild(newNode); this._element = newNode; WinJS.Utilities.addClass(this._element, "file-appbar-css"); } tearDown() { if (this._element) { disposeAndRemoveElement(this._element) this._element = null; } } testConstruction() { var appBar = new AppBar(this._element); LiveUnit.Assert.isTrue(Util.hasClass(appBar.element, _Constants.ClassNames.controlCssClass), "AppBar missing control css class"); LiveUnit.Assert.isTrue(Util.hasClass(appBar.element, _Constants.ClassNames.disposableCssClass), "AppBar missing disposable css class"); } testAppendToDomAfterConstruction(complete) { this._element.style.width = "1000px"; var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "opt 1" }), new Command(null, { type: _Constants.typeButton, label: "opt 2" }) ]); var appBar = new AppBar(null, { data: data }); var insertedHandler = function () { appBar.element.removeEventListener("WinJSNodeInserted", insertedHandler); LiveUnit.Assert.areEqual(data.length, appBar._commandingSurface._primaryCommands.length, "Primary commands array has an invalid length"); LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); complete(); } appBar.element.addEventListener("WinJSNodeInserted", insertedHandler); this._element.appendChild(appBar.element); } testElementProperty() { var el = document.createElement("div"); var appBar = new AppBar(el); LiveUnit.Assert.areEqual(Util._uniqueID(el), Util._uniqueID(appBar.element), "The element passed in the constructor should be the appBar element"); appBar = new AppBar(); LiveUnit.Assert.isNotNull(appBar.element, "An element should be created when one is not passed to the constructor"); } testDataProperty() { // Verify default (empty) var appBar = new AppBar(this._element); LiveUnit.Assert.areEqual(0, appBar.data.length, "Empty AppBar should have length 0"); // Add some data var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "opt 1" }), new Command(null, { type: _Constants.typeButton, label: "opt 2" }) ]); appBar.data = data; LiveUnit.Assert.areEqual(2, appBar.data.length, "AppBar data has an invalid length"); } xtestBadData() { // TODO: Paramaterize CommandingSurface so that the control name in the exception is "AppBar", currently reads "_CommandingSurface" var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "opt 1" }), new Command(null, { type: _Constants.typeButton, label: "opt 2" }) ]); var appBar = new AppBar(this._element, { data: data }); // set data to invalid value var property = "data"; try { appBar[property] = { invalid: 1 }; } catch (e) { LiveUnit.Assert.areEqual("WinJS.UI.AppBar.BadData", e.name); // Ensure the value of data did not change LiveUnit.Assert.areEqual(2, appBar.data.length, "AppBar data has an invalid length"); } } testDeclarativeData() { // Verify that if the AppBar element contains children elements at construction, those elements are parsed as data. var el = document.createElement("div"); var child = document.createElement("table"); el.appendChild(child); var appBar: WinJS.UI.PrivateAppBar; try { new AppBar(el); } catch (e) { LiveUnit.Assert.areEqual("WinJS.UI._CommandingSurface.MustContainCommands", e.name, "AppBar should have thrown MustContainCommands exception"); } el = document.createElement("div"); var commandEl: HTMLElement; var numberOfCommands = 5; for (var i = 0; i < numberOfCommands; i++) { commandEl = document.createElement("button"); commandEl.setAttribute("data-win-control", "WinJS.UI.AppBarCommand"); el.appendChild(commandEl); } appBar = new AppBar(el); LiveUnit.Assert.areEqual(numberOfCommands, appBar.data.length, "AppBar declarative commands were not parsed as data."); } testDispose() { this._element.style.width = "10px"; var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "opt 1", section: 'primary' }), new Command(null, { type: _Constants.typeButton, label: "opt 2", section: 'secondary' }) ]); var appBar = new AppBar(this._element, { data: data }); Helper.AppBar.useSynchronousAnimations(appBar); appBar.open(); var msg = "Shouldn't have fired due to control being disposed"; appBar.onbeforeopen = failEventHandler(_Constants.EventNames.beforeOpen, msg); appBar.onbeforeclose = failEventHandler(_Constants.EventNames.beforeClose, msg); appBar.onafteropen = failEventHandler(_Constants.EventNames.afterOpen, msg); appBar.onafterclose = failEventHandler(_Constants.EventNames.afterClose, msg); var menuCommandProjections = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).map(function (element) { return <WinJS.UI.PrivateMenuCommand>element.winControl; }); appBar.dispose(); LiveUnit.Assert.isTrue(appBar._disposed, "AppBar didn't mark itself as disposed"); LiveUnit.Assert.isTrue(appBar._commandingSurface._disposed, "AppBar's commandingSurface was not disposed"); LiveUnit.Assert.isTrue(menuCommandProjections.every(function (menuCommand) { return menuCommand._disposed; }), "Disposing the AppBar should have disposed all the overflowarea MenuCommands."); LiveUnit.Assert.isTrue(appBar.data.every(function (command) { var privateCommand = <WinJS.UI.PrivateCommand>command; return privateCommand._disposed; }), "Disposing the AppBar should have disposed all of its commands."); // Events should not fire appBar.close(); appBar.open(); } testDoubleDispose() { var appBar = new AppBar(); LiveUnit.Assert.isTrue(appBar.dispose); LiveUnit.Assert.isFalse(appBar._disposed); // Double dispose sentinel var sentinel: any = document.createElement("div"); sentinel.disposed = false; WinJS.Utilities.addClass(sentinel, "win-disposable"); appBar.element.appendChild(sentinel); sentinel.dispose = function () { if (sentinel.disposed) { LiveUnit.Assert.fail("Unexpected double dispose occured."); } sentinel.disposed = true; }; appBar.dispose(); LiveUnit.Assert.isTrue(sentinel.disposed); LiveUnit.Assert.isTrue(appBar._disposed); appBar.dispose(); } testVerifyDefaultTabIndex() { var appBar = new AppBar(); LiveUnit.Assert.areEqual("-1", appBar.element.getAttribute("tabIndex"), "AppBar should've assigned a default tabIndex"); var el = document.createElement("div"); el.setAttribute("tabIndex", "4"); appBar = new AppBar(el); LiveUnit.Assert.areEqual("4", appBar.element.getAttribute("tabIndex"), "AppBar should have not assigned a default tabIndex"); } testAria() { var appBar = new AppBar(); LiveUnit.Assert.areEqual("menubar", appBar.element.getAttribute("role"), "Missing default aria role"); LiveUnit.Assert.areEqual("App Bar", appBar.element.getAttribute("aria-label"), "Missing default aria label"); var el = document.createElement("div"); appBar = new AppBar(el); el.setAttribute("role", "list"); el.setAttribute("aria-label", "myList"); LiveUnit.Assert.areEqual("list", appBar.element.getAttribute("role"), "AppBar should have not set a default aria role"); LiveUnit.Assert.areEqual("myList", appBar.element.getAttribute("aria-label"), "AppBar should have not set a default aria label"); } testOverflowButtonHiddenWithoutSecondaryCommands() { this._element.style.width = "1000px"; var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "opt 1" }), new Command(null, { type: _Constants.typeButton, label: "opt 2" }) ]); var appBar = new AppBar(this._element, { data: data }); LiveUnit.Assert.areEqual(data.length, appBar._commandingSurface._primaryCommands.length, "Primary commands array has an invalid length"); LiveUnit.Assert.areEqual(0, appBar._commandingSurface._secondaryCommands.length, "Secondary commands array has an invalid length"); } testOverflowButtonVisibleForSecondaryCommand() { this._element.style.width = "1000px"; var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "opt 1" }), new Command(null, { type: _Constants.typeButton, label: "opt 2", section: _Constants.secondaryCommandSection }) ]); var appBar = new AppBar(this._element, { data: data }); LiveUnit.Assert.areEqual(1, appBar._commandingSurface._primaryCommands.length, "Primary commands array has an invalid length"); LiveUnit.Assert.areEqual(1, appBar._commandingSurface._secondaryCommands.length, "Secondary commands array has an invalid length"); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); } testOverflowButtonVisibleForOverflowingPrimaryCommand() { this._element.style.width = "10px"; var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "opt 1" }), new Command(null, { type: _Constants.typeButton, label: "opt 2" }) ]); var appBar = new AppBar(this._element, { data: data }); LiveUnit.Assert.areEqual(data.length, appBar._commandingSurface._primaryCommands.length, "Primary commands array has an invalid length"); LiveUnit.Assert.areEqual(0, appBar._commandingSurface._secondaryCommands.length, "Secondary commands array has an invalid length"); } testForceLayout() { // Verify that force layout will correctly update commands layout when: // 1. The AppBar constructor could not measure any of the commands because the AppBar element was originally display "none". // 2. The width of the AppBar itself has changed. // 3. The width of content commands in the AppBar have changed var customContentBoxWidth = 100; var customEl = document.createElement("div"); customEl.style.width = customContentBoxWidth + "px"; customEl.style.height = "50px"; this._element.style.display = "none"; this._element.style.width = "1000px"; var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "opt 1" }), new Command(customEl, { type: _Constants.typeContent, label: "opt 2" }), new Command(null, { type: _Constants.typeButton, label: "sec opt 1", section: _Constants.secondaryCommandSection }) ]); var appBar = new AppBar(this._element, { data: data, closedDisplayMode: AppBar.ClosedDisplayMode.compact, }); // The measurement stage of the CommandLayoutPipeline should have failed because our element was display "none". // Therefore, the layout stage should not have been reached and not even secondary commands will have made it into the overflow area yet. // Sanity check our test expectations before we begin. LiveUnit.Assert.areEqual(2, appBar._commandingSurface._primaryCommands.length, "TEST ERROR: Primary commands array has an invalid length"); LiveUnit.Assert.areEqual(1, appBar._commandingSurface._secondaryCommands.length, "TEST ERROR: Secondary commands array has an invalid length"); LiveUnit.Assert.areEqual(3, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "TEST ERROR: until a layout can occur, actionarea should have 3 commands"); LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "TEST ERROR: until a layout can occur, overflowarea should have 0 commands"); // Restore the display, then test forceLayout this._element.style.display = ""; appBar.forceLayout(); LiveUnit.Assert.areEqual(2, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "actionarea should have 2 commands"); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "overflowarea should have 1 commands"); // Decrease the width of the AppBar so that it is 1px too thin to fit both primary commands, then test forceLayout. var customContentTotalWidth = appBar._commandingSurface._getCommandWidth(data.getAt(1)); var args: Helper._CommandingSurface.ISizeForCommandsArgs = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 1, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: customContentTotalWidth - 1, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "actionarea should have 1 commands"); LiveUnit.Assert.areEqual(3 /* 1 primary command + 1 separator + 1 secondary command */, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "overflowarea should have 3 commands"); // Decrease width of content command by 1px so that both primary commands will fit in the action area, then test forceLayout customContentBoxWidth--; customEl.style.width = customContentBoxWidth + "px" appBar.forceLayout(); LiveUnit.Assert.areEqual(2, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "actionarea should have 2 commands"); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "overflowarea should have 1 command"); } testResizeHandler() { // Verify that the resize handler knows how to correctly re-layout commands if the CommandingSurface width has changed. // - while the control is closed. // - while the control is opened. // Typically the resizeHandler is only called by the window resize event. // Test all closedDisplayModes https://github.com/winjs/winjs/issues/1183 Object.keys(AppBar.ClosedDisplayMode).forEach((mode) => { var prefix = "closedDisplayMode: " + mode + ", "; // ClosedDisplayMode: "none" can't measure or layout commands while closed because element.style.display is none. // ClosedDisplayMode: "minimal" can't layout commands correctly while closed because all commands are display: "none". var doesModeSupportVisibleCommandsWhileClosed = (mode === AppBar.ClosedDisplayMode.compact || mode === AppBar.ClosedDisplayMode.full); // Make sure everything will fit. var appBarElement = document.createElement("DIV"); appBarElement.style.width = "1000px"; this._element.appendChild(appBarElement); var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "opt 1" }), new Command(null, { type: _Constants.typeButton, label: "opt 2" }), new Command(null, { type: _Constants.typeButton, label: "sec opt 1", section: _Constants.secondaryCommandSection }) ]); var appBar = new AppBar(appBarElement, { data: data, opened: false, closedDisplayMode: mode, }); Helper.AppBar.useSynchronousAnimations(appBar); if (doesModeSupportVisibleCommandsWhileClosed) { LiveUnit.Assert.areEqual(2, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "TEST ERROR: " + prefix + "Test expects actionarea should have 2 commands at start"); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "TEST ERROR: " + prefix + "Test expects overflowarea should have 1 command at start"); } // Decrease the width of our control to fit exactly 1 command + the overflow button in the actionarea. var args: Helper._CommandingSurface.ISizeForCommandsArgs = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 1, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(appBar.element, args); // Ensure that the resizeHandler will have overflowed all but one primary command into the overflowarea WinJS.Utilities._resizeNotifier._handleResize(); if (doesModeSupportVisibleCommandsWhileClosed) { // Verify commands laid our correctly while closed. LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, prefix + "closed actionarea should have 1 command after width decrease"); LiveUnit.Assert.areEqual(3 /* 1 primary command + 1 separator + 1 secondary command */, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, prefix + "closed overflowarea should have 3 commands after width decrease"); } // Verify commands are laid out correctly, the first time the control is opened following a resize. appBar.open(); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, prefix + "actionarea should have 1 command after opening"); LiveUnit.Assert.areEqual(3 /* 1 primary command + 1 separator + 1 secondary command */, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, prefix + "overflowarea should have 3 commands after opening"); // Increase element size while opened, and verify the resizeHandler has reflowed all primary commands // back into the action area. appBarElement.style.width = "1000px"; WinJS.Utilities._resizeNotifier._handleResize(); LiveUnit.Assert.areEqual(2, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, prefix + "opened actionarea should have 2 commands after width increase"); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, prefix + "opened overflowarea should have 1 command after width increase"); disposeAndRemoveElement(appBar.element); }); } testSeparatorAddedBetweenPrimaryAndSecondary() { this._element.style.width = "10px"; var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "opt 1" }), new Command(null, { type: _Constants.typeButton, label: "opt 2", section: _Constants.secondaryCommandSection }) ]); var appBar = new AppBar(this._element, { data: data }); var overflowCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea); LiveUnit.Assert.areEqual(3, overflowCommands.length, "Menu commands list has an invalid length"); LiveUnit.Assert.areEqual("opt 1", overflowCommands[0].winControl.label); LiveUnit.Assert.areEqual(_Constants.typeSeparator, overflowCommands[1].winControl.type); LiveUnit.Assert.areEqual("opt 2", overflowCommands[2].winControl.label); } testOverflowBehaviorOfCustomContent() { var customEl = document.createElement("div"); customEl.style.width = "2000px"; customEl.style.height = "50px"; var data = new WinJS.Binding.List([ new Command(customEl, { type: _Constants.typeContent, label: "1", extraClass: "c1" }), ]); this._element.style.width = "200px"; var appBar = new AppBar(this._element, { data: data }); LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); // Custom content should overflow as a flyout menu item var menuCommand = <WinJS.UI.MenuCommand>(Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea)[0]["winControl"]); LiveUnit.Assert.areEqual(_Constants.typeFlyout, menuCommand.type, "Custom content should overflow with type flyout"); LiveUnit.Assert.areEqual(appBar._commandingSurface._contentFlyout, menuCommand.flyout, "Invalid flyout target for custom command in the overflowarea"); LiveUnit.Assert.areEqual("1", menuCommand.label, "Invalid label for custom command in the overflowarea"); LiveUnit.Assert.areEqual("c1", menuCommand.extraClass, "Invalid extraClass for custom command in the overflowarea"); } testOverflowBehaviorOfButtonCommand(complete) { WinJS.Utilities.markSupportedForProcessing(complete); var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "1", extraClass: "c1", disabled: true, onclick: Helper._CommandingSurface.getVisibleCommandsInElement }), new Command(null, { type: _Constants.typeButton, label: "2", extraClass: "c2", disabled: false, onclick: complete }), ]); this._element.style.width = "10px"; var appBar = new AppBar(this._element, { data: data }); LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(2, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); var menuCommand = <WinJS.UI.MenuCommand>(Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea)[0]["winControl"]); LiveUnit.Assert.areEqual(_Constants.typeButton, menuCommand.type, "Invalid menuCommand type"); LiveUnit.Assert.isNull(menuCommand.flyout, "Flyout target for button should be null"); LiveUnit.Assert.areEqual("1", menuCommand.label, "Invalid menuCommand label"); LiveUnit.Assert.areEqual("c1", menuCommand.extraClass, "Invalid menuCommand extraClass"); LiveUnit.Assert.isTrue(menuCommand.disabled, "Invalid menuCommand disabled property value"); LiveUnit.Assert.areEqual(Helper._CommandingSurface.getVisibleCommandsInElement, menuCommand.onclick, "Invalid menuCommand onclick property value"); menuCommand = <WinJS.UI.MenuCommand>(Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea)[1]["winControl"]); LiveUnit.Assert.areEqual(_Constants.typeButton, menuCommand.type, "Invalid menuCommand type"); LiveUnit.Assert.isNull(menuCommand.flyout, "Flyout target for button should be null"); LiveUnit.Assert.areEqual("2", menuCommand.label, "Invalid menuCommand label"); LiveUnit.Assert.areEqual("c2", menuCommand.extraClass, "Invalid menuCommand extraClass"); LiveUnit.Assert.isFalse(menuCommand.disabled, "Invalid menuCommand disabled property value"); LiveUnit.Assert.areEqual(complete, menuCommand.onclick, "Invalid menuCommand onclick property value"); // Verify onclick calls complete menuCommand.element.click(); } testOverflowBehaviorOfToggleCommand() { var clickWasHandled = false; function test_handleClick(event) { clickWasHandled = true; LiveUnit.Assert.isFalse(event.target.winControl.selected, "Invalid menuCommand selected property value"); } WinJS.Utilities.markSupportedForProcessing(test_handleClick); var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeToggle, label: "1", extraClass: "c1", selected: true, onclick: test_handleClick }), new Command(null, { type: _Constants.typeButton, label: "2", extraClass: "c2", disabled: true, onclick: test_handleClick }), ]); this._element.style.width = "10px"; var appBar = new AppBar(this._element, { data: data }); LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(2, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); var menuCommand = <WinJS.UI.MenuCommand>(Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea)[0]["winControl"]); LiveUnit.Assert.areEqual(_Constants.typeToggle, menuCommand.type, "Invalid menuCommand type"); LiveUnit.Assert.isNull(menuCommand.flyout, "Flyout target for button should be null"); LiveUnit.Assert.areEqual("1", menuCommand.label, "Invalid menuCommand label"); LiveUnit.Assert.areEqual("c1", menuCommand.extraClass, "Invalid menuCommand extraClass"); LiveUnit.Assert.isFalse(menuCommand.disabled, "Invalid menuCommand disabled property value"); LiveUnit.Assert.isTrue(menuCommand.selected, "Invalid menuCommand selected property value"); LiveUnit.Assert.areEqual(test_handleClick, menuCommand.onclick, "Invalid menuCommand onclick property value"); menuCommand.element.click(); LiveUnit.Assert.isTrue(clickWasHandled, "menuCommand click behavior not functioning"); } testOverflowBehaviorOfToggleCommandChangingValues() { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeToggle, label: "1", extraClass: "c1", selected: true }), new Command(null, { type: _Constants.typeButton, label: "2", extraClass: "c2", disabled: true }), ]); this._element.style.width = "10px"; var appBar = new AppBar(this._element, { data: data, closedDisplayMode: AppBar.ClosedDisplayMode.compact, }); var menuCommand = <WinJS.UI.MenuCommand>(Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea)[0]["winControl"]); LiveUnit.Assert.isTrue(menuCommand.selected, "Invalid menuCommand selected property value"); // Deselect the toggle button in the menu var menuCommandEl = (<HTMLElement> appBar._commandingSurface._dom.overflowArea.children[0]); menuCommandEl.click(); // Increase the size of the control to fit both commands. var args: Helper._CommandingSurface.ISizeForCommandsArgs = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 2, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: false, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); // Ensure that the command in the actionarea now has the toggle de-selected var command = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea)[0]; LiveUnit.Assert.isFalse(command.winControl.selected, "Invalid menuCommand selected property value"); } testOverflowBehaviorOfFlyoutCommand(complete) { var flyout = new WinJS.UI.Flyout(); this._element.parentElement.appendChild(flyout.element); var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeFlyout, label: "1", extraClass: "c1", flyout: flyout }), new Command(null, { type: _Constants.typeButton, label: "2", extraClass: "c2", disabled: true }), ]); this._element.style.width = "10px"; var appBar = new AppBar(this._element, { data: data }); LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(2, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); var menuCommand = <WinJS.UI.MenuCommand>(Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea)[0]["winControl"]); LiveUnit.Assert.areEqual(_Constants.typeFlyout, menuCommand.type, "Invalid menuCommand type"); LiveUnit.Assert.areEqual(flyout, menuCommand.flyout, "Invalid menuCommand flyout property value"); LiveUnit.Assert.areEqual("1", menuCommand.label, "Invalid menuCommand label"); LiveUnit.Assert.areEqual("c1", menuCommand.extraClass, "Invalid menuCommand extraClass"); LiveUnit.Assert.isFalse(menuCommand.disabled, "Invalid menuCommand disabled property value"); menuCommand.element.click(); flyout.addEventListener("aftershow", function afterShow() { flyout.removeEventListener("aftershow", afterShow, false); flyout.dispose() flyout.element.parentElement.removeChild(flyout.element); complete(); }, false); } testOverflowBehaviorOfSeparatorCommand() { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "2", extraClass: "c2", disabled: true }), new Command(null, { type: _Constants.typeSeparator }), ]); this._element.style.width = "10px"; var appBar = new AppBar(this._element, { data: data }); LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); var menuCommand = appBar._commandingSurface._dom.overflowArea.querySelectorAll(_Constants.commandSelector)[1]["winControl"]; LiveUnit.Assert.areEqual(_Constants.typeSeparator, menuCommand.type, "Invalid menuCommand type"); } testOverflowBehaviorDefaultPriority() { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "1" }), new Command(null, { type: _Constants.typeSeparator, label: "2" }), new Command(null, { type: _Constants.typeButton, label: "3" }), new Command(null, { type: _Constants.typeButton, label: "4" }), new Command(null, { type: _Constants.typeSeparator, label: "5" }), new Command(null, { type: _Constants.typeButton, label: "6" }), ]); var appBar = new AppBar(this._element, { data: data, closedDisplayMode: AppBar.ClosedDisplayMode.compact, }); // Make sure everything fits, nothing should overflow var args: Helper._CommandingSurface.ISizeForCommandsArgs = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 4, numSeparatorsShownInActionArea: 2, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: false, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(6, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); // Decrease size to overflow 1 command args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 3, numSeparatorsShownInActionArea: 2, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(5 - 1 /* trailing separator is hidden */, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); // Increase size to put command back into the actionarea args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 4, numSeparatorsShownInActionArea: 2, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: false, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(6, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); // Decrease size to overflow 2 commands args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 3, numSeparatorsShownInActionArea: 1, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(4, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(2 - 1 /* leading separator is hidden */, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); // Decrease size to overflow 3 commands args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 2, numSeparatorsShownInActionArea: 1, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(3, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(3, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); // Decrease size to overflow 4 commands args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 1, numSeparatorsShownInActionArea: 1, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(2 - 1 /* trailing separator is hidden */, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(4, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); // Decrease size to overflow 5 commands args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 1, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(5 - 1 /* leading separator is hidden */, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); // Decrease size to overflow 6 commands args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 0, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: false, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(6, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); } testOverflowBehaviorDefaultPriorityWithCustomContent() { var customEl1 = document.createElement("div"); customEl1.style.width = "200px"; customEl1.style.height = "50px"; var customEl2 = document.createElement("div"); customEl2.style.width = "350px"; customEl2.style.height = "50px"; var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "1" }), new Command(customEl1, { type: _Constants.typeContent, label: "2" }), new Command(customEl2, { type: _Constants.typeContent, label: "3" }), ]); var appBar = new AppBar(this._element, { data: data, closedDisplayMode: AppBar.ClosedDisplayMode.compact, }); var customContent1Width = appBar._commandingSurface._getCommandWidth(data.getAt(1)); var customContent2Width = appBar._commandingSurface._getCommandWidth(data.getAt(2)); // Make sure everything fits, nothing should overflow var args: Helper._CommandingSurface.ISizeForCommandsArgs = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 1, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: customContent1Width + customContent2Width, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(3, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); // Decrease size to overflow 1 command args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 1, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: customContent1Width, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(2, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); // Decrease size to overflow 2 commands args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 1, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: customContent1Width - 1, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(2, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); } testOverflowBehaviorCustomPriorityContentInFlyout(complete) { var createCustomElement = (text: string) => { var customEl = document.createElement("div"); var customContent = document.createElement("div"); customContent.style.width = "200px"; customContent.style.height = "50px"; customContent.innerHTML = text; customContent.style.backgroundColor = "red"; customEl.appendChild(customContent); return customEl; } var data = new WinJS.Binding.List([ new Command(createCustomElement("custom 1"), { type: _Constants.typeContent, label: "1", priority: 5, section: _Constants.secondaryCommandSection }), new Command(createCustomElement("custom 2"), { type: _Constants.typeContent, label: "2", priority: 5, section: _Constants.secondaryCommandSection }), ]); var appBar = new AppBar(this._element, { data: data, opened: true }); // Click on the first menu item var menuCommand = (<HTMLElement> appBar._commandingSurface._dom.overflowArea.children[0]); menuCommand.click(); LiveUnit.Assert.areEqual("custom 1", appBar._commandingSurface._contentFlyoutInterior.textContent, "The custom content flyout has invalid content"); var testSecondCommandClick = () => { appBar._commandingSurface._contentFlyout.removeEventListener("afterhide", testSecondCommandClick); // Click on the second menu item menuCommand = (<HTMLElement> appBar._commandingSurface._dom.overflowArea.children[1]); menuCommand.click(); LiveUnit.Assert.areEqual("custom 2", appBar._commandingSurface._contentFlyoutInterior.textContent, "The custom content flyout has invalid content"); complete(); }; appBar._commandingSurface._contentFlyout.addEventListener("afterhide", testSecondCommandClick); appBar._commandingSurface._contentFlyout.hide(); } testOverflowBehaviorCustomPriority() { var customEl = document.createElement("div"); var customContent = document.createElement("div"); customContent.style.width = "200px"; customContent.style.height = "50px"; customContent.innerHTML = "custom 2"; customContent.style.backgroundColor = "red"; customEl.appendChild(customContent); var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "1", priority: 1 }), new Command(customEl, { type: _Constants.typeContent, label: "2", priority: 5 }), new Command(null, { type: _Constants.typeSeparator, priority: 2 }), new Command(null, { type: _Constants.typeButton, label: "3", priority: 3 }), new Command(null, { type: _Constants.typeButton, label: "4", priority: 2 }), new Command(null, { type: _Constants.typeButton, label: "5", priority: 4 }), new Command(null, { type: _Constants.typeSeparator, priority: 5 }), new Command(null, { type: _Constants.typeButton, label: "6", priority: 5 }), new Command(null, { type: _Constants.typeButton, label: "sec 1", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "sec 2", section: _Constants.secondaryCommandSection }), ]); var appBar = new AppBar(this._element, { data: data, closedDisplayMode: AppBar.ClosedDisplayMode.compact, }); var customContentWidth = appBar._commandingSurface._getCommandWidth(data.getAt(1)); // Make sure everything fits, nothing should overflow var args: Helper._CommandingSurface.ISizeForCommandsArgs = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 5, numSeparatorsShownInActionArea: 2, widthOfContentCommandsShownInActionArea: customContentWidth, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(8, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); LiveUnit.Assert.areEqual(2, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Menu commands list has an invalid length"); // Decrease size to overflow priority 5 commands args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 5, numSeparatorsShownInActionArea: 2, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: customContentWidth - 1, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(5, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); var expectedMenuCommands = 6 /* 2 secondary commands + 1 separator + 2 primary commands with 1 separator */; var visibleMenuCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea); LiveUnit.Assert.areEqual(expectedMenuCommands, visibleMenuCommands.length, "Menu commands list has an invalid length"); Helper._CommandingSurface.verifyOverflowMenuContent(visibleMenuCommands, ["2", _Constants.typeSeparator, "6", _Constants.typeSeparator, "sec 1", "sec 2"]); // Decrease size to overflow priority 4 commands args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 3, numSeparatorsShownInActionArea: 1, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(4, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); var expectedMenuCommands = 7 /* 2 secondary commands + 1 separator + 3 primary commands with 1 separator */; var visibleMenuCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea); LiveUnit.Assert.areEqual(expectedMenuCommands, visibleMenuCommands.length, "Menu commands list has an invalid length"); Helper._CommandingSurface.verifyOverflowMenuContent(visibleMenuCommands, ["2", "5", _Constants.typeSeparator, "6", _Constants.typeSeparator, "sec 1", "sec 2"]); // Decrease size to overflow priority 3 commands args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 2, numSeparatorsShownInActionArea: 1, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(3, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); var expectedMenuCommands = 8 /* 2 secondary commands + 1 separator + 4 primary commands with 1 separator */; var visibleMenuCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea); LiveUnit.Assert.areEqual(expectedMenuCommands, visibleMenuCommands.length, "Menu commands list has an invalid length"); Helper._CommandingSurface.verifyOverflowMenuContent(visibleMenuCommands, ["2", "3", "5", _Constants.typeSeparator, "6", _Constants.typeSeparator, "sec 1", "sec 2"]); // Decrease size to overflow priority 2 commands args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 1, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); var expectedMenuCommands = 10 /* 2 secondary commands + 1 separator + 5 primary commands with 2 separators */; var visibleMenuCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea); LiveUnit.Assert.areEqual(expectedMenuCommands, visibleMenuCommands.length, "Menu commands list has an invalid length"); Helper._CommandingSurface.verifyOverflowMenuContent(visibleMenuCommands, ["2", _Constants.typeSeparator, "3", "4", "5", _Constants.typeSeparator, "6", _Constants.typeSeparator, "sec 1", "sec 2"]); // Decrease size to overflow priority 1 commands args = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 0, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Invalid number of commands in the actionarea"); var expectedMenuCommands = 11 /* 2 secondary commands + 1 separator + 6 primary commands with 2 separator */; var visibleMenuCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea); LiveUnit.Assert.areEqual(expectedMenuCommands, visibleMenuCommands.length, "Menu commands list has an invalid length"); Helper._CommandingSurface.verifyOverflowMenuContent(visibleMenuCommands, ["1", "2", _Constants.typeSeparator, "3", "4", "5", _Constants.typeSeparator, "6", _Constants.typeSeparator, "sec 1", "sec 2"]); } testMinWidth() { this._element.style.width = "10px"; var appBar = new AppBar(this._element); LiveUnit.Assert.areEqual(_Constants.controlMinWidth, parseInt(getComputedStyle(this._element).width, 10), "Invalid min width of appBar element"); } testOverflowAreaContainerHeightWhenThereIsNoOverflow() { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeContent, label: "1" }), new Command(null, { type: _Constants.typeContent, label: "2" }), ]); var appBar = new AppBar(this._element, { data: data }); LiveUnit.Assert.areEqual(0, WinJS.Utilities._getPreciseTotalHeight(appBar._commandingSurface._dom.overflowArea), "Invalid height for the overflowarea container when there are no commands that overflow"); } xtestOverflowAreaContainerSize() { // TODO Finish redline changes and then reimplement var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "1" }), new Command(null, { type: _Constants.typeButton, label: "2" }), new Command(null, { type: _Constants.typeButton, label: "3" }), new Command(null, { type: _Constants.typeButton, label: "4" }), new Command(null, { type: _Constants.typeButton, label: "5" }), new Command(null, { type: _Constants.typeButton, label: "6" }), new Command(null, { type: _Constants.typeButton, label: "1", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label this is a really long label ", section: _Constants.secondaryCommandSection }), ]); this._element.style.width = "10px"; var appBar = new AppBar(this._element, { data: data, opened: true, closedDisplayMode: AppBar.ClosedDisplayMode.compact, }); // Make sure primary commands fit exactly var args: Helper._CommandingSurface.ISizeForCommandsArgs = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 6, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); LiveUnit.Assert.areEqual(2, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "There should only be 2 commands in the overflowarea"); LiveUnit.Assert.areEqual(2 * _Constants.overflowCommandHeight, WinJS.Utilities._getPreciseTotalHeight(appBar._commandingSurface._dom.overflowArea), "Invalid height for the overflowarea container"); LiveUnit.Assert.areEqual(parseInt(this._element.style.width), WinJS.Utilities._getPreciseTotalWidth(appBar._commandingSurface._dom.overflowArea), "Invalid width for the overflowarea container"); LiveUnit.Assert.areEqual(appBar.element, appBar._commandingSurface._dom.overflowArea.parentNode, "Invalid parent for the overflowarea container"); LiveUnit.Assert.areEqual(appBar.element, appBar._commandingSurface._dom.actionArea.parentNode, "Invalid parent for the actionarea container"); } xtestOverflowMaxHeightForOnlySecondaryCommands() { // TODO Finish redline changes and then reimplement var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "1", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "2", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "3", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "4", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "5", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "6", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "7", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "8", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "9", section: _Constants.secondaryCommandSection }), ]); this._element.style.width = "1000px"; var appBar = new AppBar(this._element, { data: data, opened: true }); LiveUnit.Assert.areEqual(4.5 * _Constants.overflowCommandHeight, WinJS.Utilities._getPreciseTotalHeight(appBar._commandingSurface._dom.overflowArea), "Invalid height for the overflowarea container"); LiveUnit.Assert.areEqual(9, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "There should be 9 commands in the overflowarea"); } xtestOverflowMaxHeightForMixedCommands() { // TODO Finish redline changes and then reimplement var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "1" }), new Command(null, { type: _Constants.typeButton, label: "2" }), new Command(null, { type: _Constants.typeButton, label: "3" }), new Command(null, { type: _Constants.typeButton, label: "4" }), new Command(null, { type: _Constants.typeButton, label: "5" }), new Command(null, { type: _Constants.typeButton, label: "6" }), new Command(null, { type: _Constants.typeButton, label: "7" }), new Command(null, { type: _Constants.typeButton, label: "8" }), new Command(null, { type: _Constants.typeButton, label: "s1", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "s2", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "s3", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "s4", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "s5", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "s6", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "s7", section: _Constants.secondaryCommandSection }), ]); this._element.style.width = "320px"; var appBar = new AppBar(this._element, { data: data, opened: true }); LiveUnit.Assert.areEqual(4.5 * _Constants.overflowCommandHeight, WinJS.Utilities._getPreciseTotalHeight(appBar._commandingSurface._dom.overflowArea), "Invalid height for the overflowarea container"); } testDataEdits(complete) { var Key = WinJS.Utilities.Key; var firstEL = document.createElement("button"); var data = new WinJS.Binding.List([ new Command(firstEL, { type: _Constants.typeButton, label: "1" }), new Command(null, { type: _Constants.typeButton, label: "2" }), new Command(null, { type: _Constants.typeButton, label: "3" }), new Command(null, { type: _Constants.typeButton, label: "4" }), new Command(null, { type: _Constants.typeButton, label: "s1", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "s2", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "s3", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeContent, label: "content", section: _Constants.secondaryCommandSection }), ]); this._element.style.width = "10px"; var appBar = new AppBar(this._element, { data: data, closedDisplayMode: AppBar.ClosedDisplayMode.compact, }); // Limit the width of the control to fit only 3 commands. var args: Helper._CommandingSurface.ISizeForCommandsArgs = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 3, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); // The actionarea should now show | 1 | 2 | 3 | ... | LiveUnit.Assert.areEqual(3, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length); // Delete item wth label 3 appBar.data.splice(2, 1); WinJS.Utilities.Scheduler.schedule(() => { LiveUnit.Assert.areEqual("4", Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea)[2].textContent); // The actionarea should now show | 1 | 2 | 4 | ... | LiveUnit.Assert.areEqual(3, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length); appBar.data.splice(0, 0, new Command(null, { type: _Constants.typeButton, label: "new" })); WinJS.Utilities.Scheduler.schedule(() => { var visibleCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea); LiveUnit.Assert.areEqual("new", visibleCommands[0].textContent); LiveUnit.Assert.areEqual("1", visibleCommands[1].textContent); LiveUnit.Assert.areEqual("2", visibleCommands[2].textContent); // The actionarea should now show | new | 1 | 2 | ... | LiveUnit.Assert.areEqual(3, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length); // Force all commands into the overflowarea this._element.style.width = "10px"; appBar.forceLayout(); // Delete the first command and verify AppBar Dom updates. // Also verify that we dispose the deleted command's associated MenuCommand projection. var deletedCommand = appBar.data.splice(data.length - 1, 1)[0]; // PRECONDITION: Sanity check that the command we got back is our content command. LiveUnit.Assert.areEqual(_Constants.typeContent, deletedCommand.type); var deletedMenuCommand = Helper._CommandingSurface.getProjectedCommandFromOriginalCommand(appBar._commandingSurface, deletedCommand); WinJS.Utilities.Scheduler.schedule(() => { LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length); LiveUnit.Assert.areEqual(8, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length); LiveUnit.Assert.isTrue(deletedMenuCommand._disposed, "Removing a command from the CommandingSurface's overflowarea should dispose the associated menucommand projection"); LiveUnit.Assert.isFalse(appBar._commandingSurface._contentFlyout._disposed, "Disposing a menucommand projection should not dispose the CommandingSurface._contentFlyout"); complete(); }); }, WinJS.Utilities.Scheduler.Priority.high); }, WinJS.Utilities.Scheduler.Priority.high); } testDataEditEmptyScenario(complete) { var Key = WinJS.Utilities.Key; var firstEL = document.createElement("button"); var data = new WinJS.Binding.List([ new Command(firstEL, { type: _Constants.typeButton, label: "1" }), new Command(null, { type: _Constants.typeButton, label: "2" }), new Command(null, { type: _Constants.typeButton, label: "3" }), new Command(null, { type: _Constants.typeButton, label: "4" }), new Command(null, { type: _Constants.typeButton, label: "s1", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "s2", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "s3", section: _Constants.secondaryCommandSection }), new Command(null, { type: _Constants.typeButton, label: "s4", section: _Constants.secondaryCommandSection }), ]); this._element.style.width = "10px"; var appBar = new AppBar(this._element, { data: data, closedDisplayMode: AppBar.ClosedDisplayMode.compact, }); // Limit the width of the control to fit 3 commands. var args: Helper._CommandingSurface.ISizeForCommandsArgs = { closedDisplayMode: appBar.closedDisplayMode, numStandardCommandsShownInActionArea: 3, numSeparatorsShownInActionArea: 0, widthOfContentCommandsShownInActionArea: 0, isACommandVisbleInTheOverflowArea: true, additionalFreeSpace: 0, }; Helper._CommandingSurface.sizeForCommands(this._element, args); appBar.forceLayout(); // The actionarea should now show | 1 | 2 | 3 | ... | LiveUnit.Assert.areEqual(3, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length); var menuCommandProjections = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).map(function (element) { return <WinJS.UI.PrivateMenuCommand>element.winControl; }); // Delete all items appBar.data = new WinJS.Binding.List([]); WinJS.Utilities.Scheduler.schedule(() => { LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea).length, "Action area should be empty"); LiveUnit.Assert.areEqual(0, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Overflow area should be empty"); LiveUnit.Assert.isTrue(menuCommandProjections.every(function (menuCommand) { return menuCommand._disposed; }), "Setting new data should have disposed all previous overflowarea MenuCommand projections."); complete(); }, WinJS.Utilities.Scheduler.Priority.high); } testDataMutationsAreProjectedToOverflowCommands(complete) { // Verifies that mutations to an ICommand in the actionarea are reflected to that ICommand's MenuCommand projection // in the overflowarea, if such a projection exists. // var buttonCmd = new Command(null, { type: _Constants.typeButton, label: "button", section: 'primary', extraClass: "myClass", }); var toggleCmd = new Command(null, { type: _Constants.typeToggle, label: 'toggle', section: 'primary' }); var flyoutCmd = new Command(null, { type: _Constants.typeFlyout, label: "flyout", section: 'primary' }); var data = new WinJS.Binding.List([buttonCmd, toggleCmd, flyoutCmd]); this._element.style.width = "10px"; var appBar = new AppBar(this._element, { data: data, opened: true }); Helper.AppBar.useSynchronousAnimations(appBar); var startingLength = 3; // PRECONDITION: Test assumes there are 3 overflowing primary commands in the overflowarea. LiveUnit.Assert.areEqual(startingLength, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "TEST ERROR: Test expects 3 overflowing commands at the start"); // Commands in the overflowarea are all MenuCommand projections of the original ICommands in the actionarea. // These projections and the rest of the overflowarea are redrawn whenever the data in the binding list changes // or when certain properties of ICommands in the CommandingSurface are mutated. var projections = { get button() { return Helper._CommandingSurface.getProjectedCommandFromOriginalCommand(appBar._commandingSurface, buttonCmd); }, get toggle() { return Helper._CommandingSurface.getProjectedCommandFromOriginalCommand(appBar._commandingSurface, toggleCmd); }, get flyout() { return Helper._CommandingSurface.getProjectedCommandFromOriginalCommand(appBar._commandingSurface, flyoutCmd); } } var msg = " property of projected menucommand should have updated"; buttonCmd.label = "new label"; new WinJS.Promise((c) => { appBar._commandingSurface._layoutCompleteCallback = () => { LiveUnit.Assert.areEqual(buttonCmd.label, projections.button.label, "label" + msg); c(); }; }).then( () => { buttonCmd.disabled = true; return new WinJS.Promise((c) => { appBar._commandingSurface._layoutCompleteCallback = () => { LiveUnit.Assert.areEqual(buttonCmd.disabled, projections.button.disabled, "disabled" + msg); c(); }; }); } ).then( () => { buttonCmd.disabled = false; return new WinJS.Promise((c) => { appBar._commandingSurface._layoutCompleteCallback = () => { LiveUnit.Assert.areEqual(buttonCmd.disabled, projections.button.disabled, "disabled" + msg); c(); }; }); } ).then( () => { buttonCmd.extraClass = "new class"; return new WinJS.Promise((c) => { appBar._commandingSurface._layoutCompleteCallback = () => { LiveUnit.Assert.areEqual(buttonCmd.extraClass, projections.button.extraClass, "extraClass" + msg); c(); }; }); } ).then( () => { buttonCmd.onclick = () => { }; return new WinJS.Promise((c) => { appBar._commandingSurface._layoutCompleteCallback = () => { LiveUnit.Assert.areEqual(buttonCmd.onclick, projections.button.onclick, "onclick" + msg); c(); }; }); } ).then( () => { buttonCmd.hidden = true; return new WinJS.Promise((c) => { appBar._commandingSurface._layoutCompleteCallback = () => { LiveUnit.Assert.isNull(projections.button, "Setting hidden = true on an overflowing ICommand should remove its menucommand projection from the overflowarea"); LiveUnit.Assert.areEqual(startingLength - 1, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Setting hidden = true on an overflowing ICommand should remove its menucommand projection from the overflowarea"); c(); }; }); } ).then( () => { buttonCmd.hidden = false; return new WinJS.Promise((c) => { appBar._commandingSurface._layoutCompleteCallback = () => { LiveUnit.Assert.isNotNull(projections.button, "Setting hidden = false on an overflowing ICommand should add a menucommand projection of it to the overflowarea"); LiveUnit.Assert.areEqual(startingLength, Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea).length, "Setting hidden = false on an overflowing ICommand should add a menucommand projection of it to the overflowarea"); c(); }; }); } ).then( () => { toggleCmd.selected = true; return new WinJS.Promise((c) => { appBar._commandingSurface._layoutCompleteCallback = () => { LiveUnit.Assert.areEqual(toggleCmd.selected, projections.toggle.selected, "selected" + msg); c(); }; }); } ).then( () => { toggleCmd.selected = false; return new WinJS.Promise((c) => { appBar._commandingSurface._layoutCompleteCallback = () => { LiveUnit.Assert.areEqual(toggleCmd.selected, projections.toggle.selected, "selected" + msg); c(); }; }); } ).then( () => { var flyout = new WinJS.UI.Flyout(); flyoutCmd.flyout = flyout; return new WinJS.Promise((c) => { appBar._commandingSurface._layoutCompleteCallback = () => { LiveUnit.Assert.areEqual(flyoutCmd.flyout, projections.flyout.flyout, "flyout" + msg); flyout.dispose(); c(); }; }); } ).done(complete); } testSelectionAndGlobalSection() { // Values of "global" and "selection" are deprecated starting in WinJS 4.0. // Makes sure they are both just parsed as "primary" commands. this._element.style.width = "1000px"; var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "opt 1", section: 'selection' }), new Command(null, { type: _Constants.typeButton, label: "opt 2", section: 'global' }), new Command(null, { type: _Constants.typeButton, label: "opt 3", section: 'primary' }), new Command(null, { type: _Constants.typeButton, label: "opt 4", section: _Constants.secondaryCommandSection }) ]); var appBar = new AppBar(this._element, { data: data }); Helper._CommandingSurface.verifyActionAreaVisibleCommandsLabels(appBar._commandingSurface, ["opt 1", "opt 2", "opt 3"]); Helper._CommandingSurface.verifyOverflowAreaCommandsLabels(appBar._commandingSurface, ["opt 4"]); } testClosedDisplayModeConstructorOptions() { var appBar = new AppBar(); LiveUnit.Assert.areEqual(_Constants.defaultClosedDisplayMode, appBar.closedDisplayMode, "'closedDisplayMode' property has incorrect default value."); appBar.dispose(); Object.keys(AppBar.ClosedDisplayMode).forEach(function (mode) { appBar = new AppBar(null, { closedDisplayMode: mode }); LiveUnit.Assert.areEqual(mode, appBar.closedDisplayMode, "closedDisplayMode does not match the value passed to the constructor."); appBar.dispose(); }) } testClosedDisplayModes() { this._element.style.width = "1000px"; var contentElement = document.createElement("DIV"); contentElement.style.height = "100px"; contentElement.style.border = "none"; var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, icon: 'add', label: "button" }), new Command(null, { type: _Constants.typeSeparator }), new Command(contentElement, { type: _Constants.typeContent, label: "content" }), new Command(null, { type: _Constants.typeButton, section: 'secondary', label: "secondary" }), ]); var appBar = new AppBar(this._element, { data: data, opened: false, }); var msg = "Changing the closedDisplayMode property should not trigger this event"; appBar.onbeforeopen = failEventHandler(_Constants.EventNames.beforeOpen, msg); appBar.onbeforeclose = failEventHandler(_Constants.EventNames.beforeClose, msg); appBar.onafteropen = failEventHandler(_Constants.EventNames.afterOpen, msg); appBar.onafterclose = failEventHandler(_Constants.EventNames.afterClose, msg); Object.keys(AppBar.ClosedDisplayMode).forEach(function (mode) { appBar.closedDisplayMode = mode; LiveUnit.Assert.areEqual(mode, appBar.closedDisplayMode, "closedDisplayMode property should be writeable."); Helper.AppBar.verifyRenderedClosed(appBar); }); } testPlacementConstructorOptions() { var appBar = new AppBar(); LiveUnit.Assert.areEqual(_Constants.defaultPlacement, appBar.placement, "'placement' property has incorrect default value."); appBar.dispose(); Object.keys(AppBar.Placement).forEach(function (placement) { appBar = new AppBar(null, { placement: placement }); LiveUnit.Assert.areEqual(placement, appBar.placement, "placement does not match the value passed to the constructor."); appBar.dispose(); }) } testPlacementProperty() { this._element.style.width = "1000px"; var contentElement = document.createElement("DIV"); contentElement.style.height = "100px"; contentElement.style.border = "none"; var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, icon: 'add', label: "button" }), new Command(null, { type: _Constants.typeSeparator }), new Command(contentElement, { type: _Constants.typeContent, label: "content" }), new Command(null, { type: _Constants.typeButton, section: 'secondary', label: "secondary" }), ]); var appBar = new AppBar(this._element, { data: data, opened: false, }); Object.keys(AppBar.Placement).forEach(function (placement) { appBar.placement = placement; LiveUnit.Assert.areEqual(placement, appBar.placement, "placement property should be writeable."); Helper.AppBar.verifyPlacementProperty(appBar); }); } testOpen() { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, icon: 'add', label: "button" }), new Command(null, { type: _Constants.typeSeparator }), new Command(null, { type: _Constants.typeButton, section: 'secondary', label: "secondary" }) ]); var appBar = new AppBar(this._element, { data: data, opened: false }); Helper.AppBar.useSynchronousAnimations(appBar); appBar.open(); LiveUnit.Assert.isTrue(appBar.opened) Helper.AppBar.verifyRenderedOpened(appBar); } testOpenIsIdempotent() { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, icon: 'add', label: "button" }), new Command(null, { type: _Constants.typeSeparator }), new Command(null, { type: _Constants.typeButton, section: 'secondary', label: "secondary" }) ]); // Initialize opened. var appBar = new AppBar(this._element, { data: data, opened: true }); Helper.AppBar.useSynchronousAnimations(appBar); var msg = "Opening an already opened AppBar should not fire events"; appBar.onbeforeopen = failEventHandler(_Constants.EventNames.beforeOpen, msg); appBar.onbeforeclose = failEventHandler(_Constants.EventNames.beforeClose, msg); appBar.onafteropen = failEventHandler(_Constants.EventNames.afterOpen, msg); appBar.onafterclose = failEventHandler(_Constants.EventNames.afterClose, msg); // Verify nothing changes when opening again. var originalOpenedRect = appBar.element.getBoundingClientRect(); appBar.open(); LiveUnit.Assert.isTrue(appBar.opened) Helper.AppBar.verifyRenderedOpened(appBar); Helper.Assert.areBoundingClientRectsEqual(originalOpenedRect, appBar.element.getBoundingClientRect(), "opening an opened AppBar should not affect its bounding client rect", 0); } testClose() { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, icon: 'add', label: "button" }), new Command(null, { type: _Constants.typeSeparator }), new Command(null, { type: _Constants.typeButton, section: 'secondary', label: "secondary" }) ]); var appBar = new AppBar(this._element, { data: data, opened: true }); Helper.AppBar.useSynchronousAnimations(appBar); appBar.close(); LiveUnit.Assert.isFalse(appBar.opened) Helper.AppBar.verifyRenderedClosed(appBar); } testCloseIsIdempotent() { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, icon: 'add', label: "button" }), new Command(null, { type: _Constants.typeSeparator }), new Command(null, { type: _Constants.typeButton, section: 'secondary', label: "secondary" }) ]); // Initialize closed. var appBar = new AppBar(this._element, { data: data, opened: false }); Helper.AppBar.useSynchronousAnimations(appBar); var msg = "Closing an already closed AppBar should not fire events"; appBar.onbeforeopen = failEventHandler(_Constants.EventNames.beforeOpen, msg); appBar.onbeforeclose = failEventHandler(_Constants.EventNames.beforeClose, msg); appBar.onafteropen = failEventHandler(_Constants.EventNames.afterOpen, msg); appBar.onafterclose = failEventHandler(_Constants.EventNames.afterClose, msg); // Verify nothing changes when closing again. var originalClosedRect = appBar.element.getBoundingClientRect(); appBar.close(); LiveUnit.Assert.isFalse(appBar.opened) Helper.AppBar.verifyRenderedClosed(appBar); Helper.Assert.areBoundingClientRectsEqual(originalClosedRect, appBar.element.getBoundingClientRect(), "closing a closed AppBar should not affect its bounding client rect", 0); } testOpenedPropertyConstructorOptions() { var appBar = new AppBar(); LiveUnit.Assert.areEqual(_Constants.defaultOpened, appBar.opened, "opened property has incorrect default value"); appBar.dispose(); [true, false].forEach(function (initiallyOpen) { appBar = new AppBar(null, { opened: initiallyOpen }); LiveUnit.Assert.areEqual(initiallyOpen, appBar.opened, "opened property does not match the value passed to the constructor."); appBar.dispose(); }) } testTogglingOpenedProperty() { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, icon: 'add', label: "button" }), new Command(null, { type: _Constants.typeSeparator }), new Command(null, { type: _Constants.typeButton, section: 'secondary', label: "secondary" }) ]); var appBar = new AppBar(this._element, { data: data, opened: false }); Helper.AppBar.useSynchronousAnimations(appBar); Helper.AppBar.verifyRenderedClosed(appBar); appBar.opened = true; LiveUnit.Assert.isTrue(appBar.opened, "opened property should be writeable."); Helper.AppBar.verifyRenderedOpened(appBar); appBar.opened = false; LiveUnit.Assert.isFalse(appBar.opened, "opened property should be writeable."); Helper.AppBar.verifyRenderedClosed(appBar); } testOverFlowButtonClick() { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, icon: 'add', label: "button" }), new Command(null, { type: _Constants.typeSeparator }), new Command(null, { type: _Constants.typeButton, section: 'secondary', label: "secondary" }) ]); var appBar = new AppBar(this._element, { data: data, opened: true }); Helper.AppBar.useSynchronousAnimations(appBar); appBar._commandingSurface._dom.overflowButton.click() LiveUnit.Assert.isFalse(appBar.opened) Helper.AppBar.verifyRenderedClosed(appBar); appBar._commandingSurface._dom.overflowButton.click() LiveUnit.Assert.isTrue(appBar.opened) Helper.AppBar.verifyRenderedOpened(appBar); } testDomLevel0_OpenCloseEvents() { testEvents(this._element, (appBar: WinJS.UI.PrivateAppBar, eventName: string, handler: Function) => { appBar["on" + eventName] = handler; }); } testDomLevel2_OpenCloseEvents() { testEvents(this._element, (appBar: WinJS.UI.PrivateAppBar, eventName: string, handler: Function) => { appBar.addEventListener(eventName, handler); }); } testBeforeOpenIsCancelable() { var appBar = new AppBar(this._element, { opened: false }); Helper.AppBar.useSynchronousAnimations(appBar); appBar.onbeforeopen = function (eventObject) { eventObject.preventDefault(); }; appBar.onafteropen = function (eventObject) { LiveUnit.Assert.fail("afteropen shouldn't have fired due to beforeopen being canceled"); }; appBar.open(); LiveUnit.Assert.isFalse(appBar.opened, "AppBar should still be closed"); appBar.opened = true; LiveUnit.Assert.isFalse(appBar.opened, "AppBar should still be closed"); } testBeforeCloseIsCancelable() { var appBar = new AppBar(this._element, { opened: true }); Helper.AppBar.useSynchronousAnimations(appBar); appBar.onbeforeclose = function (eventObject) { eventObject.preventDefault(); }; appBar.onafterclose = function (eventObject) { LiveUnit.Assert.fail("afterclose shouldn't have fired due to beforeclose being canceled"); }; appBar.close(); LiveUnit.Assert.isTrue(appBar.opened, "AppBar should still be open"); appBar.opened = false; LiveUnit.Assert.isTrue(appBar.opened, "AppBar should still be open"); } testAppBarAddsClassNamesToCommandingSurface() { // Make sure the appropriate AppBar CSS classes are on _CommandingSurface subcomponents to allow for proper developer styling story. var appBar = new AppBar(this._element, { opened: true }); var actionArea = appBar._commandingSurface._dom.actionArea; var overflowArea = appBar._commandingSurface._dom.overflowArea; var overflowButton = appBar._commandingSurface._dom.overflowButton; var overflowButtonEllipsis = <HTMLElement>overflowButton.querySelector(".win-commandingsurface-ellipsis"); LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(actionArea, _Constants.ClassNames.actionAreaCssClass), "AppBar missing actionarea class"); LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(overflowArea, _Constants.ClassNames.overflowAreaCssClass), "AppBar missing overflowarea class"); LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(overflowButton, _Constants.ClassNames.overflowButtonCssClass), "AppBar missing overflowbutton class"); LiveUnit.Assert.isTrue(WinJS.Utilities.hasClass(overflowButtonEllipsis, _Constants.ClassNames.ellipsisCssClass), "AppBar missing ellipsis class"); } testPositionOffsetsAreCalculateAtConstructionTime() { var badOffset = "-1px"; // Verify that the AppBar sets its element's inline style offsets during construction. This is to support scenarios where an AppBar // is constructed while the IHM is already showing. this._element.style.top = badOffset; this._element.style.bottom = badOffset; var appBar = new AppBar(this._element); LiveUnit.Assert.areNotEqual(badOffset, this._element.style.top, "AppBar style.top should be set during construction."); LiveUnit.Assert.areNotEqual(badOffset, this._element.style.bottom, "AppBar style.bottom should be set during construction."); } testPositionOffsetsAreUpdatedCorrectly(complete) { // AppBar needs to be aware of the IHM when positioning itself to the top or bottom of the visible document. // Verify scenarios that should update the AppBar element offsets. var badOffset = "-1px"; var appBar = new AppBar(this._element, { placement: AppBar.Placement.bottom }); function resetOffsets() { appBar.element.style.top = badOffset; appBar.element.style.bottom = badOffset; appBar._updateDomImpl_renderedState.adjustedOffsets = { top: badOffset, bottom: badOffset }; } // Verify that updating AppBar's placement property will update the inline style offsets. Particularly important in scenarios // Where placement is set while the IHM is already shown. AppBar's changing to top will have to clear IHM offsets and AppBars // changing to bottom will have to add them. resetOffsets(); appBar.placement = AppBar.Placement.top; LiveUnit.Assert.areNotEqual(badOffset, this._element.style.top, "Setting placement property should update AppBar style.top"); LiveUnit.Assert.areNotEqual(badOffset, this._element.style.bottom, "Setting placement property should update AppBar style.bottom"); resetOffsets(); appBar.placement = AppBar.Placement.bottom; LiveUnit.Assert.areNotEqual(badOffset, this._element.style.top, "Setting placement should update AppBar style.top"); LiveUnit.Assert.areNotEqual(badOffset, this._element.style.bottom, "Setting placement should update AppBar style.bottom"); // Call the AppBar's IHM "showing" event handler to verify that AppBar offsets are updated in response to the IHM showing. LiveUnit.Assert.areEqual(AppBar.Placement.bottom, appBar.placement, "TEST ERROR: scenario requires AppBar with placement 'bottom'"); var origFunc = AppBar.prototype._shouldAdjustForShowingKeyboard; AppBar.prototype._shouldAdjustForShowingKeyboard = () => { return true; }; resetOffsets(); appBar._handleShowingKeyboard().then(() => { LiveUnit.Assert.areNotEqual(badOffset, this._element.style.top, "AppBar should update style.top after IHM has finished showing"); LiveUnit.Assert.areNotEqual(badOffset, this._element.style.bottom, "AppBar should update style.bottom after IHM has finished showing"); AppBar.prototype._shouldAdjustForShowingKeyboard = origFunc; // Call the AppBar's IHM "hiding" event handler to verify that the bottom AppBar offsets are updated in response to the IHM hiding. LiveUnit.Assert.areEqual(AppBar.Placement.bottom, appBar.placement, "TEST ERROR: scenario requires AppBar with placement 'bottom'"); resetOffsets(); appBar._handleHidingKeyboard(); LiveUnit.Assert.areNotEqual(badOffset, this._element.style.top, "AppBar should update style.top when the IHM starts to hide"); LiveUnit.Assert.areNotEqual(badOffset, this._element.style.bottom, "AppBar should update style.bottom when the IHM starts to hide"); complete(); }); } testGetCommandById() { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "A", id: "extraneous" }) ]); this._element.style.width = "10px"; var appBar = new AppBar(this._element, { data: data }); LiveUnit.Assert.isNull(appBar.getCommandById("someID")); var firstAddedCommand = new Command(null, { type: _Constants.typeButton, label: "B", id: "someID" }); data.push(firstAddedCommand); LiveUnit.Assert.areEqual(firstAddedCommand, appBar.getCommandById("someID")); var secondAddedCommand = new Command(null, { type: _Constants.typeButton, label: "C", id: "someID" }); data.push(secondAddedCommand); LiveUnit.Assert.areEqual(firstAddedCommand, appBar.getCommandById("someID")); } testShowOnlyCommands(complete) { var data = new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, label: "A", id: "A" }), new Command(null, { type: _Constants.typeButton, label: "B", id: "B" }), new Command(null, { type: _Constants.typeButton, label: "C", id: "C", section: "secondary" }), new Command(null, { type: _Constants.typeButton, label: "D", id: "D" }), new Command(null, { type: _Constants.typeButton, label: "E", id: "E" }) ]); this._element.style.width = "1000px"; var appBar = new AppBar(this._element, { data: data }); function checkCommandVisibility(expectedShown, expectedHidden) { return new WinJS.Promise(c => { appBar._commandingSurface._layoutCompleteCallback = function () { for (var i = 0, len = expectedShown.length; i < len; i++) { var shownCommand = appBar.getCommandById(expectedShown[i]); LiveUnit.Assert.isFalse(shownCommand.hidden); if (shownCommand.section === "secondary") { LiveUnit.Assert.areEqual("none", getComputedStyle(shownCommand.element).display); var overflowAreaCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea); LiveUnit.Assert.areEqual(shownCommand.label, overflowAreaCommands[0].winControl.label); } else { LiveUnit.Assert.areEqual("inline-block", getComputedStyle(shownCommand.element).display); } } for (var i = 0, len = expectedHidden.length; i < len; i++) { var hiddenCommand = appBar.getCommandById(expectedHidden[i]); LiveUnit.Assert.isTrue(hiddenCommand.hidden); LiveUnit.Assert.areEqual("none", getComputedStyle(hiddenCommand.element).display); } c(); }; }); } appBar.showOnlyCommands([]); checkCommandVisibility([], ["A", "B", "C", "D", "E"]).then( () => { appBar.showOnlyCommands(["A", "B", "C", "D", "E"]); return checkCommandVisibility(["A", "B", "C", "D", "E"], []); }).then(() => { appBar.showOnlyCommands(["A"]); return checkCommandVisibility(["A"], ["B", "C", "D", "E"]); }).then(() => { appBar.showOnlyCommands([data.getAt(1)]); return checkCommandVisibility(["B"], ["A", "C", "D", "E"]); }).then(() => { appBar.showOnlyCommands(["C", data.getAt(4)]); checkCommandVisibility(["C", "E"], ["A", "B", "D"]); }).done(complete); } testThatHiddenCommandsDoNotAppearVisible(complete) { // Regression test for https://github.com/winjs/winjs/issues/915 var p0 = new Command(null, { id: "p0", label: "p0", type: _Constants.typeButton, section: "primary", hidden: false }); var p1 = new Command(null, { id: "p1", label: "p1", type: _Constants.typeButton, section: "primary", hidden: false }); var p2 = new Command(null, { id: "p2", label: "p2", type: _Constants.typeButton, section: "primary", hidden: true }); var s0 = new Command(null, { id: "s0", label: "s0", type: _Constants.typeButton, section: "secondary", hidden: false }); var s1 = new Command(null, { id: "s1", label: "s1", type: _Constants.typeButton, section: "secondary", hidden: true }); this._element.style.width = "1000px"; var appBar = new AppBar(this._element, { data: new WinJS.Binding.List([p0, p1, p2, s0, s1]) }); var actionAreaCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea); var overflowAreaCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea); // The actionarea should only show | p0 | p1 | ... | LiveUnit.Assert.areEqual(2, actionAreaCommands.length, "actionarea should display 2 command"); LiveUnit.Assert.areEqual(p0.label, actionAreaCommands[0].winControl.label); LiveUnit.Assert.areEqual(p1.label, actionAreaCommands[1].winControl.label); // The overflowarea should only show | s0 | LiveUnit.Assert.areEqual(1, overflowAreaCommands.length, "overflowarea should display 1 command"); LiveUnit.Assert.areEqual(s0.label, overflowAreaCommands[0].winControl.label); new WinJS.Promise((c) => { appBar._commandingSurface._layoutCompleteCallback = () => { actionAreaCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.actionArea); overflowAreaCommands = Helper._CommandingSurface.getVisibleCommandsInElement(appBar._commandingSurface._dom.overflowArea); // The actionarea should not show any commands LiveUnit.Assert.areEqual(0, actionAreaCommands.length, "actionarea should display 0 command"); // The overflowarea should show | p0 | p1 | separator | s0 | LiveUnit.Assert.areEqual(4, overflowAreaCommands.length, "overflowarea should display 4 command"); LiveUnit.Assert.areEqual(p0.label, overflowAreaCommands[0].winControl.label); LiveUnit.Assert.areEqual(p1.label, overflowAreaCommands[1].winControl.label); LiveUnit.Assert.areEqual(_Constants.typeSeparator, overflowAreaCommands[2].winControl.type); LiveUnit.Assert.areEqual(s0.label, overflowAreaCommands[3].winControl.label); c(); }; // Overflow everything this._element.style.width = "10px"; appBar.forceLayout(); }).done(complete); } private _testLightDismissWithTrigger(dismissAppBar) { var button = document.createElement("button"); button.textContent = "Initially Focused"; var element = document.createElement("div"); this._element.appendChild(button); this._element.appendChild(element); var appBar = new AppBar(element, { data: new WinJS.Binding.List([ new Command(null, { type: _Constants.typeButton, icon: 'add', label: "add" }), new Command(null, { type: _Constants.typeButton, icon: 'remove', label: "remove" }), new Command(null, { type: _Constants.typeButton, icon: 'accept', label: "accept" }), new Command(null, { type: _Constants.typeSeparator }), new Command(null, { type: _Constants.typeButton, section: 'secondary', label: "secondary" }) ]) }); Helper.AppBar.useSynchronousAnimations(appBar); return Helper.focus(button).then(() => { LiveUnit.Assert.areEqual(button, document.activeElement, "Button should have focus initially"); return Helper.waitForFocusWithin(appBar.element, () => { appBar.open(); }); }).then(() => { LiveUnit.Assert.areEqual(appBar.data.getAt(0).element, document.activeElement, "AppBar's leftmost primary command should have focus after opening"); LiveUnit.Assert.isTrue(_LightDismissService.isTopmost(appBar._dismissable), "AppBar should be the topmost light dismissable"); return Helper.waitForFocus(button, () => { dismissAppBar(appBar); }); }).then(() => { LiveUnit.Assert.areEqual(button, document.activeElement, "Focus should have been restored to the button"); LiveUnit.Assert.isFalse(_LightDismissService.isShown(appBar._dismissable), "AppBar should not be in the light dismissable stack"); }); } testLightDismissWithClose(complete) { this._testLightDismissWithTrigger((appBar) => { appBar.close(); }).then(complete); } testLightDismissWithDispose(complete) { this._testLightDismissWithTrigger((appBar) => { appBar.dispose(); }).then(complete); } testLightDismissWithTap(complete) { this._testLightDismissWithTrigger((appBar) => { _LightDismissService._clickEaterTapped(); }).then(complete); } } } LiveUnit.registerTestClass("CorsicaTests.AppBarTests");
the_stack
import { render, svg } from 'lit-html'; import { define } from 'elements-sk/define'; import { Job, Task, TaskDependencies, TaskDimensions, TaskSummaries, TaskSummary, } from '../rpc'; type TaskName = string; export class TaskGraphSk extends HTMLElement { draw(jobs: Job[], swarmingServer: string, selectedTask?: Task) { const graph: Map<TaskName, TaskName[]> = new Map(); const taskData: Map<TaskName, TaskSummary[]> = new Map(); const taskDims: Map<TaskName, string[]> = new Map(); jobs.forEach((job: Job) => { job.dependencies?.forEach((dep: TaskDependencies) => { if (!graph.get(dep.task)) { graph.set(dep.task, dep.dependencies || []); } }); job.taskDimensions?.forEach((dims: TaskDimensions) => { if (!taskDims.has(dims.taskName)) { taskDims.set(dims.taskName, dims.dimensions!); } }); job.tasks?.forEach((taskSummaries: TaskSummaries) => { const tasks = taskData.get(taskSummaries.name) || []; taskSummaries.tasks?.forEach((task: TaskSummary) => { if (!tasks.find((item) => item.id === task.id)) { tasks.push(task); } }); taskData.set(taskSummaries.name, tasks); }); }); // Sort the tasks and task specs for consistency. graph.forEach((tasks: string[]) => { tasks.sort(); }); taskData.forEach((tasks: TaskSummary[]) => { tasks.sort((a: TaskSummary, b: TaskSummary) => a.attempt - b.attempt); }); // Compute the "depth" of each task spec. interface cell { name: string; tasks: TaskSummary[]; } const depth: Map<TaskName, number> = new Map(); const cols: cell[][] = []; const visited: Map<string, boolean> = new Map(); const visit = function(current: string) { visited.set(current, true); let myDepth = 0; (graph.get(current) || []).forEach((dep: string) => { // Visit the dep if we haven't yet. Its depth may be zero, so we have // to explicitly use "depth[dep] == undefined" instead of "!depth[dep]" if (!visited.get(dep)) { visit(dep); } if ((depth.get(dep) || 0) >= myDepth) { myDepth = (depth.get(dep) || 0) + 1; } }); depth.set(current, myDepth); if (cols.length == myDepth) { cols.push([]); } else if (myDepth > cols.length) { console.log('_computeTasksGraph skipped a column!'); return; } cols[myDepth].push({ name: current, tasks: taskData.get(current) || [], }); }; // Visit all of the nodes. graph.forEach((_: string[], key: string) => { if (!visited.get(key)) { visit(key); } }); const arrowWidth = 4; const arrowHeight = 4; const botLinkFontSize = 11; const botLinkMarginX = 10; const botLinkMarginY = 4; const botLinkHeight = botLinkFontSize + 2 * botLinkMarginY; const botLinkText = 'view swarming bots'; const fontFamily = 'Arial'; const fontSize = 12; const taskSpecMarginX = 20; const taskSpecMarginY = 20; const taskMarginX = 10; const taskMarginY = 10; const textMarginX = 10; const textMarginY = 10; const taskWidth = 30; const taskHeight = 30; const taskLinkFontSize = botLinkFontSize; const taskLinkMarginX = botLinkMarginX; const taskLinkMarginY = botLinkMarginY; const taskLinkHeight = taskLinkFontSize + 2 * taskLinkMarginY; const taskLinkText = 'view swarming tasks'; const textOffsetX = textMarginX; const textOffsetY = fontSize + textMarginY; const textHeight = fontSize + 2 * textMarginY; const botLinkOffsetY = textOffsetY + botLinkFontSize + botLinkMarginY; const taskLinkOffsetY = botLinkOffsetY + taskLinkFontSize + taskLinkMarginY; const taskSpecHeight = textHeight + botLinkHeight + taskLinkHeight + taskHeight + taskMarginY; // Compute the task spec block width for each column. const maxTextWidth = 0; const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d')!; ctx.font = `${botLinkFontSize}px ${fontFamily}`; const botLinkTextWidth = ctx.measureText(botLinkText).width + 2 * botLinkMarginX; ctx.font = `${taskLinkFontSize}px ${fontFamily}`; const taskLinkTextWidth = ctx.measureText(taskLinkText).width + 2 * taskLinkMarginX; ctx.font = `${fontSize}px ${fontFamily}`; const taskSpecWidth: number[] = []; cols.forEach((col: cell[]) => { // Get the minimum width of a task spec block needed to fit the entire // task spec name. let maxWidth = Math.max(botLinkTextWidth, taskLinkTextWidth); for (let i = 0; i < col.length; i++) { const oldFont = ctx.font; const text = col[i].name; if (text == selectedTask?.taskKey?.name) { ctx.font = `bold ${ctx.font}`; } const textWidth = ctx.measureText(text).width + 2 * textMarginX; ctx.font = oldFont; if (textWidth > maxWidth) { maxWidth = textWidth; } const numTasks = col[i].tasks.length || 1; const tasksWidth = taskMarginX + numTasks * (taskWidth + taskMarginX); if (tasksWidth > maxWidth) { maxWidth = tasksWidth; } } taskSpecWidth.push(maxWidth); }); // Lay out the task specs and tasks. interface taskSpecRect { x: number; y: number; width: number; height: number; name: string; numTasks: number; } interface taskRect { x: number; y: number; width: number; height: number; task: TaskSummary; } let totalWidth = 0; let totalHeight = 0; const taskSpecs: taskSpecRect[] = []; const tasks: taskRect[] = []; const byName: Map<string, taskSpecRect> = new Map(); let curX = taskMarginX; cols.forEach((col: cell[], colIdx: number) => { let curY = taskMarginY; // Add an entry for each task. col.forEach((taskSpec: cell) => { const entry: taskSpecRect = { x: curX, y: curY, width: taskSpecWidth[colIdx], height: taskSpecHeight, name: taskSpec.name, numTasks: taskSpec.tasks.length, }; taskSpecs.push(entry); byName.set(taskSpec.name, entry); const taskX = curX + taskMarginX; const taskY = curY + textHeight + botLinkHeight + taskLinkHeight; taskSpec.tasks.forEach((task: TaskSummary, taskIdx: number) => { tasks.push({ x: taskX + taskIdx * (taskWidth + taskMarginX), y: taskY, width: taskWidth, height: taskHeight, task: task, }); }); curY += taskSpecHeight + taskSpecMarginY; }); if (curY > totalHeight) { totalHeight = curY; } curX += taskSpecWidth[colIdx] + taskSpecMarginX; }); totalWidth = curX; // Compute the arrows. const arrows: string[] = []; graph.forEach((deps: string[], name: TaskName) => { const dst = byName.get(name)!; if (deps) { deps.forEach((dep: string) => { const src = byName.get(dep); if (!src) { console.log( `Error: task ${dst.name} has unknown parent ${dep}`, ); return ''; } // Start and end points. const x1 = src.x + src.width; const y1 = src.y + src.height / 2; const x2 = dst.x - arrowWidth; const y2 = dst.y + dst.height / 2; // Control points. const cx1 = x1 + taskSpecMarginX - arrowWidth / 2; const cy1 = y1; const cx2 = x2 - taskSpecMarginX + arrowWidth / 2; const cy2 = y2; arrows.push( `M${ x1 } ${ y1 } C${ cx1 } ${ cy1 } ${ cx2 } ${ cy2 } ${ x2 } ${ y2}`, ); }); } }); const taskStatusToClass: { [key: string]: string } = { TASK_STATUS_PENDING: 'bg-in-progress', TASK_STATUS_RUNNING: 'bg-in-progress', TASK_STATUS_SUCCESS: 'bg-success', TASK_STATUS_FAILURE: 'bg-failure', TASK_STATUS_MISHAP: 'bg-mishap', }; // Draw the graph. render( svg` <svg width="${totalWidth}" height="${totalHeight}"> <marker id="arrowhead" class="arrowhead" viewBox="0 0 10 10" refX="0" refY="5" markerUnits="strokeWidth" markerWidth="${arrowWidth}" markerHeight="${arrowHeight}" orient="auto" > <path d="M 0 0 L 10 5 L 0 10 Z"></path> </marker> ${arrows.map((arrow: string) => svg` <path class="arrow" marker-end="url(#arrowhead)" d="${arrow}" > </path> `)} ${taskSpecs.map( (taskSpec: taskSpecRect) => svg` <rect rx="4" ry="4" x="${taskSpec.x}" y="${taskSpec.y}" width="${taskSpec.width}" height="${taskSpec.height}" class="${ taskSpec.name == selectedTask?.taskKey?.name ? 'emphasis' : '' }" > </rect> <text x="${taskSpec.x + textOffsetX}" y="${taskSpec.y + textOffsetY}" class="${ taskSpec.name == selectedTask?.taskKey?.name ? 'emphasis' : '' }" > ${taskSpec.name} </text> <a target="_blank" href="${TaskGraphSk.computeBotsLink( taskDims.get(taskSpec.name)!, swarmingServer, )}"> <text class="links" x="${taskSpec.x + textOffsetX}" y="${taskSpec.y + botLinkOffsetY}" > ${botLinkText} </text> </a> <a target="_blank" href="${TaskGraphSk.computeTasksLink( taskSpec.name, swarmingServer, )}"> <text class="links" x="${taskSpec.x + textOffsetX}" y="${taskSpec.y + taskLinkOffsetY}" > ${taskLinkText} </text> </a> `, )} ${tasks.map( (task) => svg` <a class="task" target="_blank" href="${TaskGraphSk.computeTaskLink(task.task!, swarmingServer)}"> <rect class="task ${ task.task.id == selectedTask?.id ? 'emphasis' : '' } ${taskStatusToClass[task.task!.status]}" rx="4" ry="4" x="${task.x}" y="${task.y}" width="${task.width}" height="${task.height}" > </rect> </a> `, )} </svg> `, this, ); } private static computeBotsLink( dims: string[], swarmingServer: string, ): string { let link = `https://${swarmingServer}/botlist`; if (dims) { for (let i = 0; i < dims.length; i++) { if (i == 0) { link += '?'; } else { link += '&'; } link += `f=${encodeURIComponent(dims[i])}`; } } return link; } private static computeTaskLink( task: TaskSummary, swarmingServer: string, ): string { const swarmingLink = `https://${swarmingServer}/task?id=${task.swarmingTaskId}`; return ( `https://task-driver.skia.org/td/${ task.id }?ifNotFound=${ encodeURIComponent(swarmingLink)}` ); } private static computeTasksLink( name: string, swarmingServer: string, ): string { return `https://${swarmingServer}/tasklist?f=sk_name-tag:${name}`; } } define('task-graph-sk', TaskGraphSk);
the_stack
import { finalize, map, switchMap, tap } from 'rxjs/operators'; import { forkJoin, Observable, of, throwError } from 'rxjs'; import { ODataEntitySetResource, ODataEntityResource, ODataNavigationPropertyResource, ODataEntitiesAnnotations, ODataOptions, ODataEntities, ODataPropertyResource, ODataEntityAnnotations, Select, Expand, OptionHandler, Transform, Filter, OrderBy, EntityKey, ODataQueryArguments, ODataQueryArgumentsOptions, } from '../resources/index'; import { EventEmitter } from '@angular/core'; import { Types } from '../utils/types'; import { ODataModel } from './model'; import { BUBBLING, ODataModelResource, ODataCollectionResource, ODataModelOptions, ODataModelEvent, ODataModelField, ODataModelState, ODataModelEntry, INCLUDE_DEEP, INCLUDE_SHALLOW, } from './options'; import { ODataHelper } from '../helper'; import { DEFAULT_VERSION } from '../constants'; export class ODataCollection<T, M extends ODataModel<T>> implements Iterable<M> { static model: typeof ODataModel | null = null; _parent: | [ ODataModel<any> | ODataCollection<any, ODataModel<any>>, ODataModelField<any> | null ] | null = null; _resource?: ODataCollectionResource<T>; _annotations!: ODataEntitiesAnnotations; _entries: ODataModelEntry<T, M>[] = []; _model: typeof ODataModel; models() { return this._entries .filter((e) => e.state !== ODataModelState.Removed) .map((e) => e.model); } get length(): number { return this.models().length; } //Events events$ = new EventEmitter<ODataModelEvent<T>>(); constructor( entities: Partial<T>[] | { [name: string]: any }[] = [], { parent, resource, annots, model, reset = false, }: { parent?: [ODataModel<any>, ODataModelField<any>]; resource?: ODataCollectionResource<T>; annots?: ODataEntitiesAnnotations; model?: typeof ODataModel; reset?: boolean; } = {} ) { const Klass = this.constructor as typeof ODataCollection; if (model === undefined && Klass.model !== null) model = Klass.model; if (model === undefined) throw new Error('Collection need model'); this._model = model; // Parent if (parent !== undefined) { this._parent = parent; } else { // Resource resource = resource || this._model.meta.collectionResourceFactory(); if (resource === undefined) throw new Error(`Can't create collection without resource`); this.attach(resource); } // Annotations this._annotations = annots || new ODataEntitiesAnnotations( resource?.api.options.helper || ODataHelper[DEFAULT_VERSION] ); entities = entities || []; this.assign(entities, { reset }); } isParentOf( child: ODataModel<any> | ODataCollection<any, ODataModel<any>> ): boolean { return ( child !== this && ODataModelOptions.chain(child).some((p) => p[0] === this) ); } resource(): ODataCollectionResource<T> { return ODataModelOptions.resource<T>(this) as ODataCollectionResource<T>; } attach(resource: ODataCollectionResource<T>) { if ( this._resource !== undefined && this._resource.type() !== resource.type() && !resource.isSubtypeOf(this._resource) ) throw new Error( `Can't reattach ${resource.type()} to ${this._resource.type()}` ); this._entries.forEach(({ model }) => { const mr = this._model.meta.modelResourceFactory({ baseResource: resource, }) as ODataModelResource<T>; model.attach(mr); }); const current = this._resource; if (current === undefined || !current.isEqualTo(resource)) { this._resource = resource; this.events$.emit( new ODataModelEvent('attach', { collection: this, previous: current, value: resource, }) ); } } asEntitySet<R>(func: (collection: this) => R): R { const parent = this._parent; this._parent = null; const result = func(this); if (result instanceof Observable) { return (result as any).pipe(finalize(() => (this._parent = parent))); } else { this._parent = parent; return result; } } annots() { return this._annotations; } private modelFactory( data: Partial<T> | { [name: string]: any }, { reset = false }: { reset?: boolean } = {} ): M { let Model = this._model; const helper = this._annotations.helper; const annots = new ODataEntityAnnotations( helper, helper.annotations(data) || {} ); if (annots?.type !== undefined && Model.meta !== null) { let schema = Model.meta.findChildOptions((o) => o.isTypeOf(annots.type as string) )?.schema; if (schema !== undefined && schema.model !== undefined) // Change to child model Model = schema.model; } return new Model(data, { annots, reset, parent: [this, null], }) as M; } toEntities({ client_id = false, include_navigation = false, include_concurrency = false, include_computed = false, include_key = true, include_non_field = false, changes_only = false, field_mapping = false, chain = [], }: { client_id?: boolean; include_navigation?: boolean; include_concurrency?: boolean; include_computed?: boolean; include_key?: boolean; include_non_field?: boolean; changes_only?: boolean; field_mapping?: boolean; chain?: (ODataModel<any> | ODataCollection<any, ODataModel<any>>)[]; } = {}): (T | { [name: string]: any })[] { return this._entries .filter( ({ model, state }) => state !== ODataModelState.Removed && chain.every((c) => c !== model) ) .map(({ model, state }) => { var changesOnly = changes_only && state !== ODataModelState.Added; return model.toEntity({ client_id, include_navigation, include_concurrency, include_computed, include_key, include_non_field, field_mapping, changes_only: changesOnly, chain: [this, ...chain], }); }); } hasChanged({ include_navigation }: { include_navigation?: boolean } = {}) { return ( this._entries.some((e) => e.state !== ODataModelState.Unchanged) || this.models().some((m) => m.hasChanged({ include_navigation })) ); } clone<C extends ODataCollection<T, M>>() { let Ctor = <typeof ODataCollection>this.constructor; return new Ctor(this.toEntities(INCLUDE_SHALLOW), { resource: this.resource() as ODataCollectionResource<T>, annots: this.annots(), }) as C; } fetch({ withCount, ...options }: ODataOptions & { withCount?: boolean; } = {}): Observable<this> { const resource = this.resource(); if (resource === undefined) return throwError('fetch: Resource is undefined'); let obs$: Observable<ODataEntities<any>>; if (resource instanceof ODataEntitySetResource) { obs$ = resource.fetch({ withCount, ...options }); } else if (resource instanceof ODataNavigationPropertyResource) { obs$ = resource.fetch({ responseType: 'entities', withCount, ...options, }); } else { obs$ = resource.fetch({ responseType: 'entities', withCount, ...options, }); } this.events$.emit( new ODataModelEvent('request', { collection: this, value: obs$ }) ); return obs$.pipe( map(({ entities, annots }) => { this._annotations = annots; this.assign(entities || [], { reset: true }); this.events$.emit(new ODataModelEvent('sync', { collection: this })); return this; }) ); } fetchAll(options?: ODataOptions): Observable<this> { const resource = this.resource() as ODataCollectionResource<T> | undefined; if (resource === undefined) return throwError('fetchAll: Resource is undefined'); if (resource instanceof ODataPropertyResource) return throwError('fetchAll: Resource is ODataPropertyResource'); const obs$ = resource.fetchAll(options); this.events$.emit( new ODataModelEvent('request', { collection: this, options: { observable: obs$ }, }) ); return obs$.pipe( map((entities) => { this._annotations = new ODataEntitiesAnnotations( resource?.api.options.helper ); this.assign(entities || [], { reset: true }); this.events$.emit( new ODataModelEvent('sync', { collection: this, options: { entities }, }) ); return this; }) ); } /** * Save all models in the collection * @param relModel The model is relationship * @param method The method to use * @param options HttpOptions */ save({ relModel = false, method, ...options }: ODataOptions & { relModel?: boolean; method?: 'update' | 'modify'; } = {}): Observable<this> { const resource = this.resource(); if (resource === undefined) return throwError('saveAll: Resource is undefined'); if (resource instanceof ODataPropertyResource) return throwError('fetchAll: Resource is ODataPropertyResource'); let toDestroyEntity: M[] = []; let toRemoveReference: M[] = []; let toDestroyContained: M[] = []; let toCreateEntity: M[] = []; let toAddReference: M[] = []; let toCreateContained: M[] = []; let toUpdateEntity: M[] = []; let toUpdateContained: M[] = []; this._entries.forEach(({ model, state }) => { if (state === ODataModelState.Removed) { if (relModel) { toDestroyEntity.push(model); } else if (!model.isNew()) { toRemoveReference.push(model); } else { toDestroyContained.push(model); } } else if (state === ODataModelState.Added) { if (relModel) { toCreateEntity.push(model); } else if (!model.isNew()) { toAddReference.push(model); } else { toCreateContained.push(model); } } else if (model.hasChanged()) { toUpdateEntity.push(model); } }); if ( toDestroyEntity.length > 0 || toRemoveReference.length > 0 || toDestroyContained.length > 0 || toCreateEntity.length > 0 || toAddReference.length > 0 || toCreateContained.length > 0 || toUpdateEntity.length > 0 || toUpdateContained.length > 0 ) { const obs$ = forkJoin([ ...toDestroyEntity.map((m) => m.asEntity((e) => e.destroy(options))), ...toRemoveReference.map((m) => this.removeReference(m, options)), ...toDestroyContained.map((m) => m.destroy(options)), ...toCreateEntity.map((m) => m.asEntity((e) => e.save({ method: 'create', ...options })) ), ...toAddReference.map((m) => this.addReference(m, options)), ...toCreateContained.map((m) => m.save({ method: 'create', ...options }) ), ...toUpdateEntity.map((m) => m.asEntity((e) => e.save({ method, ...options })) ), ...toUpdateContained.map((m) => m.save({ method, ...options })), ]); this.events$.emit( new ODataModelEvent('request', { collection: this, options: { observable: obs$ }, }) ); return obs$.pipe( map(() => { this._entries = this._entries .filter((entry) => entry.state !== ODataModelState.Removed) .map((entry) => ({ ...entry, state: ODataModelState.Unchanged })); this.events$.emit(new ODataModelEvent('sync', { collection: this })); return this; }) ); } return of(this); } private addReference(model: M, options?: ODataOptions): Observable<M> { const resource = this.resource(); if (!model.isNew() && resource instanceof ODataNavigationPropertyResource) { return resource .reference() .add( model._meta.entityResource(model) as ODataEntityResource<T>, options ) .pipe(map(() => model)); } return of(model); } private _addModel( model: M, { silent = false, reset = false, position = -1, }: { silent?: boolean; reset?: boolean; position?: number } = {} ): M | undefined { const key = model.key(); let entry = this._findEntry({ model, key, cid: (<any>model)[this._model.meta.cid], }); if (entry === undefined || entry.state === ODataModelState.Removed) { if (entry !== undefined && entry.state === ODataModelState.Removed) { const index = this._entries.indexOf(entry); this._entries.splice(index, 1); } // Create Entry entry = { state: reset ? ODataModelState.Unchanged : ODataModelState.Added, model, key: model.key(), }; // Subscribe this._subscribe(entry); // Now add if (position >= 0) this._entries.splice(position, 0, entry); else this._entries.push(entry); if (!silent) { model.events$.emit( new ODataModelEvent('add', { model, collection: this }) ); } return entry.model; } return undefined; } protected addModel( model: M, { silent = false, reset = false, position = -1, }: { silent?: boolean; reset?: boolean; position?: number } = {} ) { if (position < 0) position = this._bisect(model); const added = this._addModel(model, { silent, reset, position }); if (!silent && added !== undefined) { this.events$.emit( new ODataModelEvent('update', { collection: this, options: { added: [added], removed: [], merged: [] }, }) ); } } add( model: M, { silent = false, server = true, position = -1, }: { silent?: boolean; server?: boolean; position?: number } = {} ): Observable<this> { if (server) { return this.addReference(model).pipe( map((model) => { this.addModel(model, { silent, position, reset: true }); return this; }) ); } else { this.addModel(model, { silent, position }); return of(this); } } private removeReference(model: M, options?: ODataOptions): Observable<M> { const resource = this.resource(); if (!model.isNew() && resource instanceof ODataNavigationPropertyResource) { return resource .reference() .remove( model._meta.entityResource(model) as ODataEntityResource<T>, options ) .pipe(map(() => model)); } return of(model); } private _removeModel( model: M, { silent = false, reset = false, }: { silent?: boolean; reset?: boolean } = {} ): M | undefined { const key = model.key(); let entry = this._findEntry({ model, key, cid: (<any>model)[this._model.meta.cid], }); if (entry !== undefined && entry.state !== ODataModelState.Removed) { // Emit Event if (!silent) model.events$.emit( new ODataModelEvent('remove', { model, collection: this }) ); // Now remove const index = this._entries.indexOf(entry); this._entries.splice(index, 1); if (!(reset || entry.state === ODataModelState.Added)) { // Move to end of array and mark as removed entry.state = ODataModelState.Removed; this._entries.push(entry); } this._unsubscribe(entry); return entry.model; } return undefined; } protected removeModel( model: M, { silent = false, reset = false, }: { silent?: boolean; reset?: boolean } = {} ) { const removed = this._removeModel(model, { silent, reset }); if (!silent && removed !== undefined) { this.events$.emit( new ODataModelEvent('update', { collection: this, options: { added: [], removed: [removed], merged: [] }, }) ); } } remove( model: M, { silent = false, server = true, }: { silent?: boolean; server?: boolean } = {} ): Observable<this> { if (server) { return this.removeReference(model).pipe( map((model) => { this.removeModel(model, { silent, reset: true }); return this; }) ); } else { this.removeModel(model, { silent }); return of(this); } } create( attrs: T = {} as T, { silent = false, server = true, }: { silent?: boolean; server?: boolean } = {} ) { const model = this.modelFactory(attrs); return (model.isValid() && server ? model.save() : of(model)).pipe( switchMap((model) => this.add(model, { silent, server })), map(() => model) ); } set(path: string | string[], value: any) { const Model = this._model; const pathArray = ( Types.isArray(path) ? path : (path as string).match(/([^[.\]])+/g) ) as any[]; if (pathArray.length === 0) return undefined; if (pathArray.length > 1) { const model = this._entries[Number(pathArray[0])].model; return model.set(pathArray.slice(1), value); } if (pathArray.length === 1 && ODataModelOptions.isModel(value)) { let toAdd: M[] = []; let toMerge: M[] = []; let toRemove: M[] = []; let index = Number(pathArray[0]); const model = this.models()[index]; const entry = this._findEntry({ model }); if (entry !== undefined) { //TODO: Remove/Add or Merge? // Merge entry.model.assign( value.toEntity({ client_id: true, ...INCLUDE_DEEP }) ); if (entry.model.hasChanged()) toMerge.push(model); } else { // Add this._addModel(value); toAdd.push(model); } this.events$.emit( new ODataModelEvent('update', { collection: this, options: { added: toAdd, removed: toRemove, merged: toMerge }, }) ); return value; } } get(path: number): M; get(path: string | string[]): any; get(path: any): any { const Model = this._model; const pathArray = ( Types.isArray(path) ? path : `${path}`.match(/([^[.\]])+/g) ) as any[]; if (pathArray.length === 0) return undefined; const value = this.models()[Number(pathArray[0])]; if (pathArray.length > 1 && ODataModelOptions.isModel(value)) { return value.get(pathArray.slice(1)); } return value; } reset({ path, silent = false, }: { path?: string | string[]; silent?: boolean } = {}) { if (Types.isEmpty(path)) { this.models().forEach((m) => m.reset({ silent })); } else { const Model = this._model; const pathArray = ( Types.isArray(path) ? path : `${path}`.match(/([^[.\]])+/g) ) as any[]; const value = this.models()[Number(pathArray[0])]; if (ODataModelOptions.isModel(value)) { value.reset({ path: pathArray.slice(1), silent }); } } } assign( objects: Partial<T>[] | { [name: string]: any }[] | M[], { reset = false, silent = false, }: { reset?: boolean; silent?: boolean } = {} ) { const Model = this._model; let toAdd: M[] = []; let toMerge: M[] = []; let toRemove: M[] = []; let toSort: [M, number][] = []; let modelMap: string[] = []; objects.forEach((obj, index) => { const isModel = ODataModelOptions.isModel(obj); const key = Model !== null && Model.meta ? Model.meta.resolveKey(obj) : undefined; const cid = Model.meta.cid in obj ? (<any>obj)[Model.meta.cid] : undefined; // Try find entry const entry = isModel ? this._findEntry({ model: obj as M }) // By Model : this._findEntry({ cid, key }); // By Cid or Key let model: M; if (entry !== undefined) { // Merge model = entry.model; if (model !== obj) { // Get entity from model if (isModel) { const entity = (obj as M).toEntity({ client_id: true, ...INCLUDE_DEEP, }); model.assign(entity, { reset, silent }); } else { const helper = this._annotations.helper; const annots = new ODataEntityAnnotations( helper, helper.annotations(obj) || {} ); const entity = annots.attributes<T>(obj, 'full'); model._annotations = annots; model.assign(entity, { reset, silent }); } // Model Change? if (model.hasChanged()) toMerge.push(model); } // Has Sort or Index Change? if (toSort.length > 0 || index !== this.models().indexOf(model)) { toSort.push([model, index]); } } else { // Add model = isModel ? (obj as M) : this.modelFactory(obj as Partial<T> | { [name: string]: any }, { reset, }); toAdd.push(model); } modelMap.push((<any>model)[Model.meta.cid]); }); this._entries .filter((e) => modelMap.indexOf((<any>e.model)[Model.meta.cid]) === -1) .forEach((entry) => { toRemove.push(entry.model); }); toRemove.forEach((m) => this._removeModel(m, { silent: silent, reset })); toAdd.forEach((m) => { this._addModel(m, { silent: silent, reset }); // Set Parent m._parent = [this, null]; }); toSort.forEach((m) => { this._removeModel(m[0], { silent: true, reset }); this._addModel(m[0], { silent: true, reset, position: m[1] }); }); if ( toAdd.length > 0 || toRemove.length > 0 || toMerge.length > 0 || toSort.length > 0 ) { this._sortBy = null; if (!silent) { this.events$.emit( new ODataModelEvent(reset ? 'reset' : 'update', { collection: this, options: { added: toAdd, removed: toRemove, merged: toMerge, sorted: toSort, }, }) ); } } } query( func: (q: { select(opts?: Select<T>): OptionHandler<Select<T>>; expand(opts?: Expand<T>): OptionHandler<Expand<T>>; transform(opts?: Transform<T>): OptionHandler<Transform<T>>; search(opts?: string): OptionHandler<string>; filter(opts?: Filter): OptionHandler<Filter>; orderBy(opts?: OrderBy<T>): OptionHandler<OrderBy<T>>; format(opts?: string): OptionHandler<string>; top(opts?: number): OptionHandler<number>; skip(opts?: number): OptionHandler<number>; skiptoken(opts?: string): OptionHandler<string>; paging({ skip, skiptoken, top, }: { skip?: number; skiptoken?: string; top?: number; }): void; clearPaging(): void; apply(query: ODataQueryArguments<T>): void; }) => void ) { const resource = this.resource(); func(resource.query); this.attach(resource); return this; } protected callFunction<P, R>( name: string, params: P | null, responseType: 'property' | 'model' | 'collection' | 'none', { ...options }: {} & ODataQueryArgumentsOptions<R> = {} ): Observable<R | ODataModel<R> | ODataCollection<R, ODataModel<R>> | null> { const resource = this.resource(); if (resource instanceof ODataEntitySetResource) { const func = resource.function<P, R>(name); func.query.apply(options); switch (responseType) { case 'property': return func.callProperty(params, options); case 'model': return func.callModel(params, options); case 'collection': return func.callCollection(params, options); default: return func.call(params, { responseType, ...options }); } } return throwError(`Can't function without ODataEntitySetResource`); } protected callAction<P, R>( name: string, params: P | null, responseType: 'property' | 'model' | 'collection' | 'none', { ...options }: {} & ODataQueryArgumentsOptions<R> = {} ): Observable<R | ODataModel<R> | ODataCollection<R, ODataModel<R>> | null> { const resource = this.resource(); if (resource instanceof ODataEntitySetResource) { const action = resource.action<P, R>(name); action.query.apply(options); switch (responseType) { case 'property': return action.callProperty(params, options); case 'model': return action.callModel(params, options); case 'collection': return action.callCollection(params, options); default: return action.call(params, { responseType, ...options }); } } return throwError(`Can't action without ODataEntitySetResource`); } private _unsubscribe(entry: ODataModelEntry<T, M>) { if (entry.subscription) { entry.subscription.unsubscribe(); delete entry.subscription; } } private _subscribe(entry: ODataModelEntry<T, M>) { if (entry.subscription) { throw new Error('Subscription already exists'); } entry.subscription = entry.model.events$.subscribe( (event: ODataModelEvent<T>) => { if ( BUBBLING.indexOf(event.name) !== -1 && event.bubbling && !event.visited(this) ) { if (event.model === entry.model) { if (event.name === 'destroy') { this.removeModel(entry.model, { reset: true }); } else if (event.name === 'change' && event.options?.key) { entry.key = entry.model.key(); } } const index = this.models().indexOf(entry.model); event.push(this, index); this.events$.emit(event); } } ); } private _findEntry({ model, cid, key, }: { model?: ODataModel<T>; cid?: string; key?: EntityKey<T> | { [name: string]: any }; } = {}) { return this._entries.find((entry) => { const byModel = model !== undefined && entry.model.equals(model); const byCid = cid !== undefined && (<any>entry.model)[this._model.meta.cid] === cid; const byKey = key !== undefined && entry.key !== undefined && Types.isEqual(entry.key, key); return byModel || byCid || byKey; }); } // Collection functions equals(other: ODataCollection<T, ODataModel<T>>) { return this === other; } get [Symbol.toStringTag]() { return 'Collection'; } public [Symbol.iterator]() { let pointer = 0; let models = this.models(); return { next(): IteratorResult<M> { return { done: pointer === models.length, value: models[pointer++], }; }, }; } filter(predicate: (m: M, index: number) => boolean): M[] { return this.models().filter(predicate); } find(predicate: (m: M, index: number) => boolean): M | undefined { return this.models().find(predicate); } first(): M | undefined { return this.models()[0]; } last(): M | undefined { const models = this.models(); return models[models.length - 1]; } every(predicate: (m: M, index: number) => boolean): boolean { return this.models().every(predicate); } some(predicate: (m: M, index: number) => boolean): boolean { return this.models().some(predicate); } contains(model: M) { return this.some((m) => m.equals(model)); } indexOf(model: M): number { const models = this.models(); const m = models.find((m) => m.equals(model)); return m === undefined ? -1 : models.indexOf(m); } //#region Sort private _bisect(model: M) { let index = -1; if (this._sortBy !== null) { for (index = 0; index < this._entries.length; index++) { if (this._compare(model, this._entries[index], this._sortBy, 0) < 0) { return index; } } } return index; } private _compare( e1: ODataModelEntry<T, M> | M, e2: ODataModelEntry<T, M> | M, by: { field: string | keyof T; order?: 1 | -1 }[], index: number ): number { let m1 = ODataModelOptions.isModel(e1) ? (e1 as M) : (e1 as ODataModelEntry<T, M>).model; let m2 = ODataModelOptions.isModel(e2) ? (e2 as M) : (e2 as ODataModelEntry<T, M>).model; let value1 = m1.get(by[index].field as string); let value2 = m2.get(by[index].field as string); let result: number = 0; if (value1 == null && value2 != null) result = -1; else if (value1 != null && value2 == null) result = 1; else if (value1 == null && value2 == null) result = 0; else if (typeof value1 == 'string' || value1 instanceof String) { if (value1.localeCompare && value1 != value2) { return (by[index].order || 1) * value1.localeCompare(value2); } } else { result = value1 < value2 ? -1 : 1; } if (value1 == value2) { return by.length - 1 > index ? this._compare(e1, e2, by, index + 1) : 0; } return (by[index].order || 1) * result; } _sortBy: { field: string | keyof T; order?: 1 | -1 }[] | null = null; isSorted() { return this._sortBy !== null; } sort( by: { field: string | keyof T; order?: 1 | -1 }[], { silent }: { silent?: boolean } = {} ) { this._sortBy = by; this._entries = this._entries.sort( (e1: ODataModelEntry<T, M>, e2: ODataModelEntry<T, M>) => this._compare(e1, e2, by, 0) ); if (!silent) { this.events$.emit( new ODataModelEvent('update', { collection: this, }) ); } } //#endregion }
the_stack
import {format} from "../Text/Utility"; import {InvalidOperationException} from "../Exceptions/InvalidOperationException"; import {ArgumentException} from "../Exceptions/ArgumentException"; import {ArgumentNullException} from "../Exceptions/ArgumentNullException"; import {EnumeratorBase} from "./Enumeration/EnumeratorBase"; import {ILinkedNode, ILinkedNodeWithValue} from "./ILinkedListNode"; import {IEnumerateEach} from "./Enumeration/IEnumerateEach"; import {IDisposable} from "../Disposable/IDisposable"; import {ILinkedNodeList} from "./ILinkedList"; import {IEnumerator} from "./Enumeration/IEnumerator"; import {ActionWithIndex, PredicateWithIndex, Selector, SelectorWithIndex} from "../FunctionTypes"; import {ArrayLikeWritable} from "./Array/ArrayLikeWritable"; import __extendsImport from "../../extends"; // noinspection JSUnusedLocalSymbols const __extends = __extendsImport; /***************************** * IMPORTANT NOTES ABOUT PERFORMANCE: * http://jsperf.com/simulating-a-queue * * Adding to an array is very fast, but modifying is slow. * LinkedList wins when modifying contents. * http://stackoverflow.com/questions/166884/array-versus-linked-list *****************************/ /** * This class is useful for managing a list of linked nodes, but it does not protect against modifying individual links. * If the consumer modifies a link (sets the previous or next value) it will effectively break the collection. * * It is possible to declare a node type of any kind as long as it contains a previous and next value that can reference another node. * Although not as safe as the included LinkedList, this class has less overhead and is more flexible. * * The count (or length) of this LinkedNodeList is not tracked since it could be corrupted at any time. */ export class LinkedNodeList<TNode extends ILinkedNode<TNode>> implements ILinkedNodeList<TNode>, IEnumerateEach<TNode>, IDisposable { private _first:TNode|null; private _last:TNode|null; unsafeCount:number; constructor() { this._first = null; this._last = null; this.unsafeCount = 0; this._version = 0; } private _version:number; assertVersion(version:number):true|never { if(version!==this._version) throw new InvalidOperationException("Collection was modified."); return true; } /** * The first node. Will be null if the collection is empty. */ get first():TNode|null { return this._first; } /** * The last node. */ get last():TNode|null { return this._last; } /** * Iteratively counts the number of linked nodes and returns the value. * @returns {number} */ get count():number { let next:TNode|null|undefined = this._first; let i:number = 0; while(next) { i++; next = next.next; } return i; } // Note, no need for 'useCopy' since this avoids any modification conflict. // If iterating over a arrayCopy is necessary, a arrayCopy should be made manually. forEach( action:ActionWithIndex<TNode>, ignoreVersioning?:boolean):number forEach( action:PredicateWithIndex<TNode>, ignoreVersioning?:boolean):number forEach( action:ActionWithIndex<TNode> | PredicateWithIndex<TNode>, ignoreVersioning?:boolean):number { const _ = this; let current:TNode|null|undefined = null, next:TNode|null|undefined = _.first; // Be sure to track the next node so if current node is removed. const version = _._version; let index:number = 0; do { if(!ignoreVersioning) _.assertVersion(version); current = next; next = current && current.next; } while(current && <any>action(current, index++)!==false); return index; } map<T>(selector:Selector<TNode,T>):T[] map<T>(selector:SelectorWithIndex<TNode,T>):T[] map<T>(selector:SelectorWithIndex<TNode,T>):T[] { if(!selector) throw new ArgumentNullException('selector'); const result:T[] = []; this.forEach((node, i)=> { result.push(selector(node, i)); }); return result; } /** * Erases the linked node's references to each other and returns the number of nodes. * @returns {number} */ clear():number { const _ = this; let n:TNode|null|undefined, cF:number = 0, cL:number = 0; // First, clear in the forward direction. n = _._first; _._first = null; while(n) { cF++; let current = n; n = n.next; current.next = null; } // Last, clear in the reverse direction. n = _._last; _._last = null; while(n) { cL++; let current = n; n = n.previous; current.previous = null; } if(cF!==cL) console.warn('LinkedNodeList: Forward versus reverse count does not match when clearing. Forward: ' + cF + ", Reverse: " + cL); _._version++; _.unsafeCount = 0; return cF; } /** * Clears the list. */ dispose():void { this.clear(); } /** * Iterates the list to see if a node exists. * @param node * @returns {boolean} */ contains(node:TNode):boolean { return this.indexOf(node)!= -1; } /** * Gets the index of a particular node. * @param index */ getNodeAt(index:number):TNode|null { if(index<0) return null; let next = this._first; let i:number = 0; while(next && i++<index) { next = next.next || null; } return next; } find(condition:PredicateWithIndex<TNode>):TNode|null { let node:TNode|null = null; this.forEach((n, i)=> { if(condition(n, i)) { node = n; return false; } }); return node; } /** * Iterates the list to find the specified node and returns its index. * @param node * @returns {boolean} */ indexOf(node:TNode):number { if(node && (node.previous || node.next)) { let index = 0; let c:TNode|null|undefined, n:TNode|null|undefined = this._first; do { c = n; if(c===node) return index; index++; } while((n = c && c.next)); } return -1; } /** * Removes the first node and returns true if successful. * @returns {boolean} */ removeFirst():boolean { return !!this._first && this.removeNode(this._first); } /** * Removes the last node and returns true if successful. * @returns {boolean} */ removeLast():boolean { return !!this._last && this.removeNode(this._last); } /** * Removes the specified node. * Returns true if successful and false if not found (already removed). * @param node * @returns {boolean} */ removeNode(node:TNode):boolean { if(node==null) throw new ArgumentNullException('node'); const _ = this; const prev:TNode|null = node.previous || null, next:TNode|null = node.next || null; let a:boolean = false, b:boolean = false; if(prev) prev.next = next; else if(_._first==node) _._first = next; else a = true; if(next) next.previous = prev; else if(_._last==node) _._last = prev; else b = true; if(a!==b) { throw new ArgumentException( 'node', format( "Provided node is has no {0} reference but is not the {1} node!", a ? "previous" : "next", a ? "first" : "last" ) ); } const removed = !a && !b; if(removed) { _._version++; _.unsafeCount--; node.previous = null; node.next = null; } return removed; } /** * Adds a node to the end of the list. * @param node * @returns {LinkedNodeList} */ addNode(node:TNode):this { this.addNodeAfter(node); return this; } /** * Inserts a node before the specified 'before' node. * If no 'before' node is specified, it inserts it as the first node. * @param node * @param before * @returns {LinkedNodeList} */ addNodeBefore(node:TNode, before:TNode|null = null):this { assertValidDetached(node); const _ = this; if(!before) { before = _._first; } if(before) { let prev = before.previous; node.previous = prev; node.next = before; before.previous = node; if(prev) prev.next = node; if(before==_._first) _._first = node; } else { _._first = _._last = node; } _._version++; _.unsafeCount++; return this; } /** * Inserts a node after the specified 'after' node. * If no 'after' node is specified, it appends it as the last node. * @param node * @param after * @returns {LinkedNodeList} */ addNodeAfter(node:TNode, after:TNode|null = null):this { assertValidDetached(node); const _ = this; if(!after) { after = _._last; } if(after) { let next = after.next; node.next = next; node.previous = after; after.next = node; if(next) next.previous = node; if(after==_._last) _._last = node; } else { _._first = _._last = node; } _._version++; _.unsafeCount++; return _; } /** * Takes and existing node and replaces it. * @param node * @param replacement * @returns {any} */ replace(node:TNode, replacement:TNode):this { if(node==null) throw new ArgumentNullException('node'); if(node==replacement) return this; assertValidDetached(replacement, 'replacement'); const _ = this; replacement.previous = node.previous; replacement.next = node.next; if(node.previous) node.previous.next = replacement; if(node.next) node.next.previous = replacement; if(node==_._first) _._first = replacement; if(node==_._last) _._last = replacement; _._version++; return _; } static valueEnumeratorFrom<T>(list:LinkedNodeList<ILinkedNodeWithValue<T>>):IEnumerator<T> { if(!list) throw new ArgumentNullException('list'); let current:ILinkedNodeWithValue<T>|null|undefined, next:ILinkedNodeWithValue<T>|null|undefined, version:number; return new EnumeratorBase<T>( () => { // Initialize anchor... current = null; next = list.first; version = list._version; }, (yielder)=> { if(next) { list.assertVersion(version); current = next; next = current && current.next; return yielder.yieldReturn(current.value); } return yielder.yieldBreak(); } ); } static copyValues<T,TDestination extends ArrayLikeWritable<any>>( list:LinkedNodeList<ILinkedNodeWithValue<T>>, array:TDestination, index:number = 0):TDestination { if(list && list.first) { if(!array) throw new ArgumentNullException('array'); list.forEach( (node, i) => { array[index + i] = node.value; } ); } return array; } } function assertValidDetached<TNode extends ILinkedNode<TNode>>( node:TNode, propName:string = 'node') { if(node==null) throw new ArgumentNullException(propName); if(node.next || node.previous) throw new InvalidOperationException("Cannot add a node to a LinkedNodeList that is already linked."); } export default LinkedNodeList;
the_stack
import { Browser } from '@syncfusion/ej2-base'; import { PointModel } from '../primitives/point-model'; import { Point } from '../primitives/point'; import { IElement, IClickEventArgs, IDoubleClickEventArgs, IMouseEventArgs, StackEntryObject } from '../objects/interface/IElement'; import { UserHandleEventsArgs } from '../objects/interface/IElement'; import { ICommandExecuteEventArgs, IKeyEventArgs } from '../objects/interface/IElement'; import { IBlazorDoubleClickEventArgs, IBlazorClickEventArgs, IBlazorMouseEventArgs } from '../objects/interface/IElement'; import { DiagramElement } from '../core/elements/diagram-element'; import { Container } from '../core/containers/container'; import { MarginModel } from '../core/appearance-model'; import { Diagram } from '../diagram'; import { Connector } from '../objects/connector'; import { NodeDrawingTool, ConnectorDrawingTool, TextDrawingTool } from './tool'; import { PolygonDrawingTool, PolyLineDrawingTool, FixedUserHandleTool } from './tool'; import { Native, Node, SwimLane } from '../objects/node'; import { ConnectorModel } from '../objects/connector-model'; import { PointPortModel } from '../objects/port-model'; import { NodeModel, BpmnShapeModel, BasicShapeModel, SwimLaneModel, LaneModel, PhaseModel } from '../objects/node-model'; import { ToolBase, SelectTool, MoveTool, ResizeTool, RotateTool, ConnectTool, ExpandTool, LabelTool, ZoomPanTool } from './tool'; import { LabelDragTool, LabelResizeTool, LabelRotateTool } from './tool'; import { ConnectorEditing } from './connector-editing'; import { Selector } from '../objects/node'; import { CommandHandler } from './command-manager'; import { Actions, findToolToActivate, isSelected, getCursor, contains } from './actions'; import { DiagramAction, KeyModifiers, Keys, DiagramEvent, DiagramTools, RendererAction, DiagramConstraints } from '../enum/enum'; import { BlazorAction, ScrollActions } from '../enum/enum'; import { isPointOverConnector, findObjectType, insertObject, getObjectFromCollection, getTooltipOffset, findParentInSwimlane } from '../utility/diagram-util'; import { getObjectType, getInOutConnectPorts, removeChildNodes, cloneBlazorObject, checkPort } from '../utility/diagram-util'; import { canZoomPan, canDraw, canDrag, canZoomTextEdit, canVitualize, canPreventClearSelection } from './../utility/constraints-util'; import { selectionHasConnector } from '../utility/diagram-util'; import { canMove, canEnablePointerEvents, canSelect, canEnableToolTip } from './../utility/constraints-util'; import { canOutConnect, canInConnect, canPortInConnect, canPortOutConnect, canAllowDrop, canUserInteract, defaultTool } from './../utility/constraints-util'; import { CommandModel } from '../diagram/keyboard-commands-model'; import { updateTooltip } from '../objects/tooltip'; import { DiagramTooltipModel } from '../objects/tooltip-model'; import { PortVisibility, NodeConstraints, ConnectorConstraints, RealAction } from '../enum/enum'; import { addTouchPointer, measureHtmlText, getAdornerLayerSvg } from '../utility/dom-util'; import { TextElement } from '../core/elements/text-element'; import { Size } from '../primitives/size'; import { cloneObject as clone, cloneObject } from './../utility/base-util'; import { TransformFactor } from '../interaction/scroller'; import { InputArgs } from '@syncfusion/ej2-inputs'; import { Rect } from '../primitives/rect'; import { identityMatrix, rotateMatrix, transformPointByMatrix, Matrix } from './../primitives/matrix'; import { LayerModel } from '../diagram/layer-model'; import { ITouches, ActiveLabel } from '../objects/interface/interfaces'; import { removeRulerMarkers, drawRulerMarkers, getRulerSize, updateRuler } from '../ruler/ruler'; import { canContinuousDraw, canDrawOnce } from '../utility/constraints-util'; import { SelectorModel } from '../objects/node-model'; import { getFunction, cornersPointsBeforeRotation } from '../utility/base-util'; import { ShapeAnnotationModel, PathAnnotationModel } from '../objects/annotation-model'; import { ShapeAnnotation, PathAnnotation } from '../objects/annotation'; import { updateCanvasBounds, checkChildNodeInContainer, checkParentAsContainer, removeChildInContainer } from './container-interaction'; import { moveChildInStack, renderStackHighlighter } from './container-interaction'; import { updateSwimLaneObject } from '../utility/swim-lane-util'; import { getConnectors, updateHeaderMaxWidth, laneInterChanged, updateConnectorsProperties } from '../utility/swim-lane-util'; import { HistoryEntry } from '../diagram/history'; import { GridPanel } from '../core/containers/grid'; import { Canvas } from '../core/containers/canvas'; import { DiagramHtmlElement } from '../core/elements/html-element'; import { randomId } from '../index'; import { Tooltip } from '@syncfusion/ej2-popups'; import { isBlazor } from '@syncfusion/ej2-base'; import { BlazorTooltip } from '../blazor-tooltip/blazor-Tooltip'; /** * This module handles the mouse and touch events */ export class DiagramEventHandler { private currentAction: Actions = 'None'; private previousAction: Actions = 'None'; /** @private */ public focus: boolean = false; private get action(): Actions { return this.currentAction; } private set action(action: Actions) { if (action !== this.currentAction) { if (this.currentAction === 'PortDraw') { this.diagram.tool &= ~DiagramTools.DrawOnce; if (this.tool) { this.tool.mouseUp({ position: this.currentPosition }); } this.tool = null; } if (action === 'Rotate' || action === 'LabelRotate') { this.diagram.diagramCanvas.classList.add('e-diagram-rotate'); } else if (this.currentAction === 'Rotate' || this.currentAction === 'LabelRotate') { this.diagram.diagramCanvas.classList.remove('e-diagram-rotate'); } this.currentAction = action; if (this.currentAction !== 'None' && this.currentAction !== 'Select' && !(this.diagram.diagramActions & DiagramAction.TextEdit) || this.commandHandler.isUserHandle(this.currentPosition)) { this.diagram.diagramActions = this.diagram.diagramActions | DiagramAction.ToolAction; } else { this.diagram.diagramActions = this.diagram.diagramActions & ~DiagramAction.ToolAction; } this.diagram.setCursor(this.diagram.getCursor(action, this.inAction)); } } private isBlocked: boolean = false; private get blocked(): boolean { return this.isBlocked; } private set blocked(blocked: boolean) { this.isBlocked = blocked; if (this.blocked) { this.diagram.setCursor('not-allowed'); } else { this.diagram.setCursor(this.diagram.getCursor(this.action, this.inAction)); } } private commandHandler: CommandHandler; private isMouseDown: boolean = false; private inAction: boolean = false; private resizeTo: Object; private currentPosition: PointModel; private timeOutValue: Object; private doingAutoScroll: boolean = false; private prevPosition: PointModel; private diagram: Diagram = null; private objectFinder: ObjectFinder = null; private tool: ToolBase = null; private eventArgs: MouseEventArgs = null; private userHandleObject: string; private lastObjectUnderMouse: NodeModel | ConnectorModel; private hoverElement: NodeModel | ConnectorModel; private hoverNode: NodeModel; private isScrolling: boolean; private initialEventArgs: MouseEventArgs; /** @private */ public touchStartList: ITouches[] | TouchList; /** @private */ public touchMoveList: ITouches[] | TouchList; /** @private */ constructor(diagram: Diagram, commandHandler: CommandHandler) { this.diagram = diagram; this.objectFinder = new ObjectFinder(); this.commandHandler = commandHandler; } /** @private */ public getMousePosition(e: MouseEvent | PointerEvent | TouchEvent): PointModel { let touchArg: TouchEvent; let offsetX: number; let offsetY: number; if (e.type.indexOf('touch') !== -1) { touchArg = <TouchEvent & PointerEvent>e; offsetX = touchArg.changedTouches[0].clientX; offsetY = touchArg.changedTouches[0].clientY; } else { offsetX = (e as PointerEvent).clientX; offsetY = (e as PointerEvent).clientY; } let position: Size = new Size(); position = getRulerSize(this.diagram); const boundingRect: ClientRect = this.diagram.element.getBoundingClientRect(); offsetX = offsetX + this.diagram.diagramCanvas.scrollLeft - boundingRect.left - position.width; offsetY = offsetY + this.diagram.diagramCanvas.scrollTop - boundingRect.top - position.height; offsetX /= this.diagram.scroller.transform.scale; offsetY /= this.diagram.scroller.transform.scale; offsetX -= this.diagram.scroller.transform.tx; offsetY -= this.diagram.scroller.transform.ty; return { x: offsetX, y: offsetY }; } /** * @private */ public windowResize(evt: Event): boolean { if (this.resizeTo) { clearTimeout(this.resizeTo as number); } this.resizeTo = setTimeout( (): void => { this.updateViewPortSize(this.diagram.element); }, 300); return false; } /** * @private */ public updateViewPortSize(element: HTMLElement): void { const container: HTMLElement = document.getElementById(element.id); if (container) { const bounds: ClientRect = container.getBoundingClientRect(); this.diagram.scroller.setViewPortSize(bounds.width, bounds.height); let position: Size = new Size(); position = getRulerSize(this.diagram); const width: string = this.diagram.getSizeValue(this.diagram.width, position.width); const height: string = this.diagram.getSizeValue(this.diagram.height, position.height); this.diagram.diagramCanvas.style.width = width; this.diagram.diagramCanvas.style.height = height; this.diagram.scroller.setSize(); this.diagram.transformLayers(); if (this.diagram.rulerSettings.showRulers) { updateRuler(this.diagram); } } } /** @private */ public canHideResizers(): boolean { return ((this.tool instanceof MoveTool || this.tool instanceof RotateTool) && this.isMouseDown); } /** @private */ private updateCursor(): void { if ((this.diagram.selectedItems.nodes.length === 1 || this.diagram.selectedItems.connectors.length === 1)) { let list: (NodeModel | ConnectorModel)[] = []; list = list.concat(this.diagram.selectedItems.nodes, this.diagram.selectedItems.connectors); // Bug fix - EJ2-44495 -Node does not gets selected on slight movement of mouse when drag constraints disabled for node this.blocked = (this.eventArgs && this.eventArgs.source && !canMove(this.eventArgs.source)) ? false : (this.isMouseDown && list.length === 1 && this.tool instanceof SelectTool && !canMove(list[0])); } } private isForeignObject(target: HTMLElement, isTextBox?: boolean): HTMLElement { let foreignobject: HTMLElement = target; if (foreignobject) { while (foreignobject.parentNode !== null) { if (typeof foreignobject.className === 'string' && ((!isTextBox && foreignobject.className.indexOf('foreign-object') !== -1) || (isTextBox && foreignobject.className.indexOf('e-diagram-text-edit') !== -1))) { return foreignobject; } else { foreignobject = foreignobject.parentNode as HTMLElement; } } } return null; } private isMetaKey(evt: PointerEvent | WheelEvent | KeyboardEvent): boolean { return navigator.platform.match('Mac') ? evt.metaKey : evt.ctrlKey; } private renderUmlHighLighter(args: MouseEventArgs): void { this.diagram.commandHandler.removeStackHighlighter(); const node: NodeModel = this.diagram.selectedItems.nodes[0]; if (node && node.container && node.container.type === 'Stack' && node.shape.type === 'UmlClassifier') { const bound: Rect = node.wrapper.bounds; if (!bound.containsPoint(this.currentPosition)) { // eslint-disable-next-line max-len const objects: IElement[] = this.diagram.findObjectsUnderMouse({ x: this.currentPosition.x - 20, y: this.currentPosition.y }); const target: IElement = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); if (target && (target as Node).parentId && ((target as Node).parentId === node.id)) { // eslint-disable-next-line max-len const isVertical: boolean = this.diagram.nameTable[(target as Node).parentId].container.orientation === 'Vertical'; renderStackHighlighter( target.wrapper, isVertical, args.position, this.diagram, true); } } } } private isDeleteKey(key: string, value: string): boolean { return (navigator.platform.match('Mac') && key === 'Backspace' && value === 'delete'); } private isMouseOnScrollBar(evt: PointerEvent): boolean { const x: number = evt.offsetX; const y: number = evt.offsetY; const diagramCanvas: HTMLElement = this.diagram.diagramCanvas; const height: number = diagramCanvas.offsetHeight; const width: number = diagramCanvas.offsetWidth; let topLeft: PointModel; let topRight: PointModel; let bottomLeft: PointModel; let bottomRight: PointModel; let bounds: Rect; if (height < diagramCanvas.scrollHeight) { //default scrollbar width in browser is '17pixels'. topLeft = { x: (width - 17), y: 0 }; topRight = { x: width, y: 0 }; bottomLeft = { x: (width - 17), y: height }; bottomRight = { x: width, y: height }; bounds = Rect.toBounds([topLeft, topRight, bottomLeft, bottomRight]); if (bounds.containsPoint({ x: x, y: y })) { return true; } } if (width < diagramCanvas.scrollWidth) { topLeft = { x: 0, y: (height - 17) }; topRight = { x: width, y: (height - 17) }; bottomLeft = { x: 0, y: height }; bottomRight = { x: width, y: height }; bounds = Rect.toBounds([topLeft, topRight, bottomLeft, bottomRight]); if (bounds.containsPoint({ x: x, y: y })) { return true; } } return false; } /** @private */ public updateVirtualization(): void { const delay: number = 50; //let removeObjectInterval: Object; const removeObjectInterval: Object = setInterval( (args: PointerEvent | TouchEvent) => { this.diagram.removeVirtualObjects(removeObjectInterval); }, delay); setTimeout( () => { this.diagram.deleteVirtualObject = true; }, delay); } private checkPreviousAction(): void { if (this.action !== this.previousAction && this.diagram.selectedItems.userHandles.length) { for (let i: number = 0; i < this.diagram.selectedItems.userHandles.length; i++) { if (this.previousAction && this.diagram.selectedItems.userHandles[i]) { this.checkUserHandleEvent(DiagramEvent.onUserHandleMouseLeave); this.previousAction = 'None'; } } } } private checkUserHandleEvent(eventName: DiagramEvent): void { if (this.diagram.selectedItems && this.diagram.selectedItems.userHandles.length > 0) { const currentAction: Actions = (eventName === DiagramEvent.onUserHandleMouseLeave) ? this.previousAction : this.action; const arg: UserHandleEventsArgs = { element: undefined }; for (let i: number = 0; i < this.diagram.selectedItems.userHandles.length; i++) { if ((currentAction === this.diagram.selectedItems.userHandles[i].name) || (eventName === DiagramEvent.onUserHandleMouseUp && currentAction === 'Select')) { arg.element = this.diagram.selectedItems.userHandles[i]; if (eventName === DiagramEvent.onUserHandleMouseEnter) { this.previousAction = this.action; } if (eventName === DiagramEvent.onUserHandleMouseDown) { this.userHandleObject = this.diagram.selectedItems.userHandles[i].name; } const element: HTMLElement = document.getElementById(this.diagram.selectedItems.userHandles[i].name + '_userhandle'); if (eventName === DiagramEvent.onUserHandleMouseUp) { if (this.commandHandler.isUserHandle(this.currentPosition) && element && element.id === this.userHandleObject + '_userhandle') { this.diagram.triggerEvent(eventName, arg); } } else { this.diagram.triggerEvent(eventName, arg); } } } } } public mouseDown(evt: PointerEvent): void { if (this.inAction === true && (this.tool) instanceof NodeDrawingTool) { return; } this.focus = true; //let touches: TouchList; const touches: TouchList = (<TouchEvent & PointerEvent>evt).touches; if (this.isMouseOnScrollBar(evt)) { this.isScrolling = true; evt.preventDefault(); return; } // commanded by gowtham- unwanted cloning of selectedItems // if (isBlazor()) { // this.commandHandler.oldSelectedObjects = cloneObject(this.diagram.selectedItems); // } this.checkUserHandleEvent(DiagramEvent.onUserHandleMouseDown); if (!this.checkEditBoxAsTarget(evt) && (canUserInteract(this.diagram)) || (canZoomPan(this.diagram) && !defaultTool(this.diagram))) { if (this.action === 'Select' || this.action === 'Drag') { this.diagram.updatePortVisibility(this.hoverElement as Node, PortVisibility.Hover, true); } if (((this.tool instanceof PolygonDrawingTool || this.tool instanceof PolyLineDrawingTool) && (evt.button === 2 || evt.buttons === 2))) { // eslint-disable-next-line const arg: IClickEventArgs = { element: cloneBlazorObject(this.diagram), position: cloneBlazorObject(this.currentPosition), count: evt.buttons, actualObject: cloneBlazorObject(this.eventArgs.actualObject), button: (evt.button === 0) ? 'Left' : (evt.button === 1) ? 'Middle' : 'Right' }; this.inAction = false; this.tool.mouseUp(this.eventArgs); } else if (((this.inAction === true) && this.isMouseDown === true && (this.tool instanceof PolygonDrawingTool || this.tool instanceof PolyLineDrawingTool))) { this.isMouseDown = true; this.eventArgs = {}; this.getMouseEventArgs(this.currentPosition, this.eventArgs); this.eventArgs.position = this.currentPosition; this.tool.mouseDown(this.eventArgs); } else { this.isMouseDown = true; this.currentPosition = this.prevPosition = this.getMousePosition(evt); this.eventArgs = {}; if (this.diagram.textEditing && !this.isMouseOnScrollBar(evt)) { this.diagram.endEdit(); this.diagram.textEditing = false; } let target: NodeModel | PointPortModel | ShapeAnnotationModel | PathAnnotationModel; const objects: IElement[] = this.objectFinder.findObjectsUnderMouse( this.currentPosition, this.diagram, this.eventArgs, null, this.action); const obj: IElement = this.objectFinder.findObjectUnderMouse( this.diagram, objects, this.action, this.inAction, this.eventArgs, this.currentPosition); let sourceElement: DiagramElement = null; if (obj !== null) { sourceElement = this.diagram.findElementUnderMouse(obj, this.currentPosition); if (sourceElement) { target = this.commandHandler.findTarget(sourceElement, obj); } } this.action = this.diagram.findActionToBeDone(obj, sourceElement, this.currentPosition, target); //work around - correct it const ctrlKey: boolean = this.isMetaKey(evt); if (ctrlKey && evt.shiftKey && this.diagram.connectorEditingToolModule) { this.action = 'SegmentEnd'; } else if ((ctrlKey || evt.shiftKey) && (!canZoomPan(this.diagram))) { this.action = 'Select'; } this.tool = this.diagram.getTool(this.action); if (!this.tool) { this.action = 'Select'; this.tool = this.diagram.getTool(this.action); } this.getMouseEventArgs(this.currentPosition, this.eventArgs); if (ctrlKey || evt.shiftKey) { const info: Info = (ctrlKey && evt.shiftKey) ? { ctrlKey: ctrlKey, shiftKey: evt.shiftKey } : { ctrlKey: true }; this.eventArgs.info = info; } this.eventArgs.position = this.currentPosition; this.tool.mouseDown(this.eventArgs); this.initialEventArgs = { source: this.eventArgs.source, sourceWrapper: this.eventArgs.sourceWrapper }; this.initialEventArgs.position = this.currentPosition; this.initialEventArgs.info = this.eventArgs.info; this.inAction = false; if (evt.type === 'touchstart') { if (touches && touches.length >= 2) { this.touchStartList = addTouchPointer(<ITouches[]>this.touchStartList, evt, touches); } if (!touches) { evt.preventDefault(); } } } } if (!this.isForeignObject(evt.target as HTMLElement) && !this.isForeignObject(evt.target as HTMLElement, true) && (!touches)) { evt.preventDefault(); } } /** @private */ public mouseMoveExtend(e: PointerEvent | TouchEvent, obj: IElement): void { if (this.tool instanceof PolygonDrawingTool || this.tool instanceof PolyLineDrawingTool) { this.tool.mouseMove(this.eventArgs); } if (this.diagram.scrollSettings.canAutoScroll) { this.checkAutoScroll(e); } else { if (!this.blocked) { (this.tool.mouseMove(this.eventArgs)); } } if (this.eventArgs.target) { this.hoverElement = this.eventArgs.target; } const isNode: boolean = this.eventArgs.target instanceof Node && obj instanceof Node ? false : true; if (this.tool instanceof ConnectTool) { this.diagram.updatePortVisibility( this.hoverElement instanceof Node ? this.hoverElement : this.hoverNode as Node, PortVisibility.Connect | PortVisibility.Hover, isNode); } if (this.hoverElement instanceof Node && this.hoverNode instanceof Node && this.hoverNode && this.hoverNode.id !== this.hoverElement.id) { this.diagram.updatePortVisibility(this.hoverNode, PortVisibility.Connect | PortVisibility.Hover, true); } this.hoverElement = isNode ? null : obj; this.hoverNode = isNode ? null : obj; } /** @private */ public checkAction(obj: IElement): void { if (this.action === 'LabelSelect' && this.eventArgs.sourceWrapper && (this.eventArgs.sourceWrapper instanceof TextElement || this.eventArgs.sourceWrapper instanceof DiagramHtmlElement)) { const annotation: ShapeAnnotation | PathAnnotation = this.commandHandler.findTarget( this.eventArgs.sourceWrapper, this.eventArgs.source) as ShapeAnnotation | PathAnnotation; if (!isSelected(this.diagram, annotation, false, this.eventArgs.sourceWrapper) && canMove(annotation)) { this.action = 'LabelDrag'; this.tool = this.getTool(this.action); this.tool.mouseDown(this.initialEventArgs); } } else if (canMove(obj) && canSelect(obj) && this.initialEventArgs && this.initialEventArgs.source && this.action === 'Select') { if (!isSelected(this.diagram, this.eventArgs.source, false) && this.eventArgs.source instanceof Selector) { this.getMouseEventArgs(this.currentPosition, this.eventArgs); } if (!(obj instanceof Connector) || (obj instanceof Connector && !(contains(this.currentPosition, obj.sourcePoint, obj.hitPadding) || contains(this.currentPosition, obj.targetPoint, obj.hitPadding)))) { this.action = 'Drag'; } this.tool = this.getTool(this.action); this.tool.mouseDown(this.initialEventArgs); } } private isSwimlaneElements(obj: Node): boolean { if (obj && (obj.isLane || obj.isPhase || obj.isHeader)) { return false; } else { return true; } } /* tslint:disable */ /** @private */ public mouseMove(e: PointerEvent | TouchEvent, touches: TouchList): void { this.focus = true; if (this.isScrolling) { e.preventDefault(); return; } if (canUserInteract(this.diagram) || (canZoomPan(this.diagram) && !defaultTool(this.diagram))) { this.currentPosition = this.getMousePosition(e); const objects: IElement[] = this.diagram.findObjectsUnderMouse(this.currentPosition); const obj: IElement = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); drawRulerMarkers(this.diagram, this.currentPosition); let force: boolean = false; let target: NodeModel | PointPortModel | ShapeAnnotationModel | PathAnnotationModel; if (e.type === 'touchmove') { touches = (<TouchEvent & PointerEvent>e).touches; if (touches && touches.length > 1) { this.touchMoveList = addTouchPointer(<ITouches[]>this.touchMoveList, (<PointerEvent>e), touches); if (this.action !== 'PinchZoom') { force = true; } } } if (Point.equals(this.currentPosition, this.prevPosition) === false || this.inAction) { if (this.isMouseDown === false || force) { this.eventArgs = {}; let sourceElement: DiagramElement = null; if (obj !== null) { sourceElement = this.diagram.findElementUnderMouse(obj, this.currentPosition); if (obj !== this.hoverElement) { const content: string | HTMLElement = this.getContent(); if (this.hoverElement && this.hoverElement.tooltip.openOn === 'Auto' && content !== '') { this.elementLeave(); } this.diagram.updatePortVisibility(this.hoverElement as Node, PortVisibility.Hover, true); if (obj instanceof Node) { this.hoverNode = obj; } let canResetElement: boolean = true; if (!this.isSwimlaneElements(obj as Node) && (this.hoverElement && this.isSwimlaneElements(this.hoverElement as Node))) { canResetElement = false; } this.hoverElement = canResetElement ? obj : this.hoverElement; if (canResetElement) { this.elementEnter(this.currentPosition, false); } else { this.hoverElement = obj; } } else if (!this.hoverElement && this.hoverElement === obj) { this.elementEnter(this.currentPosition, true); } if (sourceElement) { target = this.commandHandler.findTarget(sourceElement, obj); } } this.action = this.diagram.findActionToBeDone(obj, sourceElement, this.currentPosition, target); this.checkUserHandleEvent(DiagramEvent.onUserHandleMouseEnter); this.checkPreviousAction(); this.getMouseEventArgs(this.currentPosition, this.eventArgs); this.tool = this.getTool(this.action); this.mouseEvents(); if (this.tool instanceof ConnectorDrawingTool || this.tool instanceof PolyLineDrawingTool || this.tool instanceof PolygonDrawingTool) { this.tool.mouseMove(this.eventArgs); } else if (touches && this.tool instanceof ZoomPanTool) { this.tool.mouseDown(this.eventArgs); } this.updateCursor(); this.renderUmlHighLighter(this.eventArgs); let isNode: boolean = false; if (!(this.hoverElement && (!(this.tool instanceof ZoomPanTool)) && (obj instanceof Node && this.isSwimlaneElements(obj)) && (this.diagram.selectedItems.nodes.length === 0 || !isSelected(this.diagram, this.hoverElement)))) { isNode = true; } this.diagram.updatePortVisibility(this.hoverElement as Node, PortVisibility.Hover, isNode); const content: string | HTMLElement = this.getContent(); if (obj === null && this.hoverElement && this.hoverElement.tooltip.openOn === 'Auto' && content) { this.hoverElement = null; this.elementLeave(); } force = false; } else { this.eventArgs.position = this.currentPosition; if (this.action === 'Drag' && !isSelected(this.diagram, this.eventArgs.source, false) && this.eventArgs.source instanceof Selector) { this.getMouseEventArgs(this.currentPosition, this.eventArgs); } this.mouseEvents(); if (e.ctrlKey || e.shiftKey) { const info: Info = (e.ctrlKey && e.shiftKey) ? { ctrlKey: e.ctrlKey, shiftKey: e.shiftKey } : { ctrlKey: true }; this.eventArgs.info = info; } this.checkAction(obj); const padding: number = this.getConnectorPadding(this.eventArgs); this.getMouseEventArgs(this.currentPosition, this.eventArgs, this.eventArgs.source, padding); this.updateCursor(); this.inAction = true; this.initialEventArgs = null; if (this.action === 'Drag' || this.action === 'Rotate') { this.diagram.diagramActions = this.diagram.diagramActions | DiagramAction.Interactions; } this.mouseMoveExtend(e, obj); } this.prevPosition = this.currentPosition; if (!this.isForeignObject(e.target as HTMLElement, true)) { e.preventDefault(); } } } } /* tslint:enable */ private getContent(): string | HTMLElement { const isPrivateTooltip: number = ((this.hoverElement instanceof Node) && (this.hoverElement as Node).constraints & NodeConstraints.Tooltip) || ((this.hoverElement instanceof Connector) && (this.hoverElement as Connector).constraints & ConnectorConstraints.Tooltip); const content: string | HTMLElement = isPrivateTooltip ? this.hoverElement.tooltip.content : this.diagram.tooltip.content; return content; } private checkAutoScroll(e: PointerEvent | TouchEvent): void { const autoScrollPosition: string = this.startAutoScroll(e); if (!autoScrollPosition && this.doingAutoScroll) { this.doingAutoScroll = false; clearInterval(this.timeOutValue as number); } else if (autoScrollPosition) { if ((this.tool instanceof NodeDrawingTool || this.tool instanceof ConnectorDrawingTool || this.tool instanceof MoveTool || this.tool instanceof ResizeTool || this.tool instanceof SelectTool) && this.inAction) { // eslint-disable-next-line @typescript-eslint/no-this-alias const diagram: DiagramEventHandler = this; const delay: number = 100; if (this.diagram.scrollSettings.canAutoScroll && autoScrollPosition && !this.doingAutoScroll) { this.doingAutoScroll = true; this.timeOutValue = setInterval( (args: PointerEvent | TouchEvent) => { diagram.doAutoScroll(autoScrollPosition, e, delay); }, delay); } } } else { this.blocked = !(this.tool.mouseMove(this.eventArgs)); } } /* tslint:disable */ /** @private */ public mouseUp(evt: PointerEvent): void { this.checkUserHandleEvent(DiagramEvent.onUserHandleMouseUp); if (this.diagram.mode === 'SVG' && canVitualize(this.diagram)) { this.updateVirtualization(); } this.diagram.previousSelectedObject = null; this.diagram.diagramRenderer.rendererActions = this.diagram.removeConstraints(this.diagram.diagramRenderer.rendererActions, RendererAction.DrawSelectorBorder); const touches: TouchList = (<TouchEvent & PointerEvent>evt).touches; if (this.isScrolling) { this.isScrolling = false; evt.preventDefault(); return; } if (!this.checkEditBoxAsTarget(evt) && (canUserInteract(this.diagram)) || (canZoomPan(this.diagram) && !defaultTool(this.diagram))) { if (this.tool && (!(this.tool instanceof PolygonDrawingTool || this.tool instanceof PolyLineDrawingTool) || ((this.tool instanceof PolygonDrawingTool || this.tool instanceof PolyLineDrawingTool) && evt.detail === 2))) { if (!this.isForeignObject(evt.target as HTMLElement) && this.isMouseDown) { document.getElementById(this.diagram.element.id + 'content').focus(); } if (!this.inAction && evt.which !== 3) { if (this.action === 'Drag') { this.action = 'Select'; let oldSelectedValue = (this.diagram.selectedItems.nodes.concat(this.diagram.selectedItems.connectors as NodeModel)) const objects: IElement[] = this.diagram.findObjectsUnderMouse(this.currentPosition); const obj: IElement = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); let isMultipleSelect: boolean = true; if ((!evt.ctrlKey && this.isMouseDown && (this.diagram.selectedItems.nodes.length + this.diagram.selectedItems.connectors.length) > 1) && evt.which === 1 && !canPreventClearSelection(this.diagram.diagramActions)) { isMultipleSelect = false; this.commandHandler.clearSelection(); } if (!isSelected(this.diagram, obj) || (!isMultipleSelect)) { this.commandHandler.selectObjects([obj], undefined, oldSelectedValue); } } } let avoidDropChildren: boolean = false; const history: HistoryLog = this.updateContainerProperties(); let isGroupAction: boolean; this.addUmlNode(); this.inAction = false; this.isMouseDown = false; this.currentPosition = this.getMousePosition(evt); if (this.diagram.selectedObject.helperObject) { isGroupAction = this.updateContainerBounds(); } if (this.tool && (this.tool.prevPosition || this.tool instanceof LabelTool)) { this.eventArgs.position = this.currentPosition; const padding: number = this.getConnectorPadding(this.eventArgs); this.getMouseEventArgs(this.currentPosition, this.eventArgs, this.eventArgs.source, padding); const ctrlKey: boolean = this.isMetaKey(evt); if (ctrlKey || evt.shiftKey) { const info: Info = (ctrlKey && evt.shiftKey) ? { ctrlKey: ctrlKey, shiftKey: evt.shiftKey } : { ctrlKey: true }; this.eventArgs.info = info; } if (this.diagram.diagramActions & DiagramAction.Interactions) { this.diagram.diagramActions = this.diagram.diagramActions & ~DiagramAction.Interactions; } this.eventArgs.clickCount = evt.detail; if (this.diagram.selectedObject.helperObject && (this.tool instanceof MoveTool || this.tool instanceof ResizeTool)) { if (this.diagram.selectedObject.actualObject && (this.diagram.selectedObject.actualObject as Node).parentId !== '') { const parentNode: Node = this.diagram.getObject( (this.diagram.selectedObject.actualObject as Node).parentId) as Node; if (parentNode && parentNode.isLane) { this.commandHandler.isContainer = true; } } avoidDropChildren = this.diagram.lineRoutingModule && this.diagram.nameTable["helper"] && this.eventArgs.target && (this.eventArgs.target as Node).isLane && ((this.eventArgs.source instanceof Selector && (this.eventArgs.source as Selector).nodes.length > 0 && ((this.eventArgs.source as Selector).nodes[0] as Node).parentId === "") || ((this.eventArgs.source as Node).parentId === "")); if (avoidDropChildren) { this.diagram.diagramActions = this.diagram.diagramActions | DiagramAction.PreventLaneContainerUpdate; } this.tool.mouseUp(this.eventArgs, history.isPreventHistory); } else { this.tool.mouseUp(this.eventArgs); if (this.diagram.checkMenu && (window.navigator.userAgent.indexOf('Linux') !== -1 || window.navigator.userAgent.indexOf('X11') !== -1)) { if (!evt.pageY && (evt instanceof TouchEvent) && evt.changedTouches) { window.getSelection().removeAllRanges(); this.diagram.contextMenuModule.contextMenu.open(evt.changedTouches[0].pageY, evt.changedTouches[0].pageX, this.diagram.element); evt.preventDefault(); } else { this.diagram.contextMenuModule.contextMenu.open(evt.pageY, evt.pageX, this.diagram.element); } this.diagram.checkMenu = false; } } if (history.hasStack) { this.diagram.endGroupAction(); } } if (isGroupAction) { this.diagram.endGroupAction(); } this.updateContainerBounds(true); if (this.eventArgs.clickCount !== 2) { this.commandHandler.updateSelectedNodeProperties(this.eventArgs.source); if (avoidDropChildren) { this.diagram.diagramActions = this.diagram.diagramActions & ~DiagramAction.PreventLaneContainerUpdate let nodes: NodeModel[] = this.eventArgs.source instanceof Selector ? (this.eventArgs.source as Selector).nodes : [this.eventArgs.source as Node] if (nodes) { for (let i = 0; i < nodes.length; i++) { if (!nodes[i].container) { this.commandHandler.dropChildToContainer(this.eventArgs.target, nodes[i]); this.commandHandler.renderContainerHelper(nodes[i]); } } } } } if (this.diagram.selectedObject && this.diagram.selectedObject.helperObject) { this.diagram.remove(this.diagram.selectedObject.helperObject); this.diagram.selectedObject = { helperObject: undefined, actualObject: undefined }; // EJ2-42605 - Annotation undo redo not working properly if the line routing is enabled committed by sivakumar sekar // committed to remove the diagram actions public method when line routing is enabled // eslint-disable-next-line if ((this.diagram.diagramActions & DiagramAction.PublicMethod) && (this.diagram.constraints & DiagramConstraints.LineRouting)) { this.diagram.diagramActions = this.diagram.diagramActions & ~DiagramAction.PublicMethod; } } this.blocked = false; if (this.hoverElement) { let portVisibility: PortVisibility = PortVisibility.Connect; if (isSelected(this.diagram, this.hoverElement)) { portVisibility |= PortVisibility.Hover; } this.diagram.updatePortVisibility(this.hoverElement as Node, portVisibility, true); this.hoverElement = null; } this.touchStartList = null; this.touchMoveList = null; if (!(this.tool instanceof TextDrawingTool)) { this.tool = null; } } if (!touches) { evt.preventDefault(); } this.diagram.currentDrawingObject = undefined; const selector: SelectorModel = this.diagram.selectedItems; let disbleRenderSelector: boolean = false; if (this.commandHandler.isUserHandle(this.currentPosition)) { if (this.isForeignObject(evt.target as HTMLElement)) { disbleRenderSelector = true; } } if (!this.inAction && selector.wrapper && selector.userHandles.length > 0 && !disbleRenderSelector) { this.diagram.renderSelector(true); } if (!this.inAction && !this.diagram.currentSymbol && this.eventArgs) { let arg: IClickEventArgs | IBlazorClickEventArgs = { element: cloneBlazorObject(this.eventArgs.source) || cloneBlazorObject(this.diagram), position: cloneBlazorObject(this.eventArgs.position), count: evt.detail, actualObject: cloneBlazorObject(this.eventArgs.actualObject), button: (evt.button === 0) ? 'Left' : (evt.button === 1) ? 'Middle' : 'Right' }; if (isBlazor() && this.diagram.click) { arg = this.getBlazorClickEventArgs(arg); } if (this.diagram.tool !== DiagramTools.ZoomPan) { this.diagram.triggerEvent(DiagramEvent.click, arg); } } this.eventArgs = {}; } this.diagram.diagramActions = this.diagram.diagramActions & ~DiagramAction.PreventLaneContainerUpdate this.eventArgs = {}; this.diagram.commandHandler.removeStackHighlighter();// end the corresponding tool } /* tslint:enable */ private getConnectorPadding(eventArgs: MouseEventArgs): number { let padding: number; const targetObject: SelectorModel = eventArgs.source; if (targetObject && (targetObject instanceof Selector) && targetObject.connectors.length) { const selectedConnector: ConnectorModel = targetObject.connectors[0]; padding = (selectedConnector.constraints & ConnectorConstraints.ConnectToNearByPort) ? selectedConnector.connectionPadding : 0; } else if (targetObject && (targetObject instanceof Connector) && this.action === 'PortDraw' && (this.tool instanceof ConnectorDrawingTool)) { if (targetObject.constraints & ConnectorConstraints.ConnectToNearByPort) { padding = targetObject.connectionPadding; } } return padding || 0; } private getBlazorClickEventArgs(arg: IClickEventArgs | IBlazorClickEventArgs): IBlazorClickEventArgs { arg = { element: this.eventArgs.source ? { selector: cloneBlazorObject(this.eventArgs.source) } : { diagram: cloneBlazorObject(this.diagram) }, position: cloneBlazorObject(this.eventArgs.position), count: arg.count, actualObject: this.eventArgs.actualObject ? { selector: cloneBlazorObject(this.eventArgs.actualObject) } : { diagram: cloneBlazorObject(this.diagram) }, button: arg.button } as IBlazorClickEventArgs; if (this.eventArgs.source instanceof Node) { (arg as IBlazorClickEventArgs).element.selector.nodes = []; (arg as IBlazorClickEventArgs).element.selector.nodes.push(cloneBlazorObject(this.eventArgs.source) as Node); } else if (this.eventArgs.source instanceof Connector) { (arg as IBlazorClickEventArgs).element.selector.connectors = []; (arg as IBlazorClickEventArgs).element.selector.connectors.push(cloneBlazorObject(this.eventArgs.source) as Connector); } return arg; } public addSwimLaneObject(selectedNode: NodeModel): void { let swimlaneNode: NodeModel; let targetNode: NodeModel; let shape: SwimLaneModel; let value: number; let canInsert: boolean; let index: number = 0; let offset: number; const actualShape: SwimLaneModel = (selectedNode.shape as SwimLaneModel); const objects: IElement[] = this.objectFinder.findObjectsUnderMouse( this.currentPosition, this.diagram, this.eventArgs, null, this.action); if (!targetNode) { targetNode = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); } this.diagram.clearSelectorLayer(); if (targetNode && !((targetNode as Node).isLane || (targetNode as Node).isPhase || (targetNode as Node).isHeader)) { for (let i: number = 0; i < objects.length; i++) { const laneNode: Node = this.diagram.nameTable[(objects[i] as NodeModel).id]; if (laneNode.isLane || laneNode.isPhase || laneNode.isHeader) { targetNode = laneNode; } } } if (targetNode && (actualShape.isPhase || (actualShape.isLane && (targetNode as SwimLaneModel).isLane))) { const id: string = (targetNode as Node).parentId; swimlaneNode = this.diagram.nameTable[id]; } if (swimlaneNode) { shape = (swimlaneNode.shape as SwimLaneModel); canInsert = (actualShape.isLane) ? actualShape.orientation === shape.orientation : actualShape.orientation !== shape.orientation; } if (canInsert && (targetNode as Node)) { if (shape.header && (shape as SwimLane).hasHeader && shape.orientation === 'Horizontal') { index = 1; } if (shape.phases.length > 0) { index += 1; } if (actualShape.isPhase) { if (shape.orientation === 'Horizontal') { offset = this.currentPosition.x - swimlaneNode.wrapper.bounds.x; } else { offset = this.currentPosition.y - (swimlaneNode.wrapper.bounds.y + shape.header.height); } const phases: PhaseModel = { id: randomId(), offset: offset, header: { annotation: { content: 'Phase' } } } as PhaseModel; this.diagram.addPhases(swimlaneNode, [phases]); } else { //const laneHeight: number = actualShape.lanes[0].header.height; const lane: LaneModel = { id: randomId(), style: actualShape.lanes[0].style, header: { annotation: { content: actualShape.lanes[0].header.annotation.content, style: actualShape.lanes[0].header.annotation.style }, style: actualShape.lanes[0].header.style } } as LaneModel; const orientation: boolean = (actualShape.orientation === 'Horizontal') ? true : false; // eslint-disable-next-line @typescript-eslint/no-unused-expressions orientation ? lane.height = actualShape.lanes[0].height : lane.width = actualShape.lanes[0].width; if (shape.orientation === 'Horizontal') { value = (targetNode as Node).rowIndex ? (targetNode as Node).rowIndex : this.diagram.nameTable[(targetNode as Node).parentId].rowIndex; if (targetNode.wrapper.offsetY < this.currentPosition.y) { value += 1; } } else { value = (targetNode as Node).columnIndex ? (targetNode as Node).columnIndex : this.diagram.nameTable[(targetNode as Node).parentId].columnIndex; if (this.currentPosition.x < targetNode.wrapper.bounds.center.x) { value -= 1; } } if (shape.lanes.length > (value - index)) { lane.header.width = shape.lanes[value - index].header.width; lane.header.height = shape.lanes[value - index].header.height; } else { lane.header.width = shape.lanes[value - index - 1].header.width; lane.header.height = shape.lanes[value - index - 1].header.height; } this.diagram.addLanes(swimlaneNode, [lane], value - index); } this.commandHandler.select(swimlaneNode); } else if (actualShape.isLane) { const swimLaneobj: NodeModel = { id: randomId(), width: selectedNode.width, height: selectedNode.height, addInfo: selectedNode.addInfo, shape: { type: 'SwimLane', header: { annotation: { content: 'Header' }, height: 50, style: actualShape.lanes[0].header.style }, phases: [{ id: randomId(), header: { annotation: { content: 'Phase' } } }], lanes: [{ id: randomId(), height: selectedNode.height, width: selectedNode.width, style: actualShape.lanes[0].style, header: { annotation: { content: actualShape.lanes[0].header.annotation.content, style: actualShape.lanes[0].header.annotation.style }, style: actualShape.lanes[0].header.style } }], orientation: actualShape.orientation } } as NodeModel; if (actualShape.orientation === 'Vertical') { swimLaneobj.width += 20; } swimLaneobj.offsetX = this.currentPosition.x + (swimLaneobj.width / 2); swimLaneobj.offsetY = this.currentPosition.y + (swimLaneobj.height / 2); this.diagram.add(swimLaneobj); } } /** @private */ public mouseLeave(evt: PointerEvent): void { //Define what has to happen on mouse leave if (this.tool && this.inAction) { this.tool.mouseLeave(this.eventArgs); } if (this.diagram.selectedObject.helperObject) { this.updateContainerProperties(); const isGroupAction: boolean = this.updateContainerBounds(); if (isGroupAction) { this.diagram.endGroupAction(); } } if (this.eventArgs && this.eventArgs.source) { this.diagram.updatePortVisibility(this.eventArgs.source as Node, PortVisibility.Hover, true); this.hoverElement = null; } if (this.eventArgs && !this.eventArgs.source && this.hoverElement) { this.hoverElement = null; } if (this.tool instanceof ConnectTool && this.eventArgs && this.eventArgs.target && this.eventArgs.target instanceof Node) { this.diagram.updatePortVisibility(this.eventArgs.target as Node, PortVisibility.Hover | PortVisibility.Connect, true); this.hoverElement = null; } const selector: SelectorModel = this.diagram.selectedItems; if (selector && selector.wrapper) { if (!(selectionHasConnector(this.diagram, selector as Selector))) { this.diagram.renderSelector(true); } } if (this.diagram.diagramActions & DiagramAction.Interactions || this.diagram.diagramActions & DiagramAction.ToolAction) { this.diagram.diagramActions = this.diagram.diagramActions & ~DiagramAction.ToolAction; } this.isMouseDown = false; this.focus = false; this.touchStartList = null; this.touchMoveList = null; this.elementLeave(); this.commandHandler.removeSnap(); this.inAction = false; this.eventArgs = {}; if (this.diagram.selectedObject && this.diagram.selectedObject.helperObject) { this.diagram.remove(this.diagram.selectedObject.helperObject); this.diagram.selectedObject = { helperObject: undefined, actualObject: undefined }; } this.tool = null; removeRulerMarkers(); if (this.action === 'Rotate') { this.diagram.diagramCanvas.classList.remove('e-diagram-rotate'); } evt.preventDefault(); } /** @private */ public mouseWheel(evt: WheelEvent): void { this.diagram.blazorActions |= BlazorAction.interaction; // eslint-disable-next-line @typescript-eslint/no-explicit-any const up: boolean = ((evt as any).wheelDelta > 0 || -40 * evt.detail > 0) ? true : false; const mousePosition: PointModel = this.getMousePosition(evt); this.diagram.tooltipObject.close(); const ctrlKey: boolean = this.isMetaKey(evt); if (ctrlKey) { this.diagram.zoom(up ? (1.2) : 1 / (1.2), mousePosition); evt.preventDefault(); } else { const horizontalOffset: number = this.diagram.scroller.horizontalOffset; const verticalOffset: number = this.diagram.scroller.verticalOffset; const change: number = up ? 20 : -20; if (this.tool && (this.tool instanceof PolygonDrawingTool || this.tool instanceof PolyLineDrawingTool)) { this.eventArgs = {}; this.getMouseEventArgs(mousePosition, this.eventArgs); this.eventArgs.position = mousePosition; this.tool.mouseWheel(this.eventArgs); } this.diagram.scrollActions |= ScrollActions.Interaction; if (evt.shiftKey) { this.diagram.scroller.zoom(1, change, 0, mousePosition); } else { this.diagram.scroller.zoom(1, 0, change, mousePosition); } this.diagram.scrollActions &= ~ScrollActions.Interaction; if (horizontalOffset !== this.diagram.scroller.horizontalOffset || verticalOffset !== this.diagram.scroller.verticalOffset) { evt.preventDefault(); } } if (this.diagram.textEditing) { this.diagram.isTriggerEvent = true; if (this.diagram.activeLabel.parentId) { const node: NodeModel | ConnectorModel = this.diagram.getObject(this.diagram.activeLabel.parentId); this.diagram.startTextEdit(node, this.diagram.activeLabel.id); } this.diagram.isTriggerEvent = false; } this.diagram.blazorActions = this.diagram.blazorActions & ~BlazorAction.interaction; } private keyArgs: IKeyEventArgs = {}; /** @private */ public keyDown(evt: KeyboardEvent): void { if (!(this.diagram.diagramActions & DiagramAction.TextEdit) && !(this.checkEditBoxAsTarget(evt)) || (evt.key === 'Escape' || evt.keyCode === 27)) { let i: string; const inAction: string = 'inAction'; let command: CommandModel; const keycode: number = evt.keyCode ? evt.keyCode : evt.which; const key: string = evt.key; const ctrlKey: boolean = this.isMetaKey(evt); if (this.diagram.commandManager && this.diagram.commands) { const commands: {} = this.diagram.commands; for (const i of Object.keys(commands)) { command = this.diagram.commands[i]; if (command && (command.gesture.keyModifiers || command.gesture.key)) { if ((keycode === command.gesture.key || (key === Keys[command.gesture.key]) || this.isDeleteKey(key, i)) && (((!command.gesture.keyModifiers) && (!evt.altKey) && (!evt.shiftKey) && (!ctrlKey)) || (command.gesture.keyModifiers && (ctrlKey || evt.altKey || evt.shiftKey) && (this.altKeyPressed(command.gesture.keyModifiers) && evt.altKey) || (this.shiftKeyPressed(command.gesture.keyModifiers) && evt.shiftKey) || (this.ctrlKeyPressed(command.gesture.keyModifiers) && ctrlKey)))) { const canExecute: Function = getFunction(command.canExecute); if (isBlazor() || (canExecute && canExecute({ 'keyDownEventArgs': KeyboardEvent, parameter: command.parameter }))) { evt.preventDefault(); if (evt.key === 'Escape') { if (this.checkEditBoxAsTarget(evt)) { document.getElementById(this.diagram.diagramCanvas.id).focus(); } else if (this.diagram.currentSymbol) { const selectedSymbols: string = 'selectedSymbols'; const source: string = 'sourceElement'; const intDestroy: string = 'intDestroy'; this.diagram.removeFromAQuad(this.diagram.currentSymbol); this.diagram.removeObjectsFromLayer(this.diagram.nameTable[this.diagram.currentSymbol.id]); this.diagram.removeElements(this.diagram.currentSymbol); removeChildNodes(this.diagram.currentSymbol as Node, this.diagram); delete this.diagram.nameTable[this.diagram.currentSymbol.id]; const sourceElement: HTMLElement = this.diagram.droppable[source]; sourceElement.draggable[intDestroy](); const element: HTMLElement = this.diagram.droppable[selectedSymbols]; element.parentNode.removeChild(element); const diagramActions: DiagramAction = this.diagram.diagramActions; this.diagram.diagramActions = this.diagram.addConstraints(diagramActions, DiagramAction.PreventClearSelection); this.tool.mouseUp(this.eventArgs); this.diagram.diagramRenderer.rendererActions = this.diagram.removeConstraints( this.diagram.diagramRenderer.rendererActions, RendererAction.DrawSelectorBorder ); if (this.diagram.previousSelectedObject) { this.diagram.select(this.diagram.previousSelectedObject); } this.action = 'Select'; this.diagram.previousSelectedObject = null; this.diagram.currentSymbol = null; this.diagram.diagramActions = this.diagram.removeConstraints(diagramActions, DiagramAction.PreventClearSelection); this.isMouseDown = false; } else if (this.inAction && this.diagram.drawingObject && this.tool && this.tool[inAction]) { this.tool.mouseUp(this.eventArgs); this.tool = null; this.isMouseDown = false; } } if (command.execute) { if (this.diagram.tool !== DiagramTools.ZoomPan) { // if (i === 'nudgeUp' || i === 'nudgeRight' || i === 'nudgeDown' || i === 'nudgeLeft') { // command.execute() // } else { const execute: Function = getFunction(command.execute); execute({ 'keyDownEventArgs': KeyboardEvent, parameter: command.parameter }); } // } } if (isBlazor()) { const arg: ICommandExecuteEventArgs = { gesture: command.gesture }; this.diagram.triggerEvent(DiagramEvent.commandExecute, arg); } break; } } } } } } // eslint-disable-next-line let selectedObject: (NodeModel | ConnectorModel)[] = (this.diagram.selectedItems.nodes.length) ? this.diagram.selectedItems.nodes : this.diagram.selectedItems.connectors; this.keyArgs = { element: cloneBlazorObject(this.diagram.selectedItems), key: evt.key, keyCode: evt.keyCode ? evt.keyCode : evt.which }; this.getKeyModifier(this.keyArgs, evt); if ((this.diagram.diagramActions & DiagramAction.TextEdit)) { this.getlabel(this.keyArgs, evt); } this.diagram.triggerEvent(DiagramEvent.keyDown, this.keyArgs); } private getlabel(args: IKeyEventArgs, evt: KeyboardEvent): void { const label: ActiveLabel = this.diagram.activeLabel; args.target = this.diagram.element.id + '_editBox'; const node: NodeModel = this.diagram.nameTable[label.parentId]; if (document.getElementById(this.diagram.element.id + '_editBox')) { args.text = (document.getElementById(this.diagram.element.id + '_editBox') as HTMLTextAreaElement).value; for (let i: number = 0; i < node.annotations.length; i++) { if (node.annotations[i].id === label.id) { args.label = node.annotations[i]; break; } } } } private getKeyModifier(args: IKeyEventArgs, evt: KeyboardEvent): void { args.keyModifiers = KeyModifiers.None; if (evt.ctrlKey) { args.keyModifiers |= KeyModifiers.Control; } if (evt.shiftKey) { args.keyModifiers |= KeyModifiers.Shift; } if (evt.altKey) { args.keyModifiers |= KeyModifiers.Alt; } if (this.isMetaKey(evt)) { args.keyModifiers |= KeyModifiers.Meta; } } public keyUp(evt: KeyboardEvent): void { this.keyArgs = { element: cloneBlazorObject(this.diagram.selectedItems), key: evt.key, keyCode: evt.keyCode ? evt.keyCode : evt.which }; const selectedObject: (NodeModel | ConnectorModel)[] = (this.diagram.selectedItems.nodes.length) ? this.diagram.selectedItems.nodes : this.diagram.selectedItems.connectors; this.getKeyModifier(this.keyArgs, evt); if ((this.diagram.diagramActions & DiagramAction.TextEdit)) { this.getlabel(this.keyArgs, evt); } this.diagram.triggerEvent(DiagramEvent.keyUp, this.keyArgs); } private startAutoScroll(e: PointerEvent | TouchEvent): string { const position: PointModel = this.getMousePosition(e); position.x *= this.diagram.scroller.currentZoom; position.y *= this.diagram.scroller.currentZoom; const rulerSize: Size = getRulerSize(this.diagram); let movingPosition: string; const autoScrollBorder: MarginModel = this.diagram.scrollSettings.autoScrollBorder; if (Browser.info.name === 'mozilla') { if (this.diagram.scroller.viewPortWidth === 0) { const bounds: ClientRect | DOMRect = document.getElementById(this.diagram.element.id).getBoundingClientRect(); if (bounds.width !== this.diagram.scroller.viewPortWidth) { this.diagram.scroller.setViewPortSize(bounds.width, bounds.height); } } } if (this.diagram.scrollSettings.canAutoScroll) { if (position.x + this.diagram.scroller.horizontalOffset + autoScrollBorder.right + rulerSize.width >= this.diagram.scroller.viewPortWidth - 18) { movingPosition = 'right'; } else if (position.x + this.diagram.scroller.horizontalOffset < autoScrollBorder.left) { movingPosition = 'left'; } else if (position.y + this.diagram.scroller.verticalOffset + autoScrollBorder.bottom + rulerSize.height > this.diagram.scroller.viewPortHeight - 18) { movingPosition = 'bottom'; } else if (position.y + this.diagram.scroller.verticalOffset < autoScrollBorder.top) { movingPosition = 'top'; } } return movingPosition; } private doAutoScroll(option: string, e: PointerEvent | TouchEvent, delay?: number, autoScroll?: boolean): void { const position: string = option; if ((this.tool instanceof NodeDrawingTool || this.tool instanceof ConnectorDrawingTool || this.tool instanceof MoveTool || this.tool instanceof ResizeTool || this.tool instanceof SelectTool) && this.inAction) { // eslint-disable-next-line @typescript-eslint/no-this-alias const diagram: DiagramEventHandler = this; const pos: PointModel = this.getMousePosition(e); const autoScrollBorder: MarginModel = this.diagram.scrollSettings.autoScrollBorder; const newDelay: number = delay ? delay : 100; let left: number = 0; let top: number = 0; const point: PointModel = { x: pos.x, y: pos.y }; switch (position) { case 'right': point.x = pos.x + 10; left = 10; break; case 'left': point.x = pos.x - 10; left = -10; break; case 'bottom': point.y = pos.y + 10; top = 10; break; case 'top': point.y = pos.y - 10; top = -10; break; } this.eventArgs.position = { x: point.x, y: point.y }; this.currentPosition = this.eventArgs.position; const objects: IElement[] = this.objectFinder.findObjectsUnderMouse( this.currentPosition, this.diagram, this.eventArgs, null, this.action); this.eventArgs.target = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); this.tool.mouseMove(this.eventArgs); this.diagram.scrollActions |= ScrollActions.Interaction; this.diagram.scroller.zoom(1, -left, -top, pos); this.diagram.scrollActions &= ~ScrollActions.Interaction; } } private mouseEvents(): void { const target: (NodeModel | ConnectorModel)[] = this.diagram.findObjectsUnderMouse(this.currentPosition); for (let i: number = 0; i < target.length; i++) { if (this.eventArgs.actualObject === target[i]) { target.splice(i, 1); } } let arg: IMouseEventArgs | IBlazorMouseEventArgs = { targets: {} as NodeModel[] } as IMouseEventArgs; if (!isBlazor()) { arg = { targets: cloneBlazorObject(target) as NodeModel[], element: cloneBlazorObject((this.eventArgs.source === this.eventArgs.actualObject) ? undefined : this.eventArgs.source), actualObject: cloneBlazorObject(this.eventArgs.actualObject) }; } if (isBlazor() && (this.diagram.mouseEnter || this.diagram.mouseOver)) { arg.actualObject = getObjectType(this.eventArgs.actualObject) === Connector ? { connector: cloneBlazorObject(this.eventArgs.actualObject) } : { node: cloneBlazorObject(this.eventArgs.actualObject) }; (arg as IBlazorMouseEventArgs).targets.connector = []; (arg as IBlazorMouseEventArgs).targets.node = []; this.getBlazorCollectionObject(target, arg as IBlazorMouseEventArgs); } if (this.lastObjectUnderMouse && this.diagram.mouseLeave && (!this.eventArgs.actualObject || (this.lastObjectUnderMouse !== this.eventArgs.actualObject))) { let arg: IMouseEventArgs | IBlazorMouseEventArgs = { targets: undefined, element: cloneBlazorObject(this.lastObjectUnderMouse), actualObject: undefined }; if (isBlazor()) { arg = { targets: undefined, element: getObjectType(this.lastObjectUnderMouse) === Connector ? { connector: cloneBlazorObject(target) } : { node: cloneBlazorObject(this.lastObjectUnderMouse) }, actualObject: undefined } as IBlazorMouseEventArgs; } this.diagram.triggerEvent(DiagramEvent.mouseLeave, arg); this.lastObjectUnderMouse = null; } if (!this.lastObjectUnderMouse && this.eventArgs.source || (this.lastObjectUnderMouse !== this.eventArgs.actualObject)) { this.lastObjectUnderMouse = this.eventArgs.actualObject; if (this.eventArgs.actualObject !== undefined) { this.diagram.triggerEvent(DiagramEvent.mouseEnter, arg); } } if (this.eventArgs.actualObject) { this.diagram.triggerEvent(DiagramEvent.mouseOver, arg); } } private getBlazorCollectionObject(obj: (NodeModel | ConnectorModel)[], arg1: IBlazorMouseEventArgs): void { if (obj) { for (let i: number = 0; i < obj.length; i++) { if (getObjectType(obj[i]) === Connector) { arg1.targets.connector.push(cloneBlazorObject(obj[i])); } else { arg1.targets.node.push(cloneBlazorObject(obj[i])); } } } } private elementEnter(mousePosition: PointModel, elementOver: Boolean): void { if (!elementOver) { const isPrivateTooltip: number = ((this.hoverElement instanceof Node) && (this.hoverElement as Node).constraints & NodeConstraints.Tooltip) || ((this.hoverElement instanceof Connector) && (this.hoverElement as Connector).constraints & ConnectorConstraints.Tooltip); const content: string | HTMLElement = this.getContent(); if (this.hoverElement.tooltip.openOn === 'Auto' && content !== '') { updateTooltip(this.diagram, isPrivateTooltip ? this.hoverElement : undefined); } this.diagram.tooltipObject.offsetX = 0; this.diagram.tooltipObject.offsetY = 0; const objects: IElement[] = this.diagram.findObjectsUnderMouse(this.currentPosition); const obj: IElement = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); let idName: string = ((obj as Node).shape && (((obj as Node).shape) instanceof Native)) ? '_content_native_element' : '_groupElement'; let targetEle: HTMLElement = document.getElementById((obj as Node).id + idName); if (this.hoverElement.tooltip.openOn === 'Auto' && content !== '') { (this.diagram.tooltipObject as Tooltip).close(); (this.diagram.tooltipObject as DiagramTooltipModel).openOn = (this.hoverElement.tooltip as DiagramTooltipModel).openOn; if (isBlazor()) { (this.diagram.tooltipObject as BlazorTooltip).open(targetEle, {}); } else { (this.diagram.tooltipObject as Tooltip).dataBind(); } } if (canEnableToolTip(this.hoverElement, this.diagram) && this.hoverElement.tooltip.openOn === 'Auto') { (this.diagram.tooltipObject as Tooltip).open(targetEle); } } } private elementLeave(): void { if (this.diagram.tooltipObject && (this.diagram.tooltipObject as DiagramTooltipModel).openOn !== 'Custom') { this.diagram.tooltipObject.close(); } } private altKeyPressed(keyModifier: KeyModifiers): boolean { if (keyModifier & KeyModifiers.Alt) { return true; } return false; } private ctrlKeyPressed(keyModifier: KeyModifiers): boolean { if (keyModifier & KeyModifiers.Control) { return true; } return false; } private shiftKeyPressed(keyModifier: KeyModifiers): boolean { if (keyModifier & KeyModifiers.Shift) { return true; } return false; } /** @private */ public scrolled(evt: PointerEvent): void { this.diagram.updateScrollOffset(); if (isBlazor() && (this.diagram.realActions & RealAction.OverViewAction)) { this.diagram.setBlazorDiagramProps(false); } } /** @private */ public doubleClick(evt: PointerEvent): void { if (canUserInteract(this.diagram)) { let annotation: DiagramElement; const objects: IElement[] = this.diagram.findObjectsUnderMouse(this.currentPosition); const obj: IElement = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); if (obj !== null && canUserInteract(this.diagram)) { const node: (NodeModel | ConnectorModel) = obj; annotation = this.diagram.findElementUnderMouse(obj, this.currentPosition); if (this.tool && (this.tool instanceof PolygonDrawingTool || this.tool instanceof PolyLineDrawingTool)) { const arg: IDoubleClickEventArgs = { source: cloneBlazorObject(obj) || cloneBlazorObject(this.diagram), position: this.currentPosition, count: evt.detail }; this.tool.mouseUp(this.eventArgs); this.isMouseDown = false; this.eventArgs = {}; this.tool = null; evt.preventDefault(); } else { const layer: LayerModel = this.diagram.commandHandler.getObjectLayer((obj as NodeModel).id); if (layer && !layer.lock && layer.visible) { if (!(this.diagram.diagramActions & DiagramAction.TextEdit)) { let id: string = ''; if (((obj as Node).shape as BpmnShapeModel).shape === 'TextAnnotation') { id = obj.wrapper.children[1].id.split('_')[1]; } this.diagram.startTextEdit // eslint-disable-next-line no-unexpected-multiline (obj, id || (annotation instanceof TextElement ? (annotation.id).split((obj as Node).id + '_')[1] : undefined)); } } } } let arg: IDoubleClickEventArgs | IBlazorDoubleClickEventArgs = { source: cloneBlazorObject(obj) || cloneBlazorObject(this.diagram), position: this.currentPosition, count: evt.detail }; if (isBlazor()) { let selector: SelectorModel; if (obj instanceof Node) { selector = { nodes: [cloneBlazorObject(obj) as Node] }; } else if (obj instanceof Connector) { selector = { connectors: [cloneBlazorObject(obj) as Connector] }; } else { selector = cloneBlazorObject(obj); } arg = { source: obj ? { selector: selector } : { diagram: cloneBlazorObject(this.diagram) }, position: this.currentPosition, count: evt.detail } as IBlazorDoubleClickEventArgs; } this.diagram.triggerEvent(DiagramEvent.doubleClick, arg); } } /** * @private */ public itemClick(actualTarget: NodeModel, diagram: Diagram): NodeModel { const obj: Node = actualTarget as Node; if (checkParentAsContainer(this.diagram, obj, true)) { return obj; } return null; } /** * @private */ public inputChange(evt: InputArgs): void { const minWidth: number = 90; let maxWidth: number; const minHeight: number = 12; let fontsize: number; let textWrapper: DiagramElement; let node: NodeModel | ConnectorModel; let height: number; let width: number; let textBounds: Size; let textBoxWidth: number; let transforms: TransformFactor; let scale: number; const editTextBox: HTMLElement = document.getElementById(this.diagram.element.id + '_editBox'); const editTextBoxDiv: HTMLElement = document.getElementById(this.diagram.element.id + '_editTextBoxDiv'); const text: string = ((editTextBox as HTMLTextAreaElement).value); const line: string[] = text.split('\n'); node = (this.diagram.selectedItems.nodes[0]) ? this.diagram.selectedItems.nodes[0] : this.diagram.selectedItems.connectors[0]; if ((!node && this.tool instanceof TextDrawingTool) || (node && node.shape.type === 'SwimLane')) { node = this.diagram.nameTable[this.diagram.activeLabel.parentId]; } if (node && ((node.shape.type !== 'Text' && node.annotations.length > 0) || (node.shape.type === 'Text'))) { textWrapper = this.diagram.getWrapper(node.wrapper, this.diagram.activeLabel.id); maxWidth = node.wrapper.bounds.width < textWrapper.bounds.width ? node.wrapper.bounds.width : textWrapper.bounds.width; maxWidth = maxWidth > minWidth ? maxWidth : minWidth; textBounds = measureHtmlText(textWrapper.style, text, undefined, undefined, maxWidth); fontsize = Number((editTextBox.style.fontSize).split('px')[0]); if (line.length > 1 && line[line.length - 1] === '') { textBounds.height = textBounds.height + fontsize; } transforms = this.diagram.scroller.transform; scale = canZoomTextEdit(this.diagram) ? transforms.scale : 1; width = textBounds.width; width = ((minWidth > width) ? minWidth : width) * scale; height = ((minHeight > textBounds.height) ? minHeight : textBounds.height) * scale; editTextBoxDiv.style.left = ((((textWrapper.bounds.center.x + transforms.tx) * transforms.scale) - width / 2) - 2.5) + 'px'; editTextBoxDiv.style.top = ((((textWrapper.bounds.center.y + transforms.ty) * transforms.scale) - height / 2) - 3) + 'px'; editTextBoxDiv.style.width = width + 'px'; editTextBoxDiv.style.height = height + 'px'; editTextBox.style.minHeight = minHeight + 'px'; editTextBox.style.minWidth = minWidth + 'px'; editTextBox.style.width = width + 'px'; editTextBox.style.height = height + 'px'; } } /** * @private */ public isAddTextNode(node: Node | Connector, focusOut?: boolean): boolean { if (this.tool instanceof TextDrawingTool || focusOut) { this.tool = null; if (node && (!(canContinuousDraw(this.diagram)))) { this.diagram.drawingObject = undefined; this.diagram.currentDrawingObject = undefined; } if (getObjectFromCollection(this.diagram.nodes, node.id) || getObjectFromCollection(this.diagram.connectors, node.id) || (this.diagram.bpmnModule && this.diagram.bpmnModule.textAnnotationConnectors.indexOf(node as Connector) > -1)) { return false; } return true; } return false; } private checkEditBoxAsTarget(evt: PointerEvent | KeyboardEvent | TouchEvent): boolean { if ((evt.target && (evt.target as HTMLElement).id === this.diagram.element.id + '_editBox')) { return true; } return false; } private getMouseEventArgs(position: PointModel, args: MouseEventArgs, source?: IElement, padding?: number): MouseEventArgs { args.position = position; let obj: IElement; let objects: IElement[]; if (!source) { if (this.action === 'Drag' || this.action === 'ConnectorSourceEnd' || this.action === 'SegmentEnd' || this.action === 'OrthoThumb' || this.action === 'BezierSourceThumb' || this.action === 'BezierTargetThumb' || this.action === 'ConnectorTargetEnd' || this.action.indexOf('Rotate') !== -1 || this.action.indexOf('Resize') !== -1) { obj = this.diagram.selectedItems as IElement; if (!this.diagram.currentSymbol && this.action === 'Drag' && obj && this.diagram.selectedItems.nodes.length > 0 && this.diagram.selectedItems.nodes[0].shape.type === 'SwimLane') { objects = this.diagram.findObjectsUnderMouse(this.currentPosition); obj = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); } } else { objects = this.diagram.findObjectsUnderMouse(this.currentPosition); obj = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); } } else { objects = this.diagram.findObjectsUnderMouse(this.currentPosition, source); obj = this.diagram.findTargetObjectUnderMouse(objects, this.action, this.inAction, args.position, source); } if (obj && (obj as Node).isHeader) { obj = this.diagram.nameTable[(obj as Node).parentId]; this.eventArgs.actualObject = obj; } let wrapper: DiagramElement; if (obj) { wrapper = this.diagram.findElementUnderMouse(obj, this.currentPosition, padding); let currentConnector: ConnectorModel; let nearNode: IElement; let i: number; if ((wrapper && (obj as Node).ports && (obj as Node).ports.length && !checkPort(obj, wrapper) || !wrapper || !(obj as Node)) && objects && objects.length && (source instanceof Selector)) { currentConnector = source.connectors[0]; for (i = objects.length - 1; i >= 0; i--) { nearNode = objects[i]; if ((nearNode instanceof Node) && currentConnector && currentConnector.connectionPadding) { obj = nearNode; wrapper = this.diagram.findElementUnderMouse(obj, this.currentPosition, padding); if (((currentConnector.constraints & ConnectorConstraints.ConnectToNearByPort) && (obj as Node) && (obj as Node).ports && (obj as Node).ports.length && checkPort(obj, wrapper))) { break; } if ((nearNode instanceof Node) && currentConnector && currentConnector.connectionPadding && nearNode.wrapper.outerBounds.containsPoint(this.currentPosition) && (currentConnector.constraints & ConnectorConstraints.ConnectToNearByNode) && !(currentConnector.constraints & ConnectorConstraints.ConnectToNearByPort)) { obj = nearNode; wrapper = this.diagram.findElementUnderMouse(obj, this.currentPosition, 0); break; } } } } } if (!source) { args.source = obj; args.sourceWrapper = wrapper; } else { args.target = obj; args.targetWrapper = wrapper; } args.actualObject = this.eventArgs.actualObject; if (args.source instanceof Selector && args.actualObject === undefined && (args.source.nodes.length > 0 || args.source.connectors.length > 0)) { args.actualObject = args.source.nodes.length > 0 ? this.diagram.nameTable[args.source.nodes[0].id] : this.diagram.nameTable[args.source.connectors[0].id]; } args.startTouches = this.touchStartList; args.moveTouches = this.touchMoveList; return args; } /** @private */ public resetTool(): void { this.action = 'Select'; this.hoverElement = null; this.hoverNode = null; this.tool = this.diagram.getTool(this.action); this.updateCursor(); } /** @private */ public getTool(action: Actions): ToolBase { switch (action) { case 'Select': return new SelectTool(this.commandHandler, true); case 'Drag': return new MoveTool(this.commandHandler); case 'Rotate': return new RotateTool(this.commandHandler); case 'LayoutAnimation': return new ExpandTool(this.commandHandler); case 'FixedUserHandle': return new FixedUserHandleTool(this.commandHandler, true); case 'Hyperlink': return new LabelTool(this.commandHandler); case 'ResizeSouthEast': case 'ResizeSouthWest': case 'ResizeNorthEast': case 'ResizeNorthWest': case 'ResizeSouth': case 'ResizeNorth': case 'ResizeWest': case 'ResizeEast': return new ResizeTool(this.commandHandler, action); case 'ConnectorSourceEnd': case 'ConnectorTargetEnd': case 'BezierSourceThumb': case 'BezierTargetThumb': return new ConnectTool(this.commandHandler, action); case 'SegmentEnd': case 'OrthoThumb': return new ConnectorEditing(this.commandHandler, action); case 'Draw': const shape: string = 'shape'; const basicShape: string = 'basicShape'; const type: string = findObjectType(this.diagram.drawingObject); if (type === 'Node' && this.diagram.drawingObject.shape.type === 'Text') { return new TextDrawingTool(this.commandHandler); } else if (type === 'Node' && (this.diagram.drawingObject.shape[shape] === 'Polygon' || (isBlazor() && this.diagram.drawingObject.shape[basicShape] === 'Polygon')) && !((this.diagram.drawingObject.shape as BasicShapeModel).points)) { return new PolygonDrawingTool(this.commandHandler); } else if (type === 'Node' || (type === 'Node' && this.diagram.drawingObject.shape[shape] === 'Polygon' && ((this.diagram.drawingObject.shape as BasicShapeModel).points))) { return new NodeDrawingTool(this.commandHandler, this.diagram.drawingObject as Node); } else if (type === 'Connector' && (this.diagram.drawingObject as Connector).type === 'Polyline') { return new PolyLineDrawingTool( this.commandHandler); } else if (type === 'Connector') { return new ConnectorDrawingTool( this.commandHandler, 'ConnectorSourceEnd', this.diagram.drawingObject as Connector); } break; case 'Pan': return new ZoomPanTool(this.commandHandler, false); case 'PinchZoom': return new ZoomPanTool(this.commandHandler, true); case 'PortDrag': return new MoveTool(this.commandHandler, 'Port'); case 'PortDraw': return new ConnectorDrawingTool( this.commandHandler, 'ConnectorSourceEnd', this.diagram.drawingObject as Connector); case 'LabelSelect': return new SelectTool(this.commandHandler, true, 'LabelSelect'); case 'LabelDrag': return new LabelDragTool(this.commandHandler); case 'LabelResizeSouthEast': case 'LabelResizeSouthWest': case 'LabelResizeNorthEast': case 'LabelResizeNorthWest': case 'LabelResizeSouth': case 'LabelResizeNorth': case 'LabelResizeWest': case 'LabelResizeEast': return new LabelResizeTool(this.commandHandler, action); case 'LabelRotate': return new LabelRotateTool(this.commandHandler); //for coverage // case 'Custom': // return this.diagram.getTool(action); } return null; } /** @private */ public getCursor(action: Actions): string { const object: DiagramElement | SelectorModel = ((this.diagram.selectedItems as Selector).annotation) ? this.diagram.selectedItems.wrapper.children[0] : this.diagram.selectedItems; const rotateAngle: number = ((this.diagram.selectedItems as Selector).annotation) ? (object.rotateAngle + (object as DiagramElement).parentTransform) : object.rotateAngle; return getCursor(action, rotateAngle); } //start region - interface betweend diagram and interaction /** @private */ public findElementUnderMouse(obj: IElement, position: PointModel, padding?: number): DiagramElement { return this.objectFinder.findElementUnderSelectedItem(obj, position, padding); } /** @private */ public findObjectsUnderMouse(position: PointModel, source?: IElement): IElement[] { return this.objectFinder.findObjectsUnderMouse(position, this.diagram, this.eventArgs, source); } /** @private */ public findObjectUnderMouse(objects: (NodeModel | ConnectorModel)[], action: Actions, inAction: boolean): IElement { return this.objectFinder.findObjectUnderMouse(this.diagram, objects, action, inAction, this.eventArgs, this.currentPosition); } /** @private */ public findTargetUnderMouse( objects: (NodeModel | ConnectorModel)[], action: Actions, inAction: boolean, position: PointModel, source?: IElement): IElement { return this.objectFinder.findObjectUnderMouse(this.diagram, objects, action, inAction, this.eventArgs, position, source); } /** @private */ public findActionToBeDone( obj: NodeModel | ConnectorModel, wrapper: DiagramElement, position: PointModel, target?: NodeModel | PointPortModel | ShapeAnnotationModel | PathAnnotationModel): Actions { return findToolToActivate( obj, wrapper, this.currentPosition, this.diagram, this.touchStartList, this.touchMoveList, target); } private updateContainerBounds(isAfterMouseUp?: boolean): boolean { let isGroupAction: boolean = false; if (this.diagram.selectedObject.helperObject && this.diagram.selectedObject.actualObject instanceof Node) { const boundsUpdate: boolean = (this.tool instanceof ResizeTool) ? true : false; const obj: NodeModel = this.diagram.selectedObject.actualObject; const parentNode: Node = this.diagram.nameTable[(obj as Node).parentId]; if (isAfterMouseUp) { removeChildInContainer(this.diagram, obj, this.currentPosition, boundsUpdate); } else { if (!parentNode || (parentNode && parentNode.shape.type !== 'SwimLane')) { this.diagram.updateDiagramObject(obj); } isGroupAction = updateCanvasBounds(this.diagram, obj, this.currentPosition, boundsUpdate); this.diagram.updateSelector(); if ((obj as Node).isLane || (obj as Node).isPhase) { this.diagram.clearSelection(); this.commandHandler.selectObjects([obj]); } } } return isGroupAction; } // tslint:disable-next-line:max-func-body-length private updateContainerProperties(): HistoryLog { let helperObject: NodeModel; let isChangeProperties: boolean = false; let hasStack: boolean; let connectors: string[]; let hasGroup: boolean = false; let obj: NodeModel; let history: HistoryLog = { hasStack: false, isPreventHistory: false }; if (this.diagram.selectedObject.helperObject) { const objects: IElement[] = this.diagram.findObjectsUnderMouse(this.currentPosition); let target: IElement = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); helperObject = this.diagram.selectedObject.helperObject as Node; obj = this.diagram.selectedObject.actualObject; if (obj instanceof Node) { if (obj.shape.type === 'SwimLane') { connectors = getConnectors(this.diagram, (obj.wrapper.children[0] as GridPanel), 0, true); } if (obj.shape.type !== 'SwimLane' && (obj as Node).parentId && (this.diagram.getObject((obj as Node).parentId) as NodeModel).shape.type === 'SwimLane') { if (target instanceof Node && this.diagram.getObject((target as Node).parentId) && (this.diagram.getObject((target as Node).parentId) as NodeModel).shape.type !== 'SwimLane') { target = this.diagram.getObject(target.parentId) as Node; } } if (this.currentAction === 'Drag' && obj.container && obj.container.type === 'Canvas' && (obj as Node).parentId && (this.diagram.getObject((obj as Node).parentId) as NodeModel).shape.type === 'SwimLane' && target && target !== obj && (target as Node).container && (target as Node).container.type === 'Canvas' && (target as Node).isLane && (obj as Node).isLane && (target as Node).parentId === (obj as Node).parentId) { laneInterChanged(this.diagram, obj, (target as Node), this.currentPosition); history.isPreventHistory = true; } else { let parentNode: Node = this.diagram.nameTable[(obj as Node).parentId]; if (!parentNode || (parentNode && parentNode.shape.type !== 'SwimLane')) { if (parentNode && parentNode.isLane && (obj.constraints & NodeConstraints.AllowMovingOutsideLane)) { const swimlane: Node = this.diagram.getObject(parentNode.parentId) as Node; const laneId: string = swimlane.id + (swimlane.shape as SwimLaneModel).lanes[0].id + '0'; const firstlane: NodeModel = this.diagram.getObject(laneId) as Node; const x: number = firstlane.wrapper.bounds.x; const y: number = firstlane.wrapper.bounds.y; const width: number = swimlane.wrapper.bounds.bottomRight.x - x; const height: number = swimlane.wrapper.bounds.bottomRight.y - y; const swimlaneBounds: Rect = new Rect(x, y, width, height); if (swimlaneBounds.containsPoint(this.currentPosition)) { (obj as Node).offsetX = helperObject.offsetX; (obj as Node).offsetY = helperObject.offsetY; (obj as Node).width = helperObject.width; (obj as Node).height = helperObject.height; (obj as Node).rotateAngle = helperObject.rotateAngle; } } else { (obj as Node).offsetX = helperObject.offsetX; (obj as Node).offsetY = helperObject.offsetY; if (obj && obj.shape && obj.shape.type !== 'UmlClassifier') { if (obj.shape.type !== 'Bpmn' || (obj.shape.type === 'Bpmn' && (obj.shape as BpmnShapeModel).shape !== 'TextAnnotation')) { (obj as Node).width = helperObject.width; (obj as Node).height = helperObject.height; } } (obj as Node).rotateAngle = helperObject.rotateAngle; } } let undoElement: StackEntryObject; if (parentNode && parentNode.container && parentNode.container.type === 'Stack') { this.diagram.startGroupAction(); hasGroup = true; } if (!target && parentNode && parentNode.container && parentNode.container.type === 'Stack' && this.action === 'Drag') { const index: number = parentNode.wrapper.children.indexOf(obj.wrapper); undoElement = { targetIndex: undefined, target: undefined, sourceIndex: index, source: clone(obj) }; if (index > -1) { const children: string[] = parentNode.children; children.splice(children.indexOf(obj.id), 1); this.diagram.nameTable[obj.id].parentId = ''; hasStack = true; parentNode.wrapper.children.splice(index, 1); } } moveChildInStack(obj as Node, target as Node, this.diagram, this.action); parentNode = checkParentAsContainer(this.diagram, obj) ? this.diagram.nameTable[(obj as Node).parentId] : (this.diagram.nameTable[(obj as Node).parentId] || obj); if (parentNode && parentNode.container && parentNode.container.type === 'Canvas') { parentNode.wrapper.maxWidth = parentNode.maxWidth = parentNode.wrapper.actualSize.width; parentNode.wrapper.maxHeight = parentNode.maxHeight = parentNode.wrapper.actualSize.height; isChangeProperties = true; } if (checkParentAsContainer(this.diagram, obj, true) && parentNode && parentNode.container.type === 'Canvas') { checkChildNodeInContainer(this.diagram, obj as NodeModel); } else { history = this.updateContainerPropertiesExtend(parentNode, obj, connectors, helperObject, history); } if ((this.diagram.lineRoutingModule && (this.diagram.constraints & DiagramConstraints.LineRouting)) && (!checkParentAsContainer(this.diagram, obj, true))) { if (obj.children) { this.diagram.realActions |= RealAction.EnableGroupAction; } this.diagram.nodePropertyChange(obj, {} as Node, { width: obj.width, height: obj.height, offsetX: obj.offsetX, offsetY: obj.offsetY } as Node); if (obj.children) { this.diagram.realActions &= ~RealAction.EnableGroupAction; } } if ((obj.shape as SwimLaneModel).lanes) { this.updateLaneChildNode(obj); } if (isChangeProperties) { parentNode.maxWidth = parentNode.wrapper.maxWidth = undefined; parentNode.maxHeight = parentNode.wrapper.maxHeight = undefined; } if (hasStack) { this.diagram.nodePropertyChange(parentNode, {} as Node, { offsetX: parentNode.offsetX, offsetY: parentNode.offsetY, width: parentNode.width, height: parentNode.height, rotateAngle: parentNode.rotateAngle } as Node); const entry: HistoryEntry = { redoObject: { sourceIndex: undefined, source: undoElement.source } as NodeModel, type: 'StackChildPositionChanged', undoObject: undoElement as NodeModel, category: 'Internal' }; if (!(this.diagram.diagramActions & DiagramAction.UndoRedo)) { this.diagram.addHistoryEntry(entry); } } if (obj && obj.container && (obj.container.type === 'Stack' || (obj.container.type === 'Canvas' && (obj as Node).parentId === ''))) { if (obj && obj.shape && obj.shape.type === 'UmlClassifier') { obj.wrapper.measureChildren = true; } this.diagram.nodePropertyChange(obj as Node, {} as Node, { offsetX: obj.offsetX, offsetY: obj.offsetY, width: obj.width, height: obj.height, rotateAngle: obj.rotateAngle } as Node); if (obj && obj.shape && obj.shape.type === 'UmlClassifier') { obj.wrapper.measureChildren = false; } } } updateConnectorsProperties(connectors, this.diagram); history.hasStack = hasGroup; } } if (obj && ((obj as SwimLane).isPhase || (obj as SwimLane).isLane || (obj.shape && obj.shape.type === 'SwimLane'))) { this.diagram.updateDiagramElementQuad(); } return history; } private updateLaneChildNode(obj: NodeModel): void { for (let i: number = 0; i < ((obj.shape as SwimLaneModel).lanes.length); i++) { if ((obj.shape as SwimLaneModel).lanes[i].children && (obj.shape as SwimLaneModel).lanes[i].children.length > 0) { for (let j: number = 0; j < (obj.shape as SwimLaneModel).lanes[i].children.length; j++) { const id: string = (obj.shape as SwimLaneModel).lanes[i].children[j].id; const childNode: NodeModel = this.diagram.nameTable[id]; childNode.offsetX = childNode.wrapper.offsetX; childNode.offsetY = childNode.wrapper.offsetY; } } } } private updateContainerPropertiesExtend( parentNode: Node, obj: NodeModel, connectors: string[], helperObject: NodeModel, history: HistoryLog): HistoryLog { if (this.currentAction === 'ResizeEast' || this.currentAction === 'ResizeSouth' || obj.shape.type === 'SwimLane') { const undoObj: NodeModel = cloneObject(obj); let isUpdateRow: boolean = false; if (parentNode && parentNode.container && parentNode.container.type === 'Grid') { const shape: boolean = parentNode.shape.type === 'SwimLane' ? true : false; const container: GridPanel = (shape ? parentNode.wrapper.children[0] : parentNode.wrapper) as GridPanel; const padding: number = shape ? (parentNode.shape as SwimLane).padding : undefined; const x: number = parentNode.wrapper.bounds.x; const y: number = parentNode.wrapper.bounds.y; if (obj.columnIndex !== undefined && (parentNode.container.orientation === 'Horizontal' && ((shape && (obj as Node).isPhase) || (!shape && obj.rowIndex === 1))) || (parentNode.container.orientation === 'Vertical' && ((!shape && obj.rowIndex > 0 && obj.columnIndex > 0) || (shape && (obj as Node).isLane)))) { if (parentNode.container.orientation === 'Horizontal' && (obj as Node).isPhase && obj.wrapper.width > obj.maxWidth) { obj.maxWidth = obj.wrapper.width; obj.wrapper.maxWidth = obj.wrapper.width; } updateSwimLaneObject(this.diagram, obj as Node, parentNode, helperObject); container.updateColumnWidth(obj.columnIndex, helperObject.width, true, padding); if ((obj as Node).isPhase) { const id: string = (parentNode.shape as SwimLaneModel).phases[obj.columnIndex].header.id; const node: Node = this.diagram.nameTable[id]; if (node.maxWidth < helperObject.width) { node.maxWidth = helperObject.width; node.wrapper.maxWidth = helperObject.width; } } if (parentNode.shape.type === 'SwimLane') { parentNode.width = (parentNode.width) ? container.width : parentNode.width; updateHeaderMaxWidth(this.diagram, parentNode); parentNode.wrapper.width = parentNode.width; connectors = getConnectors(this.diagram, container, obj.rowIndex, false); } } else if (obj.rowIndex !== undefined) { isUpdateRow = true; updateSwimLaneObject(this.diagram, obj as Node, parentNode, helperObject); container.updateRowHeight(obj.rowIndex, helperObject.height, true, padding); if (parentNode.shape.type === 'SwimLane') { parentNode.height = (parentNode.height) ? container.height : parentNode.height; parentNode.wrapper.height = parentNode.height; connectors = getConnectors(this.diagram, container, obj.rowIndex, true); } } if (parentNode.shape.type === 'SwimLane') { history.isPreventHistory = true; } this.diagram.nodePropertyChange(parentNode, {} as Node, { offsetX: parentNode.offsetX, offsetY: parentNode.offsetY, rotateAngle: parentNode.rotateAngle } as Node); this.diagram.drag(parentNode, x - parentNode.wrapper.bounds.x, y - parentNode.wrapper.bounds.y); } else { if (obj && obj.shape && obj.shape.type === 'UmlClassifier') { obj.wrapper.measureChildren = true; } this.diagram.nodePropertyChange(obj as Node, {} as Node, { offsetX: obj.offsetX, offsetY: obj.offsetY, width: obj.width, height: obj.height, rotateAngle: obj.rotateAngle } as Node); obj.wrapper.measureChildren = false; } obj.wrapper.measure(new Size(obj.wrapper.width, obj.wrapper.height)); obj.wrapper.arrange(obj.wrapper.desiredSize); if (this.currentAction === 'ResizeEast' || this.currentAction === 'ResizeSouth') { const redoObject: NodeModel = cloneObject(obj); const entry: HistoryEntry = { category: 'Internal', type: (isUpdateRow) ? 'RowHeightChanged' : 'ColumnWidthChanged', undoObject: undoObj, redoObject: redoObject }; this.diagram.addHistoryEntry(entry); } } updateConnectorsProperties(connectors, this.diagram); return history; } private addUmlNode(): void { const node: NodeModel = this.diagram.selectedItems.nodes[0]; let objects: IElement[] = this.diagram.findObjectsUnderMouse({ x: this.currentPosition.x + 20, y: this.currentPosition.y }); let target: IElement = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); if (!target) { objects = this.diagram.findObjectsUnderMouse({ x: this.currentPosition.x - 20, y: this.currentPosition.y }); target = this.diagram.findObjectUnderMouse(objects, this.action, this.inAction); } if (node && node.container && node.container.type === 'Stack' && (target as Node) && (target as Node).parentId && (target as Node).parentId === node.id) { const innerNode: NodeModel = target as NodeModel; const adornerSvg: SVGElement = getAdornerLayerSvg(this.diagram.element.id); const highlighter: SVGElement = (adornerSvg as SVGSVGElement).getElementById(adornerSvg.id + '_stack_highlighter') as SVGElement; if (highlighter) { const index: number = node.wrapper.children.indexOf(target.wrapper) + 1; this.diagram.enableServerDataBinding(false); const temp: NodeModel = new Node( this.diagram, 'nodes', { style: { fill: node.style.fill, strokeColor: (node.style.strokeColor === 'black') ? '#ffffff00' : node.style.strokeColor }, annotations: (target as Node).annotations, verticalAlignment: 'Stretch', horizontalAlignment: 'Stretch', constraints: (NodeConstraints.Default | NodeConstraints.HideThumbs) & ~ (NodeConstraints.Rotate | NodeConstraints.Drag | NodeConstraints.Resize), minHeight: 25 } as NodeModel, true); temp.annotations[0].content = ' + Name : Type'; const id: string[] = innerNode.id.split('_'); temp.id = randomId() + temp.id; (temp as Node).parentId = node.id; temp.zIndex = -1; (temp as Node).umlIndex = index; this.diagram.startGroupAction(); const redoElement: StackEntryObject = { sourceIndex: node.wrapper.children.indexOf(temp.wrapper), source: temp, target: undefined, targetIndex: undefined }; this.diagram.enableServerDataBinding(true); this.diagram.add(temp); this.diagram.updateConnectorEdges(node as Node); this.diagram.clearSelection(); this.diagram.select([this.diagram.nameTable[temp.id]]); this.diagram.endGroupAction(); this.diagram.startTextEdit(); } } } //end region - interface } /** @private */ class ObjectFinder { /** @private */ public findObjectsUnderMouse( pt: PointModel, diagram: Diagram, eventArgs: MouseEventArgs, source?: IElement, actions?: Actions): IElement[] { // finds the collection of the object that is under the mouse; let actualTarget: (NodeModel | ConnectorModel)[] = []; if (source && source instanceof Selector) { if (source.nodes.length + source.connectors.length === 1) { source = (source.nodes[0] || source.connectors[0]) as IElement; if ((source as Node).children && (source as Node).children.length === 0) { eventArgs.actualObject = source; } } } let container: Container; let bounds: Rect; let child: DiagramElement; let matrix: Matrix; const endPadding: number = (source && (source instanceof Connector) && ((source.constraints & ConnectorConstraints.ConnectToNearByNode) || (source.constraints & ConnectorConstraints.ConnectToNearByPort)) && source.connectionPadding) || 0; const objArray: Object[] = diagram.spatialSearch.findObjects( new Rect(pt.x - 50 - endPadding, pt.y - 50 - endPadding, 100 + endPadding, 100 + endPadding)); const layerObjTable: {} = {}; let layerTarger: (NodeModel | ConnectorModel)[]; for (const obj of objArray) { let point: PointModel = pt; bounds = (obj as NodeModel).wrapper.outerBounds; let pointInBounds: boolean = ((obj as NodeModel).rotateAngle) ? false : bounds.containsPoint(point, endPadding); if ((obj !== source || diagram.currentDrawingObject instanceof Connector) && (obj instanceof Connector) ? obj !== diagram.currentDrawingObject : true && (obj as NodeModel).wrapper.visible) { const layer: LayerModel = diagram.commandHandler.getObjectLayer((obj as NodeModel).id); if (layer && !layer.lock && layer.visible) { layerTarger = layerObjTable[layer.zIndex] = layerObjTable[layer.zIndex] || []; if ((obj as NodeModel).rotateAngle) { container = (obj as NodeModel).wrapper; bounds = cornersPointsBeforeRotation(container); for (child of container.children) { matrix = identityMatrix(); rotateMatrix( matrix, -(child.rotateAngle + child.parentTransform), child.offsetX, child.offsetY); point = transformPointByMatrix(matrix, pt); if (cornersPointsBeforeRotation(child).containsPoint(point, endPadding)) { pointInBounds = true; } } } if (!source || (isSelected(diagram, obj) === false)) { if (canEnablePointerEvents(obj, diagram)) { if ((obj instanceof Connector) ? isPointOverConnector(obj, pt) : pointInBounds) { const padding: number = (obj instanceof Connector) ? obj.hitPadding || 0 : 0; //let element: DiagramElement; const element: DiagramElement = this.findElementUnderMouse(obj as IElement, pt, endPadding || padding); if (element && (obj as Node).id !== 'helper') { insertObject(obj, 'zIndex', layerTarger); } } } } } } } for (const layer of diagram.layers) { actualTarget = actualTarget.concat(layerObjTable[layer.zIndex] || []); for (const obj of actualTarget) { const eventHandler: string = 'eventHandler'; if (obj.shape.type === 'Bpmn' && (obj as Node).processId && (!(diagram[eventHandler].tool instanceof MoveTool) || (diagram[eventHandler].tool instanceof MoveTool) && canAllowDrop(obj))) { const index: number = actualTarget.indexOf(diagram.nameTable[(obj as Node).processId]); if (index > -1) { actualTarget.splice(index, 1); } } if (obj.shape.type === 'UmlClassifier' && (obj as Node).container && (obj as Node).container.type === 'Stack') { const index: number = actualTarget.indexOf(diagram.nameTable[diagram.nameTable[obj.id].wrapper.children[0].id]); if (index > -1) { actualTarget.splice(index, 1); } } } } for (let i: number = 0; i < actualTarget.length; i++) { let parentObj: NodeModel = diagram.nameTable[(actualTarget[i] as Node).parentId]; if (parentObj) { const portElement: DiagramElement = this.findElementUnderMouse(parentObj as IElement, pt); for (let j: number = 0; j < parentObj.ports.length; j++) { if (portElement.id.match('_' + parentObj.ports[j].id + '$')) { const port: PointPortModel = parentObj.ports[j]; if (canDrag(port, diagram) || canDraw(port, diagram)) { return actualTarget as IElement[]; } } } } while (parentObj) { const index: number = actualTarget.indexOf(parentObj); if (index !== -1) { actualTarget.splice(index, 1); } else { break; } parentObj = diagram.nameTable[(parentObj as Node).parentId]; } } this.checkSwimlane(actualTarget, diagram); if (eventArgs && !eventArgs.source) { for (let i: number = 0; i < actualTarget.length; i++) { const parentNode: NodeModel = diagram.nameTable[(actualTarget[i] as Node).parentId]; if (parentNode && parentNode.shape.type === 'SwimLane') { for (let j: number = 0; j < actualTarget.length; j++) { const connector: ConnectorModel | NodeModel = actualTarget[j]; if (connector instanceof Connector) { actualTarget.splice(i, 1); } } } } } return actualTarget as IElement[]; } /** @private */ public checkSwimlane(actualTarget: (NodeModel | ConnectorModel)[], diagram: Diagram): void { let isNode: Boolean; for (let m: number = 0; m < actualTarget.length; m++) { let obj: NodeModel | ConnectorModel = actualTarget[m]; let parentNode: string; let node: Node; if (obj instanceof Node) { parentNode = (actualTarget[m] as Node).parentId; node = obj as Node; } if (parentNode === '') { if (node.shape.type !== 'SwimLane') { isNode = true; } else { isNode = false; } } let parent: NodeModel = diagram.nameTable[parentNode]; if (parent && (parent as Node).isLane && diagram.nameTable[(parent as Node).parentId].zIndex > (obj as Node).zIndex ) { actualTarget[m] = parent; } if (m > 0 && isNode && node && (node.isLane || node.isPhase || node.isHeader)) { if ((actualTarget[m] as Node).zIndex < (actualTarget[m - 1] as Node).zIndex) { let swap: NodeModel | ConnectorModel = actualTarget[m]; actualTarget[m] = actualTarget[m - 1]; actualTarget[m - 1] = swap; } } } if (actualTarget.length >= 2) { let parent: string = ''; for (let i: number = actualTarget.length - 1; i >= 0; i--) { if ((actualTarget[i] as Node).parentId) { let parent1: string = findParentInSwimlane(actualTarget[i] as Node, diagram, parent); let parent2: string = findParentInSwimlane(actualTarget[i - 1] as Node, diagram, parent); let parentNode1: Node = diagram.nameTable[parent1]; let parentNode2: Node = diagram.nameTable[parent2]; if (parentNode2 && parent1 !== parent2 && parentNode1.zIndex < parentNode2.zIndex) { actualTarget.splice(i, 1); } } } } } /** @private */ public isTarget(actualTarget: Node, diagram: Diagram, action: string): IElement { const connector: ConnectorModel = diagram.selectedItems.connectors[0]; let node: Node; node = action === 'ConnectorSourceEnd' ? diagram.nameTable[connector.targetID] : node = diagram.nameTable[connector.sourceID]; if (node && (!node.processId && !actualTarget.processId || node.processId !== actualTarget.processId)) { if (node.processId !== actualTarget.processId) { actualTarget = null; } if (actualTarget && actualTarget.parentId && diagram.nameTable[actualTarget.parentId].shape.type === 'UmlClassifier') { actualTarget = diagram.nameTable[actualTarget.parentId]; } } if (action === 'ConnectorSourceEnd' && connector.targetID) { const targetNode: NodeModel = diagram.nameTable[connector.targetID]; if (targetNode && targetNode.shape && ((targetNode.shape as BpmnShapeModel).shape === 'TextAnnotation')) { const id: string[] = connector.id.split('_'); if (((targetNode.shape.type === 'Bpmn') && actualTarget.shape.type !== 'Bpmn') || (id[0] === actualTarget.id) || (actualTarget.shape as BpmnShapeModel).shape === 'TextAnnotation') { actualTarget = null; } if (actualTarget.parentId && diagram.nameTable[actualTarget.parentId].shape.type === 'UmlClassifier') { actualTarget = diagram.nameTable[actualTarget.parentId]; } } } return actualTarget; } /* tslint:disable */ /** @private */ public findObjectUnderMouse( diagram: Diagram, objects: (NodeModel | ConnectorModel)[], action: Actions, inAction: boolean, eventArg: MouseEventArgs, position?: PointModel, source?: IElement ): IElement { //we will get the wrapper object here //we have to choose the object to be interacted with from the given wrapper //Find the object that is under mouse const eventHandler: string = 'eventHandler'; const endPoint: string = 'endPoint'; let inPort: PointPortModel; let outPort: PointPortModel; let actualTarget: NodeModel | ConnectorModel = null; if (objects.length !== 0) { if (source && source instanceof Selector) { if (source.nodes.length + source.connectors.length === 1) { source = (source.nodes[0] || source.connectors[0]) as IElement; } } if ((action === 'ConnectorSourceEnd' && source || action === 'PortDraw') || ((canDrawOnce(diagram) || canContinuousDraw(diagram)) && getObjectType(diagram.drawingObject) === Connector)) { const connector: ConnectorModel = diagram.selectedItems.connectors[0]; for (let i: number = objects.length - 1; i >= 0; i--) { outPort = getInOutConnectPorts(objects[i] as Node, false); inPort = getInOutConnectPorts(objects[i] as Node, true); const tool: ConnectTool = (diagram[eventHandler].tool as ConnectTool); const portElement: DiagramElement = this.findTargetElement(objects[i].wrapper, position, undefined); if (action === 'Draw' && portElement && (objects[i] instanceof Node) && !checkPort(objects[i], portElement)) { if (((tool && tool[endPoint] === 'ConnectorSourceEnd') && !canOutConnect(objects[i] as NodeModel)) || ((tool && tool[endPoint] === 'ConnectorTargetEnd') && !canInConnect(objects[i] as NodeModel))) { return actualTarget as IElement; } } // eslint-disable-next-line max-len if (objects[i] instanceof Node && ((canOutConnect(objects[i] as NodeModel) || (canPortOutConnect(outPort)) || canInConnect(objects[i] as NodeModel) || (canPortInConnect(inPort))) || (action === 'PortDraw' && (tool instanceof ConnectTool) && tool[endPoint] === 'ConnectorTargetEnd' && (canInConnect(objects[i] as NodeModel) || (canPortInConnect(inPort)))))) { actualTarget = objects[i]; if (connector) { actualTarget = this.isTarget(actualTarget as Node, diagram, action); } eventArg.actualObject = actualTarget as Node; return actualTarget as IElement; } } } else if (action === 'ConnectorTargetEnd' && source) { for (let i: number = objects.length - 1; i >= 0; i--) { inPort = getInOutConnectPorts(objects[i] as Node, true); if (objects[i] instanceof Node && (canInConnect(objects[i] as NodeModel) || (canPortInConnect(inPort)))) { actualTarget = objects[i]; actualTarget = this.isTarget(actualTarget as Node, diagram, action); eventArg.actualObject = actualTarget as Node; return actualTarget as IElement; } } } else if (source && (action === 'Drag' || (diagram[eventHandler].tool instanceof MoveTool))) { let index: number = 0; for (let i: number = 0; i < objects.length; i++) { const temp: NodeModel | ConnectorModel = objects[i]; if (source !== temp && (temp instanceof Connector || !position || temp.wrapper.bounds.containsPoint(position))) { if (canAllowDrop(temp as NodeModel | ConnectorModel)) { if (!actualTarget) { actualTarget = temp; index = (actualTarget as Node | Connector).zIndex; } else { actualTarget = index >= (temp as Node | Connector).zIndex ? actualTarget : temp; index = Math.max(index, (temp as Node | Connector).zIndex); } } } } if (actualTarget && actualTarget.shape.type === 'Bpmn') { if (diagram.selectedItems.nodes.length > 0 && diagram.selectedItems.nodes[0].shape.type === 'Bpmn') { // eslint-disable-next-line no-self-assign actualTarget = actualTarget; } else { actualTarget = null; } } if (actualTarget) { eventArg.actualObject = actualTarget as Node; } return actualTarget as IElement; } else if ((action === 'Select' || action === 'Pan') && diagram[eventHandler].tool) { for (let i: number = objects.length - 1; i >= 0; i--) { if (objects[i] instanceof Connector) { const objj1 = objects[i - 1] as NodeModel; if (objects[i - 1] instanceof Node && objj1.ports) { const portElement: DiagramElement = this.findTargetElement(objj1.wrapper, position, undefined); if ((portElement && (portElement.id.match('_icon_content_shape$') || portElement.id.match('_icon_content_rect$')))) { return objj1 as IElement; } for (let j: number = 0; j < objj1.ports.length; j++) { if (portElement && portElement.id.match('_' + objj1.ports[j].id + '$')) { if (canDraw(objj1.ports[j], diagram)) { return objj1 as IElement; } } } } } } actualTarget = objects[objects.length - 1]; eventArg.actualObject = actualTarget as Node; if (!diagram[eventHandler].itemClick(actualTarget, true)) { if ((actualTarget as Node).parentId) { let obj: Node = actualTarget as Node; const selected: boolean = isSelected(diagram, obj); while (obj) { if (isSelected(diagram, obj) && !selected) { break; } actualTarget = obj; obj = diagram.nameTable[obj.parentId]; } } } } else if (action === 'Pan' || action === 'LayoutAnimation') { for (let i: number = objects.length - 1; i >= 0; i--) { if (objects[i] instanceof Node || objects[i] instanceof Connector) { const portElement = this.findTargetElement(objects[i].wrapper, position, undefined); if ((action === 'Pan') || ((portElement && (portElement.id.match('_icon_content_shape$') || portElement.id.match('_icon_content_rect$'))))) { return objects[i] as IElement; } } } } else { actualTarget = objects[objects.length - 1]; if (eventArg && actualTarget) { eventArg.actualObject = actualTarget as Node; } } } return actualTarget as IElement; } /* tslint:enable */ /** @private */ public findElementUnderSelectedItem(obj: IElement, position: PointModel, padding?: number): DiagramElement { //rewrite this for multiple selection if (obj instanceof Selector) { if (obj.nodes.length === 1 && (!obj.connectors || !obj.connectors.length)) { return this.findElementUnderMouse(obj.nodes[0] as IElement, position); } else if ((!obj.nodes || obj.nodes.length) && obj.connectors.length === 1) { return this.findElementUnderMouse(obj.connectors[0] as IElement, position); } } else { return this.findElementUnderMouse(obj, position, padding); } return null; } private findElementUnderMouse(obj: IElement, position: PointModel, padding?: number): DiagramElement { return this.findTargetElement(obj.wrapper, position, padding); } /** @private */ public findTargetElement(container: Container, position: PointModel, padding?: number): DiagramElement { for (let i: number = container.children.length - 1; i >= 0; i--) { const element: DiagramElement = container.children[i]; if (element && element.outerBounds.containsPoint(position, padding || 0)) { if (element instanceof Container) { const target: DiagramElement = this.findTargetElement(element, position); if (target) { return target; } } if (element.bounds.containsPoint(position, padding || 0)) { return element; } } } if (container.bounds.containsPoint(position, padding) && container.style.fill !== 'none') { return container; } return null; } } /** @private */ export interface Info { ctrlKey?: boolean; shiftKey?: boolean; } /** @private */ export interface MouseEventArgs { position?: PointModel; source?: IElement; sourceWrapper?: DiagramElement; target?: IElement; targetWrapper?: DiagramElement; info?: Info; startTouches?: TouchList | ITouches[]; moveTouches?: TouchList | ITouches[]; clickCount?: number; actualObject?: IElement; portId?: string; } /** @private */ export interface HistoryLog { hasStack?: boolean; isPreventHistory?: boolean; }
the_stack
import fetchMock from 'jest-fetch-mock'; import NetInfo from '../index'; import NativeInterface from '../internal/nativeInterface'; import {NetInfoStateType, NetInfoCellularGeneration} from '../internal/types'; import {DEVICE_CONNECTIVITY_EVENT} from '../internal/privateTypes'; // Mock modules fetchMock.enableMocks(); jest.mock('../internal/nativeModule'); const mockNativeModule = jest.requireMock('../internal/nativeModule').default; beforeEach(() => { mockNativeModule.getCurrentState.mockReset(); }); describe('@react-native-community/netinfo fetch', () => { describe('with cellular data types', () => { describe('5g cellular generation', () => { function dataProvider() { return [ { description: 'should resolve the promise correctly with expected 5g settings', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['5g'], }, }, }, { description: 'should resolve the promise correctly when 5g returns not connected', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: false, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['5g'], }, }, }, { description: 'should resolve the promise correctly when 5g returns internet not reachable', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: false, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['5g'], }, }, }, ]; } dataProvider().forEach(testCase => { it(testCase.description, () => { mockNativeModule.getCurrentState.mockResolvedValue( testCase.expectedConnectionInfo, ); NativeInterface.eventEmitter.emit( DEVICE_CONNECTIVITY_EVENT, testCase.expectedConnectionInfo, ); expect(NetInfo.fetch()).resolves.toEqual( testCase.expectedConnectionInfo, ); }); }); }); describe('4g cellular generation', () => { function dataProvider() { return [ { description: 'should resolve the promise correctly with expected 4g settings', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['4g'], }, }, }, { description: 'should resolve the promise correctly when 4g returns not connected', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: false, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['4g'], }, }, }, { description: 'should resolve the promise correctly when 4g returns internet not reachable', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: false, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['4g'], }, }, }, ]; } dataProvider().forEach(testCase => { it(testCase.description, () => { mockNativeModule.getCurrentState.mockResolvedValue( testCase.expectedConnectionInfo, ); NativeInterface.eventEmitter.emit( DEVICE_CONNECTIVITY_EVENT, testCase.expectedConnectionInfo, ); expect(NetInfo.fetch()).resolves.toEqual( testCase.expectedConnectionInfo, ); }); }); }); describe('3g cellular generation', () => { function dataProvider() { return [ { description: 'should resolve the promise correctly with expected settings', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['3g'], }, }, }, { description: 'should resolve the promise correctly when not connected', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: false, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['3g'], }, }, }, { description: 'should resolve the promise correctly when internet is not reachable', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: false, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['3g'], }, }, }, ]; } dataProvider().forEach(testCase => { it(testCase.description, () => { mockNativeModule.getCurrentState.mockResolvedValue( testCase.expectedConnectionInfo, ); NativeInterface.eventEmitter.emit( DEVICE_CONNECTIVITY_EVENT, testCase.expectedConnectionInfo, ); expect(NetInfo.fetch()).resolves.toEqual( testCase.expectedConnectionInfo, ); }); }); }); describe('2g cellular generation', () => { function dataProvider() { return [ { description: 'should resolve the promise correctly with expected settings', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['2g'], }, }, }, { description: 'should resolve the promise correctly when not connected', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: false, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['2g'], }, }, }, { description: 'should resolve the promise correctly when internet is not reachable', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: false, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['2g'], }, }, }, ]; } dataProvider().forEach(testCase => { it(testCase.description, () => { mockNativeModule.getCurrentState.mockResolvedValue( testCase.expectedConnectionInfo, ); NativeInterface.eventEmitter.emit( DEVICE_CONNECTIVITY_EVENT, testCase.expectedConnectionInfo, ); expect(NetInfo.fetch()).resolves.toEqual( testCase.expectedConnectionInfo, ); }); }); }); describe('null cellular generation', () => { function dataProvider() { return [ { description: 'should resolve the promise correctly with expected settings', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: null, }, }, }, { description: 'should resolve the promise correctly when not connected', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: false, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: null, }, }, }, { description: 'should resolve the promise correctly when internet is not reachable', expectedConnectionInfo: { type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: false, details: { isConnectionExpensive: true, cellularGeneration: null, }, }, }, ]; } dataProvider().forEach(testCase => { it(testCase.description, () => { mockNativeModule.getCurrentState.mockResolvedValue( testCase.expectedConnectionInfo, ); NativeInterface.eventEmitter.emit( DEVICE_CONNECTIVITY_EVENT, testCase.expectedConnectionInfo, ); expect(NetInfo.fetch()).resolves.toEqual( testCase.expectedConnectionInfo, ); }); }); }); }); describe('with unknown and no connection data types', () => { function dataProvider() { return [ { description: 'should resolve the promise correctly when no connection is established (airplane mode)', expectedConnectionInfo: { type: NetInfoStateType.none, isConnected: false, isInternetReachable: true, details: null, }, }, { description: 'should resolve the promise correctly when connection type cannot be determined', expectedConnectionInfo: { type: NetInfoStateType.unknown, isConnected: false, isInternetReachable: true, details: null, }, }, ]; } dataProvider().forEach(testCase => { it(testCase.description, () => { mockNativeModule.getCurrentState.mockResolvedValue( testCase.expectedConnectionInfo, ); NativeInterface.eventEmitter.emit( DEVICE_CONNECTIVITY_EVENT, testCase.expectedConnectionInfo, ); expect(NetInfo.fetch()).resolves.toEqual( testCase.expectedConnectionInfo, ); }); }); }); describe('rejected promises are handled', () => { it('will properly reject a promise if the connection request cannot be resolved', async () => { const rejectionMessage = 'nope, no connection info for you'; // Mock `_fetchCurrentState` in the State constructor. mockNativeModule.getCurrentState.mockResolvedValueOnce({ type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['4g'], }, }); mockNativeModule.getCurrentState.mockRejectedValue( new Error(rejectionMessage), ); try { await NetInfo.fetch(); } catch (error) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore expect(error.message).toMatch(rejectionMessage); } }); }); describe('with configuration options', () => { beforeAll(() => { // Prevent `_checkInternetReachability` from rescheduling. jest.useFakeTimers(); }); beforeEach(() => { fetchMock.resetMocks(); }); describe('reachabilityShouldRun', () => { function dataProvider() { return [ { description: 'reachabilityShouldRun returns true', configuration: { reachabilityShouldRun: () => true, }, expectedConnectionInfo: { type: 'wifi', isConnected: true, details: { isConnectionExpensive: true, cellularGeneration: 'unknown', }, }, expectedIsInternetReachable: null, expectFetchToBeCalled: true, }, { description: 'reachabilityShouldRun returns false', configuration: { reachabilityShouldRun: () => false, }, expectedConnectionInfo: { type: 'wifi', isConnected: true, details: { isConnectionExpensive: true, cellularGeneration: 'unknown', }, }, expectedIsInternetReachable: false, expectFetchToBeCalled: false, }, ]; } dataProvider().forEach(testCase => { it(testCase.description, async () => { mockNativeModule.getCurrentState.mockResolvedValue( testCase.expectedConnectionInfo, ); // Configure NetInfo. NetInfo.configure(testCase.configuration); await expect(NetInfo.fetch()).resolves.toEqual({ ...testCase.expectedConnectionInfo, isInternetReachable: testCase.expectedIsInternetReachable, }); testCase.expectFetchToBeCalled ? expect(fetchMock).toHaveBeenCalled() : expect(fetchMock).not.toHaveBeenCalled(); }); }); }); }); });
the_stack
import { uriToName } from 'common-utils/uriHelper.js'; import * as vscode from 'vscode'; import { toUri } from '../util/uriHelper'; import { ClientConfigKind, ClientConfigScope, ClientConfigTarget, ClientConfigTargetCSpell, ClientConfigTargetDictionary, ClientConfigTargetVSCode, ConfigKinds, } from './clientConfigTarget'; import { configurationTargetToDictionaryScope } from './targetAndScope'; type ConfigKindMask = { [key in ClientConfigKind]?: boolean; }; type ConfigScopeMask = { [key in ClientConfigScope]?: boolean; }; export type ConfigTargetMatchPattern = { [key in ClientConfigKind | ClientConfigScope]?: boolean; }; export type ConfigTargetMatchPatternKey = keyof ConfigTargetMatchPattern; type ConfigTargetMatchPatternKeyNames = { [key in ConfigTargetMatchPatternKey]-?: key; }; const configTargetMatchPatternKeyNames: ConfigTargetMatchPatternKeyNames = { dictionary: 'dictionary', cspell: 'cspell', vscode: 'vscode', unknown: 'unknown', folder: 'folder', workspace: 'workspace', user: 'user', } as const; export const matchKindNone: ConfigKindMask = { dictionary: false, cspell: false, vscode: false }; export const matchKindAll: ConfigKindMask = { dictionary: true, cspell: true, vscode: true }; export const matchKindConfig: ConfigKindMask = { cspell: true, vscode: true }; export const matchKindCSpell: ConfigKindMask = { cspell: true }; export const matchKindVSCode: ConfigKindMask = { vscode: true }; export const matchKindDictionary: ConfigKindMask = { dictionary: true, cspell: false, vscode: false }; export const matchScopeNone: ConfigScopeMask = { unknown: false, folder: false, workspace: false, user: false }; export const matchScopeAll: ConfigScopeMask = { unknown: true, folder: true, workspace: true, user: true }; export const matchScopeAllButUser: ConfigScopeMask = { unknown: true, folder: true, workspace: true, user: false }; export const matchScopeUser: ConfigScopeMask = { user: true }; export const matchScopeWorkspace: ConfigScopeMask = { workspace: true }; export const matchScopeFolder: ConfigScopeMask = { folder: true }; export const matchScopeUnknown: ConfigScopeMask = { unknown: true }; export type MatchTargetsSyncFn = (configTargets: ClientConfigTarget[]) => ClientConfigTarget[] | undefined; export type MatchTargetsAsyncFn = ( configTargets: ClientConfigTarget[] ) => Promise<ClientConfigTarget[] | undefined> | ClientConfigTarget[] | undefined; export type MatchTargetsSingleSyncFn = (configTargets: ClientConfigTarget[]) => [ClientConfigTarget] | undefined; export type MatchTargetsSingleAsyncFn = ( configTargets: ClientConfigTarget[] ) => Promise<ClientConfigTarget[] | undefined> | [ClientConfigTarget] | undefined; export type MatchTargetsFn = MatchTargetsSyncFn | MatchTargetsSingleSyncFn | MatchTargetsAsyncFn | MatchTargetsSingleAsyncFn; export type TargetMatchFn = (target: ClientConfigTarget) => boolean; const KindKeys = Object.freeze(Object.values(ConfigKinds)); // const ScopeKeys = Object.freeze(Object.keys(matchScopeAll) as ClientConfigScope[]); const AllKeys = Object.freeze(Object.values(configTargetMatchPatternKeyNames)); export const dictionaryTargetBestMatches = _buildQuickPickBestMatchTargetFn(matchKindAll, matchScopeAllButUser); export const dictionaryTargetBestMatchesUser = _buildQuickPickBestMatchTargetFn(matchKindAll, matchScopeUser); export const dictionaryTargetBestMatchesWorkspace = _buildQuickPickBestMatchTargetFn(matchKindAll, matchScopeWorkspace); export const dictionaryTargetBestMatchesFolder = _buildQuickPickBestMatchTargetFn(matchKindAll, matchScopeFolder); export const dictionaryTargetBestMatchesCSpell = _buildQuickPickBestMatchTargetFn(matchKindCSpell, matchScopeAll); export const dictionaryTargetBestMatchesVSCodeUser = _buildQuickPickBestMatchTargetFn(matchKindVSCode, matchScopeUser); export const dictionaryTargetBestMatchesVSCodeWorkspace = _buildQuickPickBestMatchTargetFn(matchKindVSCode, matchScopeWorkspace); export const dictionaryTargetBestMatchesVSCodeFolder = _buildQuickPickBestMatchTargetFn(matchKindVSCode, matchScopeFolder); export const patternMatchNoDictionaries = createConfigTargetMatchPattern(negateKind(matchKindDictionary), matchScopeAll); export const patternMatchAll = createConfigTargetMatchPattern(matchKindAll, matchScopeAll); export function findBestMatchingConfigTargets( pattern: ConfigTargetMatchPattern, configTargets: ClientConfigTarget[] ): ClientConfigTarget[] { const matches: ClientConfigTarget[] = []; for (const t of configTargets) { if (!pattern[t.kind] || !pattern[t.scope]) continue; if (matches.length && (matches[0].kind !== t.kind || matches[0].scope !== t.scope)) break; matches.push(t); } return matches; } export function _buildQuickPickBestMatchTargetFn(...params: ConfigTargetMatchPattern[]): MatchTargetsFn { const match = createConfigTargetMatchPattern(...params); return buildQuickPickBestMatchTargetFn(match); } export function buildQuickPickBestMatchTargetFn(match: ConfigTargetMatchPattern, canPickMany: boolean = false): MatchTargetsFn { return async function (configTargets: ClientConfigTarget[]) { const foundTargets = findBestMatchingConfigTargets(match, configTargets); return quickPickTargets(foundTargets, canPickMany); }; } export function buildQuickPickMatchTargetFn(match: ConfigTargetMatchPattern): MatchTargetsFn { return async function (configTargets: ClientConfigTarget[]) { const foundTargets = filterClientConfigTargets(configTargets, match); return quickPickTargets(foundTargets); }; } export async function quickPickBestMatchTarget( targets: ClientConfigTarget[], match: ConfigTargetMatchPattern, canPickMany?: false | undefined ): Promise<[ClientConfigTarget] | undefined>; export async function quickPickBestMatchTarget( targets: ClientConfigTarget[], match: ConfigTargetMatchPattern, canPickMany: true ): Promise<ClientConfigTarget[] | undefined>; export async function quickPickBestMatchTarget( targets: ClientConfigTarget[], match: ConfigTargetMatchPattern, canPickMany: boolean = false ): Promise<ClientConfigTarget[] | undefined> { const fn = buildQuickPickBestMatchTargetFn(match, canPickMany); return fn(targets); } export async function quickPickTargets( targets: ClientConfigTarget[], canPickMany?: undefined | false ): Promise<[ClientConfigTarget] | undefined>; export async function quickPickTargets(targets: ClientConfigTarget[], canPickMany: true): Promise<ClientConfigTarget[] | undefined>; export async function quickPickTargets( targets: ClientConfigTarget[], canPickMany: boolean | undefined ): Promise<ClientConfigTarget[] | undefined>; export async function quickPickTargets( targets: ClientConfigTarget[], canPickMany: boolean = false ): Promise<ClientConfigTarget[] | undefined> { if (!targets.length) throw new UnableToFindTarget('No matching configuration found.'); if (targets.length === 1) return targets; const title = 'Choose Destination'; const items = targets.map((f) => ({ label: f.name, _found: f })); // This bit of strangeness is done to keep the correct return type of `sel`. const sel = canPickMany ? await vscode.window.showQuickPick(items, { title, canPickMany: true }) : await vscode.window.showQuickPick(items, { title }); if (!sel) return undefined; const selected = Array.isArray(sel) ? sel : [sel]; return selected.map((s) => s._found); } export async function quickPickTarget(targets: ClientConfigTarget[]): Promise<ClientConfigTarget | undefined> { const t = await quickPickTargets(targets, false); return t && t[0]; } export function filterClientConfigTargets( targets: ClientConfigTarget[], filterBy: ConfigTargetMatchPattern | TargetMatchFn ): ClientConfigTarget[] { const fn: TargetMatchFn = typeof filterBy === 'function' ? filterBy : filterClientConfigTarget(filterBy); return targets.filter(fn); } export function filterClientConfigTarget(pattern: ConfigTargetMatchPattern): TargetMatchFn { return (t) => doesTargetMatchPattern(t, pattern); } export function doesTargetMatchPattern(target: ClientConfigTarget, pattern: ConfigTargetMatchPattern): boolean { return !!pattern[target.kind] && !!pattern[target.scope]; } export function createConfigTargetMatchPattern( ...patterns: (ConfigTargetMatchPattern | ConfigTargetMatchPatternKey)[] ): ConfigTargetMatchPattern { let r: ConfigTargetMatchPattern = {}; for (const p of patterns) { if (typeof p === 'string') { r[p] = true; } else { r = mergeKeys(r, p, AllKeys); } } return r; } export function negatePattern(p: ConfigTargetMatchPattern): ConfigTargetMatchPattern { return negKeys(p, AllKeys); } export function andPattern(a: ConfigTargetMatchPattern, b: ConfigTargetMatchPattern): ConfigTargetMatchPattern { return andKeys(a, b, AllKeys); } function andKeys<K extends keyof ConfigTargetMatchPattern>( a: ConfigTargetMatchPattern, b: ConfigTargetMatchPattern, keys: readonly K[] ): ConfigTargetMatchPattern { const r: ConfigTargetMatchPattern = {}; for (const k of keys) { const value = and(a[k], b[k]); if (value !== undefined) { r[k] = value; } } return r; } /** * copy ALL of `a` and selected keys from `b` * @param a * @param b * @param keys - keys to copy from b * @returns `a` merged with selected keys from `b` */ function mergeKeys<K extends keyof ConfigTargetMatchPattern>( a: ConfigTargetMatchPattern, b: ConfigTargetMatchPattern, keys: readonly K[] ): ConfigTargetMatchPattern { const r: ConfigTargetMatchPattern = Object.assign({}, a); for (const k of keys) { const value = b[k]; if (value !== undefined) { r[k] = value; } } return r; } function negKeys<K extends keyof ConfigTargetMatchPattern>(a: ConfigTargetMatchPattern, keys: readonly K[]): ConfigTargetMatchPattern { const r: ConfigTargetMatchPattern = {}; for (const k of keys) { r[k] = neg(a[k]); } return r; } function and(a: boolean | undefined, b: boolean | undefined): boolean | undefined { return a === undefined ? b : b === undefined ? a : a && b; } function neg(a: boolean | undefined): boolean | undefined { return a === undefined ? undefined : !a; } function negateKind(k: ConfigKindMask): ConfigKindMask { return negKeys(k, KindKeys); } export function createClientConfigTargetCSpell(configUri: vscode.Uri, scope: ClientConfigScope, name?: string): ClientConfigTargetCSpell { return { kind: 'cspell', scope, name: name || uriToName(configUri), configUri, }; } export function createClientConfigTargetDictionary( dictionaryUri: vscode.Uri, scope: ClientConfigScope, name?: string ): ClientConfigTargetDictionary { return { kind: 'dictionary', scope, name: name || uriToName(dictionaryUri), dictionaryUri, }; } export function createClientConfigTargetVSCode( target: vscode.ConfigurationTarget, docUri: string | null | vscode.Uri | undefined, configScope: vscode.ConfigurationScope | undefined ): ClientConfigTargetVSCode { const scope = configurationTargetToDictionaryScope(target); const ct: ClientConfigTargetVSCode = { kind: 'vscode', scope, name: scope, docUri: toUri(docUri), configScope, }; return ct; } export class UnableToFindTarget extends Error { constructor(msg: string) { super(msg); } }
the_stack
import { vec3, quat } from 'gl-matrix'; import { lerp, hermite, bezier } from '../../../common/math'; import { Animation, UintAnimation, FloatAnimation, Vector3Animation, InterpolationType } from '../../../parsers/mdlx/animations'; import MdxModel from './model'; /** * Animated data for a specific sequence. */ class SdSequence { sd: Sd; start: number; end: number; frames: number[] = []; values: (Uint32Array | Float32Array)[] = []; inTans: (Uint32Array | Float32Array)[] = []; outTans: (Uint32Array | Float32Array)[] = []; constant = false; constructor(sd: Sd, start: number, end: number, animation: Animation, isGlobal: boolean) { this.sd = sd; this.start = start; this.end = end; const interpolationType = sd.interpolationType; const frames = animation.frames; const values = animation.values; const inTans = animation.inTans; const outTans = animation.outTans; const defval = sd.defval; // When using a global sequence, where the first key is outside of the sequence's length, it becomes its constant value. // When having one key in the sequence's range, and one key outside of it, results seem to be non-deterministic. // Sometimes the second key is used too, sometimes not. // It also differs depending where the model is viewed - the WE previewer, the WE itself, or the game. // All three show different results, none of them make sense. // Therefore, only handle the case where the first key is outside. // This fixes problems spread over many models, e.g. HeroMountainKing (compare in WE and in Magos). if (isGlobal && frames[0] > end) { this.frames[0] = frames[0]; this.values[0] = values[0]; } // Go over the keyframes, and add all of the ones that are in this sequence (start <= frame <= end). for (let i = 0, l = frames.length; i < l; i++) { const frame = frames[i]; if (frame >= start && frame <= end) { this.frames.push(frame); this.values.push(values[i]); if (interpolationType > 1) { this.inTans.push(inTans[i]); this.outTans.push(outTans[i]); } } } const tracksCount = this.frames.length; if (tracksCount === 0) { // If there are no keys, use the default value directly. this.constant = true; this.frames[0] = start; this.values[0] = defval; } else if (tracksCount === 1) { // If there's only one key, use it directly. this.constant = true; } else { const firstValue = this.values[0]; // If all of the values in this sequence are the same, might as well make it constant. this.constant = this.values.every((value) => firstValue.every((element: number, index: number) => element === value[index])); } } getValue(out: Uint32Array | Float32Array, frame: number): number { const frames = this.frames; const length = frames.length; // Fixed implementation copied directly from Retera's code. Thank you! if (this.constant || frame < this.start) { this.sd.copy(out, this.values[0]); return -1; } else { let startFrameIndex = -1; let endFrameIndex = -1; const lengthLessOne = length - 1; if ((frame < this.frames[0]) || (frame >= this.frames[lengthLessOne])) { startFrameIndex = lengthLessOne; endFrameIndex = 0; } else { for (let i = 1; i < length; i++) { if (this.frames[i] > frame) { startFrameIndex = i - 1; endFrameIndex = i; break; } } } let startFrame = this.frames[startFrameIndex]; const endFrame = this.frames[endFrameIndex]; let timeBetweenFrames = endFrame - startFrame; if (timeBetweenFrames < 0) { timeBetweenFrames += (this.end - this.start); if (frame < startFrame) { startFrame = endFrame; } } const t = ((timeBetweenFrames) == 0 ? 0 : ((frame - startFrame) / timeBetweenFrames)); this.sd.interpolate(out, this.values, this.inTans, this.outTans, startFrameIndex, endFrameIndex, t); return startFrameIndex; } } } const forcedInterpMap = { KLAV: InterpolationType.DontInterp, KATV: InterpolationType.DontInterp, KPEV: InterpolationType.DontInterp, KP2V: InterpolationType.DontInterp, KRVS: InterpolationType.DontInterp, }; const floatDefval = new Float32Array(1); const uintDefval = new Uint32Array(1); const visibilityDefval = new Float32Array([1]); const translationDefval = vec3.create(); const rotationDefval = quat.create(); const scaleDefval = vec3.fromValues(1, 1, 1); const alphaDefval = visibilityDefval; const colorDefval = translationDefval; const defVals = { // LAYS KMTF: floatDefval, KMTA: alphaDefval, // TXAN KTAT: translationDefval, KTAR: rotationDefval, KTAS: scaleDefval, // GEOA KGAO: alphaDefval, KGAC: colorDefval, // LITE KLAS: floatDefval, KLAE: floatDefval, KLAC: colorDefval, KLAI: floatDefval, KLBI: floatDefval, KLBC: colorDefval, KLAV: visibilityDefval, // ATCH KATV: visibilityDefval, // PREM KPEE: floatDefval, KPEG: floatDefval, KPLN: floatDefval, KPLT: floatDefval, KPEL: floatDefval, KPES: floatDefval, KPEV: visibilityDefval, // PRE2 KP2S: floatDefval, KP2R: floatDefval, KP2L: floatDefval, KP2G: floatDefval, KP2E: floatDefval, KP2N: floatDefval, KP2W: floatDefval, KP2V: visibilityDefval, // RIBB KRHA: floatDefval, KRHB: floatDefval, KRAL: new Float32Array([0]), // Ribbon emitter alphas default to 0 rather than 1. KRCO: colorDefval, KRTX: floatDefval, KRVS: visibilityDefval, // CAMS KCTR: translationDefval, KTTR: translationDefval, KCRL: uintDefval, // NODE KGTR: translationDefval, KGRT: rotationDefval, KGSC: scaleDefval, }; /** * Animated data. */ export abstract class Sd { defval: Float32Array | Uint32Array; model: MdxModel; name: string; globalSequence: SdSequence | null = null; sequences: SdSequence[] = []; interpolationType: InterpolationType; abstract copy(out: Uint32Array | Float32Array | vec3 | quat, value: Uint32Array | Float32Array | vec3 | quat): void; abstract interpolate(out: Uint32Array | Float32Array | vec3 | quat, values: (Uint32Array | Float32Array | vec3 | quat)[], inTans: (Uint32Array | Float32Array | vec3 | quat)[], outTans: (Uint32Array | Float32Array | vec3 | quat)[], start: number, end: number, t: number): void; constructor(model: MdxModel, animation: Animation) { const globalSequences = model.globalSequences; const globalSequenceId = animation.globalSequenceId; const forcedInterp = forcedInterpMap[animation.name]; this.model = model; this.name = animation.name; this.defval = defVals[animation.name]; // Allow to force an interpolation type. // The game seems to do this with visibility tracks, where the type is forced to None. // It came up as a bug report by a user who used the wrong interpolation type. this.interpolationType = forcedInterp !== undefined ? forcedInterp : animation.interpolationType; if (globalSequenceId !== -1 && globalSequences) { this.globalSequence = new SdSequence(this, 0, globalSequences[globalSequenceId], animation, true); } else { for (const sequence of model.sequences) { const interval = sequence.interval; this.sequences.push(new SdSequence(this, interval[0], interval[1], animation, false)); } } } getValue(out: Uint32Array | Float32Array, sequence: number, frame: number, counter: number): number { if (this.globalSequence) { return this.globalSequence.getValue(out, counter % this.globalSequence.end); } return this.sequences[sequence].getValue(out, frame); } isVariant(sequence: number): boolean { if (this.globalSequence) { return !this.globalSequence.constant; } else { return !this.sequences[sequence].constant; } } } /** * A scalar animation. */ export class ScalarSd extends Sd { copy<T extends Uint32Array | Float32Array>(out: T, value: T): void { out[0] = value[0]; } interpolate<T extends Uint32Array | Float32Array>(out: T, values: T[], inTans: T[], outTans: T[], start: number, end: number, t: number): void { const interpolationType = this.interpolationType; const startValue = values[start][0]; if (interpolationType === InterpolationType.DontInterp) { out[0] = startValue; } else if (interpolationType === InterpolationType.Linear) { out[0] = lerp(startValue, values[end][0], t); } else if (interpolationType === InterpolationType.Hermite) { out[0] = hermite(startValue, outTans[start][0], inTans[end][0], values[end][0], t); } else if (interpolationType === InterpolationType.Bezier) { out[0] = bezier(startValue, outTans[start][0], inTans[end][0], values[end][0], t); } } } /** * A vector animation. */ export class VectorSd extends Sd { copy(out: vec3, value: vec3): void { vec3.copy(out, value); } interpolate(out: vec3, values: vec3[], inTans: vec3[], outTans: vec3[], start: number, end: number, t: number): void { const interpolationType = this.interpolationType; if (interpolationType === InterpolationType.DontInterp) { vec3.copy(out, values[start]); } else if (interpolationType === InterpolationType.Linear) { vec3.lerp(out, values[start], values[end], t); } else if (interpolationType === InterpolationType.Hermite) { vec3.hermite(out, values[start], outTans[start], inTans[end], values[end], t); } else if (interpolationType === InterpolationType.Bezier) { vec3.bezier(out, values[start], outTans[start], inTans[end], values[end], t); } } } /** * A quaternion animation. */ export class QuatSd extends Sd { copy(out: quat, value: quat): void { quat.copy(out, value); } interpolate(out: quat, values: quat[], inTans: quat[], outTans: quat[], start: number, end: number, t: number): void { const interpolationType = this.interpolationType; if (interpolationType === InterpolationType.DontInterp) { quat.copy(out, values[start]); } else if (interpolationType === InterpolationType.Linear) { quat.slerp(out, values[start], values[end], t); } else if (interpolationType === InterpolationType.Hermite || interpolationType === InterpolationType.Bezier) { quat.sqlerp(out, values[start], outTans[start], inTans[end], values[end], t); } } } export function createTypedSd(model: MdxModel, animation: Animation): ScalarSd | VectorSd | QuatSd { if (animation instanceof UintAnimation || animation instanceof FloatAnimation) { return new ScalarSd(model, animation); } else if (animation instanceof Vector3Animation) { return new VectorSd(model, animation); } else { return new QuatSd(model, animation); } }
the_stack
import { FluentIterable, FluentIterableImpl } from '../utils/iterable'; import { SChildElement, SModelElementSchema, SModelRootSchema, SModelIndex, SModelElement, SParentElement } from '../base/model/smodel'; import { boundsFeature, layoutContainerFeature, layoutableChildFeature, Alignable, alignFeature, ModelLayoutOptions } from '../features/bounds/model'; import { Fadeable, fadeFeature } from '../features/fade/model'; import { Hoverable, hoverFeedbackFeature, popupFeature } from '../features/hover/model'; import { moveFeature } from '../features/move/model'; import { Selectable, selectFeature } from '../features/select/model'; import { ViewportRootElement } from '../features/viewport/viewport-root'; import { Bounds, ORIGIN_POINT, Point, center } from '../utils/geometry'; import { SShapeElement, SShapeElementSchema } from '../features/bounds/model'; import { editFeature, Routable, filterEditModeHandles } from '../features/edit/model'; import { translatePoint } from '../base/model/smodel-utils'; import { RoutedPoint, LinearEdgeRouter, IEdgeRouter } from './routing'; /** * Serializable schema for graph-like models. */ export interface SGraphSchema extends SModelRootSchema { children: SModelElementSchema[] bounds?: Bounds scroll?: Point zoom?: number layoutOptions?: ModelLayoutOptions } /** * Root element for graph-like models. */ export class SGraph extends ViewportRootElement { layoutOptions?: ModelLayoutOptions; constructor(index = new SGraphIndex()) { super(index); } } /** * A connectable element is one that can have outgoing and incoming edges, i.e. it can be the source * or target element of an edge. There are two kinds of connectable elements: nodes (`SNode`) and * ports (`SPort`). A node represents a main entity, while a port is a connection point inside a node. */ export abstract class SConnectableElement extends SShapeElement { /** * The incoming edges of this connectable element. They are resolved by the index, which must * be an `SGraphIndex`. */ get incomingEdges(): FluentIterable<SEdge> { return (this.index as SGraphIndex).getIncomingEdges(this); } /** * The outgoing edges of this connectable element. They are resolved by the index, which must * be an `SGraphIndex`. */ get outgoingEdges(): FluentIterable<SEdge> { return (this.index as SGraphIndex).getOutgoingEdges(this); } /** * Compute an anchor position for routing an edge towards this element. * * The default implementation returns the element's center point. If edges should be connected * differently, e.g. to some point on the boundary of the element's view, the according computation * should be implemented in a subclass by overriding this method. * * @param referencePoint The point from which the edge is routed towards this element * @param offset An optional offset value to be considered in the anchor computation; * positive values should shift the anchor away from this element, negative values * should shift the anchor more to the inside. */ getAnchor(referencePoint: Point, offset?: number): Point { return center(this.bounds); } /** * Compute an anchor position for routing an edge towards this element and correct any mismatch * of the coordinate systems. * * @param refPoint The point from which the edge is routed towards this element * @param refContainer The parent element that defines the coordinate system for `refPoint` * @param edge The edge for which the anchor is computed * @param offset An optional offset value (see `getAnchor`) */ getTranslatedAnchor(refPoint: Point, refContainer: SParentElement, edge: SEdge, offset?: number): Point { const translatedRefPoint = translatePoint(refPoint, refContainer, this.parent); const anchor = this.getAnchor(translatedRefPoint, offset); return translatePoint(anchor, this.parent, edge.parent); } } /** * Serializable schema for SNode. */ export interface SNodeSchema extends SShapeElementSchema { layout?: string selected?: boolean hoverFeedback?: boolean opacity?: number } /** * Model element class for nodes, which are the main entities in a graph. A node can be connected to * another node via an SEdge. Such a connection can be direct, i.e. the node is the source or target of * the edge, or indirect through a port, i.e. it contains an SPort which is the source or target of the edge. */ export class SNode extends SConnectableElement implements Selectable, Fadeable, Hoverable { children: SChildElement[]; layout?: string; selected: boolean = false; hoverFeedback: boolean = false; opacity: number = 1; hasFeature(feature: symbol): boolean { return feature === selectFeature || feature === moveFeature || feature === boundsFeature || feature === layoutContainerFeature || feature === fadeFeature || feature === hoverFeedbackFeature || feature === popupFeature; } } /** * Serializable schema for SPort. */ export interface SPortSchema extends SShapeElementSchema { selected?: boolean hoverFeedback?: boolean opacity?: number } /** * A port is a connection point for edges. It should always be contained in an SNode. */ export class SPort extends SConnectableElement implements Selectable, Fadeable, Hoverable { selected: boolean = false; hoverFeedback: boolean = false; opacity: number = 1; hasFeature(feature: symbol): boolean { return feature === selectFeature || feature === boundsFeature || feature === fadeFeature || feature === hoverFeedbackFeature; } } /** * Serializable schema for SEdge. */ export interface SEdgeSchema extends SModelElementSchema { sourceId: string targetId: string routingPoints?: Point[] selected?: boolean hoverFeedback?: boolean opacity?: number } /** * Model element class for edges, which are the connectors in a graph. An edge has a source and a target, * each of which can be either a node or a port. The source and target elements are referenced via their * ids and can be resolved with the index stored in the root element. */ export class SEdge extends SChildElement implements Fadeable, Selectable, Routable, Hoverable { sourceId: string; targetId: string; routingPoints: Point[] = []; selected: boolean = false; hoverFeedback: boolean = false; opacity: number = 1; sourceAnchorCorrection?: number; targetAnchorCorrection?: number; router?: IEdgeRouter; get source(): SConnectableElement | undefined { return this.index.getById(this.sourceId) as SConnectableElement; } get target(): SConnectableElement | undefined { return this.index.getById(this.targetId) as SConnectableElement; } route(): RoutedPoint[] { if (this.router === undefined) this.router = new LinearEdgeRouter(); const route = this.router.route(this); return filterEditModeHandles(route, this); } hasFeature(feature: symbol): boolean { return feature === fadeFeature || feature === selectFeature || feature === editFeature || feature === hoverFeedbackFeature; } } /** * Serializable schema for SLabel. */ export interface SLabelSchema extends SShapeElementSchema { text: string selected?: boolean } /** * A label can be attached to a node, edge, or port, and contains some text to be rendered in its view. */ export class SLabel extends SShapeElement implements Selectable, Alignable, Fadeable { text: string; selected: boolean = false; alignment: Point = ORIGIN_POINT; opacity = 1; hasFeature(feature: symbol) { return feature === boundsFeature || feature === alignFeature || feature === fadeFeature || feature === layoutableChildFeature; } } /** * Serializable schema for SCompartment. */ export interface SCompartmentSchema extends SShapeElementSchema { layout?: string } /** * A compartment is used to group multiple child elements such as labels of a node. Usually a `vbox` * or `hbox` layout is used to arrange these children. */ export class SCompartment extends SShapeElement implements Fadeable { children: SChildElement[]; layout?: string; layoutOptions?: {[key: string]: string | number | boolean}; opacity = 1; hasFeature(feature: symbol) { return feature === boundsFeature || feature === layoutContainerFeature || feature === layoutableChildFeature || feature === fadeFeature; } } /** * A specialized model index that tracks outgoing and incoming edges. */ export class SGraphIndex extends SModelIndex<SModelElement> { private outgoing: Map<string, SEdge[]> = new Map; private incoming: Map<string, SEdge[]> = new Map; add(element: SModelElement): void { super.add(element); if (element instanceof SEdge) { // Register the edge in the outgoing map if (element.sourceId) { const sourceArr = this.outgoing.get(element.sourceId); if (sourceArr === undefined) this.outgoing.set(element.sourceId, [element]); else sourceArr.push(element); } // Register the edge in the incoming map if (element.targetId) { const targetArr = this.incoming.get(element.targetId); if (targetArr === undefined) this.incoming.set(element.targetId, [element]); else targetArr.push(element); } } } remove(element: SModelElement): void { super.remove(element); if (element instanceof SEdge) { // Remove the edge from the outgoing map const sourceArr = this.outgoing.get(element.sourceId); if (sourceArr !== undefined) { const index = sourceArr.indexOf(element); if (index >= 0) { if (sourceArr.length === 1) this.outgoing.delete(element.sourceId); else sourceArr.splice(index, 1); } } // Remove the edge from the incoming map const targetArr = this.incoming.get(element.targetId); if (targetArr !== undefined) { const index = targetArr.indexOf(element); if (index >= 0) { if (targetArr.length === 1) this.incoming.delete(element.targetId); else targetArr.splice(index, 1); } } } } getAttachedElements(element: SModelElement): FluentIterable<SModelElement> { return new FluentIterableImpl( () => ({ outgoing: this.outgoing.get(element.id), incoming: this.incoming.get(element.id), nextOutgoingIndex: 0, nextIncomingIndex: 0 }), (state) => { let index = state.nextOutgoingIndex; if (state.outgoing !== undefined && index < state.outgoing.length) { state.nextOutgoingIndex = index + 1; return { done: false, value: state.outgoing[index] }; } index = state.nextIncomingIndex; if (state.incoming !== undefined) { // Filter out self-loops: edges that are both outgoing and incoming while (index < state.incoming.length) { const edge = state.incoming[index]; if (edge.sourceId !== edge.targetId) { state.nextIncomingIndex = index + 1; return { done: false, value: edge }; } index++; } } return { done: true, value: undefined as any }; } ); } getIncomingEdges(element: SConnectableElement): FluentIterable<SEdge> { return this.incoming.get(element.id) || []; } getOutgoingEdges(element: SConnectableElement): FluentIterable<SEdge> { return this.outgoing.get(element.id) || []; } }
the_stack
import * as stream from "readable-stream"; import * as path from "path"; import * as fs from "fs"; import * as assert from "assert"; import { testContext, disposeTestDocumentStore } from "../Utils/TestUtil"; import * as util from "util"; import { IDocumentStore, IDocumentQuery, IDocumentSession, QueryStatistics, StreamQueryStatistics, LoadOptions, } from "../../src"; import { TypeUtil } from "../../src/Utility/TypeUtil"; import { AbstractJavaScriptIndexCreationTask } from "../../src/Documents/Indexes/AbstractJavaScriptIndexCreationTask"; // tslint:disable-next-line:no-console let print = console.log; print = TypeUtil.NOOP; describe("Readme query samples", function () { let store: IDocumentStore; let session: IDocumentSession; let data: any[]; let query: IDocumentQuery<any>; let results: any; class User { public name: string; public age: number; public registeredAt: Date; constructor(opts: object) { opts = opts || {}; Object.assign(this, opts); } } beforeEach(async function () { store = await testContext.getDocumentStore(); session = store.openSession(); results = null; }); afterEach(async () => await disposeTestDocumentStore(store)); describe("with data set with includes", function () { beforeEach(async function () { data = [ new User({ name: "John", age: 30, registeredAt: new Date(2017, 10, 11), kids: ["users/2", "users/3"] }), new User({ name: "Stefanie", age: 25, registeredAt: new Date(2015, 6, 30) }), new User({ name: "Thomas", age: 25, registeredAt: new Date(2016, 3, 25) }) ]; const newSession = store.openSession(); for (let i = 0; i < data.length; i++) { await newSession.store(data[i], `users/${i + 1}`); } await newSession.saveChanges(); }); it("loading data with include()", async () => { // tslint:disable-next-line:no-shadowed-variable const session = store.openSession(); // users/1 // { // "name": "John", // "kids": ["users/2", "users/3"] // } const user1 = await session .include("kids") .load("users/1"); // Document users/1 is going to be pulled along // with docs referenced in "kids" field within a single request const user2 = await session.load("users/2"); // this won't call server again assert.ok(user1); assert.ok(user2); assert.strictEqual(session.advanced.numberOfRequests, 1); }); it("loading data with passing includes", async () => { // tslint:disable-next-line:no-shadowed-variable const session = store.openSession(); // users/1 // { // "name": "John", // "kids": ["users/2", "users/3"] // } const user1 = await session .load("users/1", { includes: [ "kids" ] } as LoadOptions<any>); const user2 = await session.load("users/2"); // this won't call server again // Document users/1 is going to be pulled along // with docs referenced in "kids" field within a single request assert.ok(user1); assert.ok(user2); assert.strictEqual(session.advanced.numberOfRequests, 1); }); }); describe("attachments", () => { it("store attachment", async () => { const doc = new User({ name: "John" }); // track entity await session.store(doc); // open and store attachment const fileStream = fs.createReadStream(path.join(__dirname, "../Assets/tubes.png")); session.advanced.attachments.store(doc, "tubes.png", fileStream, "image/png"); await session.saveChanges(); }); describe("having attachment", () => { let doc; beforeEach(async () => { doc = new User({ name: "John" }); // track entity await session.store(doc); // open and store attachment const fileStream = fs.createReadStream(path.join(__dirname, "../Assets/tubes.png")); session.advanced.attachments.store(doc, "tubes.png", fileStream, "image/png"); await session.saveChanges(); fileStream.close(); }); it("get attachment", (done) => { session.advanced.attachments.get(doc.id, "tubes.png") .then(attachment => { print(attachment.details); // attachment.data is a Readable attachment.data .pipe(fs.createWriteStream(".test/tubes.png")) .on("error", done) .on("finish", () => { attachment.dispose(); done(); }); }); }); it("attachment exists", async () => { print(await session.advanced.attachments.exists(doc.id, "tubes.png")); print(await session.advanced.attachments.exists(doc.id, "x.png")); }); it("get attachments names", async () => { { const session2 = store.openSession(); const entity = await session2.load(doc.id); print(await session2.advanced.attachments.getNames(entity)); } }); }); }); describe("bulk insert", async () => { it("example", async () => { // create bulk insert instance using DocumentStore instance const bulkInsert = store.bulkInsert(); // insert your documents for (const name of ["Anna", "Maria", "Miguel", "Emanuel", "Dayanara", "Aleida"]) { const user = new User({ name }); await bulkInsert.store(user); print(user); } // flush data and finish await bulkInsert.finish(); }); }); describe("changes", () => { it("example", async () => { const changes = store.changes(); const docsChanges = changes.forDocumentsInCollection("users"); docsChanges.on("data", change => { print(change); changes.dispose(); }); { const session2 = store.openSession(); await session2.store(new User({ name: "Starlord" })); await session2.saveChanges(); } return new Promise(resolve => setTimeout(() => { resolve(); }, 300)); }); }); describe("with user data set", function () { beforeEach(async () => prepareUserDataSet(store)); afterEach(async () => { if (query && results) { print("// RQL"); print("// " + query.getIndexQuery().query); print("// ", query.getIndexQuery().queryParameters); results.forEach(x => delete x["@metadata"]); print("// " + util.inspect(results)); } }); it("projections single field", async () => { query = session.query({ collection: "users" }) .selectFields("name"); results = await query.all(); }); it("projections multiple fields", async () => { query = session.query({ collection: "users" }) .selectFields(["name", "age"]); results = await query.all(); }); it("distinct", async () => { query = session.query({ collection: "users" }) .selectFields("age") .distinct(); results = await query.all(); }); it("where equals", async () => { query = session.query({ collection: "users" }) .whereEquals("age", 30); results = await query.all(); }); it("where in", async () => { query = session.query({ collection: "users" }) .whereIn("name", ["John", "Thomas"]); results = await query.all(); }); it("where between", async () => { query = session.query({ collection: "users" }) .whereBetween("registeredAt", new Date(2016, 0, 1), new Date(2017, 0, 1)); results = await query.all(); }); it("where greater than", async () => { query = session.query({ collection: "users" }) .whereGreaterThan("age", 29); results = await query.all(); }); it("where exists", async () => { query = session.query({ collection: "users" }) .whereExists("kids"); results = await query.all(); }); it("where contains any", async () => { query = session.query({ collection: "users" }) .containsAny("kids", ["Mara"]); results = await query.all(); }); it("search()", async () => { query = session.query({ collection: "users" }) .search("kids", "Mara John"); results = await query.all(); }); it("subclause", async () => { query = session.query({ collection: "users" }) .whereExists("kids") .orElse() .openSubclause() .whereEquals("age", 25) .whereNotEquals("name", "Thomas") .closeSubclause(); results = await query.all(); }); it("not()", async () => { query = await session.query({ collection: "users" }) .not() .whereEquals("age", 25); results = await query.all(); }); it("orElse", async () => { query = await session.query({ collection: "users" }) .whereExists("kids") .orElse() .whereLessThan("age", 30); results = await query.all(); }); it("orderBy()", async () => { query = await session.query({ collection: "users" }) .orderBy("age"); results = await query.all(); }); it("take()", async () => { query = await session.query({ collection: "users" }) .orderBy("age") .take(2); results = await query.all(); }); it("skip()", async () => { query = await session.query({ collection: "users" }) .orderBy("age") .take(1) .skip(1); results = await query.all(); }); it("can get stats", async () => { let stats: QueryStatistics; query = session.query({ collection: "users" }) .whereGreaterThan("age", 29) .statistics(s => stats = s); results = await query.all(); assert.ok(stats); assert.strictEqual(stats.totalResults, 1); assert.strictEqual(stats.skippedResults, 0); assert.strictEqual(stats.indexName, "Auto/users/Byage"); assert.strictEqual(stats.isStale, false); assert.ok(stats.resultEtag); assert.ok(stats.durationInMs); assert.ok(stats.lastQueryTime instanceof Date); assert.ok(stats.timestamp instanceof Date); assert.ok(stats.indexTimestamp instanceof Date); }); it("can stream users", async () => { const result: any = []; const userStream = await session.advanced.stream<User>("users/"); userStream.on("data", user => { result.push(user); print(user); // ... }); userStream.on("end", () => { assert.ok(result.length); }); await new Promise<void>((resolve, reject) => { stream.finished(userStream, err => { err ? reject(err) : resolve(); }); }); }); it("can stream query and get stats", async () => { let stats: StreamQueryStatistics; const items = []; query = session.query({ collection: "users" }) .whereGreaterThan("age", 29); const queryStream = await session.advanced.stream(query, _ => stats = _); queryStream.on("data", user => { print(user); items.push(user); // ... }); queryStream.once("stats", stats => { print("STREAM STATS", stats); // ... }); await new Promise<void>((resolve, reject) => { queryStream.on("end", () => { try { assert.ok(items.length); assert.ok(stats); assert.strictEqual(stats.totalResults, 1); assert.strictEqual(stats.indexName, "Auto/users/Byage"); assert.ok(stats.resultEtag); assert.ok(stats.indexTimestamp instanceof Date); } catch (err) { reject(err); } resolve(); }); }); }); it("can suggest", async () => { class UsersIndex extends AbstractJavaScriptIndexCreationTask<User, Pick<User, "name">> { constructor() { super(); this.map(User, doc => { return { name: doc.name } }); this.suggestion("name"); } } await store.executeIndex(new UsersIndex()); await testContext.waitForIndexing(store); { const session = store.openSession(); const suggestionQueryResult = await session.query(User, UsersIndex) .suggestUsing(x => x.byField("name", "Jon")) .execute(); assert.strictEqual(suggestionQueryResult.name.suggestions.length, 1); } }); it("can subscribe", async () => { // create a subscription const subscriptionName = await store.subscriptions.create({ query: "from users where age >= 30" }); // get subscription worker for your subscription const subscription = store.subscriptions.getSubscriptionWorker({ subscriptionName }); subscription.on("error", err => { // handle errors }); let done; const testDone = new Promise(resolve => done = resolve); subscription.on("batch", (batch, callback) => { try { // do batch processing print(batch.items); // call the callback, once you're done callback(); } catch (err) { // if processing fails for a particular batch // pass the error to the callback callback(err); } done(); }); await testDone; }); }); it("can use advanced.patch", async () => { store.conventions.findCollectionNameForObjectLiteral = () => "users"; { const session = store.openSession(); await session.store({ name: "Matilda", age: 17, underAge: true }, "users/1"); await session.saveChanges(); } { const session = store.openSession(); session.advanced.increment("users/1", "age", 1); session.advanced.patch("users/1", "underAge", false); await session.saveChanges(); } { const session = store.openSession(); const loaded: any = await session.load("users/1"); assert.strictEqual(loaded.underAge, false); assert.strictEqual(loaded.age, 18); assert.strictEqual(loaded.name, "Matilda"); } }); describe("with revisions set up", function() { beforeEach(async () => testContext.setupRevisions(store, false, 5)); it("can get revisions", async () => { const session = store.openSession(); const user = { name: "Marcin", age: 30, pet: "users/4" }; await session.store(user, "users/1"); await session.saveChanges(); user.name = "Roman"; user.age = 40; await session.saveChanges(); const revisions = await session.advanced.revisions.getFor("users/1"); assert.strictEqual(revisions.length, 2); }); }); describe("can use time series", function () { it("basic", async () => { { const session = store.openSession(); await session.store({ name: "John" }, "users/1"); const tsf = session.timeSeriesFor("users/1", "heartbeat"); tsf.append(new Date(), 120); await session.saveChanges(); } { const session = store.openSession(); const tsf = session.timeSeriesFor("users/1", "heartbeat"); const heartbeats = await tsf.get(); assert.strictEqual(heartbeats.length, 1); } }) }); async function prepareUserDataSet(store: IDocumentStore) { const users = [ new User({ name: "John", age: 30, registeredAt: new Date(2017, 10, 11), kids: ["Dmitri", "Mara"] }), new User({ name: "Stefanie", age: 25, registeredAt: new Date(2015, 6, 30) }), new User({ name: "Thomas", age: 25, registeredAt: new Date(2016, 3, 25) }) ]; const newSession = store.openSession(); for (const u of users) { await newSession.store(u); } await newSession.saveChanges(); return users; } });
the_stack
type float = number; type int = number; const splitter = 134217729.; // Veltkamp’s splitter (= 2^27+1 for 64-bit float) // Møller's and Knuth's summation (algorithm 2 from [1]) function twoSum(a: float, b: float) { let s = a + b; let a1 = s - b; return { hi: s, lo: (a - a1) + (b - (s - a1)) }; } // Dekker’s multiplication (algorithm 4.7 with inlined 4.6 from [2]) function twoProd(a: float, b: float) { let t = splitter * a; let ah = t + (a - t), al = a - ah; t = splitter * b; let bh = t + (b - t), bl = b - bh; t = a * b; return { hi: t, lo: ((ah * bh - t) + ah * bl + al * bh) + al * bl }; } function oneSqr(a: float) { let t = splitter * a; let ah = t + (a - t), al = a - ah; t = a * a; let hl = al * ah; return { hi: t, lo: ((ah * ah - t) + hl + hl) + al * al }; } /* Main class for double-word arithmetic */ export class Double { hi: float; lo: float; constructor(obj?: any) { if (obj instanceof Double) { this.hi = obj.hi; this.lo = obj.lo; } else if (typeof obj === 'number') { this.hi = obj; this.lo = 0.; } else if (typeof obj === 'string') { let d = Double.fromString(obj); this.hi = d.hi; this.lo = d.lo; } else if (Array.isArray(obj)) { this.hi = obj[0]; this.lo = obj[1]; } else if (typeof obj === 'object') { this.hi = obj.hi; this.lo = obj.lo; } } /* Static constructors */ static clone(X: Double): Double { let d = new Double(); d.hi = X.hi; d.lo = X.lo; return d; } static fromSum11(a: float, b: float): Double { return new Double(twoSum(a, b)); } static fromMul11(a: float, b: float): Double { return new Double(twoProd(a, b)); } static fromSqr1(a: float): Double { return new Double(oneSqr(a)); } static fromString(s: string): Double { let isPositive = (/^\s*-/.exec(s) === null); s = s.replace(/^\s*[+-]?/, ''); if (/Infinity.*/.exec(s) !== null) return (isPositive) ? Double.Infinity : Double.neg2(Double.Infinity); let rex = /^([0-9]*\.?[0-9]+)(?:[eE]([-+]?[0-9]+))?/.exec(s); if (!rex) return Double.NaN; let digits = rex[1].replace('.', ''); let exp = (rex[2] !== undefined) ? parseInt(rex[2]) : 0; let dotId = rex[0].indexOf('.'); if (dotId == -1) dotId = digits.length; if (exp + dotId - 1. < -300.) return isPositive ? Double.Zero : Double.neg2(Double.Zero); if (exp + dotId - 1. > 300.) return isPositive ? Double.Infinity : Double.neg2(Double.Infinity); let nextDigs: string, shift: Double, result = Double.Zero; for (let i = 0; i < digits.length; i += 15) { nextDigs = digits.slice(i, i + 15); shift = Double.pow2n(new Double(10.), exp + dotId - i - nextDigs.length); Double.add22(result, Double.mul21(shift, parseInt(nextDigs))); } return (isPositive) ? result : Double.neg2(result); } /* Convertations */ toNumber(): float { return this.hi + this.lo; } toExponential(precision: int): string { if (isNaN(this.hi)) return 'NaN'; if (!isFinite(this.hi) || this.toNumber() == 0.) return this.hi.toExponential(precision); let remainder = Double.clone(this); let str = remainder.hi.toExponential(precision).split('e'); if (str[0].length > 16) str[0] = str[0].slice(0, 16) let result = str[0]; let i = str[0].length - str[0].indexOf('.') - 1; if (str[0].indexOf('.') < 0) i--; Double.sub22(remainder, new Double(result + 'e' + str[1])) if (remainder.hi < 0.) Double.mul21(remainder, -1.0); if (precision !== undefined && precision > 33) precision = 33; while (true) { let nextPrecision = undefined; if (precision === undefined) { if (remainder.toNumber() <= 0.) break; } else { if (i >= precision) break; if (remainder.toNumber() <= 0.) { result += '0'; i++; continue; } nextPrecision = precision - i; if (nextPrecision > 14) nextPrecision = 14; } let next = remainder.hi.toExponential(nextPrecision).split('e'); let nextDigs = next[0].replace(/^0\.|\./, ''); let nextLength = nextDigs.length; if (nextLength > 15) nextLength = 15; if (precision === undefined) { if ((nextLength + i) > 33) nextLength = 33 - i; } else { if ((nextLength + i) > precision) nextLength = precision - i; } nextDigs = nextDigs.slice(0, nextLength); result += nextDigs; i += nextLength; if (i >= 33) break; let sub = nextDigs[0] + '.' + nextDigs.slice(1) Double.sub22(remainder, new Double(sub + 'e' + next[1])) } return result + 'e' + str[1]; } /* Arithmetic operations with two double */ // AccurateDWPlusDW (6 with inlined 1 from [1]) static add22(X: Double, Y: Double): Double { let S = twoSum(X.hi, Y.hi); let E = twoSum(X.lo, Y.lo); let c = S.lo + E.hi; let vh = S.hi + c, vl = c - (vh - S.hi); c = vl + E.lo; X.hi = vh + c; X.lo = c - (X.hi - vh); return X; } // AccurateDWPlusDW with negated Y static sub22(X: Double, Y: Double): Double { let S = twoSum(X.hi, -Y.hi); let E = twoSum(X.lo, -Y.lo); let c = S.lo + E.hi; let vh = S.hi + c, vl = c - (vh - S.hi); c = vl + E.lo; X.hi = vh + c; X.lo = c - (X.hi - vh); return X; } // DWTimesDW1 (10 with inlined 1 from [1]) static mul22(X: Double, Y: Double): Double { let S = twoProd(X.hi, Y.hi); S.lo += X.hi * Y.lo + X.lo * Y.hi; X.hi = S.hi + S.lo; X.lo = S.lo - (X.hi - S.hi); return X; } // Dekker division (div2 from [3]) static div22(X: Double, Y: Double): Double { let s = X.hi / Y.hi; let T = twoProd(s, Y.hi); let e = ((((X.hi - T.hi) - T.lo) + X.lo) - s * Y.lo) / Y.hi; X.hi = s + e; X.lo = e - (X.hi - s); return X; } /* Arithmetic operations with double and single */ // DWPlusFP (4 with inlined 1 from [1]) static add21(X: Double, f: float): Double { let S = twoSum(X.hi, f); S.lo += X.lo; X.hi = S.hi + S.lo; X.lo = S.lo - (X.hi - S.hi); return X; } static sub21(X: Double, f: float): Double { let S = twoSum(X.hi, -f); S.lo += X.lo; X.hi = S.hi + S.lo; X.lo = S.lo - (X.hi - S.hi); return X; } // DWTimesFP1 (7 with inlined 1 from [1]) static mul21(X: Double, f: float): Double { let C = twoProd(X.hi, f); let cl = X.lo * f; let th = C.hi + cl; X.lo = cl - (th - C.hi); cl = X.lo + C.lo; X.hi = th + cl; X.lo = cl - (X.hi - th); return X; } // DWDivFP1 (13 with inlined 1 from [1]) static div21(X: Double, f: float): Double { let th = X.hi / f; let P = twoProd(th, f); let D = twoSum(X.hi, -P.hi); let tl = (D.hi + (D.lo + (X.lo - P.lo))) / f; X.hi = th + tl; X.lo = tl - (X.hi - th); return X; } /* Unar operators with double */ static abs2(X: Double): Double { if (X.hi < 0.) { X.hi = -X.hi; X.lo = -X.lo; } return X; } static neg2(X: Double): Double { X.hi = -X.hi; X.lo = -X.lo; return X; } static inv2(X: Double): Double { var xh = X.hi; let s = 1. / xh; Double.mul21(X, s); let zl = (1. - X.hi - X.lo) / xh; X.hi = s + zl; X.lo = zl - (X.hi - s); return X; } static sqr2(X: Double): Double { let S = oneSqr(X.hi); let c = X.hi * X.lo; S.lo += c + c; X.hi = S.hi + S.lo; X.lo = S.lo - (X.hi - S.hi); return X; } static sqrt2(X: Double): Double { let s = Math.sqrt(X.hi); let T = oneSqr(s); let e = (X.hi - T.hi - T.lo + X.lo) * 0.5 / s; X.hi = s + e; X.lo = e - (X.hi - s); return X; } /* Comparisons */ static eq22(X: Double, Y: Double): boolean { return (X.hi === Y.hi && X.lo === Y.lo); } static ne22(X: Double, Y: Double): boolean { return (X.hi !== Y.hi || X.lo !== Y.lo); } static gt22(X: Double, Y: Double): boolean { return (X.hi > Y.hi || (X.hi === Y.hi && X.lo > Y.lo)); } static lt22(X: Double, Y: Double): boolean { return (X.hi < Y.hi || (X.hi === Y.hi && X.lo < Y.lo)); } static ge22(X: Double, Y: Double): boolean { return (X.hi > Y.hi || (X.hi === Y.hi && X.lo >= Y.lo)); } static le22(X: Double, Y: Double): boolean { return (X.hi < Y.hi || (X.hi === Y.hi && X.lo <= Y.lo)); } static eq21(X: Double, f: float): boolean { return (X.hi === f && X.lo === 0.); } static ne21(X: Double, f: float): boolean { return (X.hi !== f || X.lo !== 0.); } static gt21(X: Double, f: float): boolean { return (X.hi > f || (X.hi === f && X.lo > 0.)); } static lt21(X: Double, f: float): boolean { return (X.hi < f || (X.hi === f && X.lo < 0.)); } static ge21(X: Double, f: float): boolean { return (X.hi > f || (X.hi === f && X.lo >= 0.)); } static le21(X: Double, f: float): boolean { return (X.hi < f || (X.hi === f && X.lo <= 0.)); } /* Double constants */ static get One(): Double { let d = new Double(); d.hi = 1.; d.lo = 0.; return d; } static get Zero(): Double { let d = new Double(); d.hi = 0.; d.lo = 0.; return d; } static get Infinity(): Double { let d = new Double(); d.hi = Infinity; d.lo = Infinity; return d; } static get MinusInfinity() { let d = new Double(); d.hi = -Infinity; d.lo = -Infinity; return d; } static get NaN(): Double { let d = new Double(); d.hi = NaN; d.lo = NaN; return d; } static get Pi(): Double { let d = new Double(); d.hi = 3.141592653589793; d.lo = 1.2246467991473532e-16; return d; } static get X2Pi(): Double { let d = new Double(); d.hi = 6.283185307179586; d.lo = 2.4492935982947064e-16; return d; } static get E(): Double { let d = new Double(); d.hi = 2.718281828459045; d.lo = 1.4456468917292502e-16; return d; } static get Log2(): Double { let d = new Double(); d.hi = 0.6931471805599453; d.lo = 2.319046813846299e-17; return d; } static get Phi(): Double { let d = new Double(); d.hi = 1.618033988749895; d.lo = -5.432115203682505e-17; return d; } /* Elementary functions with double */ // [16/16] pade of exp(x) static exp2(X: Double): Double { if (Double.eq21(X, 0.)) return Double.One; if (Double.eq21(X, 1.)) return Double.E; let n = Math.floor(X.hi / Double.Log2.hi + 0.5); Double.sub22(X, Double.mul21(Double.Log2, n)); let U = Double.One, V = Double.One; let padeCoef = [1, 272, 36720, 3255840, 211629600, 10666131840, 430200650880, 14135164243200, 381649434566400, 8481098545920000, 154355993535744030, 2273242813890047700, 26521166162050560000, 236650405753681870000, 1.5213240369879552e+21, 6.288139352883548e+21, 1.2576278705767096e+22 ]; for (let i = 0, cLen = padeCoef.length; i < cLen; i++) Double.add21(Double.mul22(U, X), padeCoef[i]); for (let i = 0, cLen = padeCoef.length; i < cLen; i++) Double.add21(Double.mul22(V, X), padeCoef[i] * ((i % 2) ? -1 : 1)); X = Double.mul21pow2(Double.div22(U, V), n); return X; } static ln2(X: Double): Double { if (Double.le21(X, 0)) return Double.MinusInfinity; if (Double.eq21(X, 1)) return Double.Zero; let Z = new Double(Math.log(X.hi)); Double.sub21(Double.add22(Double.mul22(X, Double.exp2(Double.neg2(Double.clone(Z)))), Z), 1.); return X; } static sinh2(X: Double): Double { var exp = Double.exp2(X); X = Double.mul21pow2(Double.sub22(new Double(exp), Double.inv2(exp)), -1.); return X; } static cosh2(X: Double): Double { var exp = Double.exp2(X); X = Double.mul21pow2(Double.add22(new Double(exp), Double.inv2(exp)), -1.); return X; } static pow22(base: Double, exp: Double): Double { return Double.exp2(Double.mul22(Double.ln2(base), exp)); } static mul21pow2(X: Double, n: int): Double { let c = 1. << Math.abs(n); if (n < 0) c = 1 / c; X.hi = X.hi * c; X.lo = X.lo * c; return X; } static pow2n(X: Double, n: int): Double { if (n === 0) return Double.One; if (n == 1) return X; let isPositive = n > 0; if (!isPositive) n = -n; let i = 31 - Math.clz32(n | 1) let j = Math.floor(n - (1 << i)); let X0 = Double.clone(X); while (i--) Double.sqr2(X); while (j--) Double.mul22(X, X0); return isPositive ? X : Double.inv2(X); } /* Repeating static methods to instance */ add(other: any): Double { if (other instanceof Double) return Double.add22(Double.clone(this), other); else if (typeof other == 'number') return Double.add21(Double.clone(this), other); } sub(other: any): Double { if (other instanceof Double) return Double.sub22(Double.clone(this), other); else if (typeof other == 'number') return Double.sub21(Double.clone(this), other); } mul(other: any): Double { if (other instanceof Double) return Double.mul22(Double.clone(this), other); else if (typeof other == 'number') return Double.mul21(Double.clone(this), other); } div(other: any): Double { if (other instanceof Double) return Double.div22(Double.clone(this), other); else if (typeof other == 'number') return Double.div21(Double.clone(this), other); } eq(other: any): boolean { if (other instanceof Double) return Double.eq22(this, other); else if (typeof other == 'number') return Double.eq21(this, other); } ne(other: any): boolean { if (other instanceof Double) return Double.ne22(this, other); else if (typeof other == 'number') return Double.ne21(this, other); } gt(other: any): boolean { if (other instanceof Double) return Double.gt22(this, other); else if (typeof other == 'number') return Double.gt21(this, other); } lt(other: any): boolean { if (other instanceof Double) return Double.lt22(this, other); else if (typeof other == 'number') return Double.lt21(this, other); } ge(other: any): boolean { if (other instanceof Double) return Double.ge22(this, other); else if (typeof other == 'number') return Double.ge21(this, other); } le(other: any): boolean { if (other instanceof Double) return Double.le22(this, other); else if (typeof other == 'number') return Double.le21(this, other); } abs(): Double { return Double.abs2(Double.clone(this)); } neg(): Double { return Double.neg2(Double.clone(this)); } inv(): Double { return Double.inv2(Double.clone(this)); } sqr(): Double { return Double.sqr2(Double.clone(this)); } sqrt(): Double { return Double.sqrt2(Double.clone(this)); } exp(): Double { return Double.exp2(Double.clone(this)); } ln(): Double { return Double.ln2(Double.clone(this)); } sinh(): Double { return Double.sinh2(Double.clone(this)); } cosh(): Double { return Double.cosh2(Double.clone(this)); } pow(exp: Double): Double { return Double.pow22(Double.clone(this), exp); } pown(exp: float): Double { return Double.pow2n(Double.clone(this), exp); } } export default { Double };
the_stack